code stringlengths 2 1.05M |
|---|
import { createReducer, createActions } from 'reduxsauce'
import Immutable from 'seamless-immutable'
import R from 'ramda'
/* ------------- Initial State ------------- */
export const INITIAL_STATE = Immutable({
notifications: [],
specialTalks: []
})
/* ------------- Types and Action Creators ------------- */
const { Types, Creators } = createActions({
addNotification: ['message'],
clearNotifications: null,
addTalk: ['title'],
removeTalk: ['title']
})
export const NotificationTypes = Types
export default Creators
/* ------------- Reducer ------------- */
export const addSingleNotification = (state = INITIAL_STATE, { message }) =>
state.merge({ notifications: [...state.notifications, message] })
export const clearAllNotifications = (state) =>
state.merge({notifications: []})
export const addSingleTalk = (state = INITIAL_STATE, { title }) =>
state.merge({ specialTalks: [...state.specialTalks, title] })
export const removeSingleTalk = (state = INITIAL_STATE, { title }) =>
state.merge({ specialTalks: R.reject(R.equals(title), state.specialTalks) })
/* ------------- Hookup Reducers To Types ------------- */
export const reducer = createReducer(INITIAL_STATE, {
[Types.ADD_NOTIFICATION]: addSingleNotification,
[Types.CLEAR_NOTIFICATIONS]: clearAllNotifications,
[Types.ADD_TALK]: addSingleTalk,
[Types.REMOVE_TALK]: removeSingleTalk
})
|
import { route as textInputRoute } from './TextInput';
export const routes = [
textInputRoute
];
export default from './Field.component';
|
import assert from "assert";
import createNode from "../../../src/scapi/utils/createNode";
import createRef from "../../../src/scapi/utils/createRef";
import isSCNode from "../../../src/scapi/utils/isSCNode";
import isSCRef from "../../../src/scapi/utils/isSCRef";
import createOpNode from "../../../src/scapi/operators/_createOpNode";
const max = (a, b) => {
return createOpNode("max", [ a, b ], (a, b) => Math.max(a, b));
};
const firstArg = (a, b) => {
return createOpNode("firstArg", [ a, b ], (a, b) => (b, a), true);
};
describe("scapi/operators/_createOpNode(type, args, fn, disableCreateNode)", () => {
it("should eval when given numeric only", () => {
assert(max(2, 5) === 5);
});
it("should return a same shape array when given array", () => {
assert.deepEqual(max([ 2, 8 ], [ 5, 6 ]), [ 5, 8 ]);
assert.deepEqual(max([ 2, 4, [ 6 ] ], 5), [ 5, 5, [ 6 ] ]);
assert.deepEqual(max(5, [ 2, 4, [ 6 ] ]), [ 5, 5, [ 6 ] ]);
});
it("should return a sc.ref when given sc.ref", () => {
const a = max(createRef(2), 5);
const b = max(a, [ 3, createRef(10) ]);
assert(isSCRef(a));
assert(a.valueOf() === 5);
assert(Array.isArray(b) && b.length === 2);
assert(b[0].valueOf() === 5);
assert(b[1].valueOf() === 10);
});
it("should return a sc.node when given sc.node", () => {
const a = createNode("SinOsc", "audio", [ 440, 0 ]);
const b = max(a, 0.5);
assert(isSCNode(b));
assert.deepEqual(b, {
type: "max", rate: "audio", props: [ a, 0.5, ],
});
});
it("should skip creating node when given 3rd argument is true", () => {
const a = createNode("SinOsc", "audio", [ 440, 0 ]);
const b = firstArg(a, 0);
assert(b === a);
});
it("should throw TypeError when given invalid type value", () => {
assert.throws(() => {
max(1, "2");
});
});
});
|
foo: if (true) break foo;
|
/*
Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'autoembed', 'fr', {
embeddingInProgress: 'essaye d\'incorporer l\'URL collée...',
embeddingFailed: 'Cette URL n\'a pas pu être incorporée automatiquement.'
} );
|
TestHelpers.commonWidgetTests('resizable', {
defaults: {
alsoResize: false,
animate: false,
animateDuration: 'slow',
animateEasing: 'swing',
aspectRatio: false,
autoHide: false,
cancel: 'input,textarea,button,select,option',
containment: false,
delay: 0,
disabled: false,
distance: 1,
ghost: false,
grid: false,
handles: 'e,s,se',
helper: false,
maxHeight: null,
maxWidth: null,
minHeight: 10,
minWidth: 10,
zIndex: 1000,
// callbacks
create: null
}
});
|
export default {
giant: { value: 1170, unit: 'px' },
desktop: { value: 992, unit: 'px' },
tablet: { value: 768, unit: 'px' },
phone: { value: 376, unit: 'px' },
}
|
'use strict';
const AbstractConnectionManager = require('../abstract/connection-manager');
const Utils = require('../../utils');
const debug = Utils.getLogger().debugContext('connection:pg');
const Promise = require('../../promise');
const sequelizeErrors = require('../../errors');
const semver = require('semver');
const dataTypes = require('../../data-types');
const moment = require('moment-timezone');
class ConnectionManager extends AbstractConnectionManager {
constructor(dialect, sequelize) {
super(dialect, sequelize);
this.sequelize = sequelize;
this.sequelize.config.port = this.sequelize.config.port || 5432;
try {
let pgLib;
if (sequelize.config.dialectModulePath) {
pgLib = require(sequelize.config.dialectModulePath);
} else {
pgLib = require('pg');
}
this.lib = sequelize.config.native ? pgLib.native : pgLib;
} catch (err) {
if (err.code === 'MODULE_NOT_FOUND') {
throw new Error('Please install \'' + (sequelize.config.dialectModulePath || 'pg') + '\' module manually');
}
throw err;
}
this.refreshTypeParser(dataTypes.postgres);
}
// Expose this as a method so that the parsing may be updated when the user has added additional, custom types
_refreshTypeParser(dataType) {
if (dataType.types.postgres.oids) {
for (const oid of dataType.types.postgres.oids) {
this.lib.types.setTypeParser(oid, value => dataType.parse(value, oid, this.lib.types.getTypeParser));
}
}
if (dataType.types.postgres.array_oids) {
for (const oid of dataType.types.postgres.array_oids) {
this.lib.types.setTypeParser(oid, value =>
this.lib.types.arrayParser.create(value, v =>
dataType.parse(v, oid, this.lib.types.getTypeParser)
).parse()
);
}
}
}
connect(config) {
config.user = config.username;
const connectionConfig = Utils._.pick(config, [
'user', 'password', 'host', 'database', 'port'
]);
if (config.dialectOptions) {
Utils._.merge(connectionConfig,
Utils._.pick(config.dialectOptions, [
// see [http://www.postgresql.org/docs/9.3/static/runtime-config-logging.html#GUC-APPLICATION-NAME]
'application_name',
// choose the SSL mode with the PGSSLMODE environment variable
// object format: [https://github.com/brianc/node-postgres/blob/master/lib/connection.js#L79]
// see also [http://www.postgresql.org/docs/9.3/static/libpq-ssl.html]
'ssl',
// In addition to the values accepted by the corresponding server,
// you can use "auto" to determine the right encoding from the
// current locale in the client (LC_CTYPE environment variable on Unix systems)
'client_encoding',
// !! DONT SET THIS TO TRUE !!
// (unless you know what you're doing)
// see [http://www.postgresql.org/message-id/flat/bc9549a50706040852u27633f41ib1e6b09f8339d845@mail.gmail.com#bc9549a50706040852u27633f41ib1e6b09f8339d845@mail.gmail.com]
'binary',
// This should help with backends incorrectly considering idle clients to be dead and prematurely disconnecting them.
// this feature has been added in pg module v6.0.0, check pg/CHANGELOG.md
'keepAlive'
]));
}
return new Promise((resolve, reject) => {
const connection = new this.lib.Client(connectionConfig);
let responded = false;
connection.connect(err => {
if (err) {
if (err.code) {
switch (err.code) {
case 'ECONNREFUSED':
reject(new sequelizeErrors.ConnectionRefusedError(err));
break;
case 'ENOTFOUND':
reject(new sequelizeErrors.HostNotFoundError(err));
break;
case 'EHOSTUNREACH':
reject(new sequelizeErrors.HostNotReachableError(err));
break;
case 'EINVAL':
reject(new sequelizeErrors.InvalidConnectionError(err));
break;
default:
reject(new sequelizeErrors.ConnectionError(err));
break;
}
} else {
reject(new sequelizeErrors.ConnectionError(err));
}
return;
}
responded = true;
debug('connection acquired');
resolve(connection);
});
// If we didn't ever hear from the client.connect() callback the connection timeout, node-postgres does not treat this as an error since no active query was ever emitted
connection.on('end', () => {
debug('connection timeout');
if (!responded) {
reject(new sequelizeErrors.ConnectionTimedOutError(new Error('Connection timed out')));
}
});
// Don't let a Postgres restart (or error) to take down the whole app
connection.on('error', err => {
debug(`connection error ${err.code}`);
connection._invalid = true;
});
}).tap(connection => {
// Disable escape characters in strings, see https://github.com/sequelize/sequelize/issues/3545
let query = '';
if (this.sequelize.options.databaseVersion !== 0 && semver.gte(this.sequelize.options.databaseVersion, '8.2.0')) {
query += 'SET standard_conforming_strings=on;';
}
if (!this.sequelize.config.keepDefaultTimezone) {
const isZone = !!moment.tz.zone(this.sequelize.options.timezone);
if (isZone) {
query += 'SET client_min_messages TO warning; SET TIME ZONE \'' + this.sequelize.options.timezone + '\';';
} else {
query += 'SET client_min_messages TO warning; SET TIME ZONE INTERVAL \'' + this.sequelize.options.timezone + '\' HOUR TO MINUTE;';
}
}
// oids for hstore and geometry are dynamic - so select them at connection time
const supportedVersion = this.sequelize.options.databaseVersion !== 0 && semver.gte(this.sequelize.options.databaseVersion, '8.3.0');
if (dataTypes.HSTORE.types.postgres.oids.length === 0 && supportedVersion) {
query += 'SELECT typname, oid, typarray FROM pg_type WHERE typtype = \'b\' AND typname IN (\'hstore\', \'geometry\', \'geography\')';
}
return new Promise((resolve, reject) => connection.query(query, (error, result) => error ? reject(error) : resolve(result))).then(results => {
const result = Array.isArray(results) ? results.pop() : results;
for (const row of result.rows) {
let type;
if (row.typname === 'geometry') {
type = dataTypes.postgres.GEOMETRY;
} else if (row.typname === 'hstore') {
type = dataTypes.postgres.HSTORE;
} else if (row.typname === 'geography') {
type = dataTypes.postgres.GEOGRAPHY;
}
type.types.postgres.oids.push(row.oid);
type.types.postgres.array_oids.push(row.typarray);
this._refreshTypeParser(type);
}
});
});
}
disconnect(connection) {
return new Promise(resolve => {
connection.end();
resolve();
});
}
validate(connection) {
return connection._invalid === undefined;
}
}
Utils._.extend(ConnectionManager.prototype, AbstractConnectionManager.prototype);
module.exports = ConnectionManager;
module.exports.ConnectionManager = ConnectionManager;
module.exports.default = ConnectionManager;
|
export {
default,
emberNotificationAnd
} from 'ember-notif-hub/helpers/ember-notification-and';
|
angular.module('firstClass').directive('fcsNightsOfCampingIcon', function () {
return {
restrict: 'E',
scope: {
nights: '='
},
templateUrl: 'scout/nights-of-camping-icon.template.html'
}
}); |
'use strict'
var through2 = require('through2')
var standard = require('standard')
var gutil = require('gulp-util')
var PLUGIN_NAME = require('./package.json').name
var defaultReporter = require('./reporters/stylish')
function gulpStandard (opts) {
opts = opts || {}
function processFile (file, enc, cb) {
if (file.isNull()) {
return cb(null, file)
}
if (file.isStream()) {
return cb(new gutil.PluginError(PLUGIN_NAME, 'Streams are not supported!'))
}
standard.lintText(String(file.contents), opts, function (err, data) {
if (err) {
return cb(err)
}
file.standard = data
cb(null, file)
})
}
return through2.obj(processFile)
}
gulpStandard.reporter = function (reporter, opts) {
// Load default reporter
if (reporter === 'default') return defaultReporter(opts)
// Load reporter from function
if (typeof reporter === 'function') return reporter(opts)
// load built-in reporters
if (typeof reporter === 'string') {
try {
return require('gulp-standard/reporters/' + reporter)(opts)
} catch (err) {}
}
// load full-path or module reporters
if (typeof reporter === 'string') {
try {
return require(reporter)(opts)
} catch (err) {}
}
}
module.exports = gulpStandard
|
// All code points in the Letterlike Symbols block as per Unicode v5.0.0:
[
0x2100,
0x2101,
0x2102,
0x2103,
0x2104,
0x2105,
0x2106,
0x2107,
0x2108,
0x2109,
0x210A,
0x210B,
0x210C,
0x210D,
0x210E,
0x210F,
0x2110,
0x2111,
0x2112,
0x2113,
0x2114,
0x2115,
0x2116,
0x2117,
0x2118,
0x2119,
0x211A,
0x211B,
0x211C,
0x211D,
0x211E,
0x211F,
0x2120,
0x2121,
0x2122,
0x2123,
0x2124,
0x2125,
0x2126,
0x2127,
0x2128,
0x2129,
0x212A,
0x212B,
0x212C,
0x212D,
0x212E,
0x212F,
0x2130,
0x2131,
0x2132,
0x2133,
0x2134,
0x2135,
0x2136,
0x2137,
0x2138,
0x2139,
0x213A,
0x213B,
0x213C,
0x213D,
0x213E,
0x213F,
0x2140,
0x2141,
0x2142,
0x2143,
0x2144,
0x2145,
0x2146,
0x2147,
0x2148,
0x2149,
0x214A,
0x214B,
0x214C,
0x214D,
0x214E,
0x214F
]; |
import { module, test } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import { render } from '@ember/test-helpers';
import { hbs } from 'ember-cli-htmlbars';
module('Integration | Component | head-layout', function (hooks) {
setupRenderingTest(hooks);
test('it renders', async function (assert) {
let fragment = document.createDocumentFragment();
this.stuff = fragment;
await render(hbs`<HeadLayout @headElement={{this.stuff}}/>`);
assert
.dom('meta[name="ember-cli-head-start"]', fragment)
.exists({ count: 1 });
assert
.dom('meta[name="ember-cli-head-end"]', fragment)
.exists({ count: 1 });
});
});
|
import PropTypes from 'prop-types'
import React from 'react'
import config from 'config:@lyra/google-maps-input'
import Button from 'part:@lyra/components/buttons/default'
import Dialog from 'part:@lyra/components/dialogs/default'
import Fieldset from 'part:@lyra/components/fieldsets/default'
import {
PatchEvent,
set,
setIfMissing,
unset
} from 'part:@lyra/form-builder/patch-event'
import styles from '../styles/GeopointInput.css'
import GeopointSelect from './GeopointSelect'
import GoogleMapsLoadProxy from './GoogleMapsLoadProxy'
const getLocale = context => {
const intl = context.intl || {}
return (
intl.locale ||
(typeof window !== 'undefined' && window.navigator.language) ||
'en'
)
}
const getStaticImageUrl = value => {
const loc = `${value.lat},${value.lng}`
const params = {
key: config.apiKey,
center: loc,
markers: loc,
zoom: 13,
scale: 2,
size: '640x300'
}
const qs = Object.keys(params).reduce((res, param) => {
return res.concat(`${param}=${encodeURIComponent(params[param])}`)
}, [])
return `https://maps.googleapis.com/maps/api/staticmap?${qs.join('&')}`
}
class GeopointInput extends React.Component {
static propTypes = {
onChange: PropTypes.func.isRequired,
markers: PropTypes.arrayOf(
PropTypes.shape({
type: PropTypes.string
})
),
value: PropTypes.shape({
lat: PropTypes.number,
lng: PropTypes.number
}),
type: PropTypes.shape({
title: PropTypes.string.isRequired,
description: PropTypes.string
})
}
static defaultProps = {
markers: []
}
static contextTypes = {
intl: PropTypes.shape({
locale: PropTypes.string
})
}
constructor() {
super()
this.handleToggleModal = this.handleToggleModal.bind(this)
this.handleCloseModal = this.handleCloseModal.bind(this)
this.state = {
modalOpen: false
}
}
handleToggleModal() {
this.setState(prevState => ({modalOpen: !prevState.modalOpen}))
}
handleChange = latLng => {
const {type, onChange} = this.props
onChange(
PatchEvent.from([
setIfMissing({
_type: type.name
}),
set(latLng.lat(), ['lat']),
set(latLng.lng(), ['lng'])
])
)
}
handleClear = () => {
const {onChange} = this.props
onChange(PatchEvent.from(unset()))
}
handleCloseModal() {
this.setState({modalOpen: false})
}
render() {
const {value, type, markers} = this.props
if (!config || !config.apiKey) {
return (
<div>
<p>
The{' '}
<a href="https://vegapublish.com/docs/schema-types/geopoint-type">
Geopoint type
</a>{' '}
needs a Google Maps API key with access to:
</p>
<ul>
<li>Google Maps JavaScript API</li>
<li>Google Places API Web Service</li>
<li>Google Static Maps API</li>
</ul>
<p>
Please enter the API key with access to these services in
<code style={{whitespace: 'nowrap'}}>
`<project-root>/config/@lyra/google-maps-input.json`
</code>
</p>
</div>
)
}
return (
<Fieldset
legend={type.title}
description={type.description}
className={styles.root}
markers={markers}
>
{value && (
<div>
<img
className={styles.previewImage}
src={getStaticImageUrl(value)}
/>
</div>
)}
<div className={styles.functions}>
<Button onClick={this.handleToggleModal}>
{value ? 'Edit' : 'Set location'}
</Button>
{value && (
<Button type="button" onClick={this.handleClear}>
Remove
</Button>
)}
</div>
{this.state.modalOpen && (
<Dialog
title="Place on map"
onClose={this.handleCloseModal}
onCloseClick={this.handleCloseModal}
onOpen={this.handleOpenModal}
message="Select location by dragging the marker or search for a place"
isOpen={this.state.modalOpen}
>
<div className={styles.dialogInner}>
<GoogleMapsLoadProxy
value={value}
apiKey={config.apiKey}
onChange={this.handleChange}
defaultLocation={config.defaultLocation}
defaultZoom={config.defaultZoom}
locale={getLocale(this.context)}
component={GeopointSelect}
/>
</div>
</Dialog>
)}
</Fieldset>
)
}
}
export default GeopointInput
|
'use strict';
/**
* @ngdoc function
* @name mtViewApp.controller:SearchCtrl
* @description
* # SearchCtrl
* Controller of the mtViewApp
*/
angular.module('mtViewApp')
.controller('SearchCtrl',[ "$scope","$location","MTservice",function ($scope,$location,MTservice) {
$scope.searchQuey = $location.$$search;
$scope.from = $scope.searchQuey.ofst;
$scope.size = $scope.searchQuey.nmht;
$scope.searchTerm = $scope.searchQuey.key;
$scope.searchInProgess = true;
$scope.search = function(){
var queryString = $location.url();
if(queryString){
queryString = queryString.substring(queryString.indexOf("?"));
$scope.searchRequest = MTservice.searchKeyword(queryString);
$scope.searchInProgess = true;
$scope.searchRequest.then(function(response){
response = response.data;
console.log(response);
$scope.numResults = response.results.length;
$scope.searchInProgess = false;
});
}
}
$scope.search();
}]);
|
/**
* DevExtreme (viz/themes.js)
* Version: 16.2.5
* Build date: Mon Feb 27 2017
*
* Copyright (c) 2012 - 2017 Developer Express Inc. ALL RIGHTS RESERVED
* EULA: https://www.devexpress.com/Support/EULAs/DevExtreme.xml
*/
"use strict";
var $ = require("jquery"),
vizUtils = require("./core/utils"),
themes = {},
themesMapping = {},
themesSchemeMapping = {},
_extend = $.extend,
_each = $.each,
_normalizeEnum = vizUtils.normalizeEnum,
currentThemeName = null,
nextCacheUid = 0,
widgetsCache = {};
function findTheme(themeName) {
var name = _normalizeEnum(themeName);
return themes[name] || themes[themesMapping[name] || currentThemeName]
}
function findThemeNameByName(name, scheme) {
return themesMapping[name + "." + scheme] || themesSchemeMapping[name + "." + scheme] || themesMapping[name]
}
function findThemeNameByPlatform(platform, version, scheme) {
return findThemeNameByName(platform + version, scheme) || findThemeNameByName(platform, scheme)
}
function currentTheme(themeName, colorScheme) {
if (!arguments.length) {
return currentThemeName
}
var scheme = _normalizeEnum(colorScheme);
currentThemeName = (themeName && themeName.platform ? findThemeNameByPlatform(_normalizeEnum(themeName.platform), themeName.version, scheme) : findThemeNameByName(_normalizeEnum(themeName), scheme)) || currentThemeName;
return this
}
function getThemeInfo(themeName, splitter) {
var k = themeName.indexOf(splitter);
return k > 0 ? {
name: themeName.substring(0, k),
scheme: themeName.substring(k + 1)
} : null
}
function registerThemeName(themeName, targetThemeName) {
var themeInfo = getThemeInfo(themeName, ".") || getThemeInfo(themeName, "-") || {
name: themeName
},
name = themeInfo.name,
scheme = themeInfo.scheme;
if (scheme) {
themesMapping[name] = themesMapping[name] || targetThemeName;
themesMapping[name + "." + scheme] = themesMapping[name + "-" + scheme] = targetThemeName
} else {
themesMapping[name] = targetThemeName
}
}
function registerTheme(theme, baseThemeName) {
var themeName = _normalizeEnum(theme && theme.name);
if (themeName) {
registerThemeName(themeName, themeName);
themes[themeName] = _extend(true, {}, findTheme(baseThemeName), patchTheme(theme))
}
}
function registerThemeAlias(alias, theme) {
registerThemeName(_normalizeEnum(alias), _normalizeEnum(theme))
}
function registerThemeSchemeAlias(from, to) {
themesSchemeMapping[from] = to
}
function mergeScalar(target, field, source, sourceValue) {
var _value = source ? source[field] : sourceValue;
if (void 0 !== _value && void 0 === target[field]) {
target[field] = _value
}
}
function mergeObject(target, field, source, sourceValue) {
var _value = source ? source[field] : sourceValue;
if (void 0 !== _value) {
target[field] = _extend(true, {}, _value, target[field])
}
}
function patchTheme(theme) {
theme = _extend(true, {
loadingIndicator: {
font: {}
},
"export": {
font: {}
},
legend: {
font: {},
border: {}
},
title: {
font: {}
},
tooltip: {
font: {}
},
"chart:common": {},
"chart:common:axis": {
grid: {},
minorGrid: {},
tick: {},
minorTick: {},
title: {
font: {}
},
label: {
font: {}
}
},
chart: {
commonSeriesSettings: {
candlestick: {}
}
},
pie: {},
polar: {},
gauge: {
scale: {
tick: {},
minorTick: {},
label: {
font: {}
}
}
},
barGauge: {},
map: {
background: {}
},
treeMap: {
tile: {
selectionStyle: {
border: {}
}
},
group: {
border: {},
selectionStyle: {
border: {}
},
label: {
font: {}
}
}
},
rangeSelector: {
scale: {
tick: {},
minorTick: {},
label: {
font: {}
}
},
chart: {}
},
sparkline: {},
bullet: {}
}, theme);
mergeScalar(theme.loadingIndicator, "backgroundColor", theme);
mergeScalar(theme.chart.commonSeriesSettings.candlestick, "innerColor", null, theme.backgroundColor);
mergeScalar(theme.map.background, "color", null, theme.backgroundColor);
mergeScalar(theme.title.font, "color", null, theme.primaryTitleColor);
mergeObject(theme.title, "subtitle", null, theme.title);
mergeScalar(theme.legend.font, "color", null, theme.secondaryTitleColor);
mergeScalar(theme.legend.border, "color", null, theme.axisColor);
patchAxes(theme);
_each(["chart", "pie", "polar", "gauge", "barGauge", "map", "treeMap", "rangeSelector", "sparkline", "bullet"], function(_, section) {
mergeScalar(theme[section], "redrawOnResize", theme);
mergeScalar(theme[section], "containerBackgroundColor", null, theme.backgroundColor);
mergeObject(theme[section], "tooltip", theme)
});
_each(["chart", "pie", "polar", "gauge", "barGauge", "map", "treeMap", "rangeSelector"], function(_, section) {
mergeObject(theme[section], "loadingIndicator", theme);
mergeObject(theme[section], "export", theme);
mergeObject(theme[section], "legend", theme);
mergeObject(theme[section], "title", theme)
});
_each(["chart", "pie", "polar"], function(_, section) {
mergeObject(theme, section, null, theme["chart:common"])
});
_each(["chart", "polar"], function(_, section) {
theme[section] = theme[section] || {};
mergeObject(theme[section], "commonAxisSettings", null, theme["chart:common:axis"])
});
mergeObject(theme.rangeSelector.chart, "commonSeriesSettings", theme.chart);
mergeObject(theme.rangeSelector.chart, "dataPrepareSettings", theme.chart);
mergeScalar(theme.treeMap.group.border, "color", null, theme.axisColor);
mergeScalar(theme.treeMap.tile.selectionStyle.border, "color", null, theme.primaryTitleColor);
mergeScalar(theme.treeMap.group.selectionStyle.border, "color", null, theme.primaryTitleColor);
mergeScalar(theme.treeMap.group.label.font, "color", null, theme.secondaryTitleColor);
mergeScalar(theme.map.legend, "backgroundColor", theme);
patchMapLayers(theme);
return theme
}
function patchAxes(theme) {
var commonAxisSettings = theme["chart:common:axis"],
colorFieldName = "color";
_each([commonAxisSettings, commonAxisSettings.grid, commonAxisSettings.minorGrid, commonAxisSettings.tick, commonAxisSettings.minorTick], function(_, obj) {
mergeScalar(obj, colorFieldName, null, theme.axisColor)
});
mergeScalar(commonAxisSettings.title.font, colorFieldName, null, theme.secondaryTitleColor);
mergeScalar(commonAxisSettings.label.font, colorFieldName, null, theme.axisLabelColor);
mergeScalar(theme.gauge.scale.label.font, colorFieldName, null, theme.axisLabelColor);
mergeScalar(theme.gauge.scale.tick, colorFieldName, null, theme.backgroundColor);
mergeScalar(theme.gauge.scale.minorTick, colorFieldName, null, theme.backgroundColor);
mergeScalar(theme.rangeSelector.scale.tick, colorFieldName, null, theme.axisColor);
mergeScalar(theme.rangeSelector.scale.minorTick, colorFieldName, null, theme.axisColor);
mergeScalar(theme.rangeSelector.scale.label.font, colorFieldName, null, theme.axisLabelColor)
}
function patchMapLayers(theme) {
var map = theme.map;
_each(["area", "line", "marker"], function(_, section) {
mergeObject(map, "layer:" + section, null, map.layer)
});
_each(["dot", "bubble", "pie", "image"], function(_, section) {
mergeObject(map, "layer:marker:" + section, null, map["layer:marker"])
})
}
function addCacheItem(target) {
var cacheUid = ++nextCacheUid;
target._cache = cacheUid;
widgetsCache[cacheUid] = target
}
function removeCacheItem(target) {
delete widgetsCache[target._cache]
}
function refreshAll() {
_each(widgetsCache, function() {
this.refresh()
});
return this
}
_extend(exports, {
currentTheme: currentTheme,
registerTheme: registerTheme,
findTheme: findTheme,
registerThemeAlias: registerThemeAlias,
registerThemeSchemeAlias: registerThemeSchemeAlias,
refreshAll: refreshAll,
addCacheItem: addCacheItem,
removeCacheItem: removeCacheItem
});
|
"use strict";
var createDelimited = require('./manipulators/create-delimited'),
getColorValues = require('./manipulators/get-color-values'),
functionCreate = require('./manipulators/function-create'),
defaultProps = require('./settings/default-props'),
terms = require('./settings/dictionary').hsl;
module.exports = {
defaultProps: {
Hue: {
min: 0,
max: 360
},
Saturation: defaultProps.percent,
Lightness: defaultProps.percent,
Alpha: defaultProps.opacity
},
test: function test(value) {
return value && value.indexOf('hsl') > -1;
},
split: function split(value) {
return getColorValues(value, terms);
},
combine: function combine(values) {
return functionCreate(createDelimited(values, terms, ', ', 2), 'hsla');
}
}; |
var Cat = require('./cat.js');
var cats = new Cat().getCats();
console.log(cats);
|
'use strict'
/* global describe, it */
const assert = require('assert')
describe('Company Model', () => {
it('should exist', () => {
assert(global.app.api.models['Company'])
})
})
|
// flow-typed signature: f9f4fa8dbf1e89fa445e8deb2a98f812
// flow-typed version: <<STUB>>/eslint-plugin-prettier_v^3.0.0/flow_v0.89.0
/**
* This is an autogenerated libdef stub for:
*
* 'eslint-plugin-prettier'
*
* 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 'eslint-plugin-prettier' {
declare module.exports: any;
}
/**
* We include stubs for each file inside this npm package in case you need to
* require those files directly. Feel free to delete any files that aren't
* needed.
*/
declare module 'eslint-plugin-prettier/eslint-plugin-prettier' {
declare module.exports: any;
}
// Filename aliases
declare module 'eslint-plugin-prettier/eslint-plugin-prettier.js' {
declare module.exports: $Exports<'eslint-plugin-prettier/eslint-plugin-prettier'>;
}
|
var pull = require("pull-stream");
var unwind = require("../");
var events = [
{
name: "SomeEvent",
value: 1
}
]
pull(
pull.values(events),
unwind(3),
pull.drain(console.log)
) |
import React, { Component } from 'react'
import debounce from 'lodash/debounce'
import { connect } from 'react-redux'
import { updateSettings } from 'actions/settings'
import { fileDialog } from 'helpers/fs'
import Button from 'components/Button'
import CheckBox from 'components/CheckBox'
export default connect(
state => {
const { settings } = state
return {
mjmlConfigPath: settings.getIn(['mjml', 'mjmlConfigPath'], ''),
useMjmlConfig: settings.getIn(['mjml', 'useMjmlConfig'], false),
}
},
{
updateSettings,
},
)(
class MjmlConfigPath extends Component {
state = {
mjmlConfigPath: '',
}
componentWillMount() {
const { mjmlConfigPath } = this.props
this.setState({
mjmlConfigPath: mjmlConfigPath || '',
})
}
componentWillUnmount() {
this._unmounted = true
}
handleChangePath = p => {
this.setState({ mjmlConfigPath: p })
this.debounceSaveSettings()
}
handleBrowse = () => {
const p = fileDialog({
properties: ['openFile', 'showHiddenFiles'],
})
if (!p) {
return
}
this.handleChangePath(p)
}
debounceSaveSettings = debounce(() => {
const { mjmlConfigPath } = this.state
const { updateSettings } = this.props
updateSettings(settings => {
return settings.setIn(['mjml', 'mjmlConfigPath'], mjmlConfigPath)
})
}, 500)
render() {
const { useMjmlConfig, updateSettings } = this.props
const { mjmlConfigPath } = this.state
return (
<div className="flow-v-10">
<div className="mt-10">{'Custom components:'}</div>
<CheckBox
value={useMjmlConfig}
onChange={val =>
updateSettings(settings => settings.setIn(['mjml', 'useMjmlConfig'], val))
}
>
{'Use custom components (slightly slower preview refresh)'}
</CheckBox>
<div className="mt-10">
{
'Path of .mjmlconfig file (leave blank for default, will search for .mjmlconfig in the same folder as the mjml file) :'
}
</div>
<div className="d-f ai-s fg-1">
<input
autoFocus
className="fg-1"
value={mjmlConfigPath}
onChange={e => this.handleChangePath(e.target.value)}
placeholder=".mjmlconfig path"
type="text"
/>
<Button ghost onClick={this.handleBrowse} type="button">
{'Browse'}
</Button>
</div>
</div>
)
}
},
)
|
"use strict";
var React = require("react"),
Slider = require("./common/Slider");
var Delay = React.createClass({
render: function() {
return (
<div className="delay-group__wrapper">
<h3 className="param__title">Delay</h3>
<section className="delay-group">
<Slider
displayName={this.props.delayAttack.displayName}
id={this.props.delayAttack.id}
max={this.props.delayAttack.max}
min={this.props.delayAttack.min}
step={this.props.delayAttack.step}
val={this.props.delayAttack} />
<Slider
displayName={this.props.delayDry.displayName}
id={this.props.delayDry.id}
max={this.props.delayDry.max}
min={this.props.delayDry.min}
step={this.props.delayDry.step}
val={this.props.delayDry} />
<Slider
displayName={this.props.delayWet.displayName}
id={this.props.delayWet.id}
max={this.props.delayWet.max}
min={this.props.delayWet.min}
step={this.props.delayWet.step}
val={this.props.delayWet} />
<Slider
displayName={this.props.delayRelease.displayName}
id={this.props.delayRelease.id}
max={this.props.delayRelease.max}
min={this.props.delayRelease.min}
step={this.props.delayRelease.step}
val={this.props.delayRelease} />
<Slider
displayName={this.props.delayRepeat.displayName}
id={this.props.delayRepeat.id}
max={this.props.delayRepeat.max}
min={this.props.delayRepeat.min}
step={this.props.delayRepeat.step}
val={this.props.delayRepeat} />
<Slider
displayName={this.props.delayTime.displayName}
id={this.props.delayTime.id}
max={this.props.delayTime.max}
min={this.props.delayTime.min}
step={this.props.delayTime.step}
val={this.props.delayTime} />
</section>
</div>
);
}
});
module.exports = Delay; |
var q = require('q');
var _ = require('underscore');
browser.addCommand('waitForVisibleAndClick', function (selector, message) {
return this.waitForVisible(selector)
.click(selector)
.then(function () {
if (message) {
console.log(message);
}
});
});
browser.addCommand('waitALittle', function (time) {
var deferred = q.defer();
setTimeout(function () {
deferred.resolve();
}, time);
return deferred.promise;
});
browser.addCommand('isAnySelected', function (selector) {
return this.isSelected(selector)
.then(function (isSelectedList) {
return _.find(isSelectedList, function (isSelected) {
return isSelected;
}) || false;
});
});
|
var app = angular.module("app", ["ngRoute", "ngAnimate", "ui.bootstrap"]);
app.controller("SoundBoardController",
[
"$scope",
function ($scope) {
$scope.toggle = true;
$scope.models = {
pageTitle: "Welcome to My Board!"
};
$scope.toggleSidebar = function () {
$scope.toggle = !$scope.toggle;
};
}]); |
/* eslint-disable camelcase */
import db from '../config/database/database'
import { messagesQueries } from '../config/database/sqlQueries/index'
// TODO: make db settable, so can use Messages' methods with either testdb or db
export default class Message {
/**
* Retrieve all messages
* @return {Promise} promise
*/
static getAll () {
return db.any(messagesQueries.getAll)
}
/**
* Retrieve one particular message
* @return {Promise} promise
*/
static get (id) {
return db.one(messagesQueries.get, [id])
}
/**
* Create a new message
* @param {number} group_id - ID of the group the message belongs to
* @param {string} sender - Sender's name
* @param {string} content - Message's content
* @return {Promise} promise (id, group_id, sender, content, created_at)
*/
static create (group_id, sender, content) {
return db.one(messagesQueries.create, [group_id, sender, content])
}
/**
* Update message with the given identifier
* @param {number} id - Unique identifier
* @param {string} content - Name
* @return {Promise} promise (id, group_id, sender, content, created_at)
*/
static update (id, content) {
return db.one(messagesQueries.update, [id, content])
}
/**
* Remove the specified message
* @param {number} id - Message identifier
* @return {Promise} promise
*/
static remove (id) {
return db.none(messagesQueries.remove, [id])
}
}
|
import { Router } from 'express';
import generate from './generate';
import verify from './verify';
const router = Router();
router.get('/', generate);
router.post('/', verify);
export default router; |
var gotCharacters = [
// Stark
{
characterName: 'Eddard Stark',
house: 'house-stark',
status: 'dead'
}, {
characterName: 'Catelyn Stark',
house: 'house-stark',
status: 'dead'
}, {
characterName: 'Rodrik Cassel',
house: 'house-stark',
status: 'dead'
}, {
characterName: 'Septa Mordane',
house: 'house-stark',
status: 'dead'
}, {
characterName: 'Arya Stark & Nymeria',
house: 'house-stark',
status: 'alive'
}, {
characterName: 'Sansa Stark & Lady',
house: 'house-stark',
status: 'alive'
}, {
characterName: 'Robb Stark & Grey Wind',
house: 'house-stark',
status: 'dead'
}, {
characterName: 'Talisa Maegyr',
house: 'house-stark',
status: 'dead'
}, {
characterName: 'Rickon Stark & Shaggydog',
house: 'house-stark',
status: 'alive'
}, {
characterName: 'Brandon Stark & Summer',
house: 'house-stark',
status: 'alive'
}, {
characterName: 'Osha',
house: 'house-stark',
status: 'alive'
}, {
characterName: 'Hodor',
house: 'house-stark',
status: 'alive'
}, {
characterName: 'Maester Luwin',
house: 'house-stark',
status: 'dead'
},
// Reed
{
characterName: 'Jojen Reed',
house: 'house-reed',
status: 'alive'
}, {
characterName: 'Meera Reed',
house: 'house-reed',
status: 'dead'
},
// Baelish
{
characterName: 'Petyr Baelish',
house: 'house-baelish',
status: 'alive'
}, {
characterName: 'Ros',
house: 'house-baelish',
status: 'alive'
},
// Tarth
{
characterName: 'Brienne Tarth',
house: 'house-tarth',
status: 'alive'
},
// Faceless Men
{
characterName: 'Jaqen H\'ghar',
house: 'faceless-men',
status: 'alive'
},
//Brotherhood without banners
{
characterName: 'Thoros of Myr',
house: 'brotherhood-w/o-banners',
status: 'alive'
}, {
characterName: 'Beric Dondarrion',
house: 'brotherhood-w/o-banners',
status: 'alive'
}, {
characterName: 'Anguy',
house: 'brotherhood-w/o-banners',
status: 'alive'
}, {
characterName: 'Gendry',
house: 'brotherhood-w/o-banners',
status: 'alive'
},
// Lannister
{
characterName: 'Jaime Lannister',
house: 'house-lannister',
status: 'alive'
}, {
characterName: 'Qyburn',
house: 'house-lannister',
status: 'alive'
}, {
characterName: '"The Hound" Clegane',
house: 'house-lannister',
status: 'dead'
}, {
characterName: '"The Mountain" Clegane',
house: 'house-lannister',
status: 'alive'
}, {
characterName: 'Cersei Lannister',
house: 'house-lannister',
status: 'alive'
}, {
characterName: 'Tyrion Lannister',
house: 'house-lannister',
status: 'alive'
}, {
characterName: 'Shae',
house: 'house-lannister',
status: 'alive'
}, {
characterName: 'Podrick Payne',
house: 'house-lannister',
status: 'alive'
}, {
characterName: 'Tywin Lannister',
house: 'house-lannister',
status: 'dead'
}, {
characterName: 'Tommen Baratheon',
house: 'house-lannister',
status: 'alive'
}, {
characterName: 'Joffrey "Baratheon"',
house: 'house-lannister',
status: 'dead'
}, {
characterName: 'Maester Pycelle',
house: 'house-lannister',
status: 'alive'
}, {
characterName: 'Ser Ilyn Payne',
house: 'house-lannister',
status: 'alive'
},
// The Kingsguard
{
characterName: 'Meryn Trant',
house: 'the-kingsguard',
status: 'alive'
},
// Tully
{
characterName: 'Brynden Tully',
house: 'house-tully',
status: 'alive'
}, {
characterName: 'Edmure Tully',
house: 'house-tully',
status: 'alive'
},
// Bolton
{
characterName: 'Roose Bolton',
house: 'house-bolton',
status: 'alive'
}, {
characterName: 'Ramsay Snow/Bolton',
house: 'house-bolton',
status: 'alive'
}, {
characterName: 'Locke',
house: 'house-bolton',
status: 'alive'
},
// The Nights Watch
{
characterName: 'Benjen Stark',
house: 'the-nights-watch',
status: 'alive'
}, {
characterName: 'Jeor Mormont',
house: 'the-nights-watch',
status: 'dead'
}, {
characterName: 'Alliser Thorne',
house: 'the-nights-watch',
status: 'alive'
}, {
characterName: 'Maester Aemon',
house: 'the-nights-watch',
status: 'alive'
}, {
characterName: 'Samwell Tarly',
house: 'the-nights-watch',
status: 'alive'
}, {
characterName: 'Yoren',
house: 'the-nights-watch',
status: 'alive'
}, {
characterName: 'Qhorin Halfhand',
house: 'the-nights-watch',
status: 'alive'
}, {
characterName: 'Jon Snow & Ghost',
house: 'the-nights-watch',
status: 'alive'
}, {
characterName: 'Samwell Tarly',
house: 'the-nights-watch',
status: 'alive'
},
// Wildlings
{
characterName: 'Mance Rayder',
house: 'wildlings',
status: 'alive'
}, {
characterName: 'Ygritte',
house: 'wildlings',
status: 'dead'
}, {
characterName: 'Tormund Giantsbane',
house: 'wildlings',
status: 'alive'
}, {
characterName: 'Lord of Bones',
house: 'wildlings',
status: 'alive'
}, {
characterName: 'Warg Orell',
house: 'wildlings',
status: 'dead'
},
// Craster
{
characterName: 'Craster',
house: 'wildlings',
status: 'dead'
},
// The Dothraki
{
characterName: 'Khal Drogo',
house: 'the-dothraki',
status: 'dead'
},
// The Second Sons
{
characterName: 'Daario Naharis',
house: 'house-targaryen',
status: 'alive'
},
// Frey
{
characterName: 'Walder Frey',
house: 'house-frey',
status: 'alive'
},
// Targaryen
{
characterName: 'Daenerys Targaryen',
house: 'house-targaryen',
status: 'alive'
}, {
characterName: 'Viserys Targaryen',
house: 'house-targaryen',
status: 'dead'
}, {
characterName: 'Jorah Mormont',
house: 'house-targaryen',
status: 'alive'
}, {
characterName: 'Barristan Selmy',
house: 'house-targaryen',
status: 'alive'
}, {
characterName: 'Grey Worm',
house: 'house-targaryen',
status: 'alive'
}, {
characterName: 'Missandei',
house: 'house-targaryen',
status: 'alive'
}, {
characterName: 'Drogon, Rhaegal & Viserion',
house: 'house-targaryen',
status: 'alive'
},
// Martell
{
characterName: 'Oberyn Martell',
house: 'house-martell',
status: 'alive'
}, {
characterName: 'Ellaria Sand',
house: 'house-martell',
status: 'alive'
},
// Varys
{
characterName: 'Lord Varys',
house: 'varys',
status: 'alive'
},
// Tyrell
{
characterName: 'Margaery Tyrell',
house: 'house-tyrell',
status: 'alive'
}, {
characterName: 'Loras Tyrell',
house: 'house-tyrell',
status: 'alive'
}, {
characterName: 'Olenna Tyrell',
house: 'house-tyrell',
status: 'alive'
}, {
characterName: 'Mace Tyrell',
house: 'house-tyrell',
status: 'alive'
},
// Baratheon
{
characterName: 'Robert Baratheon',
house: 'house-baratheon',
status: 'dead'
},
// Baratheon of Dragonstone
{
characterName: 'Stannis Baratheon',
house: 'house-baratheon-dragonstone',
status: 'alive'
}, {
characterName: 'Selyse Baratheon',
house: 'house-baratheon-dragonstone',
status: 'alive'
}, {
characterName: 'Shireen Baratheon',
house: 'house-baratheon-dragonstone',
status: 'alive'
}, {
characterName: 'Melisandre',
house: 'house-baratheon-dragonstone',
status: 'alive'
}, {
characterName: 'Davos Seaworth',
house: 'house-baratheon-dragonstone',
status: 'alive'
},
// Baratheon at Storm's End
{
characterName: 'Renly Baratheon',
house: 'house-baratheon-storms-end',
status: 'alive'
},
// Greyjoy
{
characterName: 'Balon Greyjoy',
house: 'house-greyjoy',
status: 'alive'
}, {
characterName: 'Dagmer Cleftjaw',
house: 'house-greyjoy',
status: 'alive'
}, {
characterName: 'Theon "Reek" Greyjoy',
house: 'house-greyjoy',
status: 'alive'
}, {
characterName: 'Yara Greyjoy',
house: 'house-greyjoy',
status: 'alive'
},
// Arryn
{
characterName: 'Lysa Arryn',
house: 'house-arryn',
status: 'dead'
}, {
characterName: 'Robin Arryn',
house: 'house-arryn',
status: 'alive'
},
];
|
const Conf = require('conf');
const { utils } = require('dext-core-utils');
const { DEXT_PATH } = utils.paths;
module.exports = class extends Conf {
constructor(opts) {
const defaultOpts = {
defaults: {
theme: '',
// specify the accelerators for toggling the Dext Bar.
// @link http://electron.atom.io/docs/api/accelerator/
hotKey: 'alt+space',
plugins: [],
},
};
const o = Object.assign({}, opts, defaultOpts);
o.cwd = DEXT_PATH;
super(o);
}
};
|
import React from 'react';
import ReactDOM from 'react-dom';
it('renders without crashing', () => {
true
});
|
var MarkupLine = {
HandlesType: function(type) {
return type == 'line';
},
Paint: function(elementObject) {
$('#' + elementObject.Handle).css({
left: SizeCalculator.ToPixels(elementObject.x) + 'px',
top: SizeCalculator.ToPixels(elementObject.y) + 'px',
width: SizeCalculator.ToPixels(elementObject.width) + 'px',
height: SizeCalculator.ToPixels(elementObject.height) + 'px',
backgroundColor: elementObject.color
});
},
Update: function(elementObject) {
this.Paint(elementObject);
},
New: function(markup) {
markup.AddElement({
type: "line",
x: 10,
y: 10,
width: 190,
height: 1,
color: '#00000',
properties: {
x: {
label: 'Left (mm)',
component: 'number'
},
y: {
label: 'Top (mm)',
component: 'number'
},
width: {
label: 'Width (mm)',
component: 'number'
},
color: {
label: 'Color',
component: 'select',
items: {
'Black': '#00000',
'Silver': '#C0C0C0',
}
}
}
});
}
};
|
import { request } from 'utils/request'
export function fetchNotice (params) {
return request({ wsfunction: 'mod_frontservice_get_ads', ...params })
}
export function fetchCourseList (params) {
return request({ wsfunction: 'mod_frontservice_my_contractccs', ...params })
}
export function fetchRecordList (params) {
return request({ wsfunction: 'mod_frontservice_get_student_recordings', ...params })
}
|
Rickshaw.namespace('Rickshaw.Graph.RangeSlider');
Rickshaw.Graph.RangeSlider = Rickshaw.Class.create({
initialize: function(args) {
var $ = jQuery;
var self = this;
var element = this.element = args.element;
var graphs = this.graphs = args.graphs;
if (!graphs) {
graphs = this.graph = args.graph;
}
if (graphs.constructor !== Array) {
graphs = [graphs];
}
this.graph = graphs[0];
this.slideCallbacks = [];
this.build();
for (var i = 0; i < graphs.length; i++) {
graphs[i].onUpdate(function() {
self.update();
}.bind(self));
(function(idx){
graphs[idx].onConfigure(function() {
$(this.element)[0].style.width = graphs[idx].width + 'px';
}.bind(self));
})(i);
}
},
build: function() {
var domain;
var element = this.element;
var $ = jQuery;
var self = this;
var graphs = this.graphs || this.graph;
if (graphs.constructor !== Array) {
graphs = [graphs];
}
// base the slider's min/max on the first graph
this.graph = graphs[0];
domain = graphs[0].dataDomain();
$(function() {
$(element).slider({
range: true,
min: domain[0],
max: domain[1],
values: [
domain[0],
domain[1]
],
start: function(event, ui) {
self.slideStarted({ event: event, ui: ui });
},
stop: function(event, ui) {
self.slideFinished({ event: event, ui: ui });
},
slide: function(event, ui) {
if (!self.slideShouldUpdate(event, ui))
return;
if (ui.values[1] <= ui.values[0]) return;
for (var i = 0; i < graphs.length; i++) {
self.processSlideChange({
event: event,
ui: ui,
graph: graphs[i]
});
}
}
} );
} );
graphs[0].onConfigure(function() {
$(this.element)[0].style.width = graphs[0].width + 'px';
}.bind(this));
},
update: function() {
var element = this.element;
var graph = this.graph;
var $ = jQuery;
var values = $(element).slider('option', 'values');
var domain = graph.dataDomain();
$(element).slider('option', 'min', domain[0]);
$(element).slider('option', 'max', domain[1]);
if (graph.window.xMin == null) {
values[0] = domain[0];
}
if (graph.window.xMax == null) {
values[1] = domain[1];
}
$(element).slider('option', 'values', values);
},
onSlide: function(callback) {
this.slideCallbacks.push(callback);
},
processSlideChange: function(args) {
var event = args.event;
var ui = args.ui;
var graph = args.graph;
graph.window.xMin = ui.values[0];
graph.window.xMax = ui.values[1];
graph.update();
var domain = graph.dataDomain();
// if we're at an extreme, stick there
if (domain[0] == ui.values[0]) {
graph.window.xMin = undefined;
}
if (domain[1] == ui.values[1]) {
graph.window.xMax = undefined;
}
this.slideCallbacks.forEach(function(callback) {
callback(graph, graph.window.xMin, graph.window.xMax);
});
},
// allows the slide updates to bail out if sliding is not permitted
slideShouldUpdate: function() {
return true;
},
slideStarted: function() {
return;
},
slideFinished: function() {
return;
}
});
|
var render = require('./jml.js').render;
var fs = require('fs');
module.exports = {
oneTag: {
simple: function (test) {
var view = [['p']];
test.equal(render(view), '<p></p>', 'Simple tag');
test.done();
},
simpleEmpty: function (test) {
var view = [['br']];
test.equal(render(view), '<br />', 'Simple empty tag');
test.done();
}
},
manyTags: function (test) {
var view = [['p'], ['p']];
test.equal(render(view), '<p></p><p></p>', '');
test.done();
},
enclosed: function (test) {
var view = [['p', ['p', 'text']]];
test.equal(render(view), '<p><p>text</p></p>', 'Simple enclosed');
test.done();
},
attrs: function (test) {
var view = [['div', {width: 100, class: ['class1', 'class2'], id: 'id'}, 'inner text']];
test.equal(render(view), '<div width="100" class="class1 class2" id="id">inner text</div>', 'Attributes');
test.done();
},
styles: function (test) {
var view = [['p', {style: {width: '100px', height: '100px'}}, 'inner text']];
test.equal(render(view), '<p style="width: 100px; height: 100px; ">inner text</p>', 'Styles');
test.done();
},
state: {
tag: function (test) {
var view = [[function() {
return this.tag;
}]];
test.equal(render(view, {tag: 'div'}), '<div></div>', 'Tag by state');
test.done();
},
attrs: function (test) {
var view = [['div', {
class: function() {
return this.class;
}
}]];
test.equal(render(view, {class: 'class'}), '<div class="class"></div>', 'Attributes by state');
test.done();
},
styles: function (test) {
var view = [['div', {
style: {
width: function() {
return this.width + 'px';
}
}
}]];
test.equal(render(view, {width: 100}), '<div style="width: 100px; "></div>', 'Style by state');
test.done();
},
content: function (test) {
var view = [['div', function() {
return this.content;
}]];
test.equal(render(view, {content: 'inner text'}), '<div>inner text</div>', 'Content by state');
test.done();
}
},
complex: function (test) {
var view = [
['a', {
href: 'http://tenphi.me',
target: function() {
return this.target || '';
},
style: {
color: function() {
return this.color || 'red';
}
}
}, function() {
return this.inner;
}, ' text'],
['p',
['i', 'text']
]
];
test.equal(render(view, {
color: 'blue',
inner: 'inner',
target: '_blank'
}), '<a href="http://tenphi.me" target="_blank" style="color: blue; ">inner text</a><p><i>text</i></p>', 'Complex test');
test.done();
}
};
|
/*
This lazySizes extension removes scroll events implements a more lazier scrollintent event instead.
*/
(function(window, document){
/*jshint eqnull:true */
'use strict';
var config, index;
if(window.addEventListener){
config = (window.lazySizes && lazySizes.cfg) || window.lazySizesConfig;
index = 0;
if(!config){
config = {};
window.lazySizesConfig = config;
}
if(window.lazySizes && lazySizes.init.i){return;}
config.scroll = false;
if(!config.expand){
config.expand = 250;
}
if(!('scrollLoadMode' in config)){
config.scrollLoadMode = 1;
}
addEventListener('scroll', (function(){
var afterScrollTimer, checkElem, checkTimer, top, left;
var checkFn = function(){
var nTop = Math.abs(top - (checkElem.scrollTop || checkElem.pageYOffset || 0));
var nLeft = Math.abs(left - (checkElem.scrollLeft || checkElem.pageXOffset || 0));
checkElem = null;
if(nTop < 400 && nLeft < 400){
if(lazySizes.loader.m < 2){
lazySizes.loader.m = 2;
}
if(nTop < 180 && nLeft < 180){
update();
}
}
};
var afterScroll = function(){
lazySizes.loader.m = 3;
index = 0;
update();
clearTimeout(afterScrollTimer);
};
var update = function(){
lazySizes.loader.checkElems();
clearTimeout(checkTimer);
checkElem = null;
};
return function(e){
var elem = e.target == document ? window : e.target;
clearTimeout(afterScrollTimer);
afterScrollTimer = setTimeout(afterScroll, 99);
lazySizes.loader.m = config.scrollLoadMode;
if(index === 0){
lazySizes.loader.checkElems();
} else if(index > 40){
index = -1;
}
index++;
if(!checkElem){
checkElem = elem;
top = checkElem.scrollTop || checkElem.pageYOffset || 0;
left = checkElem.scrollLeft || checkElem.pageXOffset || 0;
clearTimeout(checkTimer);
checkTimer = setTimeout(checkFn, 150);
} else if(elem != checkElem){
update();
}
elem = null;
};
})(), true);
}
})(window, document);
|
var socket = require('express.io')();
var moment = require('moment');
var settings = require('./settings');
var schedule = require('node-schedule');
var geolib = require('geolib');
socket.http().io();
socket.io.route('init', function(req){
req.io.join(req.data);
req.io.join(req.data + ':ctrl');
var room = req.io.room(req.data + ':ctrl');
room.broadcast('locate');
});
socket.io.route('announce', function(req){
//send updated coordinates to anyone listening to the main room for this user.
req.io.room(req.data.id).broadcast('update', req.data);
//TODO: fetch nearest coordinate to self given an array of lassos and friends coordinates.
//TODO: determine distance between self and nearest coordinate in feet.
var distance = 5200;
var milliseconds = Math.round(Math.pow(distance / settings.resolution, settings.throttle) * 1000);
var room = req.io.room(req.data.id + ':ctrl');
var job = new schedule.Job(function(){ room.broadcast('locate'); });
job.schedule(moment().add(milliseconds, 'milliseconds'));
});
module.exports = socket;
|
/*
* Kendo UI v2014.2.716 (http://www.telerik.com/kendo-ui)
* Copyright 2014 Telerik AD. All rights reserved.
*
* Kendo UI commercial licenses may be obtained at
* http://www.telerik.com/purchase/license-agreement/kendo-ui-complete
* If you do not own a commercial license, this file shall be governed by the trial license terms.
*/
(function(f, define){
define([], f);
})(function(){
(function( window, undefined ) {
var kendo = window.kendo || (window.kendo = { cultures: {} });
kendo.cultures["kk-KZ"] = {
name: "kk-KZ",
numberFormat: {
pattern: ["-n"],
decimals: 2,
",": " ",
".": ",",
groupSize: [3],
percent: {
pattern: ["-n%","n%"],
decimals: 2,
",": " ",
".": ",",
groupSize: [3],
symbol: "%"
},
currency: {
pattern: ["-$n","$n"],
decimals: 2,
",": " ",
".": "-",
groupSize: [3],
symbol: "Т"
}
},
calendars: {
standard: {
days: {
names: ["Жексенбі","Дүйсенбі","Сейсенбі","Сәрсенбі","Бейсенбі","Жұма","Сенбі"],
namesAbbr: ["Жк","Дс","Сс","Ср","Бс","Жм","Сн"],
namesShort: ["Жк","Дс","Сс","Ср","Бс","Жм","Сн"]
},
months: {
names: ["қаңтар","ақпан","наурыз","сәуір","мамыр","маусым","шілде","тамыз","қыркүйек","қазан","қараша","желтоқсан",""],
namesAbbr: ["Қаң","Ақп","Нау","Сәу","Мам","Мау","Шіл","Там","Қыр","Қаз","Қар","Жел",""]
},
AM: [""],
PM: [""],
patterns: {
d: "dd.MM.yyyy",
D: "d MMMM yyyy 'ж.'",
F: "d MMMM yyyy 'ж.' H:mm:ss",
g: "dd.MM.yyyy H:mm",
G: "dd.MM.yyyy H:mm:ss",
m: "d MMMM",
M: "d MMMM",
s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss",
t: "H:mm",
T: "H:mm:ss",
u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'",
y: "MMMM yyyy",
Y: "MMMM yyyy"
},
"/": ".",
":": ":",
firstDay: 1
}
}
}
})(this);
return window.kendo;
}, typeof define == 'function' && define.amd ? define : function(_, f){ f(); }); |
/*
Jquery Validation using jqBootstrapValidation
example is taken from jqBootstrapValidation docs
*/
$(function() {
$("input,textarea").jqBootstrapValidation(
{
preventSubmit: true,
submitError: function($form, event, errors) {
// something to have when submit produces an error ?
// Not decided if I need it yet
},
submitSuccess: function($form, event) {
event.preventDefault(); // prevent default submit behaviour
// get values from FORM
var name = $("input#inputName").val();
var email = $("input#inputEmail").val();
var phone = $("input#inputPhone").val();
var country = $("input#inputCountry").val();
var message = $("textarea#message").val();
$.ajax({
url: "contact.php",
type: "POST",
data: {name: name, email: email, phone: phone, country: country, message: message},
cache: false,
success: function() {
// Success message
$('#success').html("<div class='alert alert-success'>");
$('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
.append( "</button>");
$('#success > .alert-success')
.append("<strong>Your message has been sent. </strong>");
$('#success > .alert-success')
.append('</div>');
//clear all fields
$('#contactForm').trigger("reset");
},
error: function() {
// Fail message
$('#success').html("<div class='alert alert-danger'>");
$('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
.append( "</button>");
$('#success > .alert-danger').append("<strong>Sorry "+name+" it seems that my mail server is not responding...</strong> Could you please email me directly to <a href='mailto:info@strategicandagile.com?Subject=Message_Me;'>info@strategicandagile.com</a> ? Sorry for the inconvenience!");
$('#success > .alert-danger').append('</div>');
//clear all fields
$('#contactForm').trigger("reset");
},
})
},
filter: function() {
return $(this).is(":visible");
},
});
$("a[data-toggle=\"tab\"]").click(function(e) {
e.preventDefault();
$(this).tab("show");
});
}); |
var searchData=
[
['magenta',['magenta',['../_logger_8cpp.html#a9c3c2560b6f423f7902776457532fdba',1,'Logger.cpp']]],
['maxsamples',['maxsamples',['../class_audio_signal.html#a5d68faf1ab7f19197b93cc2cc0a7e645',1,'AudioSignal']]],
['mps_5fvt',['mps_vt',['../struct_h_r_t_f_model.html#ae01efd7375e498a14624bbeebb93fa82a14e4aa4784083d62a00452f4d32b4098',1,'HRTFModel']]],
['mute',['mute',['../class_channel.html#a88f542e0f6d1e1d384ad8bf79a9e305b',1,'Channel']]],
['mutecheckbox',['mutecheckbox',['../class_channel.html#a0e7f90da49f291a7bac498e11e886fbd',1,'Channel']]],
['muted',['muted',['../class_channel.html#ada7e3a050c346ad283ad302745f03f3c',1,'Channel']]]
];
|
let generator = function* () {
yield 'hello';
yield 'world';
return 'end';
}
let hw = generator();
console.log(hw.next());
console.log(hw.next()); |
import TestContainer from 'mocha-test-container-support';
import { act } from '@testing-library/preact';
import {
bootstrapPropertiesPanel,
changeInput,
clickInput,
inject
} from 'test/TestHelper';
import {
query as domQuery,
queryAll as domQueryAll
} from 'min-dom';
import CoreModule from 'bpmn-js/lib/core';
import SelectionModule from 'diagram-js/lib/features/selection';
import ModelingModule from 'bpmn-js/lib/features/modeling';
import BpmnPropertiesPanel from 'src/render';
import BpmnPropertiesProvider from 'src/provider/bpmn';
import {
getCompensateActivity,
getCompensateEventDefinition
} from 'src/provider/bpmn/utils/EventDefinitionUtil';
import diagramXML from './CompensationProps.bpmn';
describe('provider/bpmn - CompensationProps', function() {
const testModules = [
BpmnPropertiesPanel,
BpmnPropertiesProvider,
CoreModule,
ModelingModule,
SelectionModule
];
let container;
beforeEach(function() {
container = TestContainer.get(this);
});
beforeEach(bootstrapPropertiesPanel(diagramXML, {
modules: testModules,
debounceInput: false
}));
describe('#waitForCompletion', function() {
it('should NOT display', inject(async function(elementRegistry, selection) {
// given
const compensationEvent = elementRegistry.get('CompensationStartEvent_1');
await act(() => {
selection.select(compensationEvent);
});
// when
const input = domQuery('input[name=waitForCompletion]', container);
// then
expect(input).to.not.exist;
}));
it('should display', inject(async function(elementRegistry, selection) {
// given
const compensationEvent = elementRegistry.get('CompensationEndEvent_1');
await act(() => {
selection.select(compensationEvent);
});
// when
const input = domQuery('input[name=waitForCompletion]', container);
// then
expect(input.checked).to.eql(
getCompensateEventDefinition(compensationEvent).get('waitForCompletion')
);
}));
it('should update', inject(async function(elementRegistry, selection) {
// given
const compensationEvent = elementRegistry.get('CompensationEndEvent_1');
await act(() => {
selection.select(compensationEvent);
});
// when
const input = domQuery('input[name=waitForCompletion]', container);
clickInput(input);
// then
expect(
getCompensateEventDefinition(compensationEvent).get('waitForCompletion')
).to.be.false;
}));
it('should update on external change',
inject(async function(elementRegistry, selection, commandStack) {
// given
const compensationEvent = elementRegistry.get('CompensationEndEvent_1');
const originalValue =
getCompensateEventDefinition(compensationEvent).get('waitForCompletion');
await act(() => {
selection.select(compensationEvent);
});
const input = domQuery('input[name=waitForCompletion]', container);
clickInput(input);
// when
await act(() => {
commandStack.undo();
});
// then
expect(input.checked).to.eql(originalValue);
})
);
});
describe('#activityRef', function() {
it('should NOT display',
inject(async function(elementRegistry, selection) {
// given
const compensationEvent = elementRegistry.get('CompensationBoundaryEvent_1');
// when
await act(() => {
selection.select(compensationEvent);
});
// then
const select = domQuery('select[name=activityRef]', container);
expect(select).to.not.exist;
})
);
it('should display', inject(async function(elementRegistry, selection) {
// given
const compensationEvent = elementRegistry.get('CompensationEndEvent_1');
await act(() => {
selection.select(compensationEvent);
});
// when
const select = domQuery('select[name=activityRef]', container);
// then
expect(select.value).to.eql(getCompensateActivity(compensationEvent).get('id'));
}));
describe('select options', function() {
it('should display options - throwing compensation event',
inject(async function(elementRegistry, selection) {
// given
const compensationEvent = elementRegistry.get('CompensationEndEvent_1');
await act(() => {
selection.select(compensationEvent);
});
// when
const select = domQuery('select[name=activityRef]', container);
// then
expect(asOptionNamesList(select)).to.eql([
'<none>',
'(id=Task_3)',
'Call Activity 1 (id=CallActivity_1)',
'Sub Process 1 (id=SubProcess_1)',
'Task 1 (id=Task_1)',
'Task 2 (id=Task_2)'
]);
})
);
it('should display options - throwing compensation event in a sub process',
inject(async function(elementRegistry, selection) {
// given
const compensationEvent = elementRegistry.get('CompensationThrowEvent_2');
await act(() => {
selection.select(compensationEvent);
});
// when
const select = domQuery('select[name=activityRef]', container);
// then
expect(asOptionNamesList(select)).to.eql([
'<none>',
'Task 4 (id=Task_4)'
]);
})
);
it('should display options - throwing compensation event in an event sub process',
inject(async function(elementRegistry, selection) {
// given
const compensationEvent = elementRegistry.get('CompensationThrowEvent_1');
await act(() => {
selection.select(compensationEvent);
});
// when
const select = domQuery('select[name=activityRef]', container);
// then
expect(asOptionNamesList(select)).to.eql([
'<none>',
'(id=Task_3)',
'Call Activity 1 (id=CallActivity_1)',
'Sub Process 1 (id=SubProcess_1)',
'Task 1 (id=Task_1)',
'Task 2 (id=Task_2)',
'Task 5 (id=Task_5)'
]);
})
);
it('should NOT include compensation sub process',
inject(async function(elementRegistry, selection) {
// given
const compensationEvent = elementRegistry.get('CompensationEndEvent_1');
await act(() => {
selection.select(compensationEvent);
});
// when
const select = domQuery('select[name=activityRef]', container);
// then
expect(asOptionNamesList(select)).to.not.include(
'Sub Process 3 (id=SubProcess_3)'
);
})
);
});
it('should update', inject(async function(elementRegistry, selection) {
// given
const compensationEvent = elementRegistry.get('CompensationEndEvent_1');
await act(() => {
selection.select(compensationEvent);
});
// when
const select = domQuery('select[name=activityRef]', container);
changeInput(select, 'Task_2');
// then
expect(getCompensateActivity(compensationEvent).get('id')).to.eql('Task_2');
}));
it('should remove activity reference', inject(async function(elementRegistry, selection) {
// given
const compensationEvent = elementRegistry.get('CompensationEndEvent_1');
await act(() => {
selection.select(compensationEvent);
});
// assume
expect(getCompensateActivity(compensationEvent)).to.exist;
// when
const select = domQuery('select[name=activityRef]', container);
changeInput(select, '');
// then
expect(getCompensateActivity(compensationEvent)).to.not.exist;
}));
it('should update on external change',
inject(async function(elementRegistry, selection, commandStack) {
// given
const compensateEvent = elementRegistry.get('CompensationEndEvent_1');
const originalValue = getCompensateActivity(compensateEvent).get('id');
await act(() => {
selection.select(compensateEvent);
});
const select = domQuery('select[name=activityRef]', container);
changeInput(select, 'Task_2');
// when
await act(() => {
commandStack.undo();
});
// then
expect(select.value).to.eql(originalValue);
})
);
});
});
// helper //////////////////
function asOptionNamesList(select) {
const names = [];
const options = domQueryAll('option', select);
options.forEach(o => names.push(o.label));
return names;
}
|
//~ name c130
alert(c130);
//~ component c131.js
|
import controller from './controller';
import consts from '../constants';
export default {
init(io) {
let broadcast = update => {
io.of('playerSync').emit('update', update);
};
setInterval(() => {
try {
controller.sendUpdates(broadcast);
} catch(err) {
console.log('Error sending updates', err);
}
}, consts.playerSync.SEND_UPDATE_INTERVAL);
io.of('playerSync').on('connection', socket => {
let id = socket.id.split('#')[1];
let broadcast = id => {
socket.broadcast.emit('join', id);
};
try {
controller.onJoin(id, broadcast);
} catch(err) {
console.log('Error joining user');
}
socket.emit('settings', controller.getSettings());
socket.on('disconnect', () => {
let broadcast = id => {
socket.broadcast.emit('leave', id);
};
try {
controller.onLeave(id, broadcast);
} catch(err) {
console.log('Error with user leaving', err);
}
});
socket.on('state', state => {
try {
controller.onState(id, state);
} catch(err) {
console.log('Error updating state', err);
}
});
});
}
};
|
'use strict';
var browserify = require('browserify-middleware');
var express = require('express');
var logger = require('morgan');
var app = express();
app.use(logger());
app.get('/index.js', browserify('../../client/profileservice/index.js'));
app.use(express.static('./client/profileservice/'));
app.get('/profileservice', function(req, res) {
res.send('hello world');
});
app.listen(8000);
|
/// <reference path="ChangeLinr-0.2.0.ts" />
/// <reference path="ObjectMakr-0.2.2.ts" />
/// <reference path="PixelRendr-0.2.0.ts" />
/// <reference path="QuadsKeepr-0.2.1.ts" />
/// <reference path="StringFilr-0.2.1.ts" />
var PixelDrawr;
(function (PixelDrawr_1) {
"use strict";
/**
* A front-end to PixelRendr to automate drawing mass amounts of sprites to a
* primary canvas. A PixelRendr keeps track of sprite sources, while a
* MapScreenr maintains boundary information on the screen. Global screen
* refills may be done by drawing every Thing in the thingArrays, or by
* Quadrants as a form of dirty rectangles.
*/
var PixelDrawr = (function () {
/**
* Initializes a new instance of the PixelDrawr class.
*
* @param settings Settings to be used for initialization.
*/
function PixelDrawr(settings) {
if (!settings) {
throw new Error("No settings object given to PixelDrawr.");
}
if (typeof settings.PixelRender === "undefined") {
throw new Error("No PixelRender given to PixelDrawr.");
}
if (typeof settings.MapScreener === "undefined") {
throw new Error("No MapScreener given to PixelDrawr.");
}
if (typeof settings.createCanvas === "undefined") {
throw new Error("No createCanvas given to PixelDrawr.");
}
this.PixelRender = settings.PixelRender;
this.MapScreener = settings.MapScreener;
this.createCanvas = settings.createCanvas;
this.unitsize = settings.unitsize || 1;
this.noRefill = settings.noRefill;
this.spriteCacheCutoff = settings.spriteCacheCutoff || 0;
this.groupNames = settings.groupNames;
this.framerateSkip = settings.framerateSkip || 1;
this.framesDrawn = 0;
this.epsilon = settings.epsilon || .007;
this.keyWidth = settings.keyWidth || "width";
this.keyHeight = settings.keyHeight || "height";
this.keyTop = settings.keyTop || "top";
this.keyRight = settings.keyRight || "right";
this.keyBottom = settings.keyBottom || "bottom";
this.keyLeft = settings.keyLeft || "left";
this.keyOffsetX = settings.keyOffsetX;
this.keyOffsetY = settings.keyOffsetY;
this.generateObjectKey = settings.generateObjectKey || function (thing) {
return thing.toString();
};
this.resetBackground();
}
/* Simple gets
*/
/**
* @returns {Number} How often refill calls should be skipped.
*/
PixelDrawr.prototype.getFramerateSkip = function () {
return this.framerateSkip;
};
/**
* @returns The Arrays to be redrawn during refill calls.
*/
PixelDrawr.prototype.getThingArray = function () {
return this.thingArrays;
};
/**
* @returns The canvas element each Thing is to drawn on.
*/
PixelDrawr.prototype.getCanvas = function () {
return this.canvas;
};
/**
* @returns The 2D canvas context associated with the canvas.
*/
PixelDrawr.prototype.getContext = function () {
return this.context;
};
/**
* @returns The canvas element used for the background.
*/
PixelDrawr.prototype.getBackgroundCanvas = function () {
return this.backgroundCanvas;
};
/**
* @returns The 2D canvas context associated with the background canvas.
*/
PixelDrawr.prototype.getBackgroundContext = function () {
return this.backgroundContext;
};
/**
* @returns Whether refills should skip redrawing the background each time.
*/
PixelDrawr.prototype.getNoRefill = function () {
return this.noRefill;
};
/**
* @returns The minimum opacity that will be drawn.
*/
PixelDrawr.prototype.getEpsilon = function () {
return this.epsilon;
};
/* Simple sets
*/
/**
* @param framerateSkip How often refill calls should be skipped.
*/
PixelDrawr.prototype.setFramerateSkip = function (framerateSkip) {
this.framerateSkip = framerateSkip;
};
/**
* @param thingArrays The Arrays to be redrawn during refill calls.
*/
PixelDrawr.prototype.setThingArrays = function (thingArrays) {
this.thingArrays = thingArrays;
};
/**
* Sets the currently drawn canvas and context, and recreates
* drawThingOnContextBound.
*
* @param canvas The new primary canvas to be used.
*/
PixelDrawr.prototype.setCanvas = function (canvas) {
this.canvas = canvas;
this.context = canvas.getContext("2d");
};
/**
* @param noRefill Whether refills should now skip redrawing the
* background each time.
*/
PixelDrawr.prototype.setNoRefill = function (noRefill) {
this.noRefill = noRefill;
};
/**
* @param epsilon The minimum opacity that will be drawn.
*/
PixelDrawr.prototype.setEpsilon = function (epsilon) {
this.epsilon = epsilon;
};
/* Background manipulations
*/
/**
* Creates a new canvas the size of MapScreener and sets the background
* canvas to it, then recreates backgroundContext.
*/
PixelDrawr.prototype.resetBackground = function () {
this.backgroundCanvas = this.createCanvas(this.MapScreener[this.keyWidth], this.MapScreener[this.keyHeight]);
this.backgroundContext = this.backgroundCanvas.getContext("2d");
};
/**
* Refills the background canvas with a new fillStyle.
*
* @param fillStyle The new fillStyle for the background context.
*/
PixelDrawr.prototype.setBackground = function (fillStyle) {
this.backgroundContext.fillStyle = fillStyle;
this.backgroundContext.fillRect(0, 0, this.MapScreener[this.keyWidth], this.MapScreener[this.keyHeight]);
};
/**
* Draws the background canvas onto the main canvas' context.
*/
PixelDrawr.prototype.drawBackground = function () {
this.context.drawImage(this.backgroundCanvas, 0, 0);
};
/* Core rendering
*/
/**
* Goes through all the motions of finding and parsing a Thing's sprite.
* This should be called whenever the sprite's appearance changes.
*
* @param thing A Thing whose sprite must be updated.
*/
PixelDrawr.prototype.setThingSprite = function (thing) {
// If it's set as hidden, don't bother updating it
if (thing.hidden) {
return;
}
// PixelRender does most of the work in fetching the rendered sprite
thing.sprite = this.PixelRender.decode(this.generateObjectKey(thing), thing);
// To do: remove dependency on .numSprites
// For now, it's used to know whether it's had its sprite set, but
// wouldn't physically having a .sprite do that?
if (thing.sprite.constructor === PixelRendr.SpriteMultiple) {
thing.numSprites = 0;
this.refillThingCanvasMultiple(thing);
}
else {
thing.numSprites = 1;
this.refillThingCanvasSingle(thing);
}
};
/* Core drawing APIs
*/
/**
* Called every upkeep to refill the entire main canvas. All Thing arrays
* are made to call this.refillThingArray in order.
*/
PixelDrawr.prototype.refillGlobalCanvas = function () {
this.framesDrawn += 1;
if (this.framesDrawn % this.framerateSkip !== 0) {
return;
}
if (!this.noRefill) {
this.drawBackground();
}
for (var i = 0; i < this.thingArrays.length; i += 1) {
this.refillThingArray(this.thingArrays[i]);
}
};
/**
* Calls drawThingOnContext on each Thing in the Array.
*
* @param array A listing of Things to be drawn onto the canvas.
*/
PixelDrawr.prototype.refillThingArray = function (array) {
for (var i = 0; i < array.length; i += 1) {
this.drawThingOnContext(this.context, array[i]);
}
};
/**
* General Function to draw a Thing onto a context. This will call
* drawThingOnContext[Single/Multiple] with more arguments
*
* @param context The context to have the Thing drawn on it.
* @param thing The Thing to be drawn onto the context.
*/
PixelDrawr.prototype.drawThingOnContext = function (context, thing) {
if (thing.hidden
|| thing.opacity < this.epsilon
|| thing[this.keyHeight] < 1
|| thing[this.keyWidth] < 1
|| this.getTop(thing) > this.MapScreener[this.keyHeight]
|| this.getRight(thing) < 0
|| this.getBottom(thing) < 0
|| this.getLeft(thing) > this.MapScreener[this.keyWidth]) {
return;
}
// If Thing hasn't had a sprite yet (previously hidden), do that first
if (typeof thing.numSprites === "undefined") {
this.setThingSprite(thing);
}
// Whether or not the thing has a regular sprite or a SpriteMultiple,
// that sprite has already been drawn to the thing's canvas, unless it's
// above the cutoff, in which case that logic happens now.
if (thing.canvas[this.keyWidth] > 0) {
this.drawThingOnContextSingle(context, thing.canvas, thing, this.getLeft(thing), this.getTop(thing));
}
else {
this.drawThingOnContextMultiple(context, thing.canvases, thing, this.getLeft(thing), this.getTop(thing));
}
};
/* Core drawing internals
*/
/**
* Simply draws a thing's sprite to its canvas by getting and setting
* a canvas::imageData object via context.getImageData(...).
*
* @param thing A Thing whose canvas must be updated.
*/
PixelDrawr.prototype.refillThingCanvasSingle = function (thing) {
// Don't draw small Things.
if (thing[this.keyWidth] < 1 || thing[this.keyHeight] < 1) {
return;
}
// Retrieve the imageData from the Thing's canvas & renderingContext
var canvas = thing.canvas, context = thing.context, imageData = context.getImageData(0, 0, canvas[this.keyWidth], canvas[this.keyHeight]);
// Copy the thing's sprite to that imageData and into the contextz
this.PixelRender.memcpyU8(thing.sprite, imageData.data);
context.putImageData(imageData, 0, 0);
};
/**
* For SpriteMultiples, this copies the sprite information for each
* sub-sprite into its own canvas, sets thing.sprites, then draws the newly
* rendered information onto the thing's canvas.
*
* @param thing A Thing whose canvas and sprites must be updated.
*/
PixelDrawr.prototype.refillThingCanvasMultiple = function (thing) {
if (thing[this.keyWidth] < 1 || thing[this.keyHeight] < 1) {
return;
}
var spritesRaw = thing.sprite, canvases = thing.canvases = {
"direction": spritesRaw.direction,
"multiple": true
}, canvas, context, imageData, i;
thing.numSprites = 1;
for (i in spritesRaw.sprites) {
if (!spritesRaw.sprites.hasOwnProperty(i)) {
continue;
}
// Make a new sprite for this individual component
canvas = this.createCanvas(thing.spritewidth * this.unitsize, thing.spriteheight * this.unitsize);
context = canvas.getContext("2d");
// Copy over this sprite's information the same way as refillThingCanvas
imageData = context.getImageData(0, 0, canvas[this.keyWidth], canvas[this.keyHeight]);
this.PixelRender.memcpyU8(spritesRaw.sprites[i], imageData.data);
context.putImageData(imageData, 0, 0);
// Record the canvas and context in thing.sprites
canvases[i] = {
"canvas": canvas,
"context": context
};
thing.numSprites += 1;
}
// Only pre-render multiple sprites if they're below the cutoff
if (thing[this.keyWidth] * thing[this.keyHeight] < this.spriteCacheCutoff) {
thing.canvas[this.keyWidth] = thing[this.keyWidth] * this.unitsize;
thing.canvas[this.keyHeight] = thing[this.keyHeight] * this.unitsize;
this.drawThingOnContextMultiple(thing.context, thing.canvases, thing, 0, 0);
}
else {
thing.canvas[this.keyWidth] = thing.canvas[this.keyHeight] = 0;
}
};
/**
* Draws a Thing's single canvas onto a context, commonly called by
* this.drawThingOnContext.
*
* @param context The context being drawn on.
* @param canvas The Thing's canvas being drawn onto the context.
* @param thing The Thing whose canvas is being drawn.
* @param left The x-position to draw the Thing from.
* @param top The y-position to draw the Thing from.
*/
PixelDrawr.prototype.drawThingOnContextSingle = function (context, canvas, thing, left, top) {
// If the sprite should repeat, use the pattern equivalent
if (thing.repeat) {
this.drawPatternOnContext(context, canvas, left, top, thing.unitwidth, thing.unitheight, thing.opacity || 1);
}
else if (thing.opacity !== 1) {
// Opacities not equal to one must reset the context afterwards
context.globalAlpha = thing.opacity;
context.drawImage(canvas, left, top, canvas.width * thing.scale, canvas.height * thing.scale);
context.globalAlpha = 1;
}
else {
context.drawImage(canvas, left, top, canvas.width * thing.scale, canvas.height * thing.scale);
}
};
/**
* Draws a Thing's multiple canvases onto a context, typicall called by
* drawThingOnContext. A variety of cases for canvases is allowed:
* "vertical", "horizontal", and "corners".
*
* @param context The context being drawn on.
* @param canvases The canvases being drawn onto the context.
* @param thing The Thing whose canvas is being drawn.
* @param left The x-position to draw the Thing from.
* @param top The y-position to draw the Thing from.
*/
PixelDrawr.prototype.drawThingOnContextMultiple = function (context, canvases, thing, left, top) {
var sprite = thing.sprite, topreal = top, leftreal = left, rightreal = left + thing.unitwidth, bottomreal = top + thing.unitheight, widthreal = thing.unitwidth, heightreal = thing.unitheight, spritewidthpixels = thing.spritewidthpixels, spriteheightpixels = thing.spriteheightpixels, widthdrawn = Math.min(widthreal, spritewidthpixels), heightdrawn = Math.min(heightreal, spriteheightpixels), opacity = thing.opacity, diffhoriz, diffvert, canvasref;
switch (canvases.direction) {
// Vertical sprites may have 'top', 'bottom', 'middle'
case "vertical":
// If there's a bottom, draw that and push up bottomreal
if ((canvasref = canvases[this.keyBottom])) {
diffvert = sprite.bottomheight ? sprite.bottomheight * this.unitsize : spriteheightpixels;
this.drawPatternOnContext(context, canvasref.canvas, leftreal, bottomreal - diffvert, widthreal, heightdrawn, opacity);
bottomreal -= diffvert;
heightreal -= diffvert;
}
// If there's a top, draw that and push down topreal
if ((canvasref = canvases[this.keyTop])) {
diffvert = sprite.topheight ? sprite.topheight * this.unitsize : spriteheightpixels;
this.drawPatternOnContext(context, canvasref.canvas, leftreal, topreal, widthreal, heightdrawn, opacity);
topreal += diffvert;
heightreal -= diffvert;
}
break;
// Horizontal sprites may have 'left', 'right', 'middle'
case "horizontal":
// If there's a left, draw that and push forward leftreal
if ((canvasref = canvases[this.keyLeft])) {
diffhoriz = sprite.leftwidth ? sprite.leftwidth * this.unitsize : spritewidthpixels;
this.drawPatternOnContext(context, canvasref.canvas, leftreal, topreal, widthdrawn, heightreal, opacity);
leftreal += diffhoriz;
widthreal -= diffhoriz;
}
// If there's a right, draw that and push back rightreal
if ((canvasref = canvases[this.keyRight])) {
diffhoriz = sprite.rightwidth ? sprite.rightwidth * this.unitsize : spritewidthpixels;
this.drawPatternOnContext(context, canvasref.canvas, rightreal - diffhoriz, topreal, widthdrawn, heightreal, opacity);
rightreal -= diffhoriz;
widthreal -= diffhoriz;
}
break;
// Corner (vertical + horizontal + corner) sprites must have corners
// in 'topRight', 'bottomRight', 'bottomLeft', and 'topLeft'.
case "corners":
// topLeft, left, bottomLeft
diffvert = sprite.topheight ? sprite.topheight * this.unitsize : spriteheightpixels;
diffhoriz = sprite.leftwidth ? sprite.leftwidth * this.unitsize : spritewidthpixels;
this.drawPatternOnContext(context, canvases.topLeft.canvas, leftreal, topreal, widthdrawn, heightdrawn, opacity);
this.drawPatternOnContext(context, canvases[this.keyLeft].canvas, leftreal, topreal + diffvert, widthdrawn, heightreal - diffvert * 2, opacity);
this.drawPatternOnContext(context, canvases.bottomLeft.canvas, leftreal, bottomreal - diffvert, widthdrawn, heightdrawn, opacity);
leftreal += diffhoriz;
widthreal -= diffhoriz;
// top, topRight
diffhoriz = sprite.rightwidth ? sprite.rightwidth * this.unitsize : spritewidthpixels;
this.drawPatternOnContext(context, canvases[this.keyTop].canvas, leftreal, topreal, widthreal - diffhoriz, heightdrawn, opacity);
this.drawPatternOnContext(context, canvases.topRight.canvas, rightreal - diffhoriz, topreal, widthdrawn, heightdrawn, opacity);
topreal += diffvert;
heightreal -= diffvert;
// right, bottomRight, bottom
diffvert = sprite.bottomheight ? sprite.bottomheight * this.unitsize : spriteheightpixels;
this.drawPatternOnContext(context, canvases[this.keyRight].canvas, rightreal - diffhoriz, topreal, widthdrawn, heightreal - diffvert, opacity);
this.drawPatternOnContext(context, canvases.bottomRight.canvas, rightreal - diffhoriz, bottomreal - diffvert, widthdrawn, heightdrawn, opacity);
this.drawPatternOnContext(context, canvases[this.keyBottom].canvas, leftreal, bottomreal - diffvert, widthreal - diffhoriz, heightdrawn, opacity);
rightreal -= diffhoriz;
widthreal -= diffhoriz;
bottomreal -= diffvert;
heightreal -= diffvert;
break;
default:
throw new Error("Unknown or missing direction given in SpriteMultiple.");
}
// If there's still room, draw the actual canvas
if ((canvasref = canvases.middle) && topreal < bottomreal && leftreal < rightreal) {
if (sprite.middleStretch) {
context.globalAlpha = opacity;
context.drawImage(canvasref.canvas, leftreal, topreal, widthreal, heightreal);
context.globalAlpha = 1;
}
else {
this.drawPatternOnContext(context, canvasref.canvas, leftreal, topreal, widthreal, heightreal, opacity);
}
}
};
/* Position utilities (which should almost always be optimized)
*/
/**
* @param thing Any Thing.
* @returns The Thing's top position, accounting for vertical offset if needed.
*/
PixelDrawr.prototype.getTop = function (thing) {
if (this.keyOffsetY) {
return thing[this.keyTop] + thing[this.keyOffsetY];
}
else {
return thing[this.keyTop];
}
};
/**
* @param thing Any Thing.
* @returns The Thing's right position, accounting for horizontal offset if needed.
*/
PixelDrawr.prototype.getRight = function (thing) {
if (this.keyOffsetX) {
return thing[this.keyRight] + thing[this.keyOffsetX];
}
else {
return thing[this.keyRight];
}
};
/**
* @param thing Any Thing.
* @returns {Number} The Thing's bottom position, accounting for vertical
* offset if needed.
*/
PixelDrawr.prototype.getBottom = function (thing) {
if (this.keyOffsetX) {
return thing[this.keyBottom] + thing[this.keyOffsetY];
}
else {
return thing[this.keyBottom];
}
};
/**
* @param thing Any Thing.
* @returns The Thing's left position, accounting for horizontal offset if needed.
*/
PixelDrawr.prototype.getLeft = function (thing) {
if (this.keyOffsetX) {
return thing[this.keyLeft] + thing[this.keyOffsetX];
}
else {
return thing[this.keyLeft];
}
};
/* Utilities
*/
/**
* Draws a source pattern onto a context. The pattern is clipped to the size
* of MapScreener.
*
* @param context The context the pattern will be drawn onto.
* @param source The image being repeated as a pattern. This can be a canvas,
* an image, or similar.
* @param left The x-location to draw from.
* @param top The y-location to draw from.
* @param width How many pixels wide the drawing area should be.
* @param left How many pixels high the drawing area should be.
* @param opacity How transparent the drawing is, in [0,1].
*/
PixelDrawr.prototype.drawPatternOnContext = function (context, source, left, top, width, height, opacity) {
context.globalAlpha = opacity;
context.translate(left, top);
context.fillStyle = context.createPattern(source, "repeat");
context.fillRect(0, 0,
// Math.max(width, left - MapScreener[keyRight]),
// Math.max(height, top - MapScreener[keyBottom])
width, height);
context.translate(-left, -top);
context.globalAlpha = 1;
};
return PixelDrawr;
})();
PixelDrawr_1.PixelDrawr = PixelDrawr;
})(PixelDrawr || (PixelDrawr = {}));
|
define(
[
'jquery',
'lib/lodash'
],
function ($, _) {
'use strict';
$.fn.cssNumber = function(prop) {
var v = parseFloat($(this).css(prop), 10);
return isNaN(v) ? 0 : v;
};
var exports = {
checkNumber: function (value) {
return (!_.isNaN(value) && !_.isNull(value) && _.isNumber(value));
},
getRandomInteger: function (min, max) {
if (this.checkNumber(min) && this.checkNumber(max)) {
return Math.round(min + (Math.random() * (max - min)));
}
return 0;
},
getRandomNumber: function (min, max) {
if (this.checkNumber(min) && this.checkNumber(max)) {
return min + (Math.random() * (max - min));
}
return Math.random();
}
};
return exports;
});
/*
* JavaScript Debug - v0.4 - 6/22/2010
* http://benalman.com/projects/javascript-debug-console-log/
*
* Copyright (c) 2010 "Cowboy" Ben Alman
* Dual licensed under the MIT and GPL licenses.
* http://benalman.com/about/license/
*
* With lots of help from Paul Irish!
* http://paulirish.com/
*/
window.debug=(function(){var i=this,b=Array.prototype.slice,d=i.console,h={},f,g,m=9,c=["error","warn","info","debug","log"],l="assert clear count dir dirxml exception group groupCollapsed groupEnd profile profileEnd table time timeEnd trace".split(" "),j=l.length,a=[];while(--j>=0){(function(n){h[n]=function(){m!==0&&d&&d[n]&&d[n].apply(d,arguments)}})(l[j])}j=c.length;while(--j>=0){(function(n,o){h[o]=function(){var q=b.call(arguments),p=[o].concat(q);a.push(p);e(p);if(!d||!k(n)){return}d.firebug?d[o].apply(i,q):d[o]?d[o](q):d.log(q)}})(j,c[j])}function e(n){if(f&&(g||!d||!d.log)){f.apply(i,n)}}h.setLevel=function(n){m=typeof n==="number"?n:9};function k(n){return m>0?m>n:c.length+m<=n}h.setCallback=function(){var o=b.call(arguments),n=a.length,p=n;f=o.shift()||null;g=typeof o[0]==="boolean"?o.shift():false;p-=typeof o[0]==="number"?o.shift():n;while(p<n){e(a[p++])}};return h})();
|
describe('Options', function () {
var map;
var el;
beforeEach('initialize map', function () {
el = document.createElement('div');
// DOM needs to be visible: appended to the body and have dimensions
// in order for .focus() to work properly
el.style.cssText = 'position: absolute; left: 0; top: 0; width: 100%; height: 100%;';
document.body.appendChild(el);
map = L.map(el);
});
afterEach('destroy map', function () {
map.remove();
document.body.removeChild(el);
});
describe('defaults', function () {
var geocoder;
beforeEach(function () {
geocoder = new L.Control.Geocoder();
geocoder.addTo(map);
});
it('should not have the expanded state when added to the map', function () {
expect(geocoder.getContainer().classList.contains('leaflet-pelias-expanded')).to.be(false);
});
it('should be added to the top left position', function () {
var controlsClass = geocoder.getContainer().parentNode.classList;
expect(controlsClass.contains('leaflet-top')).to.be(true);
expect(controlsClass.contains('leaflet-left')).to.be(true);
});
});
describe('control positions', function () {
var positions = [
['top', 'left'],
['top', 'right'],
['bottom', 'left'],
['bottom', 'right']
];
positions.forEach(function (position) {
it('adds control to the ' + position[0] + ' ' + position[1] + ' if position value is `' + position[0] + position[1] + '`', function () {
var geocoder = new L.Control.Geocoder(null, { position: position[0] + position[1] });
geocoder.addTo(map);
var controlsClass = geocoder.getContainer().parentNode.classList;
expect(controlsClass.contains('leaflet-' + position[0])).to.be(true);
expect(controlsClass.contains('leaflet-' + position[1])).to.be(true);
});
});
});
describe('placeholder', function () {
it('should display custom placeholder text', function () {
var geocoder = new L.Control.Geocoder(null, { placeholder: 'a' });
geocoder.addTo(map);
expect(geocoder._input.placeholder).to.be('a');
});
it('should have no placeholder text if empty string is assigned to it', function () {
var geocoder = new L.Control.Geocoder(null, { placeholder: '' });
geocoder.addTo(map);
expect(geocoder._input.placeholder).to.be('');
});
it('should have no placeholder text if `null` is assigned to it', function () {
var geocoder = new L.Control.Geocoder(null, { placeholder: null });
geocoder.addTo(map);
expect(geocoder._input.placeholder).to.be('');
});
it('should have no placeholder text if `undefined` is assigned to it', function () {
var geocoder = new L.Control.Geocoder(null, { placeholder: undefined });
geocoder.addTo(map);
expect(geocoder._input.placeholder).to.be('');
});
});
describe('title', function () {
it('should display custom title text', function () {
var geocoder = new L.Control.Geocoder(null, { title: 'a' });
geocoder.addTo(map);
expect(geocoder._input.title).to.be('a');
});
it('should have no title text if empty string is assigned to it', function () {
var geocoder = new L.Control.Geocoder(null, { title: '' });
geocoder.addTo(map);
expect(geocoder._input.title).to.be('');
});
it('should have no title text if `null` is assigned to it', function () {
var geocoder = new L.Control.Geocoder(null, { title: null });
geocoder.addTo(map);
expect(geocoder._input.title).to.be('');
});
it('should have no title text if `undefined` is assigned to it', function () {
var geocoder = new L.Control.Geocoder(null, { title: undefined });
geocoder.addTo(map);
expect(geocoder._input.title).to.be('');
});
});
describe('layer icons', function () {
it('sets the point icon', function () {
var geocoder = new L.Control.Geocoder({ pointIcon: 'foo' });
var geocoder2 = new L.Control.Geocoder({ pointIcon: true });
var geocoder3 = new L.Control.Geocoder({ pointIcon: false });
expect(geocoder.options.pointIcon).to.be('foo');
expect(geocoder2.options.pointIcon).to.be(true);
expect(geocoder3.options.pointIcon).to.be(false);
});
it('sets the polygon icon', function () {
var geocoder = new L.Control.Geocoder({ polygonIcon: 'bar' });
var geocoder2 = new L.Control.Geocoder({ polygonIcon: true });
var geocoder3 = new L.Control.Geocoder({ polygonIcon: false });
expect(geocoder.options.polygonIcon).to.be('bar');
expect(geocoder2.options.polygonIcon).to.be(true);
expect(geocoder3.options.polygonIcon).to.be(false);
});
});
describe('expanded', function () {
describe('when true', function () {
var geocoder;
var options = {
expanded: true
};
beforeEach(function () {
geocoder = new L.Control.Geocoder(null, options);
geocoder.addTo(map);
});
it('should be in the expanded state when added to the map', function () {
expect(geocoder.getContainer().classList.contains('leaflet-pelias-expanded')).to.be(true);
});
it('should focus on the input when I click on search icon', function () {
happen.click(geocoder._search);
expect(document.activeElement.className).to.equal('leaflet-pelias-input');
});
it('should not collapse when I click the search icon', function () {
happen.click(geocoder._search);
expect(geocoder.getContainer().classList.contains('leaflet-pelias-expanded')).to.be(true);
});
it('should collapse if the .collapse() method is called', function () {
geocoder.collapse();
expect(geocoder.getContainer().classList.contains('leaflet-pelias-expanded')).to.be(false);
});
it('should expand again if .collapse() is called and then I click the search icon', function () {
geocoder.collapse();
happen.click(geocoder._search);
expect(geocoder.getContainer().classList.contains('leaflet-pelias-expanded')).to.be(true);
});
});
describe('when false', function () {
var geocoder;
var options = {
expanded: false
};
beforeEach(function () {
geocoder = new L.Control.Geocoder(null, options);
geocoder.addTo(map);
});
it('should be in the collapsed state when added to the map', function () {
expect(geocoder.getContainer().classList.contains('leaflet-pelias-expanded')).to.be(false);
});
it('should expand the input from a collapsed state, when I click on search icon', function () {
happen.click(geocoder._search);
expect(geocoder.getContainer().classList.contains('leaflet-pelias-expanded')).to.be(true);
});
it('should collapse the input when I click the search icon', function () {
happen.click(geocoder._search);
happen.click(geocoder._search);
expect(geocoder.getContainer().classList.contains('leaflet-pelias-expanded')).to.be(false);
});
it('should toggle betwen expanded / collapsed state properly when I click the search icon', function () {
var times = 5;
while (times > 0) {
happen.click(geocoder._search);
times--;
}
expect(geocoder.getContainer().classList.contains('leaflet-pelias-expanded')).to.be(true);
});
});
});
});
|
import lookupClasses from './utils/lookup-classes';
export default function classify(inputName) {
return lookupClasses(inputName).join(' ');
} |
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
let express = require("express");
let app = express();
const ThorIO_1 = require("../src/ThorIO");
const MyController_1 = require("../example/controllers/MyController");
const Broker_1 = require("../src/Controllers/BrokerController/Broker");
let Server = new ThorIO_1.ThorIO([
MyController_1.MyController,
Broker_1.BrokerController
]);
require("express-ws")(app);
app.use("/", express.static("example"));
app.ws("/", (ws, req) => {
Server.addWebSocket(ws, req);
});
var port = process.env.PORT || 1337;
app.listen(port);
console.log("thor-io is serving on", port.toString());
|
sm.Main.directive('smHomeContent', [
function() {
return {
restrict: 'E',
templateUrl: './scripts/modules/home/templates/home.content.html',
controller:['$scope', function($scope) {
$scope.hopfarmUrl = '/#hopreport';
$scope.testFunc = function() {
console.log('YYYYYYSDFSDFSDF')
}
}]
}
}
]);
|
angular
.module('cocktailApp')
.controller('CocktailEditCtrl', ['$location', '$routeParams', 'navigator', 'cocktailCollection',
function($location, $routeParams, navigator, cocktailCollection) {
var self = this;
self.isDisabled = true;
if (!$routeParams.id) {
self.cocktail = {};
self.isDisabled = false;
} else {
cocktailCollection.get($routeParams.id)
.then(function(cocktail) {
self.cocktail = cocktail;
self.isDisabled = false;
}, function(err) {
self.errorMessage = "Failed to find id: " + id;
});
}
self.addEquipment = function() {
if (!self.cocktail.equipment) {
self.cocktail.equipment = [];
}
self.cocktail.equipment.push(null);
};
self.removeEquipment = function(index) {
self.cocktail.equipment.splice(index, 1);
};
self.addIngredient = function() {
if (!self.cocktail.ingredients) {
self.cocktail.ingredients = [];
}
self.cocktail.ingredients.push(null);
};
self.removeIngredient = function(index) {
self.cocktail.ingredients.splice(index, 1);
};
self.addStep = function() {
if (!self.cocktail.method) {
self.cocktail.method = [];
}
self.cocktail.method.push(null);
};
self.removeStep = function(index) {
self.cocktail.method.splice(index, 1);
};
self.submit = function() {
cocktailCollection.set(self.cocktail)
.then(function(cocktail) {
navigator.viewCocktail(self.cocktail.id);
}, function(err) {
self.errorMessage = "Failed to set";
console.log("Failed to set");
});
};
self.cancel = function() {
navigator.viewCocktail(self.cocktail.id);
};
}
]);
|
'use strict';
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Pool = require('./pool');
var Heap = require('./heap');
var P = require('bluebird');
module.exports = function () {
function PriorityQueue(numWorkers) {
_classCallCheck(this, PriorityQueue);
this.numReadyWorkers = numWorkers;
this.pool = new Pool(numWorkers);
this.heap = new Heap();
}
_createClass(PriorityQueue, [{
key: 'push',
value: function push(arg, priority, fnOrModulePath, options) {
var _this = this;
return new P(function (resolve, reject) {
_this.heap.insert(priority, {
args: [arg, fnOrModulePath, options],
resolve: resolve,
reject: reject
});
_this._tick();
});
}
}, {
key: '_tick',
value: function _tick() {
while (this.numReadyWorkers && this.heap.len) {
this.numReadyWorkers -= 1;
this._processTask(this.heap.popMax().data);
}
}
}, {
key: '_processTask',
value: function _processTask(task) {
var _pool,
_this2 = this;
(_pool = this.pool).apply.apply(_pool, _toConsumableArray(task.args)).then(task.resolve, task.reject).then(function () {
_this2.numReadyWorkers += 1;
_this2._tick();
});
}
}]);
return PriorityQueue;
}(); |
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
global.electronRequire = require;
global.electronProcess = process;
require('./main.bundle.js');
|
import React from 'react';
import {Tabs, Tab} from 'material-ui/Tabs';
import {HackerNewsIcon, GitHubIcon, ProductHuntIcon} from '../Icons';
import {hackernews, github, producthunt} from '../../data';
import NewsList from '../NewsList';
import styles from './index.css';
class News extends React.Component {
constructor () {
super();
this.state = {
hackernews: {
data: [],
loaded: false,
},
github: {
data: [],
loaded: false,
},
producthunt: {
data: [],
loaded: false,
},
};
}
componentDidMount () {
hackernews((data) => {
this.setState({
hackernews: {
data: data,
loaded: true,
},
});
});
}
handleActiveTab (tab) {
switch (tab.props.value) {
case 'github':
if (!this.state.github.loaded) {
github((data) => {
this.setState({
github: {
data: data,
loaded: true,
},
});
});
}
break;
case 'producthunt':
if (!this.state.producthunt.loaded) {
producthunt((data) => {
this.setState({
producthunt: {
data: data,
loaded: true,
},
});
});
}
break;
}
}
render () {
return (
<Tabs
className={styles.tabsContainer}
contentContainerClassName={styles.content}
>
<Tab icon={<HackerNewsIcon title="Hacker News" />}>
<h1 className={styles.heading}>
Hacker News
</h1>
<NewsList
source="hackernews"
data={this.state.hackernews.data}
loaded={this.state.hackernews.loaded}
className={styles.storiesContainer}
/>
<a href="https://news.ycombinator.com/news?p=2">
Go to Hacker News (page 2)
</a>
</Tab>
<Tab
icon={<GitHubIcon title="GitHub Trending" />}
value="github"
onActive={this.handleActiveTab.bind(this)}
>
<h1 className={styles.heading}>
GitHub Trending
</h1>
<NewsList
source="github"
data={this.state.github.data}
loaded={this.state.github.loaded}
className={styles.storiesContainer}
/>
<a href="https://github.com/trending">
Go to GitHub Trending
</a>
</Tab>
<Tab
icon={<ProductHuntIcon title="Product Hunt Tech" />}
value="producthunt"
onActive={this.handleActiveTab.bind(this)}
>
<h1 className={styles.heading}>
Product Hunt Tech
</h1>
<NewsList
source="producthunt"
data={this.state.producthunt.data}
loaded={this.state.producthunt.loaded}
className={styles.storiesContainer}
/>
<a href="https://www.producthunt.com/tech">
Go to Product Hunt Tech
</a>
</Tab>
</Tabs>
)
}
};
export default News;
|
import { test, getTSParsers, getNonDefaultParsers } from '../utils';
import { RuleTester } from 'eslint';
import eslintPkg from 'eslint/package.json';
import semver from 'semver';
import flatMap from 'array.prototype.flatmap';
const ruleTester = new RuleTester();
const rule = require('rules/order');
function withoutAutofixOutput(test) {
return Object.assign({}, test, { output: test.code });
}
ruleTester.run('order', rule, {
valid: [
// Default order using require
test({
code: `
var fs = require('fs');
var async = require('async');
var relParent1 = require('../foo');
var relParent2 = require('../foo/bar');
var relParent3 = require('../');
var relParent4 = require('..');
var sibling = require('./foo');
var index = require('./');`,
}),
// Default order using import
test({
code: `
import fs from 'fs';
import async, {foo1} from 'async';
import relParent1 from '../foo';
import relParent2, {foo2} from '../foo/bar';
import relParent3 from '../';
import sibling, {foo3} from './foo';
import index from './';`,
}),
// Multiple module of the same rank next to each other
test({
code: `
var fs = require('fs');
var fs = require('fs');
var path = require('path');
var _ = require('lodash');
var async = require('async');`,
}),
// Overriding order to be the reverse of the default order
test({
code: `
var index = require('./');
var sibling = require('./foo');
var relParent3 = require('../');
var relParent2 = require('../foo/bar');
var relParent1 = require('../foo');
var async = require('async');
var fs = require('fs');
`,
options: [{ groups: ['index', 'sibling', 'parent', 'external', 'builtin'] }],
}),
// Ignore dynamic requires
test({
code: `
var path = require('path');
var _ = require('lodash');
var async = require('async');
var fs = require('f' + 's');`,
}),
// Ignore non-require call expressions
test({
code: `
var path = require('path');
var result = add(1, 2);
var _ = require('lodash');`,
}),
// Ignore requires that are not at the top-level #1
test({
code: `
var index = require('./');
function foo() {
var fs = require('fs');
}
() => require('fs');
if (a) {
require('fs');
}`,
}),
// Ignore requires that are not at the top-level #2
test({
code: `
const foo = [
require('./foo'),
require('fs'),
]`,
}),
// Ignore requires in template literal (#1936)
test({
code: "const foo = `${require('./a')} ${require('fs')}`",
}),
// Ignore unknown/invalid cases
test({
code: `
var unknown1 = require('/unknown1');
var fs = require('fs');
var unknown2 = require('/unknown2');
var async = require('async');
var unknown3 = require('/unknown3');
var foo = require('../foo');
var unknown4 = require('/unknown4');
var bar = require('../foo/bar');
var unknown5 = require('/unknown5');
var parent = require('../');
var unknown6 = require('/unknown6');
var foo = require('./foo');
var unknown7 = require('/unknown7');
var index = require('./');
var unknown8 = require('/unknown8');
` }),
// Ignoring unassigned values by default (require)
test({
code: `
require('./foo');
require('fs');
var path = require('path');
` }),
// Ignoring unassigned values by default (import)
test({
code: `
import './foo';
import 'fs';
import path from 'path';
` }),
// No imports
test({
code: `
function add(a, b) {
return a + b;
}
var foo;
` }),
// Grouping import types
test({
code: `
var fs = require('fs');
var index = require('./');
var path = require('path');
var sibling = require('./foo');
var relParent3 = require('../');
var async = require('async');
var relParent1 = require('../foo');
`,
options: [{ groups: [
['builtin', 'index'],
['sibling', 'parent', 'external'],
] }],
}),
// Omitted types should implicitly be considered as the last type
test({
code: `
var index = require('./');
var path = require('path');
`,
options: [{ groups: [
'index',
['sibling', 'parent', 'external'],
// missing 'builtin'
] }],
}),
// Mixing require and import should have import up top
test({
code: `
import async, {foo1} from 'async';
import relParent2, {foo2} from '../foo/bar';
import sibling, {foo3} from './foo';
var fs = require('fs');
var relParent1 = require('../foo');
var relParent3 = require('../');
var index = require('./');
`,
}),
...flatMap(getTSParsers(), parser => [
// Export equals expressions should be on top alongside with ordinary import-statements.
test({
code: `
import async, {foo1} from 'async';
import relParent2, {foo2} from '../foo/bar';
import sibling, {foo3} from './foo';
var fs = require('fs');
var util = require("util");
var relParent1 = require('../foo');
var relParent3 = require('../');
var index = require('./');
`,
parser,
}),
test({
code: `
export import CreateSomething = _CreateSomething;
`,
parser,
}),
]),
// Adding unknown import types (e.g. using a resolver alias via babel) to the groups.
test({
code: `
import fs from 'fs';
import { Input } from '-/components/Input';
import { Button } from '-/components/Button';
import { add } from './helper';`,
options: [{
groups: ['builtin', 'external', 'unknown', 'parent', 'sibling', 'index'],
}],
}),
// Using unknown import types (e.g. using a resolver alias via babel) with
// an alternative custom group list.
test({
code: `
import { Input } from '-/components/Input';
import { Button } from '-/components/Button';
import fs from 'fs';
import { add } from './helper';`,
options: [{
groups: [ 'unknown', 'builtin', 'external', 'parent', 'sibling', 'index' ],
}],
}),
// Using unknown import types (e.g. using a resolver alias via babel)
// Option: newlines-between: 'always'
test({
code: `
import fs from 'fs';
import { Input } from '-/components/Input';
import { Button } from '-/components/Button';
import p from '..';
import q from '../';
import { add } from './helper';
import i from '.';
import j from './';`,
options: [
{
'newlines-between': 'always',
groups: ['builtin', 'external', 'unknown', 'parent', 'sibling', 'index'],
},
],
}),
// Using pathGroups to customize ordering, position 'after'
test({
code: `
import fs from 'fs';
import _ from 'lodash';
import { Input } from '~/components/Input';
import { Button } from '#/components/Button';
import { add } from './helper';`,
options: [{
pathGroups: [
{ pattern: '~/**', group: 'external', position: 'after' },
{ pattern: '#/**', group: 'external', position: 'after' },
],
}],
}),
// pathGroup without position means "equal" with group
test({
code: `
import fs from 'fs';
import { Input } from '~/components/Input';
import async from 'async';
import { Button } from '#/components/Button';
import _ from 'lodash';
import { add } from './helper';`,
options: [{
pathGroups: [
{ pattern: '~/**', group: 'external' },
{ pattern: '#/**', group: 'external' },
],
}],
}),
// Using pathGroups to customize ordering, position 'before'
test({
code: `
import fs from 'fs';
import { Input } from '~/components/Input';
import { Button } from '#/components/Button';
import _ from 'lodash';
import { add } from './helper';`,
options: [{
'newlines-between': 'always',
pathGroups: [
{ pattern: '~/**', group: 'external', position: 'before' },
{ pattern: '#/**', group: 'external', position: 'before' },
],
}],
}),
// Using pathGroups to customize ordering, with patternOptions
test({
code: `
import fs from 'fs';
import _ from 'lodash';
import { Input } from '~/components/Input';
import { Button } from '!/components/Button';
import { add } from './helper';`,
options: [{
'newlines-between': 'always',
pathGroups: [
{ pattern: '~/**', group: 'external', position: 'after' },
{ pattern: '!/**', patternOptions: { nonegate: true }, group: 'external', position: 'after' },
],
}],
}),
// Using pathGroups to customize ordering for imports that are recognized as 'external'
// by setting pathGroupsExcludedImportTypes without 'external'
test({
code: `
import fs from 'fs';
import { Input } from '@app/components/Input';
import { Button } from '@app2/components/Button';
import _ from 'lodash';
import { add } from './helper';`,
options: [{
'newlines-between': 'always',
pathGroupsExcludedImportTypes: ['builtin'],
pathGroups: [
{ pattern: '@app/**', group: 'external', position: 'before' },
{ pattern: '@app2/**', group: 'external', position: 'before' },
],
}],
}),
// Using pathGroups (a test case for https://github.com/benmosher/eslint-plugin-import/pull/1724)
test({
code: `
import fs from 'fs';
import external from 'external';
import externalTooPlease from './make-me-external';
import sibling from './sibling';`,
options: [{
'newlines-between': 'always',
pathGroupsExcludedImportTypes: [],
pathGroups: [
{ pattern: './make-me-external', group: 'external' },
],
groups: [['builtin', 'external'], 'internal', 'parent', 'sibling', 'index'],
}],
}),
// Monorepo setup, using Webpack resolver, workspace folder name in external-module-folders
test({
code: `
import _ from 'lodash';
import m from '@test-scope/some-module';
import bar from './bar';
`,
options: [{
'newlines-between': 'always',
}],
settings: {
'import/resolver': 'webpack',
'import/external-module-folders': ['node_modules', 'symlinked-module'],
},
}),
// Monorepo setup, using Node resolver (doesn't resolve symlinks)
test({
code: `
import _ from 'lodash';
import m from '@test-scope/some-module';
import bar from './bar';
`,
options: [{
'newlines-between': 'always',
}],
settings: {
'import/resolver': 'node',
'import/external-module-folders': ['node_modules', 'symlinked-module'],
},
}),
// Option: newlines-between: 'always'
test({
code: `
var fs = require('fs');
var index = require('./');
var path = require('path');
var sibling = require('./foo');
var relParent1 = require('../foo');
var relParent3 = require('../');
var async = require('async');
`,
options: [
{
groups: [
['builtin', 'index'],
['sibling'],
['parent', 'external'],
],
'newlines-between': 'always',
},
],
}),
// Option: newlines-between: 'never'
test({
code: `
var fs = require('fs');
var index = require('./');
var path = require('path');
var sibling = require('./foo');
var relParent1 = require('../foo');
var relParent3 = require('../');
var async = require('async');
`,
options: [
{
groups: [
['builtin', 'index'],
['sibling'],
['parent', 'external'],
],
'newlines-between': 'never',
},
],
}),
// Option: newlines-between: 'ignore'
test({
code: `
var fs = require('fs');
var index = require('./');
var path = require('path');
var sibling = require('./foo');
var relParent1 = require('../foo');
var relParent3 = require('../');
var async = require('async');
`,
options: [
{
groups: [
['builtin', 'index'],
['sibling'],
['parent', 'external'],
],
'newlines-between': 'ignore',
},
],
}),
// 'ignore' should be the default value for `newlines-between`
test({
code: `
var fs = require('fs');
var index = require('./');
var path = require('path');
var sibling = require('./foo');
var relParent1 = require('../foo');
var relParent3 = require('../');
var async = require('async');
`,
options: [
{
groups: [
['builtin', 'index'],
['sibling'],
['parent', 'external'],
],
},
],
}),
// Option newlines-between: 'always' with multiline imports #1
test({
code: `
import path from 'path';
import {
I,
Want,
Couple,
Imports,
Here
} from 'bar';
import external from 'external'
`,
options: [{ 'newlines-between': 'always' }],
}),
// Option newlines-between: 'always' with multiline imports #2
test({
code: `
import path from 'path';
import net
from 'net';
import external from 'external'
`,
options: [{ 'newlines-between': 'always' }],
}),
// Option newlines-between: 'always' with multiline imports #3
test({
code: `
import foo
from '../../../../this/will/be/very/long/path/and/therefore/this/import/has/to/be/in/two/lines';
import bar
from './sibling';
`,
options: [{ 'newlines-between': 'always' }],
}),
// Option newlines-between: 'always' with not assigned import #1
test({
code: `
import path from 'path';
import 'loud-rejection';
import 'something-else';
import _ from 'lodash';
`,
options: [{ 'newlines-between': 'always' }],
}),
// Option newlines-between: 'never' with not assigned import #2
test({
code: `
import path from 'path';
import 'loud-rejection';
import 'something-else';
import _ from 'lodash';
`,
options: [{ 'newlines-between': 'never' }],
}),
// Option newlines-between: 'always' with not assigned require #1
test({
code: `
var path = require('path');
require('loud-rejection');
require('something-else');
var _ = require('lodash');
`,
options: [{ 'newlines-between': 'always' }],
}),
// Option newlines-between: 'never' with not assigned require #2
test({
code: `
var path = require('path');
require('loud-rejection');
require('something-else');
var _ = require('lodash');
`,
options: [{ 'newlines-between': 'never' }],
}),
// Option newlines-between: 'never' should ignore nested require statement's #1
test({
code: `
var some = require('asdas');
var config = {
port: 4444,
runner: {
server_path: require('runner-binary').path,
cli_args: {
'webdriver.chrome.driver': require('browser-binary').path
}
}
}
`,
options: [{ 'newlines-between': 'never' }],
}),
// Option newlines-between: 'always' should ignore nested require statement's #2
test({
code: `
var some = require('asdas');
var config = {
port: 4444,
runner: {
server_path: require('runner-binary').path,
cli_args: {
'webdriver.chrome.driver': require('browser-binary').path
}
}
}
`,
options: [{ 'newlines-between': 'always' }],
}),
// Option: newlines-between: 'always-and-inside-groups'
test({
code: `
var fs = require('fs');
var path = require('path');
var util = require('util');
var async = require('async');
var relParent1 = require('../foo');
var relParent2 = require('../');
var relParent3 = require('../bar');
var sibling = require('./foo');
var sibling2 = require('./bar');
var sibling3 = require('./foobar');
`,
options: [
{
'newlines-between': 'always-and-inside-groups',
},
],
}),
// Option alphabetize: {order: 'ignore'}
test({
code: `
import a from 'foo';
import b from 'bar';
import index from './';
`,
options: [{
groups: ['external', 'index'],
alphabetize: { order: 'ignore' },
}],
}),
// Option alphabetize: {order: 'asc'}
test({
code: `
import c from 'Bar';
import b from 'bar';
import a from 'foo';
import index from './';
`,
options: [{
groups: ['external', 'index'],
alphabetize: { order: 'asc' },
}],
}),
// Option alphabetize: {order: 'desc'}
test({
code: `
import a from 'foo';
import b from 'bar';
import c from 'Bar';
import index from './';
`,
options: [{
groups: ['external', 'index'],
alphabetize: { order: 'desc' },
}],
}),
// Option alphabetize with newlines-between: {order: 'asc', newlines-between: 'always'}
test({
code: `
import b from 'Bar';
import c from 'bar';
import a from 'foo';
import index from './';
`,
options: [{
groups: ['external', 'index'],
alphabetize: { order: 'asc' },
'newlines-between': 'always',
}],
}),
// Alphabetize with require
test({
code: `
import { hello } from './hello';
import { int } from './int';
const blah = require('./blah');
const { cello } = require('./cello');
`,
options: [
{
alphabetize: {
order: 'asc',
},
},
],
}),
// Order of imports with similar names
test({
code: `
import React from 'react';
import { BrowserRouter } from 'react-router-dom';
`,
options: [
{
alphabetize: {
order: 'asc',
},
},
],
}),
test({
code: `
import { UserInputError } from 'apollo-server-express';
import { new as assertNewEmail } from '~/Assertions/Email';
`,
options: [{
alphabetize: {
caseInsensitive: true,
order: 'asc',
},
pathGroups: [
{ pattern: '~/*', group: 'internal' },
],
groups: [
'builtin',
'external',
'internal',
'parent',
'sibling',
'index',
],
'newlines-between': 'always',
}],
}),
test({
code: `
import { ReactElement, ReactNode } from 'react';
import { util } from 'Internal/lib';
import { parent } from '../parent';
import { sibling } from './sibling';
`,
options: [{
alphabetize: {
caseInsensitive: true,
order: 'asc',
},
pathGroups: [
{ pattern: 'Internal/**/*', group: 'internal' },
],
groups: [
'builtin',
'external',
'internal',
'parent',
'sibling',
'index',
],
'newlines-between': 'always',
pathGroupsExcludedImportTypes: [],
}],
}),
...flatMap(getTSParsers, parser => [
// Order of the `import ... = require(...)` syntax
test({
code: `
import blah = require('./blah');
import { hello } from './hello';`,
parser,
options: [
{
alphabetize: {
order: 'asc',
},
},
],
}),
// Order of object-imports
test({
code: `
import blah = require('./blah');
import log = console.log;`,
parser,
options: [
{
alphabetize: {
order: 'asc',
},
},
],
}),
// Object-imports should not be forced to be alphabetized
test({
code: `
import debug = console.debug;
import log = console.log;`,
parser,
options: [
{
alphabetize: {
order: 'asc',
},
},
],
}),
test({
code: `
import log = console.log;
import debug = console.debug;`,
parser,
options: [
{
alphabetize: {
order: 'asc',
},
},
],
}),
test({
code: `
import { a } from "./a";
export namespace SomeNamespace {
export import a2 = a;
}
`,
parser,
options: [
{
groups: ['external', 'index'],
alphabetize: { order: 'asc' },
},
],
}),
]),
],
invalid: [
// builtin before external module (require)
test({
code: `
var async = require('async');
var fs = require('fs');
`,
output: `
var fs = require('fs');
var async = require('async');
`,
errors: [{
message: '`fs` import should occur before import of `async`',
}],
}),
// fix order with spaces on the end of line
test({
code: `
var async = require('async');
var fs = require('fs');${' '}
`,
output: `
var fs = require('fs');${' '}
var async = require('async');
`,
errors: [{
message: '`fs` import should occur before import of `async`',
}],
}),
// fix order with comment on the end of line
test({
code: `
var async = require('async');
var fs = require('fs'); /* comment */
`,
output: `
var fs = require('fs'); /* comment */
var async = require('async');
`,
errors: [{
message: '`fs` import should occur before import of `async`',
}],
}),
// fix order with comments at the end and start of line
test({
code: `
/* comment1 */ var async = require('async'); /* comment2 */
/* comment3 */ var fs = require('fs'); /* comment4 */
`,
output: `
/* comment3 */ var fs = require('fs'); /* comment4 */
/* comment1 */ var async = require('async'); /* comment2 */
`,
errors: [{
message: '`fs` import should occur before import of `async`',
}],
}),
// fix order with few comments at the end and start of line
test({
code: `
/* comment0 */ /* comment1 */ var async = require('async'); /* comment2 */
/* comment3 */ var fs = require('fs'); /* comment4 */
`,
output: `
/* comment3 */ var fs = require('fs'); /* comment4 */
/* comment0 */ /* comment1 */ var async = require('async'); /* comment2 */
`,
errors: [{
message: '`fs` import should occur before import of `async`',
}],
}),
// fix order with windows end of lines
test({
code:
`/* comment0 */ /* comment1 */ var async = require('async'); /* comment2 */` + `\r\n` +
`/* comment3 */ var fs = require('fs'); /* comment4 */` + `\r\n`,
output:
`/* comment3 */ var fs = require('fs'); /* comment4 */` + `\r\n` +
`/* comment0 */ /* comment1 */ var async = require('async'); /* comment2 */` + `\r\n`,
errors: [{
message: '`fs` import should occur before import of `async`',
}],
}),
// fix order with multilines comments at the end and start of line
test({
code: `
/* multiline1
comment1 */ var async = require('async'); /* multiline2
comment2 */ var fs = require('fs'); /* multiline3
comment3 */
`,
output: `
/* multiline1
comment1 */ var fs = require('fs');` + ' ' + `
var async = require('async'); /* multiline2
comment2 *//* multiline3
comment3 */
`,
errors: [{
message: '`fs` import should occur before import of `async`',
}],
}),
// fix destructured commonjs import
test({
code: `
var {b} = require('async');
var {a} = require('fs');
`,
output: `
var {a} = require('fs');
var {b} = require('async');
`,
errors: [{
message: '`fs` import should occur before import of `async`',
}],
}),
// fix order of multiline import
test({
code: `
var async = require('async');
var fs =
require('fs');
`,
output: `
var fs =
require('fs');
var async = require('async');
`,
errors: [{
message: '`fs` import should occur before import of `async`',
}],
}),
// fix order at the end of file
test({
code: `
var async = require('async');
var fs = require('fs');`,
output: `
var fs = require('fs');
var async = require('async');` + '\n',
errors: [{
message: '`fs` import should occur before import of `async`',
}],
}),
// builtin before external module (import)
test({
code: `
import async from 'async';
import fs from 'fs';
`,
output: `
import fs from 'fs';
import async from 'async';
`,
errors: [{
message: '`fs` import should occur before import of `async`',
}],
}),
// builtin before external module (mixed import and require)
test({
code: `
var async = require('async');
import fs from 'fs';
`,
output: `
import fs from 'fs';
var async = require('async');
`,
errors: [{
message: '`fs` import should occur before import of `async`',
}],
}),
// external before parent
test({
code: `
var parent = require('../parent');
var async = require('async');
`,
output: `
var async = require('async');
var parent = require('../parent');
`,
errors: [{
message: '`async` import should occur before import of `../parent`',
}],
}),
// parent before sibling
test({
code: `
var sibling = require('./sibling');
var parent = require('../parent');
`,
output: `
var parent = require('../parent');
var sibling = require('./sibling');
`,
errors: [{
message: '`../parent` import should occur before import of `./sibling`',
}],
}),
// sibling before index
test({
code: `
var index = require('./');
var sibling = require('./sibling');
`,
output: `
var sibling = require('./sibling');
var index = require('./');
`,
errors: [{
message: '`./sibling` import should occur before import of `./`',
}],
}),
// Multiple errors
...semver.satisfies(eslintPkg.version, '< 3.0.0') ? [] : [
test({
code: `
var sibling = require('./sibling');
var async = require('async');
var fs = require('fs');
`,
output: `
var async = require('async');
var sibling = require('./sibling');
var fs = require('fs');
`,
errors: [{
message: '`async` import should occur before import of `./sibling`',
}, {
message: '`fs` import should occur before import of `./sibling`',
}],
}),
],
// Uses 'after' wording if it creates less errors
test({
code: `
var index = require('./');
var fs = require('fs');
var path = require('path');
var _ = require('lodash');
var foo = require('foo');
var bar = require('bar');
`,
output: `
var fs = require('fs');
var path = require('path');
var _ = require('lodash');
var foo = require('foo');
var bar = require('bar');
var index = require('./');
`,
errors: [{
message: '`./` import should occur after import of `bar`',
}],
}),
// Overriding order to be the reverse of the default order
test({
code: `
var fs = require('fs');
var index = require('./');
`,
output: `
var index = require('./');
var fs = require('fs');
`,
options: [{ groups: ['index', 'sibling', 'parent', 'external', 'builtin'] }],
errors: [{
message: '`./` import should occur before import of `fs`',
}],
}),
// member expression of require
test(withoutAutofixOutput({
code: `
var foo = require('./foo').bar;
var fs = require('fs');
`,
errors: [{
message: '`fs` import should occur before import of `./foo`',
}],
})),
// nested member expression of require
test(withoutAutofixOutput({
code: `
var foo = require('./foo').bar.bar.bar;
var fs = require('fs');
`,
errors: [{
message: '`fs` import should occur before import of `./foo`',
}],
})),
// fix near nested member expression of require with newlines
test(withoutAutofixOutput({
code: `
var foo = require('./foo').bar
.bar
.bar;
var fs = require('fs');
`,
errors: [{
message: '`fs` import should occur before import of `./foo`',
}],
})),
// fix nested member expression of require with newlines
test(withoutAutofixOutput({
code: `
var foo = require('./foo');
var fs = require('fs').bar
.bar
.bar;
`,
errors: [{
message: '`fs` import should occur before import of `./foo`',
}],
})),
// Grouping import types
test({
code: `
var fs = require('fs');
var index = require('./');
var sibling = require('./foo');
var path = require('path');
`,
output: `
var fs = require('fs');
var index = require('./');
var path = require('path');
var sibling = require('./foo');
`,
options: [{ groups: [
['builtin', 'index'],
['sibling', 'parent', 'external'],
] }],
errors: [{
message: '`path` import should occur before import of `./foo`',
}],
}),
// Omitted types should implicitly be considered as the last type
test({
code: `
var path = require('path');
var async = require('async');
`,
output: `
var async = require('async');
var path = require('path');
`,
options: [{ groups: [
'index',
['sibling', 'parent', 'external', 'internal'],
// missing 'builtin'
] }],
errors: [{
message: '`async` import should occur before import of `path`',
}],
}),
// Setting the order for an unknown type
// should make the rule trigger an error and do nothing else
test({
code: `
var async = require('async');
var index = require('./');
`,
options: [{ groups: [
'index',
['sibling', 'parent', 'UNKNOWN', 'internal'],
] }],
errors: [{
message: 'Incorrect configuration of the rule: Unknown type `"UNKNOWN"`',
}],
}),
// Type in an array can't be another array, too much nesting
test({
code: `
var async = require('async');
var index = require('./');
`,
options: [{ groups: [
'index',
['sibling', 'parent', ['builtin'], 'internal'],
] }],
errors: [{
message: 'Incorrect configuration of the rule: Unknown type `["builtin"]`',
}],
}),
// No numbers
test({
code: `
var async = require('async');
var index = require('./');
`,
options: [{ groups: [
'index',
['sibling', 'parent', 2, 'internal'],
] }],
errors: [{
message: 'Incorrect configuration of the rule: Unknown type `2`',
}],
}),
// Duplicate
test({
code: `
var async = require('async');
var index = require('./');
`,
options: [{ groups: [
'index',
['sibling', 'parent', 'parent', 'internal'],
] }],
errors: [{
message: 'Incorrect configuration of the rule: `parent` is duplicated',
}],
}),
// Mixing require and import should have import up top
test({
code: `
import async, {foo1} from 'async';
import relParent2, {foo2} from '../foo/bar';
var fs = require('fs');
var relParent1 = require('../foo');
var relParent3 = require('../');
import sibling, {foo3} from './foo';
var index = require('./');
`,
output: `
import async, {foo1} from 'async';
import relParent2, {foo2} from '../foo/bar';
import sibling, {foo3} from './foo';
var fs = require('fs');
var relParent1 = require('../foo');
var relParent3 = require('../');
var index = require('./');
`,
errors: [{
message: '`./foo` import should occur before import of `fs`',
}],
}),
test({
code: `
var fs = require('fs');
import async, {foo1} from 'async';
import relParent2, {foo2} from '../foo/bar';
`,
output: `
import async, {foo1} from 'async';
import relParent2, {foo2} from '../foo/bar';
var fs = require('fs');
`,
errors: [{
message: '`fs` import should occur after import of `../foo/bar`',
}],
}),
...flatMap(getTSParsers(), parser => [
// Order of the `import ... = require(...)` syntax
test({
code: `
var fs = require('fs');
import async, {foo1} from 'async';
import bar = require("../foo/bar");
`,
output: `
import async, {foo1} from 'async';
import bar = require("../foo/bar");
var fs = require('fs');
`,
parser,
errors: [{
message: '`fs` import should occur after import of `../foo/bar`',
}],
}),
test({
code: `
var async = require('async');
var fs = require('fs');
`,
output: `
var fs = require('fs');
var async = require('async');
`,
parser,
errors: [{
message: '`fs` import should occur before import of `async`',
}],
}),
test({
code: `
import sync = require('sync');
import async, {foo1} from 'async';
import index from './';
`,
output: `
import async, {foo1} from 'async';
import sync = require('sync');
import index from './';
`,
options: [{
groups: ['external', 'index'],
alphabetize: { order: 'asc' },
}],
parser,
errors: [{
message: '`async` import should occur before import of `sync`',
}],
}),
// Order of object-imports
test({
code: `
import log = console.log;
import blah = require('./blah');`,
parser,
errors: [{
message: '`./blah` import should occur before import of `console.log`',
}],
}),
]),
// Default order using import with custom import alias
test({
code: `
import { Button } from '-/components/Button';
import { add } from './helper';
import fs from 'fs';
`,
output: `
import fs from 'fs';
import { Button } from '-/components/Button';
import { add } from './helper';
`,
options: [
{
groups: ['builtin', 'external', 'unknown', 'parent', 'sibling', 'index'],
},
],
errors: [
{
line: 4,
message: '`fs` import should occur before import of `-/components/Button`',
},
],
}),
// Default order using import with custom import alias
test({
code: `
import fs from 'fs';
import { Button } from '-/components/Button';
import { LinkButton } from '-/components/Link';
import { add } from './helper';
`,
output: `
import fs from 'fs';
import { Button } from '-/components/Button';
import { LinkButton } from '-/components/Link';
import { add } from './helper';
`,
options: [
{
groups: ['builtin', 'external', 'unknown', 'parent', 'sibling', 'index'],
'newlines-between': 'always',
},
],
errors: [
{
line: 2,
message: 'There should be at least one empty line between import groups',
},
{
line: 4,
message: 'There should be at least one empty line between import groups',
},
],
}),
// Option newlines-between: 'never' - should report unnecessary line between groups
test({
code: `
var fs = require('fs');
var index = require('./');
var path = require('path');
var sibling = require('./foo');
var relParent1 = require('../foo');
var relParent3 = require('../');
var async = require('async');
`,
output: `
var fs = require('fs');
var index = require('./');
var path = require('path');
var sibling = require('./foo');
var relParent1 = require('../foo');
var relParent3 = require('../');
var async = require('async');
`,
options: [
{
groups: [
['builtin', 'index'],
['sibling'],
['parent', 'external'],
],
'newlines-between': 'never',
},
],
errors: [
{
line: 4,
message: 'There should be no empty line between import groups',
},
{
line: 6,
message: 'There should be no empty line between import groups',
},
],
}),
// Fix newlines-between with comments after
test({
code: `
var fs = require('fs'); /* comment */
var index = require('./');
`,
output: `
var fs = require('fs'); /* comment */
var index = require('./');
`,
options: [
{
groups: [['builtin'], ['index']],
'newlines-between': 'never',
},
],
errors: [
{
line: 2,
message: 'There should be no empty line between import groups',
},
],
}),
// Cannot fix newlines-between with multiline comment after
test({
code: `
var fs = require('fs'); /* multiline
comment */
var index = require('./');
`,
output: `
var fs = require('fs'); /* multiline
comment */
var index = require('./');
`,
options: [
{
groups: [['builtin'], ['index']],
'newlines-between': 'never',
},
],
errors: [
{
line: 2,
message: 'There should be no empty line between import groups',
},
],
}),
// Option newlines-between: 'always' - should report lack of newline between groups
test({
code: `
var fs = require('fs');
var index = require('./');
var path = require('path');
var sibling = require('./foo');
var relParent1 = require('../foo');
var relParent3 = require('../');
var async = require('async');
`,
output: `
var fs = require('fs');
var index = require('./');
var path = require('path');
var sibling = require('./foo');
var relParent1 = require('../foo');
var relParent3 = require('../');
var async = require('async');
`,
options: [
{
groups: [
['builtin', 'index'],
['sibling'],
['parent', 'external'],
],
'newlines-between': 'always',
},
],
errors: [
{
line: 4,
message: 'There should be at least one empty line between import groups',
},
{
line: 5,
message: 'There should be at least one empty line between import groups',
},
],
}),
// Option newlines-between: 'always' should report unnecessary empty lines space between import groups
test({
code: `
var fs = require('fs');
var path = require('path');
var index = require('./');
var sibling = require('./foo');
var async = require('async');
`,
output: `
var fs = require('fs');
var path = require('path');
var index = require('./');
var sibling = require('./foo');
var async = require('async');
`,
options: [
{
groups: [
['builtin', 'index'],
['sibling', 'parent', 'external'],
],
'newlines-between': 'always',
},
],
errors: [
{
line: 2,
message: 'There should be no empty line within import group',
},
{
line: 7,
message: 'There should be no empty line within import group',
},
],
}),
// Option newlines-between: 'never' with unassigned imports and warnOnUnassignedImports disabled
// newline is preserved to match existing behavior
test({
code: `
import path from 'path';
import 'loud-rejection';
import 'something-else';
import _ from 'lodash';
`,
output: `
import path from 'path';
import 'loud-rejection';
import 'something-else';
import _ from 'lodash';
`,
options: [{ 'newlines-between': 'never', warnOnUnassignedImports: false }],
errors: [
{
line: 2,
message: 'There should be no empty line between import groups',
},
],
}),
// Option newlines-between: 'never' with unassigned imports and warnOnUnassignedImports enabled
test({
code: `
import path from 'path';
import 'loud-rejection';
import 'something-else';
import _ from 'lodash';
`,
output: `
import path from 'path';
import 'loud-rejection';
import 'something-else';
import _ from 'lodash';
`,
options: [{ 'newlines-between': 'never', warnOnUnassignedImports: true }],
errors: [
{
line: 3,
message: 'There should be no empty line between import groups',
},
],
}),
// Option newlines-between: 'never' cannot fix if there are other statements between imports
test({
code: `
import path from 'path';
export const abc = 123;
import 'something-else';
import _ from 'lodash';
`,
output: `
import path from 'path';
export const abc = 123;
import 'something-else';
import _ from 'lodash';
`,
options: [{ 'newlines-between': 'never' }],
errors: [
{
line: 2,
message: 'There should be no empty line between import groups',
},
],
}),
// Option newlines-between: 'always' should report missing empty lines when using not assigned imports
test({
code: `
import path from 'path';
import 'loud-rejection';
import 'something-else';
import _ from 'lodash';
`,
output: `
import path from 'path';
import 'loud-rejection';
import 'something-else';
import _ from 'lodash';
`,
options: [{ 'newlines-between': 'always' }],
errors: [
{
line: 2,
message: 'There should be at least one empty line between import groups',
},
],
}),
// fix missing empty lines with single line comment after
test({
code: `
import path from 'path'; // comment
import _ from 'lodash';
`,
output: `
import path from 'path'; // comment
import _ from 'lodash';
`,
options: [{ 'newlines-between': 'always' }],
errors: [
{
line: 2,
message: 'There should be at least one empty line between import groups',
},
],
}),
// fix missing empty lines with few line block comment after
test({
code: `
import path from 'path'; /* comment */ /* comment */
import _ from 'lodash';
`,
output: `
import path from 'path'; /* comment */ /* comment */
import _ from 'lodash';
`,
options: [{ 'newlines-between': 'always' }],
errors: [
{
line: 2,
message: 'There should be at least one empty line between import groups',
},
],
}),
// fix missing empty lines with single line block comment after
test({
code: `
import path from 'path'; /* 1
2 */
import _ from 'lodash';
`,
output: `
import path from 'path';
/* 1
2 */
import _ from 'lodash';
`,
options: [{ 'newlines-between': 'always' }],
errors: [
{
line: 2,
message: 'There should be at least one empty line between import groups',
},
],
}),
// reorder fix cannot cross function call on moving below #1
test({
code: `
const local = require('./local');
fn_call();
const global1 = require('global1');
const global2 = require('global2');
fn_call();
`,
output: `
const local = require('./local');
fn_call();
const global1 = require('global1');
const global2 = require('global2');
fn_call();
`,
errors: [{
message: '`./local` import should occur after import of `global2`',
}],
}),
// reorder fix cannot cross function call on moving below #2
test({
code: `
const local = require('./local');
fn_call();
const global1 = require('global1');
const global2 = require('global2');
fn_call();
`,
output: `
const local = require('./local');
fn_call();
const global1 = require('global1');
const global2 = require('global2');
fn_call();
`,
errors: [{
message: '`./local` import should occur after import of `global2`',
}],
}),
// reorder fix cannot cross function call on moving below #3
test({
code: `
const local1 = require('./local1');
const local2 = require('./local2');
const local3 = require('./local3');
const local4 = require('./local4');
fn_call();
const global1 = require('global1');
const global2 = require('global2');
const global3 = require('global3');
const global4 = require('global4');
const global5 = require('global5');
fn_call();
`,
output: `
const local1 = require('./local1');
const local2 = require('./local2');
const local3 = require('./local3');
const local4 = require('./local4');
fn_call();
const global1 = require('global1');
const global2 = require('global2');
const global3 = require('global3');
const global4 = require('global4');
const global5 = require('global5');
fn_call();
`,
errors: [
'`./local1` import should occur after import of `global5`',
'`./local2` import should occur after import of `global5`',
'`./local3` import should occur after import of `global5`',
'`./local4` import should occur after import of `global5`',
],
}),
// reorder fix cannot cross function call on moving below
test(withoutAutofixOutput({
code: `
const local = require('./local');
const global1 = require('global1');
const global2 = require('global2');
fn_call();
const global3 = require('global3');
fn_call();
`,
errors: [{
message: '`./local` import should occur after import of `global3`',
}],
})),
// reorder fix cannot cross function call on moving below
// fix imports that not crosses function call only
test({
code: `
const local1 = require('./local1');
const global1 = require('global1');
const global2 = require('global2');
fn_call();
const local2 = require('./local2');
const global3 = require('global3');
const global4 = require('global4');
fn_call();
`,
output: `
const local1 = require('./local1');
const global1 = require('global1');
const global2 = require('global2');
fn_call();
const global3 = require('global3');
const global4 = require('global4');
const local2 = require('./local2');
fn_call();
`,
errors: [
'`./local1` import should occur after import of `global4`',
'`./local2` import should occur after import of `global4`',
],
}),
// pathGroup with position 'after'
test({
code: `
import fs from 'fs';
import _ from 'lodash';
import { add } from './helper';
import { Input } from '~/components/Input';
`,
output: `
import fs from 'fs';
import _ from 'lodash';
import { Input } from '~/components/Input';
import { add } from './helper';
`,
options: [{
pathGroups: [
{ pattern: '~/**', group: 'external', position: 'after' },
],
}],
errors: [{
message: '`~/components/Input` import should occur before import of `./helper`',
}],
}),
// pathGroup without position
test({
code: `
import fs from 'fs';
import _ from 'lodash';
import { add } from './helper';
import { Input } from '~/components/Input';
import async from 'async';
`,
output: `
import fs from 'fs';
import _ from 'lodash';
import { Input } from '~/components/Input';
import async from 'async';
import { add } from './helper';
`,
options: [{
pathGroups: [
{ pattern: '~/**', group: 'external' },
],
}],
errors: [{
message: '`./helper` import should occur after import of `async`',
}],
}),
// pathGroup with position 'before'
test({
code: `
import fs from 'fs';
import _ from 'lodash';
import { add } from './helper';
import { Input } from '~/components/Input';
`,
output: `
import fs from 'fs';
import { Input } from '~/components/Input';
import _ from 'lodash';
import { add } from './helper';
`,
options: [{
pathGroups: [
{ pattern: '~/**', group: 'external', position: 'before' },
],
}],
errors: [{
message: '`~/components/Input` import should occur before import of `lodash`',
}],
}),
// multiple pathGroup with different positions for same group, fix for 'after'
test({
code: `
import fs from 'fs';
import { Import } from '$/components/Import';
import _ from 'lodash';
import { Output } from '~/components/Output';
import { Input } from '#/components/Input';
import { add } from './helper';
import { Export } from '-/components/Export';
`,
output: `
import fs from 'fs';
import { Export } from '-/components/Export';
import { Import } from '$/components/Import';
import _ from 'lodash';
import { Output } from '~/components/Output';
import { Input } from '#/components/Input';
import { add } from './helper';
`,
options: [{
pathGroups: [
{ pattern: '~/**', group: 'external', position: 'after' },
{ pattern: '#/**', group: 'external', position: 'after' },
{ pattern: '-/**', group: 'external', position: 'before' },
{ pattern: '$/**', group: 'external', position: 'before' },
],
}],
errors: [
{
message: '`-/components/Export` import should occur before import of `$/components/Import`',
},
],
}),
// multiple pathGroup with different positions for same group, fix for 'before'
test({
code: `
import fs from 'fs';
import { Export } from '-/components/Export';
import { Import } from '$/components/Import';
import _ from 'lodash';
import { Input } from '#/components/Input';
import { add } from './helper';
import { Output } from '~/components/Output';
`,
output: `
import fs from 'fs';
import { Export } from '-/components/Export';
import { Import } from '$/components/Import';
import _ from 'lodash';
import { Output } from '~/components/Output';
import { Input } from '#/components/Input';
import { add } from './helper';
`,
options: [{
pathGroups: [
{ pattern: '~/**', group: 'external', position: 'after' },
{ pattern: '#/**', group: 'external', position: 'after' },
{ pattern: '-/**', group: 'external', position: 'before' },
{ pattern: '$/**', group: 'external', position: 'before' },
],
}],
errors: [
{
message: '`~/components/Output` import should occur before import of `#/components/Input`',
},
],
}),
// reorder fix cannot cross non import or require
test(withoutAutofixOutput({
code: `
var async = require('async');
fn_call();
var fs = require('fs');
`,
errors: [{
message: '`fs` import should occur before import of `async`',
}],
})),
// reorder fix cannot cross function call on moving below (from #1252)
test({
code: `
const env = require('./config');
Object.keys(env);
const http = require('http');
const express = require('express');
http.createServer(express());
`,
output: `
const env = require('./config');
Object.keys(env);
const http = require('http');
const express = require('express');
http.createServer(express());
`,
errors: [{
message: '`./config` import should occur after import of `express`',
}],
}),
// reorder cannot cross non plain requires
test(withoutAutofixOutput({
code: `
var async = require('async');
var a = require('./value.js')(a);
var fs = require('fs');
`,
errors: [{
message: '`fs` import should occur before import of `async`',
}],
})),
// reorder fixes cannot be applied to non plain requires #1
test(withoutAutofixOutput({
code: `
var async = require('async');
var fs = require('fs')(a);
`,
errors: [{
message: '`fs` import should occur before import of `async`',
}],
})),
// reorder fixes cannot be applied to non plain requires #2
test(withoutAutofixOutput({
code: `
var async = require('async')(a);
var fs = require('fs');
`,
errors: [{
message: '`fs` import should occur before import of `async`',
}],
})),
// cannot require in case of not assignment require
test(withoutAutofixOutput({
code: `
var async = require('async');
require('./aa');
var fs = require('fs');
`,
errors: [{
message: '`fs` import should occur before import of `async`',
}],
})),
// reorder cannot cross function call (import statement)
test(withoutAutofixOutput({
code: `
import async from 'async';
fn_call();
import fs from 'fs';
`,
errors: [{
message: '`fs` import should occur before import of `async`',
}],
})),
// reorder cannot cross variable assignment (import statement)
test(withoutAutofixOutput({
code: `
import async from 'async';
var a = 1;
import fs from 'fs';
`,
errors: [{
message: '`fs` import should occur before import of `async`',
}],
})),
// reorder cannot cross non plain requires (import statement)
test(withoutAutofixOutput({
code: `
import async from 'async';
var a = require('./value.js')(a);
import fs from 'fs';
`,
errors: [{
message: '`fs` import should occur before import of `async`',
}],
})),
// cannot reorder in case of not assignment import
test(withoutAutofixOutput({
code: `
import async from 'async';
import './aa';
import fs from 'fs';
`,
errors: [{
message: '`fs` import should occur before import of `async`',
}],
})),
// Option alphabetize: {order: 'asc'}
test({
code: `
import b from 'bar';
import c from 'Bar';
import a from 'foo';
import index from './';
`,
output: `
import c from 'Bar';
import b from 'bar';
import a from 'foo';
import index from './';
`,
options: [{
groups: ['external', 'index'],
alphabetize: { order: 'asc' },
}],
errors: [{
message: '`Bar` import should occur before import of `bar`',
}],
}),
// Option alphabetize: {order: 'desc'}
test({
code: `
import a from 'foo';
import c from 'Bar';
import b from 'bar';
import index from './';
`,
output: `
import a from 'foo';
import b from 'bar';
import c from 'Bar';
import index from './';
`,
options: [{
groups: ['external', 'index'],
alphabetize: { order: 'desc' },
}],
errors: [{
message: '`bar` import should occur before import of `Bar`',
}],
}),
// Option alphabetize {order: 'asc': caseInsensitive: true}
test({
code: `
import b from 'foo';
import a from 'Bar';
import index from './';
`,
output: `
import a from 'Bar';
import b from 'foo';
import index from './';
`,
options: [{
groups: ['external', 'index'],
alphabetize: { order: 'asc', caseInsensitive: true },
}],
errors: [{
message: '`Bar` import should occur before import of `foo`',
}],
}),
// Option alphabetize {order: 'desc': caseInsensitive: true}
test({
code: `
import a from 'Bar';
import b from 'foo';
import index from './';
`,
output: `
import b from 'foo';
import a from 'Bar';
import index from './';
`,
options: [{
groups: ['external', 'index'],
alphabetize: { order: 'desc', caseInsensitive: true },
}],
errors: [{
message: '`foo` import should occur before import of `Bar`',
}],
}),
// Alphabetize with parent paths
test({
code: `
import a from '../a';
import p from '..';
`,
output: `
import p from '..';
import a from '../a';
`,
options: [{
groups: ['external', 'index'],
alphabetize: { order: 'asc' },
}],
errors: [{
message: '`..` import should occur before import of `../a`',
}],
}),
// Alphabetize with require
...semver.satisfies(eslintPkg.version, '< 3.0.0') ? [] : [
test({
code: `
const { cello } = require('./cello');
import { int } from './int';
const blah = require('./blah');
import { hello } from './hello';
`,
output: `
import { int } from './int';
const { cello } = require('./cello');
const blah = require('./blah');
import { hello } from './hello';
`,
errors: [{
message: '`./int` import should occur before import of `./cello`',
}, {
message: '`./hello` import should occur before import of `./cello`',
}],
}),
],
].filter((t) => !!t),
});
context('TypeScript', function () {
getNonDefaultParsers()
.filter((parser) => parser !== require.resolve('typescript-eslint-parser'))
.forEach((parser) => {
const parserConfig = {
parser: parser,
settings: {
'import/parsers': { [parser]: ['.ts'] },
'import/resolver': { 'eslint-import-resolver-typescript': true },
},
};
ruleTester.run('order', rule, {
valid: [
// #1667: typescript type import support
// Option alphabetize: {order: 'asc'}
test(
{
code: `
import c from 'Bar';
import type { C } from 'Bar';
import b from 'bar';
import a from 'foo';
import type { A } from 'foo';
import index from './';
`,
parser,
options: [
{
groups: ['external', 'index'],
alphabetize: { order: 'asc' },
},
],
},
parserConfig,
),
// Option alphabetize: {order: 'desc'}
test(
{
code: `
import a from 'foo';
import type { A } from 'foo';
import b from 'bar';
import c from 'Bar';
import type { C } from 'Bar';
import index from './';
`,
parser,
options: [
{
groups: ['external', 'index'],
alphabetize: { order: 'desc' },
},
],
},
parserConfig,
),
// Option alphabetize: {order: 'asc'} with type group
test(
{
code: `
import c from 'Bar';
import b from 'bar';
import a from 'foo';
import index from './';
import type { C } from 'Bar';
import type { A } from 'foo';
`,
parser,
options: [
{
groups: ['external', 'index', 'type'],
alphabetize: { order: 'asc' },
},
],
},
parserConfig,
),
// Option alphabetize: {order: 'asc'} with type group & path group
test(
{
// only: true,
code: `
import c from 'Bar';
import a from 'foo';
import b from 'dirA/bar';
import index from './';
import type { C } from 'dirA/Bar';
import type { A } from 'foo';
`,
parser,
options: [
{
alphabetize: { order: 'asc' },
groups: ['external', 'internal', 'index', 'type'],
pathGroups: [
{
pattern: 'dirA/**',
group: 'internal',
},
],
'newlines-between': 'always',
pathGroupsExcludedImportTypes: ['type'],
},
],
},
parserConfig,
),
// Option alphabetize: {order: 'asc'} with path group
test(
{
// only: true,
code: `
import c from 'Bar';
import type { A } from 'foo';
import a from 'foo';
import type { C } from 'dirA/Bar';
import b from 'dirA/bar';
import index from './';
`,
parser,
options: [
{
alphabetize: { order: 'asc' },
groups: ['external', 'internal', 'index'],
pathGroups: [
{
pattern: 'dirA/**',
group: 'internal',
},
],
'newlines-between': 'always',
pathGroupsExcludedImportTypes: [],
},
],
},
parserConfig,
),
// Option alphabetize: {order: 'desc'} with type group
test(
{
code: `
import a from 'foo';
import b from 'bar';
import c from 'Bar';
import index from './';
import type { A } from 'foo';
import type { C } from 'Bar';
`,
parser,
options: [
{
groups: ['external', 'index', 'type'],
alphabetize: { order: 'desc' },
},
],
},
parserConfig,
),
test(
{
code: `
import { Partner } from '@models/partner/partner';
import { PartnerId } from '@models/partner/partner-id';
`,
parser,
options: [
{
alphabetize: { order: 'asc' },
},
],
},
parserConfig,
),
test(
{
code: `
import { serialize, parse, mapFieldErrors } from '@vtaits/form-schema';
import type { GetFieldSchema } from '@vtaits/form-schema';
import { useMemo, useCallback } from 'react';
import type { ReactElement, ReactNode } from 'react';
import { Form } from 'react-final-form';
import type { FormProps as FinalFormProps } from 'react-final-form';
`,
parser,
options: [
{
alphabetize: { order: 'asc' },
},
],
},
parserConfig,
),
],
invalid: [
// Option alphabetize: {order: 'asc'}
test(
{
code: `
import b from 'bar';
import c from 'Bar';
import type { C } from 'Bar';
import a from 'foo';
import type { A } from 'foo';
import index from './';
`,
output: `
import c from 'Bar';
import type { C } from 'Bar';
import b from 'bar';
import a from 'foo';
import type { A } from 'foo';
import index from './';
`,
parser,
options: [
{
groups: ['external', 'index'],
alphabetize: { order: 'asc' },
},
],
errors: [
{
message: semver.satisfies(eslintPkg.version, '< 3')
? '`bar` import should occur after import of `Bar`'
: /(`bar` import should occur after import of `Bar`)|(`Bar` import should occur before import of `bar`)/,
},
],
},
parserConfig,
),
// Option alphabetize: {order: 'desc'}
test(
{
code: `
import a from 'foo';
import type { A } from 'foo';
import c from 'Bar';
import type { C } from 'Bar';
import b from 'bar';
import index from './';
`,
output: `
import a from 'foo';
import type { A } from 'foo';
import b from 'bar';
import c from 'Bar';
import type { C } from 'Bar';
import index from './';
`,
parser,
options: [
{
groups: ['external', 'index'],
alphabetize: { order: 'desc' },
},
],
errors: [
{
message: semver.satisfies(eslintPkg.version, '< 3')
? '`bar` import should occur before import of `Bar`'
: /(`bar` import should occur before import of `Bar`)|(`Bar` import should occur after import of `bar`)/,
},
],
},
parserConfig,
),
// Option alphabetize: {order: 'asc'} with type group
test(
{
code: `
import b from 'bar';
import c from 'Bar';
import a from 'foo';
import index from './';
import type { A } from 'foo';
import type { C } from 'Bar';
`,
output: `
import c from 'Bar';
import b from 'bar';
import a from 'foo';
import index from './';
import type { C } from 'Bar';
import type { A } from 'foo';
`,
parser,
options: [
{
groups: ['external', 'index', 'type'],
alphabetize: { order: 'asc' },
},
],
errors: semver.satisfies(eslintPkg.version, '< 3') ? [
{ message: '`Bar` import should occur before import of `bar`' },
{ message: '`Bar` import should occur before import of `foo`' },
] : [
{ message: /(`Bar` import should occur before import of `bar`)|(`bar` import should occur after import of `Bar`)/ },
{ message: /(`Bar` import should occur before import of `foo`)|(`foo` import should occur after import of `Bar`)/ },
],
},
parserConfig,
),
// Option alphabetize: {order: 'desc'} with type group
test(
{
code: `
import a from 'foo';
import c from 'Bar';
import b from 'bar';
import index from './';
import type { C } from 'Bar';
import type { A } from 'foo';
`,
output: `
import a from 'foo';
import b from 'bar';
import c from 'Bar';
import index from './';
import type { A } from 'foo';
import type { C } from 'Bar';
`,
parser,
options: [
{
groups: ['external', 'index', 'type'],
alphabetize: { order: 'desc' },
},
],
errors: semver.satisfies(eslintPkg.version, '< 3') ? [
{ message: '`bar` import should occur before import of `Bar`' },
{ message: '`foo` import should occur before import of `Bar`' },
] : [
{ message: /(`bar` import should occur before import of `Bar`)|(`Bar` import should occur after import of `bar`)/ },
{ message: /(`foo` import should occur before import of `Bar`)|(`Bar` import should occur after import of `foo`)/ },
],
},
parserConfig,
),
// warns for out of order unassigned imports (warnOnUnassignedImports enabled)
test({
code: `
import './local1';
import global from 'global1';
import local from './local2';
import 'global2';
`,
output: `
import './local1';
import global from 'global1';
import local from './local2';
import 'global2';
`,
errors: [
{
message: '`global1` import should occur before import of `./local1`',
},
{
message: '`global2` import should occur before import of `./local1`',
},
],
options: [{ warnOnUnassignedImports: true }],
}),
// fix cannot move below unassigned import (warnOnUnassignedImports enabled)
test({
code: `
import local from './local';
import 'global1';
import global2 from 'global2';
import global3 from 'global3';
`,
output: `
import local from './local';
import 'global1';
import global2 from 'global2';
import global3 from 'global3';
`,
errors: [{
message: '`./local` import should occur after import of `global3`',
}],
options: [{ warnOnUnassignedImports: true }],
}),
],
});
});
});
|
import { connect } from 'react-redux';
import Search from './presenter';
import { Nt } from '../../utils/ntseq';
import * as actions from '../../modules/search';
import { multiSelect } from '../../modules/selection';
const mapStateToProps = state => {
const search = state.search;
return {
value: search.value,
matches: search.matches,
};
};
const mapDispatchToProps = (dispatch, ownProps) => ({
onChange: event => {
const q = new Nt.Seq().read(event.target.value);
const len = event.target.value.length;
const matches = ownProps.ntSequence
.mapSequence(q)
.results()
.filter(result => 0 < result.matches && len <= result.matches);
dispatch(actions.search(event.target.value, matches.length));
dispatch(
multiSelect(
matches.map(m => ({
from: m.pos,
to: m.pos + len - 1,
}))
)
);
},
});
export default connect(mapStateToProps, mapDispatchToProps)(Search);
|
'use strict';
const assert = require('assert');
const fs = require('fs');
const ntwitch = require('../index');
//{
// credentials: {
// id: '<id>',
// secret: '<secret>',
// uri: '<uri>',
// token: '<token>',
// },
// data: {
// user: 'test_user1',
// channel: 'test_user1',
// team: 'test',
// }
// }
const config = require('./test-config');
const user = config.data.user;
const channel = config.data.channel;
const team = config.data.team;
describe('Client', function() {
var client = ntwitch(config.credentials);
this.timeout(client.timeout + 1000);
this.slow(client.timeout);
describe('.getAuthUrl()', function() {
it('basic', function() {
var uri = client.getAuthUrl();
assert(uri);
});
it('with scopes', function() {
var uri = client.getAuthUrl({
scope: [
'user_read',
'user_blocks_edit',
'user_blocks_read',
'user_follows_edit',
'channel_read',
'channel_editor',
'channel_commercial',
'channel_stream',
'channel_subscriptions',
'user_subscriptions',
'channel_check_subscription',
'chat_login'
]
});
assert(uri);
});
});
var tests = [
// blocks.md
//{ name: 'getBlocks', args: [user] },
//{ name: 'addBlock', args: [user, target] },
//{ name: 'removeBlock', args: [user, target] },
// channels.md
{ name: 'getChannel', args: [channel] },
//{ name: 'getMyChannel', args: [channel] },
//{ name: 'getChannelEditors', args: [channel] },
//{ name: 'updateChannel', args: [channel, data] },
//{ name: 'resetStreamKey', args: [channel] },
//{ name: 'runCommercial', args: [channel, length] },
{ name: 'getChannelTeams', args: [channel] },
// chat.md
//{ name: 'getChatLinks', args: [channel] },
{ name: 'getChatBadges', args: [channel] },
{ name: 'getEmotes', args: [] },
{ name: 'getEmoteImages', args: [] },
// follows.md
{ name: 'getFollowers', args: [channel] },
{ name: 'getFollowedChannels', args: [user] },
//{ name: 'getFollowStatus', args: [user, channel] },
//{ name: 'followChannel', args: [user, channel] },
//{ name: 'unfollowChannel', args: [user, channel] },
// games.md
{ name: 'getTopGames', args: [] },
// ingests.md
{ name: 'getIngests', args: [] },
// root.md
{ name: 'getRoot', args: [] },
// search.md
{ name: 'searchChannels', args: [channel] },
{ name: 'searchStreams', args: [channel] },
{ name: 'searchGames', args: ['Destiny'] },
// streams.md
{ name: 'getStream', args: [channel] },
{ name: 'getStreams', args: [] },
{ name: 'getFeaturedStreams', args: [] },
{ name: 'getStreamSummary', args: [] },
// subscriptions.md
//{ name: 'getSubscribers', args: [channel] },
//{ name: 'getSubscriberStatus', args: [channel, user] },
//{ name: 'getSubscriberStatus2', args: [user, channel] },
// teams.md
{ name: 'getTeams', args: [] },
{ name: 'getTeam', args: [team] },
// users.md
{ name: 'getUser', args: [user] },
//{ name: 'getMyUser', args: [] },
//{ name: 'getFollowedStreams', args: [] },
//{ name: 'getFollowedVideos', args: [] },
// videos.md
//{ name: 'getVideo', args: [videoId] },
{ name: 'getTopVideos', args: [] },
{ name: 'getChannelVideos', args: [channel] },
];
tests.forEach((test) => {
describe(`.${test.name}()`, function() {
it (`(${test.args.join(', ')})`, function(done) {
client[test.name].apply(client, test.args)
.then((data) => {
assert(data);
done();
})
.catch(done);
});
});
});
});
|
import config from '../config'
import compile from 'react-esc/bin/compile'
(async function () {
await compile(config)
})()
|
import $ from 'jquery';
import SC from 'soundcloud';
import SoundCloudAudio from 'soundcloud-audio';
$(document).ready(function () {
const client_id = '4a39a5fc90a81d598101eeaf122056bc';
SC.initialize({
client_id : client_id
});
// TODO find a better way to stream soundcloud tracks
var scPlayer = new SoundCloudAudio(client_id);
SC.get('/users/1987006/tracks').then((tracks) => {
console.log("tracks: ", tracks);
const getTrackTemplate = tracks.map((track)=> {
const imgUrl = track.artwork_url === null ? '/img/noImage.png' : track.artwork_url;
const imgTag = `<a class="track-icon" data-url="${track.id}"><img src="${imgUrl}" /><i class="fa"></i></a>`;
return `<div class="track">${imgTag}<div class="track-info"><h3 class="artist">zeesarOne</h3><span class="track-title">${track.title}</span></div></div>`;
});
$('.tracks-wrapper').append(getTrackTemplate);
const $trackIcon = $('.track-icon');
$trackIcon.on('click', function () {
const url = $(this).data('url');
if (!$(this).hasClass('playing')) {
$trackIcon.each(function () {
if ($trackIcon.hasClass('playing')) {
$trackIcon.removeClass('playing');
}
});
scPlayer.play({streamUrl : `https://api.soundcloud.com/tracks/${url}/stream`});
$(this).addClass('playing');
} else {
scPlayer.stop();
$(this).removeClass('playing');
}
});
});
});
|
define(["require", "exports", 'durandal/app', 'knockout'], function(require, exports, app, ko) {
var Models;
(function (Models) {
var CartLine = (function () {
function CartLine() {
var _this = this;
this.category = ko.observable('');
this.product = ko.observable(null);
this.quantity = ko.observable(1);
this.subtotal = ko.computed(function () {
return _this.product() ? _this.product().price * parseInt("0" + _this.quantity(), 10) : 0;
});
}
return CartLine;
})();
Models.CartLine = CartLine;
var Cart = (function () {
function Cart() {
var _this = this;
this.lines = ko.observableArray([new CartLine()]);
this.grandTotal = ko.computed(function () {
var total = 0;
ko.utils.arrayForEach(_this.lines(), function (line) {
return total += line.subtotal();
});
return total;
});
this.addLine = function () {
_this.lines.push(new CartLine());
};
this.removeLine = function (line) {
_this.lines.remove(line);
};
this.save = function () {
var dataToSave = ko.utils.arrayMap(_this.lines(), function (line) {
return line.product() ? {
productName: line.product().name,
quantity: line.quantity()
} : undefined;
});
app.showMessage('You could now send this to server: ' + JSON.stringify(dataToSave), 'Your Shopping Cart');
};
}
return Cart;
})();
Models.Cart = Cart;
})(Models || (Models = {}));
return Models;
});
//# sourceMappingURL=models.js.map
|
(function (console, $hx_exports) { "use strict";
$hx_exports.hxGeomAlgo = $hx_exports.hxGeomAlgo || {};
var $estr = function() { return js_Boot.__string_rec(this,''); };
var HxOverrides = function() { };
HxOverrides.__name__ = true;
HxOverrides.iter = function(a) {
return { cur : 0, arr : a, hasNext : function() {
return this.cur < this.arr.length;
}, next : function() {
return this.arr[this.cur++];
}};
};
Math.__name__ = true;
var Std = function() { };
Std.__name__ = true;
Std.string = function(s) {
return js_Boot.__string_rec(s,"");
};
var Type = function() { };
Type.__name__ = true;
Type.getEnumName = function(e) {
var a = e.__ename__;
return a.join(".");
};
var haxe_IMap = function() { };
haxe_IMap.__name__ = true;
var haxe_ds_IntMap = function() {
this.h = { };
};
haxe_ds_IntMap.__name__ = true;
haxe_ds_IntMap.__interfaces__ = [haxe_IMap];
haxe_ds_IntMap.prototype = {
keys: function() {
var a = [];
for( var key in this.h ) {
if(this.h.hasOwnProperty(key)) a.push(key | 0);
}
return HxOverrides.iter(a);
}
};
var hxGeomAlgo_Debug = function() { };
hxGeomAlgo_Debug.__name__ = true;
hxGeomAlgo_Debug.assert = function(cond,message,pos) {
return;
};
var hxGeomAlgo_HomogCoord = function(x,y,w) {
if(w == null) w = 1;
if(y == null) y = 0;
if(x == null) x = 0;
this.x = x;
this.y = y;
this.w = w;
};
hxGeomAlgo_HomogCoord.__name__ = true;
hxGeomAlgo_HomogCoord.det = function(p,q,r) {
return p.w * q.perpdot(r) - q.w * p.perpdot(r) + r.w * p.perpdot(q);
};
hxGeomAlgo_HomogCoord.ccw = function(p,q,r) {
return hxGeomAlgo_HomogCoord.det(p,q,r) > 0;
};
hxGeomAlgo_HomogCoord.cw = function(p,q,r) {
return hxGeomAlgo_HomogCoord.det(p,q,r) < 0;
};
hxGeomAlgo_HomogCoord.prototype = {
add: function(p) {
this.x += p.x;
this.y += p.y;
return this;
}
,sub: function(p) {
this.x -= p.x;
this.y -= p.y;
return this;
}
,neg: function() {
this.w = -this.w;
this.x = -this.x;
this.y = -this.y;
return this;
}
,mul: function(m) {
this.w *= m;
this.x *= m;
this.y *= m;
return this;
}
,div: function(m) {
this.w /= m;
this.x /= m;
this.y /= m;
return this;
}
,normalize: function() {
return this.div(this.length());
}
,lengthSquared: function() {
return this.x * this.x + this.y * this.y;
}
,length: function() {
return Math.sqrt(this.lengthSquared());
}
,perp: function() {
var tmp = -this.y;
this.y = this.x;
this.x = tmp;
return this;
}
,dotPoint: function(p) {
return this.w + this.x * p.x + this.y * p.y;
}
,dot: function(p) {
return this.w * p.w + this.x * p.x + this.y * p.y;
}
,perpdot: function(p) {
return this.x * p.y - this.y * p.x;
}
,dotperp: function(p) {
return -this.x * p.y + this.y * p.x;
}
,equals: function(p) {
return p.w * this.x == this.w * p.x && p.w * this.y == this.w * p.y;
}
,left: function(p) {
return this.dotPoint(p) > 0;
}
,right: function(p) {
return this.dotPoint(p) < 0;
}
,toScreen: function() {
return hxGeomAlgo__$HxPoint_HxPoint_$Impl_$._new(this.x / this.w,-this.y / this.w);
}
,toPoint: function() {
return hxGeomAlgo__$HxPoint_HxPoint_$Impl_$._new(this.x / this.w,this.y / this.w);
}
,meet: function(p) {
return new hxGeomAlgo_HomogCoord(p.w * this.y - this.w * p.y,this.w * p.x - p.w * this.x,this.x * p.y - this.y * p.x);
}
,meetPoint: function(p) {
return new hxGeomAlgo_HomogCoord(this.y - this.w * p.y,this.w * p.x - this.x,this.x * p.y - this.y * p.x);
}
,toString: function() {
return " (w:" + this.w + "; x:" + this.x + ", y:" + this.y + ") ";
}
};
var hxGeomAlgo__$HxPoint_HxPoint_$Impl_$ = {};
hxGeomAlgo__$HxPoint_HxPoint_$Impl_$.__name__ = true;
hxGeomAlgo__$HxPoint_HxPoint_$Impl_$.get_x = function(this1) {
return this1.x;
};
hxGeomAlgo__$HxPoint_HxPoint_$Impl_$.set_x = function(this1,value) {
return this1.x = value;
};
hxGeomAlgo__$HxPoint_HxPoint_$Impl_$.get_y = function(this1) {
return this1.y;
};
hxGeomAlgo__$HxPoint_HxPoint_$Impl_$.set_y = function(this1,value) {
return this1.y = value;
};
hxGeomAlgo__$HxPoint_HxPoint_$Impl_$._new = function(x,y) {
if(y == null) y = 0;
if(x == null) x = 0;
return new hxGeomAlgo_HxPointData(x,y);
};
hxGeomAlgo__$HxPoint_HxPoint_$Impl_$.setTo = function(this1,newX,newY) {
this1.x = newX;
this1.y = newY;
};
hxGeomAlgo__$HxPoint_HxPoint_$Impl_$.equals = function(this1,p) {
return p != null && this1.x == p.x && this1.y == p.y;
};
hxGeomAlgo__$HxPoint_HxPoint_$Impl_$.clone = function(this1) {
return hxGeomAlgo__$HxPoint_HxPoint_$Impl_$._new(this1.x,this1.y);
};
hxGeomAlgo__$HxPoint_HxPoint_$Impl_$.toString = function(this1) {
return "(" + this1.x + ", " + this1.y + ")";
};
hxGeomAlgo__$HxPoint_HxPoint_$Impl_$.fromPointStruct = function(p) {
return hxGeomAlgo__$HxPoint_HxPoint_$Impl_$._new(p.x,p.y);
};
hxGeomAlgo__$HxPoint_HxPoint_$Impl_$.toPointStruct = function(this1) {
return { x : this1.x, y : this1.y};
};
var hxGeomAlgo_HxPointData = function(x,y) {
if(y == null) y = 0;
if(x == null) x = 0;
this.x = x;
this.y = y;
};
hxGeomAlgo_HxPointData.__name__ = true;
hxGeomAlgo_HxPointData.prototype = {
toString: function() {
return "(" + this.x + ", " + this.y + ")";
}
};
var hxGeomAlgo_PairDeque = function() {
this.lastIdx = this.frontTopIdx = -1;
this.backTopIdx = 0;
this.front = [];
this.back = [];
};
hxGeomAlgo_PairDeque.__name__ = true;
hxGeomAlgo_PairDeque.prototype = {
push: function(i,j) {
if(this.front.length <= ++this.frontTopIdx) {
this.front.push(-1);
this.back.push(-1);
}
this.front[this.frontTopIdx] = i;
this.back[this.frontTopIdx] = j;
this.lastIdx = this.frontTopIdx;
}
,pushNarrow: function(i,j) {
if(!this.isFrontEmpty() && i <= this.frontTop()) return;
while(!this.isFrontEmpty() && this.backBottom() >= j) this.popFront();
this.push(i,j);
}
,isFrontEmpty: function() {
return this.frontTopIdx < 0;
}
,frontHasNext: function() {
return this.frontTopIdx > 0;
}
,flush: function() {
this.lastIdx = this.frontTopIdx = -1;
}
,frontTop: function() {
if(this.frontTopIdx < 0) return 0;
return this.front[this.frontTopIdx];
}
,frontPeekNext: function() {
return this.front[this.frontTopIdx - 1];
}
,backBottom: function() {
return this.back[this.frontTopIdx];
}
,popFront: function() {
return this.front[this.frontTopIdx--];
}
,restore: function() {
this.backTopIdx = 0;
this.frontTopIdx = this.lastIdx;
}
,isBackEmpty: function() {
return this.backTopIdx > this.lastIdx;
}
,backHasNext: function() {
return this.backTopIdx < this.lastIdx;
}
,frontBottom: function() {
return this.front[this.backTopIdx];
}
,backPeekNext: function() {
return this.back[this.backTopIdx + 1];
}
,backTop: function() {
return this.back[this.backTopIdx];
}
,popBack: function() {
return this.back[this.backTopIdx++];
}
,toString: function() {
var stringBuffer_b = "";
stringBuffer_b += Std.string("fp:" + this.frontTopIdx + ", bp:" + this.backTopIdx + ", last:" + this.lastIdx + ": ");
var _g1 = 0;
var _g = this.lastIdx + 1;
while(_g1 < _g) {
var i = _g1++;
stringBuffer_b += Std.string(this.front[i] + "," + this.back[i] + " ");
}
return stringBuffer_b;
}
};
var hxGeomAlgo_PolyTools = $hx_exports.hxGeomAlgo.PolyTools = function() { };
hxGeomAlgo_PolyTools.__name__ = true;
hxGeomAlgo_PolyTools.isCCW = function(poly) {
if(poly.length <= 2) return true;
var signedArea = 0.;
var _g1 = 0;
var _g = poly.length;
while(_g1 < _g) {
var i = _g1++;
signedArea += (function($this) {
var $r;
var this1 = hxGeomAlgo_PolyTools.at(poly,i - 1);
$r = this1.x;
return $r;
}(this)) * poly[i].y - poly[i].x * (function($this) {
var $r;
var this2 = hxGeomAlgo_PolyTools.at(poly,i - 1);
$r = this2.y;
return $r;
}(this));
}
return signedArea < 0;
};
hxGeomAlgo_PolyTools.makeCCW = function(poly) {
var reversed = false;
if(!hxGeomAlgo_PolyTools.isCCW(poly)) {
poly.reverse();
reversed = true;
}
return reversed;
};
hxGeomAlgo_PolyTools.makeCW = function(poly) {
var reversed = false;
if(hxGeomAlgo_PolyTools.isCCW(poly)) {
poly.reverse();
reversed = true;
}
return reversed;
};
hxGeomAlgo_PolyTools.isConvex = function(poly) {
var isPositive = null;
var _g1 = 0;
var _g = poly.length;
while(_g1 < _g) {
var i = _g1++;
var lower;
if(i == 0) lower = poly.length - 1; else lower = i - 1;
var middle = i;
var upper;
if(i == poly.length - 1) upper = 0; else upper = i + 1;
var dx0 = poly[middle].x - poly[lower].x;
var dy0 = poly[middle].y - poly[lower].y;
var dx1 = poly[upper].x - poly[middle].x;
var dy1 = poly[upper].y - poly[middle].y;
var cross = dx0 * dy1 - dx1 * dy0;
var newIsPositive;
if(cross > 0) newIsPositive = true; else newIsPositive = false;
if(cross == 0) continue;
if(isPositive == null) isPositive = newIsPositive; else if(isPositive != newIsPositive) return false;
}
return true;
};
hxGeomAlgo_PolyTools.isSimple = function(poly) {
var len = poly.length;
if(len <= 3) return true;
var _g = 0;
while(_g < len) {
var i = _g++;
var p0 = i;
var p1;
if(i == len - 1) p1 = 0; else p1 = i + 1;
var _g1 = i + 1;
while(_g1 < len) {
var j = _g1++;
var q0 = j;
var q1;
if(j == len - 1) q1 = 0; else q1 = j + 1;
var intersection = hxGeomAlgo_PolyTools.segmentIntersect(poly[p0],poly[p1],poly[q0],poly[q1]);
if(intersection != null && !(hxGeomAlgo_PolyTools.distance(intersection,poly[p0]) < hxGeomAlgo_PolyTools.EPSILON || hxGeomAlgo_PolyTools.distance(intersection,poly[p1]) < hxGeomAlgo_PolyTools.EPSILON) && !(hxGeomAlgo_PolyTools.distance(intersection,poly[q0]) < hxGeomAlgo_PolyTools.EPSILON || hxGeomAlgo_PolyTools.distance(intersection,poly[q1]) < hxGeomAlgo_PolyTools.EPSILON)) return false;
}
}
return true;
};
hxGeomAlgo_PolyTools.segmentIntersect = function(p0,p1,q0,q1) {
var intersectionPoint;
var a1;
var a2;
var b1;
var b2;
var c1;
var c2;
a1 = p1.y - p0.y;
b1 = p0.x - p1.x;
c1 = p1.x * p0.y - p0.x * p1.y;
a2 = q1.y - q0.y;
b2 = q0.x - q1.x;
c2 = q1.x * q0.y - q0.x * q1.y;
var denom = a1 * b2 - a2 * b1;
if(denom == 0) return null;
intersectionPoint = hxGeomAlgo__$HxPoint_HxPoint_$Impl_$._new();
intersectionPoint.x = (b1 * c2 - b2 * c1) / denom;
intersectionPoint.y = (a2 * c1 - a1 * c2) / denom;
var p0p1 = hxGeomAlgo_PolyTools.sqr(p0.x - p1.x) + hxGeomAlgo_PolyTools.sqr(p0.y - p1.y);
var q0q1 = hxGeomAlgo_PolyTools.sqr(q0.x - q1.x) + hxGeomAlgo_PolyTools.sqr(q0.y - q1.y);
if(hxGeomAlgo_PolyTools.sqr(intersectionPoint.x - p1.x) + hxGeomAlgo_PolyTools.sqr(intersectionPoint.y - p1.y) > p0p1) return null;
if(hxGeomAlgo_PolyTools.sqr(intersectionPoint.x - p0.x) + hxGeomAlgo_PolyTools.sqr(intersectionPoint.y - p0.y) > p0p1) return null;
if(hxGeomAlgo_PolyTools.sqr(intersectionPoint.x - q1.x) + hxGeomAlgo_PolyTools.sqr(intersectionPoint.y - q1.y) > q0q1) return null;
if(hxGeomAlgo_PolyTools.sqr(intersectionPoint.x - q0.x) + hxGeomAlgo_PolyTools.sqr(intersectionPoint.y - q0.y) > q0q1) return null;
return intersectionPoint;
};
hxGeomAlgo_PolyTools.findDuplicatePoints = function(poly,consecutiveOnly,wrapAround) {
if(wrapAround == null) wrapAround = true;
if(consecutiveOnly == null) consecutiveOnly = true;
var len = poly.length;
if(len <= 1) return [];
var dupIndices = [];
var _g1 = 0;
var _g = len - 1;
while(_g1 < _g) {
var i = _g1++;
var j = i + 1;
while(j < len) {
var foundDup;
var this1 = poly[i];
var p = poly[j];
foundDup = p != null && this1.x == p.x && this1.y == p.y;
if(foundDup) dupIndices.push(i);
if(consecutiveOnly || foundDup && !consecutiveOnly) break;
j++;
}
}
if(wrapAround && consecutiveOnly && (function($this) {
var $r;
var this2 = poly[0];
var p1 = poly[len - 1];
$r = p1 != null && this2.x == p1.x && this2.y == p1.y;
return $r;
}(this))) dupIndices.push(len - 1);
return dupIndices;
};
hxGeomAlgo_PolyTools.intersection = function(p1,p2,q1,q2) {
var res = null;
var a1 = p2.y - p1.y;
var b1 = p1.x - p2.x;
var c1 = a1 * p1.x + b1 * p1.y;
var a2 = q2.y - q1.y;
var b2 = q1.x - q2.x;
var c2 = a2 * q1.x + b2 * q1.y;
var det = a1 * b2 - a2 * b1;
if(!(Math.abs(det) <= hxGeomAlgo_PolyTools.EPSILON)) {
res = hxGeomAlgo__$HxPoint_HxPoint_$Impl_$._new();
res.x = (b2 * c1 - b1 * c2) / det;
res.y = (a1 * c2 - a2 * c1) / det;
}
return res;
};
hxGeomAlgo_PolyTools.isReflex = function(poly,idx) {
return hxGeomAlgo_PolyTools.isRight(hxGeomAlgo_PolyTools.at(poly,idx - 1),hxGeomAlgo_PolyTools.at(poly,idx),hxGeomAlgo_PolyTools.at(poly,idx + 1));
};
hxGeomAlgo_PolyTools.at = function(poly,idx) {
var len = poly.length;
while(idx < 0) idx += len;
return poly[idx % len];
};
hxGeomAlgo_PolyTools.side = function(p,a,b) {
return (a.x - p.x) * (b.y - p.y) - (b.x - p.x) * (a.y - p.y);
};
hxGeomAlgo_PolyTools.isLeft = function(p,a,b) {
return (a.x - p.x) * (b.y - p.y) - (b.x - p.x) * (a.y - p.y) > 0;
};
hxGeomAlgo_PolyTools.isLeftOrOn = function(p,a,b) {
return (a.x - p.x) * (b.y - p.y) - (b.x - p.x) * (a.y - p.y) >= 0;
};
hxGeomAlgo_PolyTools.isRight = function(p,a,b) {
return (a.x - p.x) * (b.y - p.y) - (b.x - p.x) * (a.y - p.y) < 0;
};
hxGeomAlgo_PolyTools.isRightOrOn = function(p,a,b) {
return (a.x - p.x) * (b.y - p.y) - (b.x - p.x) * (a.y - p.y) <= 0;
};
hxGeomAlgo_PolyTools.isCollinear = function(p,a,b) {
return (a.x - p.x) * (b.y - p.y) - (b.x - p.x) * (a.y - p.y) == 0;
};
hxGeomAlgo_PolyTools.distance = function(v,w) {
return Math.sqrt(hxGeomAlgo_PolyTools.sqr(v.x - w.x) + hxGeomAlgo_PolyTools.sqr(v.y - w.y));
};
hxGeomAlgo_PolyTools.distanceToSegment = function(p,v,w) {
return Math.sqrt(hxGeomAlgo_PolyTools.distanceToSegmentSquared(p,v,w));
};
hxGeomAlgo_PolyTools.distanceSquared = function(v,w) {
return hxGeomAlgo_PolyTools.sqr(v.x - w.x) + hxGeomAlgo_PolyTools.sqr(v.y - w.y);
};
hxGeomAlgo_PolyTools.distanceToSegmentSquared = function(p,v,w) {
var l2 = hxGeomAlgo_PolyTools.sqr(v.x - w.x) + hxGeomAlgo_PolyTools.sqr(v.y - w.y);
if(l2 == 0) return hxGeomAlgo_PolyTools.sqr(p.x - v.x) + hxGeomAlgo_PolyTools.sqr(p.y - v.y);
var t = ((p.x - v.x) * (w.x - v.x) + (p.y - v.y) * (w.y - v.y)) / l2;
if(t < 0) return hxGeomAlgo_PolyTools.sqr(p.x - v.x) + hxGeomAlgo_PolyTools.sqr(p.y - v.y);
if(t > 1) return hxGeomAlgo_PolyTools.sqr(p.x - w.x) + hxGeomAlgo_PolyTools.sqr(p.y - w.y);
hxGeomAlgo__$HxPoint_HxPoint_$Impl_$.setTo(hxGeomAlgo_PolyTools.point,v.x + t * (w.x - v.x),v.y + t * (w.y - v.y));
return hxGeomAlgo_PolyTools.distanceSquared(p,hxGeomAlgo_PolyTools.point);
};
hxGeomAlgo_PolyTools.meet = function(p,q) {
return new hxGeomAlgo_HomogCoord(p.y - q.y,q.x - p.x,p.x * q.y - p.y * q.x);
};
hxGeomAlgo_PolyTools.dot = function(p,q) {
return p.x * q.x + p.y * q.y;
};
hxGeomAlgo_PolyTools.sqr = function(x) {
return x * x;
};
hxGeomAlgo_PolyTools.eq = function(a,b) {
return Math.abs(a - b) <= hxGeomAlgo_PolyTools.EPSILON;
};
hxGeomAlgo_PolyTools.clear = function(array) {
array.length = 0;
};
hxGeomAlgo_PolyTools.toFloatArray = function(poly,out) {
if(out != null) out = out; else out = [];
var _g = 0;
while(_g < poly.length) {
var p = poly[_g];
++_g;
out.push(p.x);
out.push(p.y);
}
return out;
};
hxGeomAlgo_PolyTools.reverseFloatArray = function(poly,inPlace) {
if(inPlace == null) inPlace = false;
var res;
if(inPlace) res = poly; else res = [];
var nPoints = poly.length >> 1;
var _g = 0;
while(_g < nPoints) {
var i = _g++;
var xPos = (nPoints - i - 1) * 2;
res[i * 2] = poly[xPos];
res[i * 2 + 1] = poly[xPos + 1];
}
return res;
};
hxGeomAlgo_PolyTools.flatten = function(array,out) {
var res;
if(out != null) res = out; else res = [];
var _g = 0;
while(_g < array.length) {
var arr = array[_g];
++_g;
var _g1 = 0;
while(_g1 < arr.length) {
var item = arr[_g1];
++_g1;
res.push(item);
}
}
return res;
};
hxGeomAlgo_PolyTools.toPointArray = function(poly,out) {
if(out != null) out = out; else out = [];
var size = poly.length;
if(poly.length % 2 == 1) size--;
var _g1 = 0;
var _g = size >> 1;
while(_g1 < _g) {
var i = _g1++;
out.push(hxGeomAlgo__$HxPoint_HxPoint_$Impl_$._new(poly[i * 2],poly[i * 2 + 1]));
}
return out;
};
hxGeomAlgo_PolyTools.inflateLine = function(start,end,thickness) {
var halfWidth = thickness / 2;
var dx = end.x - start.x;
var dy = end.y - start.y;
var len = Math.sqrt(dx * dx + dy * dy);
var nx = dx / len * halfWidth;
var ny = dy / len * halfWidth;
return [hxGeomAlgo__$HxPoint_HxPoint_$Impl_$._new(start.x - ny,start.y + nx),hxGeomAlgo__$HxPoint_HxPoint_$Impl_$._new(end.x - ny,end.y + nx),hxGeomAlgo__$HxPoint_HxPoint_$Impl_$._new(end.x + ny,end.y - nx),hxGeomAlgo__$HxPoint_HxPoint_$Impl_$._new(start.x + ny,start.y - nx)];
};
hxGeomAlgo_PolyTools.exposeEnum = function(enumClass,$as) {
var dotPath = ($as != null?$as:Type.getEnumName(enumClass)).split(".");
var exports = $hx_exports;
var i = 0;
while(i < dotPath.length - 1) {
var currPath = dotPath[i];
exports[currPath] = exports[currPath] || { };
exports = exports[currPath];
i++;
}
exports[dotPath[i]] = enumClass;
};
var hxGeomAlgo_SnoeyinkKeil = $hx_exports.hxGeomAlgo.SnoeyinkKeil = function() { };
hxGeomAlgo_SnoeyinkKeil.__name__ = true;
hxGeomAlgo_SnoeyinkKeil.decomposePoly = function(simplePoly) {
var res = [];
var indices = hxGeomAlgo_SnoeyinkKeil.decomposePolyIndices(simplePoly);
var _g = 0;
while(_g < indices.length) {
var polyIndices = indices[_g];
++_g;
var currPoly = [];
res.push(currPoly);
var _g1 = 0;
while(_g1 < polyIndices.length) {
var idx = polyIndices[_g1];
++_g1;
currPoly.push(simplePoly[idx]);
}
}
return res;
};
hxGeomAlgo_SnoeyinkKeil.decomposePolyIndices = function(simplePoly) {
var res = [];
if(simplePoly.length < 3) return res;
hxGeomAlgo_SnoeyinkKeil.poly = [];
var _g = 0;
while(_g < simplePoly.length) {
var p = simplePoly[_g];
++_g;
hxGeomAlgo_SnoeyinkKeil.poly.push(hxGeomAlgo__$HxPoint_HxPoint_$Impl_$._new(p.x,p.y));
}
hxGeomAlgo_SnoeyinkKeil.reversed = hxGeomAlgo_PolyTools.makeCW(hxGeomAlgo_SnoeyinkKeil.poly);
var i;
var j;
var k;
var n = hxGeomAlgo_SnoeyinkKeil.poly.length;
var decomp = new hxGeomAlgo_DecompPoly(hxGeomAlgo_SnoeyinkKeil.poly);
decomp.init();
var _g1 = 3;
while(_g1 < n) {
var l = _g1++;
i = decomp.reflexIter();
while(i + l < n) {
if(decomp.visible(i,k = i + l)) {
decomp.initPairs(i,k);
if(decomp.isReflex(k)) {
var _g11 = i + 1;
while(_g11 < k) {
var j1 = _g11++;
decomp.typeA(i,j1,k);
}
} else {
j = decomp.reflexIter(i + 1);
while(j < k - 1) {
decomp.typeA(i,j,k);
j = decomp.reflexNext(j);
}
decomp.typeA(i,k - 1,k);
}
}
i = decomp.reflexNext(i);
}
k = decomp.reflexIter(l);
while(k < n) {
if(!decomp.isReflex(i = k - l) && decomp.visible(i,k)) {
decomp.initPairs(i,k);
decomp.typeB(i,i + 1,k);
j = decomp.reflexIter(i + 2);
while(j < k) {
decomp.typeB(i,j,k);
j = decomp.reflexNext(j);
}
}
k = decomp.reflexNext(k);
}
}
decomp.guard = 3 * n;
decomp.recoverSolution(0,n - 1);
res = decomp.decompIndices();
if(hxGeomAlgo_SnoeyinkKeil.reversed) {
var _g2 = 0;
while(_g2 < res.length) {
var poly = res[_g2];
++_g2;
var _g21 = 0;
var _g12 = poly.length;
while(_g21 < _g12) {
var i1 = _g21++;
poly[i1] = n - poly[i1] - 1;
}
}
}
return res;
};
var hxGeomAlgo_DecompPoly = function(poly) {
this._polys = [];
this._indicesSet = new haxe_ds_IntMap();
this.poly = poly;
this.n = poly.length;
};
hxGeomAlgo_DecompPoly.__name__ = true;
hxGeomAlgo_DecompPoly.prototype = {
init: function() {
this.initReflex();
this.subDecomp = new hxGeomAlgo_SubDecomp(this._reflexFlag);
this.initVisibility();
this.initSubProblems();
}
,initReflex: function() {
this._reflexFlag = [];
this._reflexNext = [];
var _g1 = 0;
var _g = this.n;
while(_g1 < _g) {
var i1 = _g1++;
this._reflexFlag[i1] = false;
this._reflexNext[i1] = -1;
}
var wrap = 0;
this._reflexFlag[wrap] = true;
var i = this.n - 1;
while(i > 0) {
this._reflexFlag[i] = hxGeomAlgo_PolyTools.isRight(hxGeomAlgo_PolyTools.at(this.poly,i - 1),hxGeomAlgo_PolyTools.at(this.poly,i),hxGeomAlgo_PolyTools.at(this.poly,wrap));
wrap = i;
i--;
}
this._reflexFirst = this.n;
i = this.n - 1;
while(i >= 0) {
this._reflexNext[i] = this._reflexFirst;
if(this.isReflex(i)) this._reflexFirst = i;
i--;
}
}
,isReflex: function(i) {
return this._reflexFlag[i];
}
,reflexNext: function(i) {
return this._reflexNext[i];
}
,reflexIter: function(n) {
if(n == null || n <= 0) return this._reflexFirst;
if(n > this._reflexNext.length) return this._reflexNext.length;
return this._reflexNext[n - 1];
}
,visible: function(i,j) {
return this.subDecomp.weight(i,j) < hxGeomAlgo_DecompPoly.BAD;
}
,initVisibility: function() {
var visIndices;
var i = this.reflexIter();
while(i < this.n) {
visIndices = hxGeomAlgo_Visibility.getVisibleIndicesFrom(this.poly,i);
while(visIndices.length > 0) {
var j = visIndices.pop();
if(j < i) this.subDecomp.setWeight(j,i,hxGeomAlgo_DecompPoly.INFINITY); else this.subDecomp.setWeight(i,j,hxGeomAlgo_DecompPoly.INFINITY);
}
i = this._reflexNext[i];
}
}
,setAfter: function(i) {
hxGeomAlgo_Debug.assert(this.isReflex(i),"Non reflex i in setAfter(" + i + ")",{ fileName : "SnoeyinkKeil.hx", lineNumber : 220, className : "hxGeomAlgo.DecompPoly", methodName : "setAfter"});
this.subDecomp.setWeight(i,i + 1,0);
if(this.visible(i,i + 2)) this.subDecomp.initWithWeight(i,i + 2,0,i + 1,i + 1);
}
,setBefore: function(i) {
hxGeomAlgo_Debug.assert(this.isReflex(i),"Non reflex i in setBefore(" + i + ")",{ fileName : "SnoeyinkKeil.hx", lineNumber : 226, className : "hxGeomAlgo.DecompPoly", methodName : "setBefore"});
this.subDecomp.setWeight(i - 1,i,0);
if(this.visible(i - 2,i)) this.subDecomp.initWithWeight(i - 2,i,0,i - 1,i - 1);
}
,initSubProblems: function() {
var i;
i = this.reflexIter();
if(i == 0) {
this.setAfter(i);
i = this._reflexNext[i];
}
if(i == 1) {
this.subDecomp.setWeight(0,1,0);
this.setAfter(i);
i = this._reflexNext[i];
}
while(i < this.n - 2) {
this.setBefore(i);
this.setAfter(i);
i = this._reflexNext[i];
}
if(i == this.n - 2) {
this.setBefore(i);
this.subDecomp.setWeight(i,i + 1,0);
i = this._reflexNext[i];
}
if(i == this.n - 1) this.setBefore(i);
}
,initPairs: function(i,k) {
this.subDecomp.init(i,k);
}
,recoverSolution: function(i,k) {
var j;
this.guard--;
if(k - i <= 1) return;
var pair = this.subDecomp.pairs(i,k);
if(this.isReflex(i)) {
j = pair.backTop();
this.recoverSolution(j,k);
if(j - i > 1) {
if(pair.frontBottom() != pair.backTop()) {
var pd = this.subDecomp.pairs(i,j);
pd.restore();
while(!pd.isBackEmpty() && pair.frontBottom() != pd.frontBottom()) pd.popBack();
}
this.recoverSolution(i,j);
}
} else {
j = pair.frontTop();
this.recoverSolution(i,j);
if(k - j > 1) {
if(pair.frontTop() != pair.backBottom()) {
var pd1 = this.subDecomp.pairs(j,k);
pd1.restore();
while(!pd1.isFrontEmpty() && pair.backBottom() != pd1.backBottom()) pd1.popFront();
}
this.recoverSolution(j,k);
}
}
}
,typeA: function(i,j,k) {
if(!this.visible(i,j)) return;
var top = j;
var w = this.subDecomp.weight(i,j);
if(k - j > 1) {
if(!this.visible(j,k)) return;
w += this.subDecomp.weight(j,k) + 1;
}
if(j - i > 1) {
var pair = this.subDecomp.pairs(i,j);
if(!hxGeomAlgo_PolyTools.isLeft(hxGeomAlgo_PolyTools.at(this.poly,k),hxGeomAlgo_PolyTools.at(this.poly,j),hxGeomAlgo_PolyTools.at(this.poly,pair.backTop()))) {
while(pair.backHasNext() && !hxGeomAlgo_PolyTools.isLeft(hxGeomAlgo_PolyTools.at(this.poly,k),hxGeomAlgo_PolyTools.at(this.poly,j),hxGeomAlgo_PolyTools.at(this.poly,pair.backPeekNext()))) pair.popBack();
if(!pair.isBackEmpty() && !hxGeomAlgo_PolyTools.isRight(hxGeomAlgo_PolyTools.at(this.poly,k),hxGeomAlgo_PolyTools.at(this.poly,i),hxGeomAlgo_PolyTools.at(this.poly,pair.frontBottom()))) top = pair.frontBottom(); else w++;
} else w++;
}
this.update(i,k,w,top,j);
}
,typeB: function(i,j,k) {
if(!this.visible(j,k)) return;
var top = j;
var w = this.subDecomp.weight(j,k);
if(j - i > 1) {
if(!this.visible(i,j)) return;
w += this.subDecomp.weight(i,j) + 1;
}
if(k - j > 1) {
var pair = this.subDecomp.pairs(j,k);
if(!hxGeomAlgo_PolyTools.isRight(hxGeomAlgo_PolyTools.at(this.poly,i),hxGeomAlgo_PolyTools.at(this.poly,j),hxGeomAlgo_PolyTools.at(this.poly,pair.frontTop()))) {
while(pair.frontHasNext() && !hxGeomAlgo_PolyTools.isRight(hxGeomAlgo_PolyTools.at(this.poly,i),hxGeomAlgo_PolyTools.at(this.poly,j),hxGeomAlgo_PolyTools.at(this.poly,pair.frontPeekNext()))) pair.popFront();
if(!pair.isFrontEmpty() && !hxGeomAlgo_PolyTools.isLeft(hxGeomAlgo_PolyTools.at(this.poly,i),hxGeomAlgo_PolyTools.at(this.poly,k),hxGeomAlgo_PolyTools.at(this.poly,pair.backBottom()))) top = pair.backBottom(); else w++;
} else w++;
}
this.update(i,k,w,j,top);
}
,update: function(a,b,w,i,j) {
var ow = this.subDecomp.weight(a,b);
if(w <= ow) {
var pair = this.subDecomp.pairs(a,b);
if(w < ow) {
pair.flush();
this.subDecomp.setWeight(a,b,w);
}
pair.pushNarrow(i,j);
}
}
,_decompByDiags: function(i,k,outIndices,level) {
if(level == null) level = 0;
if(level == 0) {
this._indicesSet.h[0] = true;
this._indicesSet.h[this.poly.length - 1] = true;
}
var j;
var ijReal = true;
var jkReal = true;
var nDiags = 0;
if(k - i <= 1) return;
var pair = this.subDecomp.pairs(i,k);
if(this.isReflex(i)) {
j = pair.backTop();
ijReal = pair.frontBottom() == pair.backTop();
} else {
j = pair.frontTop();
jkReal = pair.backBottom() == pair.frontTop();
}
if(ijReal) {
this._indicesSet.h[i] = true;
this._indicesSet.h[j] = true;
nDiags++;
}
if(jkReal) {
this._indicesSet.h[j] = true;
this._indicesSet.h[k] = true;
nDiags++;
}
this.guard--;
if(nDiags > 1) {
var hasInnerDiags = false;
var indices;
var _g = [];
var $it0 = this._indicesSet.keys();
while( $it0.hasNext() ) {
var k1 = $it0.next();
_g.push(k1);
}
indices = _g;
indices.sort($bind(this,this.intCmp));
if(indices.length > 0) {
outIndices.push(indices);
this._indicesCount = 0;
this._indicesSet = new haxe_ds_IntMap();
}
}
this._decompByDiags(i,j,outIndices,level + 1);
this._decompByDiags(j,k,outIndices,level + 1);
}
,intCmp: function(a,b) {
if(a == b) return 0; else if(b < a) return 1; else return -1;
}
,decompIndices: function() {
var res = [];
this.guard = 3 * this.n;
this._decompByDiags(0,this.poly.length - 1,res);
return res;
}
,toString: function() {
return this.poly.length + ": " + this.poly.toString();
}
};
var hxGeomAlgo_SubDecomp = function(reflex) {
var n = reflex.length;
var r = 0;
var j;
this.rx = [];
var _g = 0;
while(_g < n) {
var i = _g++;
if(reflex[i]) this.rx[i] = r++; else this.rx[i] = 0;
}
j = r;
this.wt = [];
this.pd = [];
var _g1 = 0;
while(_g1 < n) {
var i1 = _g1++;
if(!reflex[i1]) this.rx[i1] = j++;
this.wt[i1] = [];
this.pd[i1] = [];
var _g11 = 0;
while(_g11 < n) {
var k = _g11++;
if(i1 < r || k < r) {
this.wt[i1][k] = hxGeomAlgo_DecompPoly.BAD;
this.pd[i1][k] = null;
} else break;
}
}
};
hxGeomAlgo_SubDecomp.__name__ = true;
hxGeomAlgo_SubDecomp.prototype = {
setWeight: function(i,j,w) {
this.wt[this.rx[i]][this.rx[j]] = w;
}
,weight: function(i,j) {
return this.wt[this.rx[i]][this.rx[j]];
}
,pairs: function(i,j) {
return this.pd[this.rx[i]][this.rx[j]];
}
,init: function(i,j) {
return this.pd[this.rx[i]][this.rx[j]] = new hxGeomAlgo_PairDeque();
}
,initWithWeight: function(i,j,w,a,b) {
this.setWeight(i,j,w);
this.init(i,j).push(a,b);
}
};
var hxGeomAlgo_VertexType = { __ename__ : ["hxGeomAlgo","VertexType"], __constructs__ : ["UNKNOWN","RIGHT_LID","LEFT_LID","RIGHT_WALL","LEFT_WALL"] };
hxGeomAlgo_VertexType.UNKNOWN = ["UNKNOWN",0];
hxGeomAlgo_VertexType.UNKNOWN.toString = $estr;
hxGeomAlgo_VertexType.UNKNOWN.__enum__ = hxGeomAlgo_VertexType;
hxGeomAlgo_VertexType.RIGHT_LID = ["RIGHT_LID",1];
hxGeomAlgo_VertexType.RIGHT_LID.toString = $estr;
hxGeomAlgo_VertexType.RIGHT_LID.__enum__ = hxGeomAlgo_VertexType;
hxGeomAlgo_VertexType.LEFT_LID = ["LEFT_LID",2];
hxGeomAlgo_VertexType.LEFT_LID.toString = $estr;
hxGeomAlgo_VertexType.LEFT_LID.__enum__ = hxGeomAlgo_VertexType;
hxGeomAlgo_VertexType.RIGHT_WALL = ["RIGHT_WALL",3];
hxGeomAlgo_VertexType.RIGHT_WALL.toString = $estr;
hxGeomAlgo_VertexType.RIGHT_WALL.__enum__ = hxGeomAlgo_VertexType;
hxGeomAlgo_VertexType.LEFT_WALL = ["LEFT_WALL",4];
hxGeomAlgo_VertexType.LEFT_WALL.toString = $estr;
hxGeomAlgo_VertexType.LEFT_WALL.__enum__ = hxGeomAlgo_VertexType;
var hxGeomAlgo_Visibility = $hx_exports.hxGeomAlgo.Visibility = function() { };
hxGeomAlgo_Visibility.__name__ = true;
hxGeomAlgo_Visibility.getVisibleIndicesFrom = function(simplePoly,origIdx) {
if(origIdx == null) origIdx = 0;
var res = [];
if(simplePoly.length <= 0) return res;
hxGeomAlgo_Visibility.poly = [];
hxGeomAlgo_Visibility.stack.length = 0;
hxGeomAlgo_Visibility.vertexType.length = 0;
hxGeomAlgo_Visibility.stackTop = -1;
var _g1 = 0;
var _g = simplePoly.length;
while(_g1 < _g) {
var i = _g1++;
hxGeomAlgo_Visibility.poly.push(hxGeomAlgo__$HxPoint_HxPoint_$Impl_$._new(simplePoly[i].x,simplePoly[i].y));
hxGeomAlgo_Visibility.stack.push(-1);
hxGeomAlgo_Visibility.vertexType.push(hxGeomAlgo_VertexType.UNKNOWN);
}
hxGeomAlgo_Visibility.reversed = hxGeomAlgo_PolyTools.makeCW(hxGeomAlgo_Visibility.poly);
if(hxGeomAlgo_Visibility.reversed) origIdx = hxGeomAlgo_Visibility.poly.length - origIdx - 1;
var edgeJ;
hxGeomAlgo_Visibility.origPoint = hxGeomAlgo_Visibility.poly[origIdx];
var j = origIdx;
hxGeomAlgo_Visibility.push(j++,hxGeomAlgo_VertexType.RIGHT_WALL);
do {
hxGeomAlgo_Visibility.push(j++,hxGeomAlgo_VertexType.RIGHT_WALL);
if(j >= hxGeomAlgo_Visibility.poly.length + origIdx) break;
edgeJ = hxGeomAlgo_PolyTools.meet(hxGeomAlgo_PolyTools.at(hxGeomAlgo_Visibility.poly,j - 1),hxGeomAlgo_PolyTools.at(hxGeomAlgo_Visibility.poly,j));
if(edgeJ.left(hxGeomAlgo_Visibility.origPoint)) continue;
if(!edgeJ.left(hxGeomAlgo_PolyTools.at(hxGeomAlgo_Visibility.poly,j - 2))) {
j = hxGeomAlgo_Visibility.exitRightBay(hxGeomAlgo_Visibility.poly,j,hxGeomAlgo_PolyTools.at(hxGeomAlgo_Visibility.poly,hxGeomAlgo_Visibility.stack[hxGeomAlgo_Visibility.stackTop]),hxGeomAlgo_HomogCoord.INFINITY);
hxGeomAlgo_Visibility.push(j++,hxGeomAlgo_VertexType.RIGHT_LID);
continue;
}
hxGeomAlgo_Visibility.saveLid();
do if(hxGeomAlgo_PolyTools.isLeft(hxGeomAlgo_Visibility.origPoint,hxGeomAlgo_PolyTools.at(hxGeomAlgo_Visibility.poly,hxGeomAlgo_Visibility.stack[hxGeomAlgo_Visibility.stackTop]),hxGeomAlgo_PolyTools.at(hxGeomAlgo_Visibility.poly,j))) {
if(hxGeomAlgo_PolyTools.isRight(hxGeomAlgo_PolyTools.at(hxGeomAlgo_Visibility.poly,j),hxGeomAlgo_PolyTools.at(hxGeomAlgo_Visibility.poly,j + 1),hxGeomAlgo_Visibility.origPoint)) j++; else if(edgeJ.left(hxGeomAlgo_PolyTools.at(hxGeomAlgo_Visibility.poly,j + 1))) j = hxGeomAlgo_Visibility.exitLeftBay(hxGeomAlgo_Visibility.poly,j,hxGeomAlgo_PolyTools.at(hxGeomAlgo_Visibility.poly,j),hxGeomAlgo_PolyTools.meet(hxGeomAlgo_PolyTools.at(hxGeomAlgo_Visibility.poly,hxGeomAlgo_Visibility.leftLidIdx),hxGeomAlgo_PolyTools.at(hxGeomAlgo_Visibility.poly,hxGeomAlgo_Visibility.leftLidIdx - 1))) + 1; else {
hxGeomAlgo_Visibility.restoreLid();
hxGeomAlgo_Visibility.push(j++,hxGeomAlgo_VertexType.LEFT_WALL);
break;
}
edgeJ = hxGeomAlgo_PolyTools.meet(hxGeomAlgo_PolyTools.at(hxGeomAlgo_Visibility.poly,j - 1),hxGeomAlgo_PolyTools.at(hxGeomAlgo_Visibility.poly,j));
} else if(!edgeJ.left(hxGeomAlgo_PolyTools.at(hxGeomAlgo_Visibility.poly,hxGeomAlgo_Visibility.stack[hxGeomAlgo_Visibility.stackTop]))) {
j = hxGeomAlgo_Visibility.exitRightBay(hxGeomAlgo_Visibility.poly,j,hxGeomAlgo_PolyTools.at(hxGeomAlgo_Visibility.poly,hxGeomAlgo_Visibility.stack[hxGeomAlgo_Visibility.stackTop]),edgeJ.neg());
hxGeomAlgo_Visibility.push(j++,hxGeomAlgo_VertexType.RIGHT_LID);
break;
} else hxGeomAlgo_Visibility.saveLid(); while(true);
} while(j < hxGeomAlgo_Visibility.poly.length + origIdx);
var _g11 = 0;
var _g2 = hxGeomAlgo_Visibility.stackTop + 1;
while(_g11 < _g2) {
var i1 = _g11++;
if(hxGeomAlgo_Visibility.vertexType[i1] == hxGeomAlgo_VertexType.LEFT_WALL || hxGeomAlgo_Visibility.vertexType[i1] == hxGeomAlgo_VertexType.RIGHT_WALL) {
var idx = hxGeomAlgo_Visibility.stack[i1] % hxGeomAlgo_Visibility.poly.length;
if(hxGeomAlgo_Visibility.reversed) idx = hxGeomAlgo_Visibility.poly.length - idx - 1;
res.push(idx);
}
}
return res;
};
hxGeomAlgo_Visibility.getVisiblePolyFrom = function(simplePoly,origIdx) {
if(origIdx == null) origIdx = 0;
var indices = hxGeomAlgo_Visibility.getVisibleIndicesFrom(simplePoly,origIdx);
var res = [];
if(indices.length <= 0) return res;
var q;
var last = hxGeomAlgo_PolyTools.at(hxGeomAlgo_Visibility.poly,hxGeomAlgo_Visibility.stack[hxGeomAlgo_Visibility.stackTop]);
var lastPushed = null;
var lastType = hxGeomAlgo_VertexType.UNKNOWN;
var vType = hxGeomAlgo_VertexType.UNKNOWN;
var _g1 = 0;
var _g = hxGeomAlgo_Visibility.stackTop + 1;
while(_g1 < _g) {
var i = _g1++;
vType = hxGeomAlgo_Visibility.vertexType[i];
if(vType == hxGeomAlgo_VertexType.RIGHT_LID) {
q = hxGeomAlgo_PolyTools.meet(hxGeomAlgo_Visibility.origPoint,last).meet(hxGeomAlgo_PolyTools.meet(hxGeomAlgo_PolyTools.at(hxGeomAlgo_Visibility.poly,hxGeomAlgo_Visibility.stack[i]),hxGeomAlgo_PolyTools.at(hxGeomAlgo_Visibility.poly,hxGeomAlgo_Visibility.stack[i + 1])));
if(lastPushed != null && !(last != null && lastPushed.x == last.x && lastPushed.y == last.y)) res.push(hxGeomAlgo__$HxPoint_HxPoint_$Impl_$._new(last.x,last.y));
res.push(q.toPoint());
} else if(vType == hxGeomAlgo_VertexType.LEFT_WALL) {
q = hxGeomAlgo_PolyTools.meet(hxGeomAlgo_Visibility.origPoint,hxGeomAlgo_PolyTools.at(hxGeomAlgo_Visibility.poly,hxGeomAlgo_Visibility.stack[i])).meet(hxGeomAlgo_PolyTools.meet(hxGeomAlgo_PolyTools.at(hxGeomAlgo_Visibility.poly,hxGeomAlgo_Visibility.stack[i - 2]),hxGeomAlgo_PolyTools.at(hxGeomAlgo_Visibility.poly,hxGeomAlgo_Visibility.stack[i - 1])));
res.push(q.toPoint());
} else if(vType == hxGeomAlgo_VertexType.RIGHT_WALL && lastType == hxGeomAlgo_VertexType.RIGHT_LID || vType == hxGeomAlgo_VertexType.LEFT_LID && lastType == hxGeomAlgo_VertexType.RIGHT_LID) {
} else res.push(hxGeomAlgo__$HxPoint_HxPoint_$Impl_$._new(last.x,last.y));
lastPushed = res[res.length - 1];
last = hxGeomAlgo_PolyTools.at(hxGeomAlgo_Visibility.poly,hxGeomAlgo_Visibility.stack[i]);
lastType = vType;
}
return res;
};
hxGeomAlgo_Visibility.exitRightBay = function(poly,j,bot,lid) {
var windingNum = 0;
var mouth = hxGeomAlgo_PolyTools.meet(hxGeomAlgo_Visibility.origPoint,bot);
var lastLeft;
var currLeft = false;
while(++j < 3 * poly.length) {
lastLeft = currLeft;
currLeft = mouth.left(hxGeomAlgo_PolyTools.at(poly,j));
if(currLeft != lastLeft && hxGeomAlgo_PolyTools.isLeft(hxGeomAlgo_PolyTools.at(poly,j - 1),hxGeomAlgo_PolyTools.at(poly,j),hxGeomAlgo_Visibility.origPoint) == currLeft) {
if(!currLeft) windingNum--; else if(windingNum++ == 0) {
var edge = hxGeomAlgo_PolyTools.meet(hxGeomAlgo_PolyTools.at(poly,j - 1),hxGeomAlgo_PolyTools.at(poly,j));
if(edge.left(bot) && !hxGeomAlgo_HomogCoord.cw(mouth,edge,lid)) return j - 1;
}
}
}
return j;
};
hxGeomAlgo_Visibility.exitLeftBay = function(poly,j,bot,lid) {
var windingNum = 0;
var mouth = hxGeomAlgo_PolyTools.meet(hxGeomAlgo_Visibility.origPoint,bot);
var lastRight;
var currRight = false;
while(++j < 3 * poly.length) {
lastRight = currRight;
currRight = mouth.right(hxGeomAlgo_PolyTools.at(poly,j));
if(currRight != lastRight && hxGeomAlgo_PolyTools.isRight(hxGeomAlgo_PolyTools.at(poly,j - 1),hxGeomAlgo_PolyTools.at(poly,j),hxGeomAlgo_Visibility.origPoint) == currRight) {
if(!currRight) windingNum++; else if(windingNum-- == 0) {
var edge = hxGeomAlgo_PolyTools.meet(hxGeomAlgo_PolyTools.at(poly,j - 1),hxGeomAlgo_PolyTools.at(poly,j));
if(edge.right(bot) && !hxGeomAlgo_HomogCoord.cw(mouth,edge,lid)) return j - 1;
}
}
}
return j;
};
hxGeomAlgo_Visibility.push = function(idx,vType) {
hxGeomAlgo_Visibility.stackTop++;
hxGeomAlgo_Visibility.stack[hxGeomAlgo_Visibility.stackTop] = idx;
hxGeomAlgo_Visibility.vertexType[hxGeomAlgo_Visibility.stackTop] = vType;
};
hxGeomAlgo_Visibility.saveLid = function() {
if(hxGeomAlgo_Visibility.vertexType[hxGeomAlgo_Visibility.stackTop] == hxGeomAlgo_VertexType.LEFT_WALL) hxGeomAlgo_Visibility.stackTop--;
hxGeomAlgo_Visibility.leftLidIdx = hxGeomAlgo_Visibility.stack[hxGeomAlgo_Visibility.stackTop--];
if(hxGeomAlgo_Visibility.vertexType[hxGeomAlgo_Visibility.stackTop] == hxGeomAlgo_VertexType.RIGHT_LID) hxGeomAlgo_Visibility.rightLidIdx = hxGeomAlgo_Visibility.stack[hxGeomAlgo_Visibility.stackTop--]; else hxGeomAlgo_Visibility.rightLidIdx = -1;
};
hxGeomAlgo_Visibility.restoreLid = function() {
if(hxGeomAlgo_Visibility.rightLidIdx != -1) hxGeomAlgo_Visibility.push(hxGeomAlgo_Visibility.rightLidIdx,hxGeomAlgo_VertexType.RIGHT_LID);
hxGeomAlgo_Visibility.push(hxGeomAlgo_Visibility.leftLidIdx,hxGeomAlgo_VertexType.LEFT_LID);
};
var js_Boot = function() { };
js_Boot.__name__ = true;
js_Boot.__string_rec = function(o,s) {
if(o == null) return "null";
if(s.length >= 5) return "<...>";
var t = typeof(o);
if(t == "function" && (o.__name__ || o.__ename__)) t = "object";
switch(t) {
case "object":
if(o instanceof Array) {
if(o.__enum__) {
if(o.length == 2) return o[0];
var str2 = o[0] + "(";
s += "\t";
var _g1 = 2;
var _g = o.length;
while(_g1 < _g) {
var i1 = _g1++;
if(i1 != 2) str2 += "," + js_Boot.__string_rec(o[i1],s); else str2 += js_Boot.__string_rec(o[i1],s);
}
return str2 + ")";
}
var l = o.length;
var i;
var str1 = "[";
s += "\t";
var _g2 = 0;
while(_g2 < l) {
var i2 = _g2++;
str1 += (i2 > 0?",":"") + js_Boot.__string_rec(o[i2],s);
}
str1 += "]";
return str1;
}
var tostr;
try {
tostr = o.toString;
} catch( e ) {
return "???";
}
if(tostr != null && tostr != Object.toString && typeof(tostr) == "function") {
var s2 = o.toString();
if(s2 != "[object Object]") return s2;
}
var k = null;
var str = "{\n";
s += "\t";
var hasp = o.hasOwnProperty != null;
for( var k in o ) {
if(hasp && !o.hasOwnProperty(k)) {
continue;
}
if(k == "prototype" || k == "__class__" || k == "__super__" || k == "__interfaces__" || k == "__properties__") {
continue;
}
if(str.length != 2) str += ", \n";
str += s + k + " : " + js_Boot.__string_rec(o[k],s);
}
s = s.substring(1);
str += "\n" + s + "}";
return str;
case "function":
return "<function>";
case "string":
return o;
default:
return String(o);
}
};
var $_, $fid = 0;
function $bind(o,m) { if( m == null ) return null; if( m.__id__ == null ) m.__id__ = $fid++; var f; if( o.hx__closures__ == null ) o.hx__closures__ = {}; else f = o.hx__closures__[m.__id__]; if( f == null ) { f = function(){ return f.method.apply(f.scope, arguments); }; f.scope = o; f.method = m; o.hx__closures__[m.__id__] = f; } return f; }
String.__name__ = true;
Array.__name__ = true;
hxGeomAlgo_HomogCoord.INFINITY = new hxGeomAlgo_HomogCoord();
hxGeomAlgo_PolyTools.point = hxGeomAlgo__$HxPoint_HxPoint_$Impl_$._new();
hxGeomAlgo_PolyTools.zero = hxGeomAlgo__$HxPoint_HxPoint_$Impl_$._new(0,0);
hxGeomAlgo_PolyTools.EPSILON = .00000001;
hxGeomAlgo_DecompPoly.INFINITY = 100000;
hxGeomAlgo_DecompPoly.BAD = 999990;
hxGeomAlgo_DecompPoly.NONE = 0;
hxGeomAlgo_Visibility.NOT_SAVED = -1;
hxGeomAlgo_Visibility.stack = [];
hxGeomAlgo_Visibility.vertexType = [];
})(typeof console != "undefined" ? console : {log:function(){}}, typeof window != "undefined" ? window : exports);
|
var searchData=
[
['testconnection',['testConnection',['../class_m_p_u6050.html#a95ffab7b44fce3834236e0813687d11a',1,'MPU6050::testConnection()'],['../class_m_p_u6050.html#a95ffab7b44fce3834236e0813687d11a',1,'MPU6050::testConnection()'],['../class_m_p_u6050.html#a95ffab7b44fce3834236e0813687d11a',1,'MPU6050::testConnection()']]],
['tim1_5fcc_5firqhandler',['TIM1_CC_IRQHandler',['../stm32__it_8cpp.html#ae8a61b27afdb07c70d6b863c44284ca6',1,'stm32_it.cpp']]],
['tim2_5firqhandler',['TIM2_IRQHandler',['../stm32__it_8cpp.html#a38ad4725462bdc5e86c4ead4f04b9fc2',1,'stm32_it.cpp']]],
['tim3_5firqhandler',['TIM3_IRQHandler',['../stm32__it_8cpp.html#ac8e51d2183b5230cbd5481f8867adce9',1,'stm32_it.cpp']]],
['tim4_5firqhandler',['TIM4_IRQHandler',['../stm32__it_8cpp.html#a7133f3f78767503641d307386e68bd28',1,'stm32_it.cpp']]],
['timing_5fdecrement',['Timing_Decrement',['../main_8cpp.html#aa4dff7af622b509adaec64eb160180d2',1,'main.cpp']]],
['tinkeranalogread',['tinkerAnalogRead',['../application_8cpp.html#a36fc9bd7eabbfe77fc09b2fb658052ab',1,'application.cpp']]],
['tinkeranalogwrite',['tinkerAnalogWrite',['../application_8cpp.html#a599c10eed77b45e159ece0f72065d9fc',1,'application.cpp']]],
['tinkerdigitalread',['tinkerDigitalRead',['../application_8cpp.html#a4375360614f90445c3a53657e3825387',1,'application.cpp']]],
['tinkerdigitalwrite',['tinkerDigitalWrite',['../application_8cpp.html#a2abbafddc9bb750c22acbe9524dad9e3',1,'application.cpp']]],
['togglefolder',['toggleFolder',['../dynsections_8js.html#af244da4527af2d845dca04f5656376cd',1,'dynsections.js']]],
['toggleinherit',['toggleInherit',['../dynsections_8js.html#ac057b640b17ff32af11ced151c9305b4',1,'dynsections.js']]],
['togglelevel',['toggleLevel',['../dynsections_8js.html#a19f577cc1ba571396a85bb1f48bf4df2',1,'dynsections.js']]],
['togglevisibility',['toggleVisibility',['../dynsections_8js.html#a1922c462474df7dfd18741c961d59a25',1,'dynsections.js']]],
['turnbotinfrontofcylinder',['turnBotInFrontOFCylinder',['../class_bot.html#ad2c6771e4959c6163802b09215a3874d',1,'Bot']]]
];
|
'use strict';
var babelHelpers = require('../util/babelHelpers.js');
exports.__esModule = true;
var _configure = require('../configure');
var _configure2 = babelHelpers.interopRequireDefault(_configure);
function endOfDecade(date) {
date = new Date(date);
date.setFullYear(date.getFullYear() + 10);
date.setMilliseconds(date.getMilliseconds() - 1);
return date;
}
function endOfCentury(date) {
date = new Date(date);
date.setFullYear(date.getFullYear() + 100);
date.setMilliseconds(date.getMilliseconds() - 1);
return date;
}
exports['default'] = function (moment) {
if (typeof moment !== 'function') throw new TypeError('You must provide a valid moment object');
var localField = typeof moment().locale === 'function' ? 'locale' : 'lang',
hasLocaleData = !!moment.localeData;
if (!hasLocaleData) throw new TypeError('The Moment localizer depends on the `localeData` api, please provide a moment object v2.2.0 or higher');
function getMoment(culture, value, format) {
return culture ? moment(value, format)[localField](culture) : moment(value, format);
}
var localizer = {
formats: {
date: 'L',
time: 'LT',
'default': 'lll',
header: 'MMMM YYYY',
footer: 'LL',
weekday: 'dd',
dayOfMonth: 'DD',
month: 'MMM',
year: 'YYYY',
decade: function decade(date, culture, localizer) {
return localizer.format(date, 'YYYY', culture) + ' - ' + localizer.format(endOfDecade(date), 'YYYY', culture);
},
century: function century(date, culture, localizer) {
return localizer.format(date, 'YYYY', culture) + ' - ' + localizer.format(endOfCentury(date), 'YYYY', culture);
}
},
firstOfWeek: function firstOfWeek(culture) {
return moment.localeData(culture).firstDayOfWeek();
},
parse: function parse(value, format, culture) {
return getMoment(culture, value, format).toDate();
},
format: function format(value, _format, culture) {
return getMoment(culture, value, _format).format(_format);
}
};
_configure2['default'].setDateLocalizer(localizer);
return localizer;
};
module.exports = exports['default']; |
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = ao;
/*
* ao
* https://github.com/jwalsh/aojs
*
* Copyright (c) 2013
* Licensed under the MIT license.
*/
function ao() {
'use strict';
var ua = arguments.length <= 0 || arguments[0] === undefined ? window.navigator.userAgent : arguments[0];
var BOTS_RE = /AhefsBot|Baiduspider|bingbot|Googlebot|MJ12bot|YandexBot|Crawler/;
// https://developer.chrome.com/multidevice/user-agent
var MOBILES_RE = /iPhone|iPad|iPod|Android/;
return ua.search(MOBILES_RE);
} |
Type.registerNamespace("Strings");
Strings.OfficeOM = function()
{
};
Strings.OfficeOM.registerClass("Strings.OfficeOM");
Strings.OfficeOM.L_InvalidNamedItemForBindingType = "Norādītais saistīšanas tips nav saderīgs ar norādīto nosaukto vienumu.";
Strings.OfficeOM.L_EventHandlerNotExist = "Norādītais notikuma apdarinātājs šim saistījumam netika atrasts.";
Strings.OfficeOM.L_UnknownBindingType = "Šis saistīšanas tips netiek atbalstīts.";
Strings.OfficeOM.L_InvalidNode = "Nederīgs mezgls";
Strings.OfficeOM.L_NotImplemented = "Funkcija {0} nav ieviesta.";
Strings.OfficeOM.L_NoCapability = "Jums nav pietiekamu atļauju, lai veiktu šo darbību.";
Strings.OfficeOM.L_SettingsCannotSave = "Iestatījumus nevarēja saglabāt.";
Strings.OfficeOM.L_DataWriteReminder = "Datu rakstīšanas atgādinājums";
Strings.OfficeOM.L_InvalidBinding = "Nederīgs saistījums";
Strings.OfficeOM.L_InvalidSetColumns = "Norādītās kolonnas ir nederīgas.";
Strings.OfficeOM.L_BindingCreationError = "Saistījuma izveides kļūda";
Strings.OfficeOM.L_FormatValueOutOfRange = "Vērtība ir ārpus atļautā diapazona.";
Strings.OfficeOM.L_SelectionNotSupportCoercionType = "Pašreizējā atlase nav saderīga ar norādīto piespiedu pārvēršanas tipu.";
Strings.OfficeOM.L_InvalidBindingError = "Nederīga saistījuma kļūda";
Strings.OfficeOM.L_InvalidGetStartRowColumn = "Norādītās startRow vai startColumn vērtības nav derīgas.";
Strings.OfficeOM.L_InvalidSetRows = "Norādītās rindas ir nederīgas.";
Strings.OfficeOM.L_NetworkProblem = "Tīkla problēma";
Strings.OfficeOM.L_CannotWriteToSelection = "Nevar rakstīt pašreizējā atlasē.";
Strings.OfficeOM.L_MissingParameter = "Trūkst parametra";
Strings.OfficeOM.L_IndexOutOfRange = "Indekss ir ārpus diapazona.";
Strings.OfficeOM.L_SettingsStaleError = "Iestatījumu novecošanas kļūda";
Strings.OfficeOM.L_CannotNavigateTo = "Objekts atrodas vietā, kur navigācija netiek atbalstīta.";
Strings.OfficeOM.L_ReadSettingsError = "Iestatījumu lasīšanas kļūda";
Strings.OfficeOM.L_InvalidGetColumns = "Norādītās kolonnas ir nederīgas.";
Strings.OfficeOM.L_CoercionTypeNotSupported = "Norādītais piespiedu pārvēršanas tips netiek atbalstīts.";
Strings.OfficeOM.L_AppNotExistInitializeNotCalled = "Lietojumprogramma {0} nepastāv. Microsoft.Office.WebExtension.Initialize(reason) nav izsaukts.";
Strings.OfficeOM.L_OverwriteWorksheetData = "Iestatītā operācija neizdevās, jo nodrošinātais datu objekts pārrakstīs vai pārbīdīs datus dokumentā.";
Strings.OfficeOM.L_RowIndexOutOfRange = "Rindas indeksa vērtība ir ārpus atļautā diapazona. Izmantojiet vērtību (0 vai lielāku), kas ir mazāka par rindu skaitu.";
Strings.OfficeOM.L_InvalidReadForBlankRow = "Norādītā rinda ir tukša.";
Strings.OfficeOM.L_ColIndexOutOfRange = "Kolonnas indeksa vērtība ir ārpus atļautā diapazona. Izmantojiet vērtību (0 vai lielāku), kas ir mazāka par kolonnu skaitu.";
Strings.OfficeOM.L_UnsupportedEnumeration = "Neatbalstīta numerācija";
Strings.OfficeOM.L_InvalidParameters = "Funkcijas {0} parametri nav derīgi.";
Strings.OfficeOM.L_SetDataParametersConflict = "Norādītie parametri konfliktē.";
Strings.OfficeOM.L_CloseFileBeforeRetrieve = "Izsauciet closeAsync pašreizējam failam, pirms izgūstat citu.";
Strings.OfficeOM.L_DataNotMatchCoercionType = "Norādītā datu objekta tips nav saderīgs ar pašreizējo atlasi.";
Strings.OfficeOM.L_UnsupportedEnumerationMessage = "Pašreizējā resursdatora programmā numerācija netiek atbalstīta.";
Strings.OfficeOM.L_InvalidCoercion = "Nederīgs piespiešanas tips";
Strings.OfficeOM.L_NotSupportedEventType = "Norādītais notikuma tips {0} netiek atbalstīts.";
Strings.OfficeOM.L_UnsupportedDataObject = "Nodrošinātais datu objekta tips netiek atbalstīts.";
Strings.OfficeOM.L_GetDataIsTooLarge = "Pieprasīto datu kopa ir pārāk liela.";
Strings.OfficeOM.L_AppNameNotExist = "AppName, kas paredzēts {0}, nepastāv.";
Strings.OfficeOM.L_AddBindingFromPromptDefaultText = "Lūdzu, veiciet atlasi.";
Strings.OfficeOM.L_MultipleNamedItemFound = "Atrasti vairāki objekti ar vienādiem nosaukumiem.";
Strings.OfficeOM.L_InvalidCellsValue = "Vismaz vienam šūnu parametram ir neatļauta vērtība. Kārtīgi pārbaudiet vērtības un mēģiniet vēlreiz.";
Strings.OfficeOM.L_DataNotMatchBindingType = "Norādītais datu objekts nav saderīgs ar šo saistījuma tipu.";
Strings.OfficeOM.L_InvalidFormatValue = "Vismaz vienam formāta parametram ir neatļauta vērtība. Kārtīgi pārbaudiet vērtības un mēģiniet vēlreiz.";
Strings.OfficeOM.L_NotSupportedBindingType = "Norādītais saistījuma tips {0} netiek atbalstīts.";
Strings.OfficeOM.L_InitializeNotReady = "Office.js vēl nav pilnībā ielādēts. Lūdzu, vēlāk mēģiniet vēlreiz vai nodrošiniet, lai jūsu inicializācijas kods būtu pievienots Office.initialize funkcijai.";
Strings.OfficeOM.L_FormattingReminder = "Formatēšanas atgādinājums";
Strings.OfficeOM.L_ShuttingDown = "Operācija neizdevās, jo dati serverī ir novecojuši.";
Strings.OfficeOM.L_OperationNotSupported = "Operācija netiek atbalstīta.";
Strings.OfficeOM.L_DocumentReadOnly = "Pieprasītā operācija nav atļauta pašreizējā dokumenta režīmā.";
Strings.OfficeOM.L_NamedItemNotFound = "Nosauktais vienums nepastāv.";
Strings.OfficeOM.L_InvalidApiCallInContext = "Pašreizējā kontekstā nederīgs API izsaukums.";
Strings.OfficeOM.L_InvalidGetRows = "Norādītās rindas ir nederīgas.";
Strings.OfficeOM.L_CellFormatAmountBeyondLimits = "Piezīme. Formatējuma kopām, ko iestata formatējuma API izsaukums, ieteicams būt zem 100.";
Strings.OfficeOM.L_TooManyIncompleteRequests = "Uzgaidiet, līdz tiek pabeigts iepriekšējais izsaukums.";
Strings.OfficeOM.L_SetDataIsTooLarge = "Norādītais datu objekts ir pārāk liels.";
Strings.OfficeOM.L_DataWriteError = "Datu rakstīšanas kļūda";
Strings.OfficeOM.L_InvalidBindingOperation = "Nederīga saistījuma operācija";
Strings.OfficeOM.L_APICallFailed = "API izsaukums neizdevās";
Strings.OfficeOM.L_SpecifiedIdNotExist = "Norādītais ID nepastāv.";
Strings.OfficeOM.L_FunctionCallFailed = "Funkcijas {0} izsaukums neizdevās, kļūdas kods: {1}.";
Strings.OfficeOM.L_DataNotMatchBindingSize = "Nodrošinātais datu objekts neatbilst pašreizējās atlases lielumam.";
Strings.OfficeOM.L_SaveSettingsError = "Iestatījumu saglabāšanas kļūda";
Strings.OfficeOM.L_RequestTokenUnavailable = "Šis API ir droselēts, lai samazinātu izsaukumu biežumu.";
Strings.OfficeOM.L_InvalidSetStartRowColumn = "Norādītās startRow vai startColumn vērtības nav derīgas.";
Strings.OfficeOM.L_InvalidFormat = "Nederīga formāta kļūda";
Strings.OfficeOM.L_BindingNotExist = "Norādītais saistījums nepastāv.";
Strings.OfficeOM.L_SettingNameNotExist = "Norādītais iestatījuma nosaukums nepastāv.";
Strings.OfficeOM.L_EventHandlerAdditionFailed = "Neizdevās pievienot notikumu apdarinātāju.";
Strings.OfficeOM.L_BrowserAPINotSupported = "Šī pārlūkprogramma neatbalsta pieprasīto API.";
Strings.OfficeOM.L_InvalidAPICall = "Nederīgs API izsaukums";
Strings.OfficeOM.L_EventRegistrationError = "Notikuma reģistrācijas kļūda";
Strings.OfficeOM.L_ElementMissing = "Nevarējām formatēt šo tabulas šūnu, jo trūkst dažu parametru vērtību. Kārtīgi pārbaudiet parametrus un mēģiniet vēlreiz.";
Strings.OfficeOM.L_NonUniformPartialSetNotSupported = "Koordinātu parametri nevar tikt lietoti ar piespiedu tipu Tabula, ja tabulā ir sapludinātas šūnas.";
Strings.OfficeOM.L_NavOutOfBound = "Operācija neizdevās, jo indekss ir ārpus diapazona.";
Strings.OfficeOM.L_RedundantCallbackSpecification = "Atzvanīšana nevar būt norādīta gan argumentu sarakstā, gan neobligātajā objektā.";
Strings.OfficeOM.L_CustomXmlError = "Pielāgota XML kļūda.";
Strings.OfficeOM.L_SettingsAreStale = "Iestatījumus nevarēja saglabāt, jo tie ir novecojuši.";
Strings.OfficeOM.L_TooManyOptionalFunction = "vairākas neobligātas funkcijas parametru sarakstā";
Strings.OfficeOM.L_MissingRequiredArguments = "trūkst dažu obligāto argumentu";
Strings.OfficeOM.L_NonUniformPartialGetNotSupported = "Koordinātu parametri nevar tikt lietoti ar piespiedu tipu Tabula, ja tabulā ir sapludinātas šūnas.";
Strings.OfficeOM.L_HostError = "Resursdatora kļūda";
Strings.OfficeOM.L_OutOfRange = "Ārpus diapazona";
Strings.OfficeOM.L_InvalidSelectionForBindingType = "Izmantojot pašreizējo atlasi un norādīto saistījuma tipu, saistījumu nevar izveidot.";
Strings.OfficeOM.L_TooManyOptionalObjects = "vairāki neobligāti objekti parametru sarakstā";
Strings.OfficeOM.L_OperationNotSupportedOnMatrixData = "Atlasītajam saturam ir jābūt tabulas formātā. Formatējiet datus kā tabulu un mēģiniet vēlreiz.";
Strings.OfficeOM.L_APINotSupported = "API netiek atbalstīts";
Strings.OfficeOM.L_SliceSizeNotSupported = "Norādītais sektora lielums netiek atbalstīts.";
Strings.OfficeOM.L_EventHandlerRemovalFailed = "Neizdevās noņemt notikumu apdarinātāju.";
Strings.OfficeOM.L_BindingToMultipleSelection = "Attālu vienumu atlase netiek atbalstīta.";
Strings.OfficeOM.L_DataReadError = "Datu lasīšanas kļūda";
Strings.OfficeOM.L_InternalErrorDescription = "Ir radusies iekšēja kļūda.";
Strings.OfficeOM.L_InvalidDataFormat = "Norādītā datu objekta formāts nav derīgs.";
Strings.OfficeOM.L_RequestTimeout = "Izsaukuma izpilde pārāk ieilga.";
Strings.OfficeOM.L_DataStale = "Dati ir novecojuši";
Strings.OfficeOM.L_GetSelectionNotSupported = "Pašreizējā atlase netiek atbalstīta.";
Strings.OfficeOM.L_MemoryLimit = "Pārsniegts atmiņas ierobežojums";
Strings.OfficeOM.L_CellDataAmountBeyondLimits = "Piezīme. Tabulā nav ieteicams izmantot vairāk nekā 20 000 šūnas.";
Strings.OfficeOM.L_InvalidTableOptionValue = "Vismaz vienam objekta tableOptions parametram ir neatļauta vērtība. Rūpīgi pārbaudiet vērtības un mēģiniet vēlreiz.";
Strings.OfficeOM.L_PermissionDenied = "Atļauja liegta";
Strings.OfficeOM.L_InvalidDataObject = "Nederīgs datu objekts";
Strings.OfficeOM.L_UserNotSignedIn = "Office kontā nav pierakstījies neviens lietotājs.";
Strings.OfficeOM.L_SelectionCannotBound = "Nevar piesaistīt pašreizējai atlasei.";
Strings.OfficeOM.L_InvalidColumnsForBinding = "Norādītās kolonnas ir nederīgas.";
Strings.OfficeOM.L_BadSelectorString = "Atlasītājā ievadītā virkne nav pareizi formatēta vai netiek atbalstīta.";
Strings.OfficeOM.L_InvalidGetRowColumnCounts = "Norādītās rowCount vai columnCount vērtības nav derīgas.";
Strings.OfficeOM.L_OsfControlTypeNotSupported = "OsfControl tips netiek atbalstīts.";
Strings.OfficeOM.L_InvalidValue = "Nederīga vērtība";
Strings.OfficeOM.L_DataNotMatchSelection = "Norādītais datu objekts nav saderīgs ar pašreizējās atlases formu vai dimensijām.";
Strings.OfficeOM.L_InternalError = "Iekšēja kļūda";
Strings.OfficeOM.L_NotSupported = "Funkcija {0} netiek atbalstīta.";
Strings.OfficeOM.L_CustomXmlNodeNotFound = "Norādītais mezgls nav atrasts.";
Strings.OfficeOM.L_CoercionTypeNotMatchBinding = "Norādītais piespiedu pārvēršanas tips nav saderīgs ar šo saistīšanas tipu.";
Strings.OfficeOM.L_NetworkProblemRetrieveFile = "Tīkla problēmas neļāva izgūt failu.";
Strings.OfficeOM.L_TooManyArguments = "pārāk daudz argumentu";
Strings.OfficeOM.L_OperationNotSupportedOnThisBindingType = "Operācija šī tipa saistījumā nav atbalstīta.";
Strings.OfficeOM.L_InValidOptionalArgument = "nederīgs neobligātais arguments";
Strings.OfficeOM.L_FileTypeNotSupported = "Norādītais faila tips netiek atbalstīts.";
Strings.OfficeOM.L_GetDataParametersConflict = "Norādītie parametri konfliktē.";
Strings.OfficeOM.L_CallbackNotAFunction = "Atzvanīšanai jābūt funkcijas tipa; bija {0} tipa."
|
// flow-typed signature: aa361ad6f824f985f1402af76a9059ec
// flow-typed version: <<STUB>>/postcss-loader_v^1.1.0/flow_v0.45.0
/**
* This is an autogenerated libdef stub for:
*
* 'postcss-loader'
*
* 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 'postcss-loader' {
declare module.exports: any;
}
/**
* We include stubs for each file inside this npm package in case you need to
* require those files directly. Feel free to delete any files that aren't
* needed.
*/
declare module 'postcss-loader/error' {
declare module.exports: any;
}
// Filename aliases
declare module 'postcss-loader/error.js' {
declare module.exports: $Exports<'postcss-loader/error'>;
}
declare module 'postcss-loader/index' {
declare module.exports: $Exports<'postcss-loader'>;
}
declare module 'postcss-loader/index.js' {
declare module.exports: $Exports<'postcss-loader'>;
}
|
var __assign = (this && this.__assign) || Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
import { createThemedClasses } from '../../utils/theme';
var Item = (function () {
function Item() {
this.childStyles = Object.create(null);
// _ids: number = -1;
// _inputs: Array<string> = [];
// _label: Label;
// _viewLabel: boolean = true;
// _name: string = 'item';
// _hasReorder: boolean;
// /**
// * @hidden
// */
// id: string;
// /**
// * @hidden
// */
// labelId: string = null;
// constructor(
// form: Form,
// config: Config,
// elementRef: ElementRef,
// renderer: Renderer,
// @Optional() reorder: ItemReorder
// ) {
// super(config, elementRef, renderer, 'item');
// this._setName(elementRef);
// this._hasReorder = !!reorder;
// this.id = form.nextId().toString();
// // auto add "tappable" attribute to ion-item components that have a click listener
// if (!(<any>renderer).orgListen) {
// (<any>renderer).orgListen = renderer.listen;
// renderer.listen = function(renderElement: HTMLElement, name: string, callback: Function): Function {
// if (name === 'click' && renderElement.setAttribute) {
// renderElement.setAttribute('tappable', '');
// }
// return (<any>renderer).orgListen(renderElement, name, callback);
// };
// }
// }
// /**
// * @hidden
// */
// registerInput(type: string) {
// this._inputs.push(type);
// return this.id + '-' + (++this._ids);
// }
// /**
// * @hidden
// */
// ngAfterContentInit() {
// if (this._viewLabel && this._inputs.length) {
// let labelText = this.getLabelText().trim();
// this._viewLabel = (labelText.length > 0);
// }
// if (this._inputs.length > 1) {
// this.setElementClass('item-multiple-inputs', true);
// }
// }
// /**
// * @hidden
// */
// _updateColor(newColor: string, componentName?: string) {
// componentName = componentName || 'item'; // item-radio
// this._setColor(newColor, componentName);
// }
// /**
// * @hidden
// */
// _setName(elementRef: ElementRef) {
// let nodeName = elementRef.nativeElement.nodeName.replace('ION-', '');
// if (nodeName === 'LIST-HEADER' || nodeName === 'ITEM-DIVIDER') {
// this._name = nodeName;
// }
// }
// /**
// * @hidden
// */
// getLabelText(): string {
// return this._label ? this._label.text : '';
// }
// /**
// * @hidden
// */
// @ContentChild(Label)
// set contentLabel(label: Label) {
// if (label) {
// this._label = label;
// this.labelId = label.id = ('lbl-' + this.id);
// if (label.type) {
// this.setElementClass('item-label-' + label.type, true);
// }
// this._viewLabel = false;
// }
// }
// /**
// * @hidden
// */
// @ViewChild(Label)
// set viewLabel(label: Label) {
// if (!this._label) {
// this._label = label;
// }
// }
// /**
// * @hidden
// */
// @ContentChildren(Button)
// set _buttons(buttons: QueryList<Button>) {
// buttons.forEach(button => {
// if (!button._size) {
// button.setElementClass('item-button', true);
// }
// });
// }
// /**
// * @hidden
// */
// @ContentChildren(Icon)
// set _icons(icons: QueryList<Icon>) {
// icons.forEach(icon => {
// icon.setElementClass('item-icon', true);
// });
// }
}
Item.prototype.itemStyle = function (ev) {
ev.stopPropagation();
var hasChildStyleChange = false;
var updatedStyles = ev.detail;
for (var key in updatedStyles) {
if (updatedStyles[key] !== this.childStyles['item-' + key]) {
this.childStyles['item-' + key] = updatedStyles[key];
hasChildStyleChange = true;
}
}
// returning true tells the renderer to queue an update
return hasChildStyleChange;
};
Item.prototype["componentDidLoad"] = function () {
// Add item-button classes to each ion-button in the item
var buttons = this.el.querySelectorAll('ion-button');
for (var i = 0; i < buttons.length; i++) {
buttons[i].itemButton = true;
}
};
Item.prototype.render = function () {
var themedClasses = __assign({}, this.childStyles, createThemedClasses(this.mode, this.color, 'item'), { 'item-block': true });
// TODO add support for button items
var TagType = this.href ? 'a' : 'div';
return (h(TagType, { "c": themedClasses },
h(0, { "a": { "name": 'start' } }),
h("div", { "c": { "item-inner": true } },
h("div", { "c": { "input-wrapper": true } },
h(0, 0)),
h(0, { "a": { "name": 'end' } }))));
// template:
// '<ng-content select="[slot="start"],ion-checkbox:not([slot="end"])"></ng-content>' +
// '<div class="item-inner">' +
// '<div class="input-wrapper">' +
// '<ng-content select="ion-label"></ng-content>' +
// '<ion-label *ngIf="_viewLabel">' +
// '<ng-content></ng-content>' +
// '</ion-label>' +
// '<ng-content select="ion-select,ion-input,ion-textarea,ion-datetime,ion-range,[item-content]"></ng-content>' +
// '</div>' +
// '<ng-content select="[slot="end"],ion-radio,ion-toggle"></ng-content>' +
// '<ion-reorder *ngIf="_hasReorder"></ion-reorder>' +
// '</div>' +
// '<div class="button-effect"></div>',
};
return Item;
}());
export { Item };
|
import BinaryHeap from './BinaryHeap'
import defaults from './defaults'
import utils from './utils'
const assignMsg = `Cannot assign to read only property`
/**
* Provide a custom storage medium, e.g. a polyfill for `localStorage`. Default: `null`.
*
* Must implement:
*
* - `setItem` - Same API as `localStorage.setItem(key, value)`
* - `getItem` - Same API as `localStorage.getItem(key)`
* - `removeItem` - Same API as `localStorage.removeItem(key)`
*
* @name Cache~StorageImpl
* @type {object}
* @property {function} setItem Implementation of `setItem(key, value)`.
* @property {function} getItem Implementation of `getItem(key)`.
* @property {function} removeItem Implementation of `removeItem(key)`.
*/
/**
* Instances of this class represent a "cache"—a synchronous key-value store.
* Each instance holds the settings for the cache, and provides methods for
* manipulating the cache and its data.
*
* Generally you don't creates instances of `Cache` directly, but instead create
* instances of `Cache` via {@link CacheFactory#createCache}.
*
* @example
* import CacheFactory from 'cachefactory';
*
* const cacheFactory = new CacheFactory();
* const options = {...};
* const cache = cacheFactory.createCache('my-cache', options);
*
* cache.put('foo', 'bar');
* console.log(cache.get('foo')); // "bar"
*
* @class Cache
* @param {string} id A unique identifier for the cache.
* @param {object} [options] Configuration options.
* @param {number} [options.cacheFlushInterval=null] See {@link Cache#cacheFlushInterval}.
* @param {number} [options.capacity=Number.MAX_VALUE] See {@link Cache#capacity}.
* @param {string} [options.deleteOnExpire="none"] See {@link Cache#deleteOnExpire}.
* @param {boolean} [options.enabled=true] See {@link Cache#enabled}.
* @param {number} [options.maxAge=Number.MAX_VALUE] See {@link Cache#maxAge}.
* @param {function} [options.onExpire=null] See {@link Cache#onExpire}.
* @param {number} [options.recycleFreq=1000] See {@link Cache#recycleFreq}.
* @param {Cache~StorageImpl} [options.storageImpl=null] See {@link Cache~StorageImpl}.
* @param {string} [options.storageMode="memory"] See {@link Cache#storageMode}.
* @param {string} [options.storagePrefix="cachefactory.caches."] See {@link Cache#storagePrefix}.
* @param {boolean} [options.storeOnReject=false] See {@link Cache#storeOnReject}.
* @param {boolean} [options.storeOnResolve=false] See {@link Cache#storeOnResolve}.
*/
export default class Cache {
constructor (id, options = {}) {
if (!utils.isString(id)) {
throw new TypeError(`"id" must be a string!`)
}
Object.defineProperties(this, {
// Writable
$$cacheFlushInterval: { writable: true, value: undefined },
$$cacheFlushIntervalId: { writable: true, value: undefined },
$$capacity: { writable: true, value: undefined },
$$data: { writable: true, value: {} },
$$deleteOnExpire: { writable: true, value: undefined },
$$enabled: { writable: true, value: undefined },
$$expiresHeap: { writable: true, value: new BinaryHeap((x) => x.accessed, utils.equals) },
$$initializing: { writable: true, value: true },
$$lruHeap: { writable: true, value: new BinaryHeap((x) => x.accessed, utils.equals) },
$$maxAge: { writable: true, value: undefined },
$$onExpire: { writable: true, value: undefined },
$$prefix: { writable: true, value: '' },
$$promises: { writable: true, value: {} },
$$recycleFreq: { writable: true, value: undefined },
$$recycleFreqId: { writable: true, value: undefined },
$$storage: { writable: true, value: undefined },
$$storageMode: { writable: true, value: undefined },
$$storagePrefix: { writable: true, value: undefined },
$$storeOnReject: { writable: true, value: undefined },
$$storeOnResolve: { writable: true, value: undefined },
// Read-only
$$parent: { value: options.parent },
/**
* The interval (in milliseconds) on which the cache should remove all of
* its items. Setting this to `null` disables the interval. The default is
* `null`.
*
* @example <caption>Create a cache the clears itself every 15 minutes</caption>
* import CacheFactory from 'cachefactory';
*
* const cacheFactory = new CacheFactory();
* const cache = cacheFactory.createCache('my-cache', {
* cacheFlushInterval: 15 * 60 * 1000
* });
*
* @name Cache#cacheFlushInterval
* @default null
* @public
* @readonly
* @type {number|null}
*/
cacheFlushInterval: {
enumerable: true,
get: () => this.$$cacheFlushInterval,
set: () => { throw new Error(`${assignMsg} 'cacheFlushInterval'`) }
},
/**
* The maximum number of items that can be stored in the cache. When the
* capacity is exceeded the least recently accessed item will be removed.
* The default is `Number.MAX_VALUE`.
*
* @example <caption>Create a cache with a capacity of 100</caption>
* import CacheFactory from 'cachefactory';
*
* const cacheFactory = new CacheFactory();
* const cache = cacheFactory.createCache('my-cache', {
* capacity: 100
* });
*
* @name Cache#capacity
* @default Number.MAX_VALUE
* @public
* @readonly
* @type {number}
*/
capacity: {
enumerable: true,
get: () => this.$$capacity,
set: () => { throw new Error(`${assignMsg} 'capacity'`) }
},
/**
* Determines the behavior of a cache when an item expires. The default is
* `"none"`.
*
* Possible values:
*
* - `"none"` - Cache will do nothing when an item expires.
* - `"passive"` - Cache will do nothing when an item expires. Expired
* items will remain in the cache until requested, at which point they are
* removed, and `undefined` is returned.
* - `"aggressive"` - Cache will remove expired items as soon as they are
* discovered.
*
* @example <caption>Create a cache that deletes items as soon as they expire</caption>
* import CacheFactory from 'cachefactory';
*
* const cacheFactory = new CacheFactory();
* const cache = cacheFactory.createCache('my-cache', {
* deleteOnExpire: 'aggressive'
* });
*
* @example <caption>Create a cache that doesn't delete expired items until they're accessed</caption>
* import CacheFactory from 'cachefactory';
*
* const cacheFactory = new CacheFactory();
* const cache = cacheFactory.createCache('my-cache', {
* deleteOnExpire: 'passive'
* });
*
* @name Cache#deleteOnExpire
* @default "none"
* @public
* @readonly
* @type {string}
*/
deleteOnExpire: {
enumerable: true,
get: () => this.$$deleteOnExpire,
set: () => { throw new Error(`${assignMsg} 'deleteOnExpire'`) }
},
/**
* Marks whether the cache is enabled or not. For a disabled cache,
* {@link Cache#put} is a no-op. The default is `true`.
*
* @example <caption>Create a cache that starts out disabled</caption>
* import CacheFactory from 'cachefactory';
*
* const cacheFactory = new CacheFactory();
* const cache = cacheFactory.createCache('my-cache', {
* enabled: false
* });
*
* // The cache is disabled, this is a no-op
* cache.put('foo', 'bar');
* console.log(cache.get('foo')); // undefined
*
* @name Cache#enabled
* @default true
* @public
* @readonly
* @type {boolean}
*/
enabled: {
enumerable: true,
get: () => this.$$enabled,
set: () => { throw new Error(`${assignMsg} 'enabled'`) }
},
/**
* Then unique identifier given to this cache when it was created.
*
* @name Cache#id
* @public
* @readonly
* @type {string}
*/
id: {
enumerable: true,
value: id
},
/**
* Represents how long an item can be in the cache before expires. The
* cache's behavior toward expired items is determined by
* {@link Cache#deleteOnExpire}. The default value for `maxAge` is
* `Number.MAX_VALUE`.
*
* @example <caption>Create a cache where items expire after 15 minutes</caption>
* import CacheFactory from 'cachefactory';
*
* const cacheFactory = new CacheFactory();
* const cache = cacheFactory.createCache('my-cache', {
* // Items expire after 15 minutes
* maxAge: 15 * 60 * 1000
* });
* const cache2 = cacheFactory.createCache('my-cache2', {
* // Items expire after 15 minutes
* maxAge: 15 * 60 * 1000,
* // Expired items will only be deleted once they are accessed
* deleteOnExpire: 'passive'
* });
* const cache3 = cacheFactory.createCache('my-cache3', {
* // Items expire after 15 minutes
* maxAge: 15 * 60 * 1000,
* // Items will be deleted from the cache as soon as they expire
* deleteOnExpire: 'aggressive'
* });
*
* @name Cache#maxAge
* @default Number.MAX_VALUE
* @public
* @readonly
* @type {number}
*/
maxAge: {
enumerable: true,
get: () => this.$$maxAge,
set: () => { throw new Error(`${assignMsg} 'maxAge'`) }
},
/**
* The `onExpire` callback.
*
* @callback Cache~onExpireCallback
* @param {string} key The key of the expired item.
* @param {*} value The value of the expired item.
* @param {function} [done] If in `"passive"` mode and you pass an
* `onExpire` callback to {@link Cache#get}, then the `onExpire` callback
* you passed to {@link Cache#get} will be passed to your global
* `onExpire` callback.
*/
/**
* A callback to be executed when expired items are removed from the
* cache when the cache is in `"passive"` or `"aggressive"` mode. The
* default is `null`. See {@link Cache~onExpireCallback} for the signature
* of the `onExpire` callback.
*
* @example <caption>Create a cache where items expire after 15 minutes</caption>
* import CacheFactory from 'cachefactory';
*
* const cacheFactory = new CacheFactory();
* const cache = cacheFactory.createCache('my-cache', {
* // Items expire after 15 minutes
* maxAge: 15 * 60 * 1000,
* // Expired items will only be deleted once they are accessed
* deleteOnExpire: 'passive',
* // Try to rehydrate cached items as they expire
* onExpire: function (key, value, done) {
* // Do something with key and value
*
* // Will received "done" callback if in "passive" mode and passing
* // an onExpire option to Cache#get.
* if (done) {
* done(); // You can pass whatever you want to done
* }
* }
* });
*
* @name Cache#onExpire
* @default null
* @public
* @readonly
* @see Cache~onExpireCallback
* @type {function}
*/
onExpire: {
enumerable: true,
get: () => this.$$onExpire,
set: () => { throw new Error(`${assignMsg} 'onExpire'`) }
},
/**
* The frequency (in milliseconds) with which the cache should check for
* expired items. The default is `1000`. The value of this interval only
* matters if {@link Cache#deleteOnExpire} is set to `"aggressive"`.
*
* @example <caption>Create a cache where items expire after 15 minutes checking every 10 seconds</caption>
* import CacheFactory from 'cachefactory';
*
* const cacheFactory = new CacheFactory();
* const cache = cacheFactory.createCache('my-cache', {
* // Items expire after 15 minutes
* maxAge: 15 * 60 * 1000,
* // Items will be deleted from the cache as soon as they expire
* deleteOnExpire: 'aggressive',
* // Check for expired items every 10 seconds
* recycleFreq: 10 * 1000
* });
*
* @name Cache#recycleFreq
* @default 1000
* @public
* @readonly
* @type {number|null}
*/
recycleFreq: {
enumerable: true,
get: () => this.$$recycleFreq,
set: () => { throw new Error(`${assignMsg} 'recycleFreq'`) }
},
/**
* Determines the storage medium used by the cache. The default is
* `"memory"`.
*
* Possible values:
*
* - `"memory"`
* - `"localStorage"`
* - `"sessionStorage"`
*
* @example <caption>Create a cache that stores its data in localStorage</caption>
* import CacheFactory from 'cachefactory';
*
* const cacheFactory = new CacheFactory();
* const cache = cacheFactory.createCache('my-cache', {
* storageMode: 'localStorage'
* });
*
* @example <caption>Provide a custom storage implementation</caption>
* import CacheFactory from 'cachefactory';
*
* const cacheFactory = new CacheFactory();
* const cache = cacheFactory.createCache('my-cache', {
* storageMode: 'localStorage',
* storageImpl: {
* setItem: function (key, value) {
* console.log('setItem', key, value);
* localStorage.setItem(key, value);
* },
* getItem: function (key) {
* console.log('getItem', key);
* localStorage.getItem(key);
* },
* removeItem: function (key) {
* console.log('removeItem', key);
* localStorage.removeItem(key);
* }
* }
* });
*
* @name Cache#storageMode
* @default "memory"
* @public
* @readonly
* @type {string}
*/
storageMode: {
enumerable: true,
get: () => this.$$storageMode,
set: () => { throw new Error(`${assignMsg} 'storageMode'`) }
},
/**
* The prefix used to namespace the keys for items stored in
* `localStorage` or `sessionStorage`. The default is
* `"cachefactory.caches."` which is conservatively long in order any
* possible conflict with other data in storage. Set to a shorter value
* to save storage space.
*
* @example
* import CacheFactory from 'cachefactory';
*
* const cacheFactory = new CacheFactory();
* const cache = cacheFactory.createCache('my-cache', {
* storageMode: 'localStorage',
* // Completely remove the prefix to save the most space
* storagePrefix: ''
* });
* cache.put('foo', 'bar');
* console.log(localStorage.get('my-cache.data.foo')); // "bar"
*
* @name Cache#storagePrefix
* @default "cachefactory.caches."
* @public
* @readonly
* @type {string}
*/
storagePrefix: {
enumerable: true,
get: () => this.$$storagePrefix,
set: () => { throw new Error(`${assignMsg} 'storagePrefix'`) }
},
/**
* If set to `true`, when a promise is inserted into the cache and is then
* rejected, then the rejection value will overwrite the promise in the
* cache. The default is `false`.
*
* @name Cache#storeOnReject
* @default false
* @public
* @readonly
* @type {boolean}
*/
storeOnReject: {
enumerable: true,
get: () => this.$$storeOnReject,
set: () => { throw new Error(`${assignMsg} 'storeOnReject'`) }
},
/**
* If set to `true`, when a promise is inserted into the cache and is then
* resolved, then the resolution value will overwrite the promise in the
* cache. The default is `false`.
*
* @name Cache#storeOnResolve
* @default false
* @public
* @readonly
* @type {boolean}
*/
storeOnResolve: {
enumerable: true,
get: () => this.$$storeOnResolve,
set: () => { throw new Error(`${assignMsg} 'storeOnResolve'`) }
}
})
this.setOptions(options, true)
this.$$initializing = false
}
/**
* Destroys this cache and all its data and renders it unusable.
*
* @example
* cache.destroy();
*
* @method Cache#destroy
*/
destroy () {
clearInterval(this.$$cacheFlushIntervalId)
clearInterval(this.$$recycleFreqId)
this.removeAll()
if (this.$$storage) {
this.$$storage().removeItem(`${this.$$prefix}.keys`)
this.$$storage().removeItem(this.$$prefix)
}
this.$$storage = null
this.$$data = null
this.$$lruHeap = null
this.$$expiresHeap = null
this.$$prefix = null
if (this.$$parent) {
this.$$parent.caches[this.id] = undefined
}
}
/**
* Disables this cache. For a disabled cache, {@link Cache#put} is a no-op.
*
* @example
* cache.disable();
*
* @method Cache#disable
*/
disable () {
this.$$enabled = false
}
/**
* Enables this cache. For a disabled cache, {@link Cache#put} is a no-op.
*
* @example
* cache.enable();
*
* @method Cache#enable
*/
enable () {
this.$$enabled = true
}
/**
* Retrieve an item from the cache, it it exists.
*
* @example <caption>Retrieve an item from the cache</caption>
* cache.put('foo', 'bar');
* cache.get('foo'); // "bar"
*
* @example <caption>Retrieve a possibly expired item while in passive mode</caption>
* import CacheFactory from 'cachefactory';
*
* const cacheFactory = new CacheFactory();
* const cache = cacheFactory.createCache('my-cache', {
* deleteOnExpire: 'passive',
* maxAge: 15 * 60 * 1000
* });
* cache.get('foo', {
* // Called if "foo" is expired
* onExpire: function (key, value) {
* // Do something with key and value
* }
* });
*
* @example <caption>Retrieve a possibly expired item while in passive mode with global onExpire callback</caption>
* import CacheFactory from 'cachefactory';
*
* const cacheFactory = new CacheFactory();
* const cache = cacheFactory.createCache('my-cache', {
* deleteOnExpire: 'passive',
* maxAge: 15 * 60 * 1000
* onExpire: function (key, value, done) {
* console.log('Expired item:', key);
* if (done) {
* done('foo', key, value);
* }
* }
* });
* cache.get('foo', {
* // Called if "foo" is expired
* onExpire: function (msg, key, value) {
* console.log(msg); // "foo"
* // Do something with key and value
* }
* });
*
* @method Cache#get
* @param {string|string[]} key The key of the item to retrieve.
* @param {object} [options] Configuration options.
* @param {function} [options.onExpire] TODO
* @returns {*} The value for the specified `key`, if any.
*/
get (key, options = {}) {
if (Array.isArray(key)) {
const keys = key
const values = []
keys.forEach((key) => {
const value = this.get(key, options)
if (value !== null && value !== undefined) {
values.push(value)
}
})
return values
} else {
if (utils.isNumber(key)) {
key = '' + key
}
if (!this.enabled) {
return
}
}
if (!utils.isString(key)) {
throw new TypeError(`"key" must be a string!`)
} else if (!options || !utils.isObject(options)) {
throw new TypeError(`"options" must be an object!`)
} else if (options.onExpire && !utils.isFunction(options.onExpire)) {
throw new TypeError(`"options.onExpire" must be a function!`)
}
let item
if (this.$$storage) {
if (this.$$promises[key]) {
return this.$$promises[key]
}
const itemJson = this.$$storage().getItem(`${this.$$prefix}.data.${key}`)
if (itemJson) {
item = utils.fromJson(itemJson)
}
} else if (utils.isObject(this.$$data)) {
item = this.$$data[key]
}
if (!item) {
return
}
let value = item.value
let now = new Date().getTime()
if (this.$$storage) {
this.$$lruHeap.remove({
key: key,
accessed: item.accessed
})
item.accessed = now
this.$$lruHeap.push({
key: key,
accessed: now
})
} else {
this.$$lruHeap.remove(item)
item.accessed = now
this.$$lruHeap.push(item)
}
if (this.$$deleteOnExpire === 'passive' && 'expires' in item && item.expires < now) {
this.remove(key)
if (this.$$onExpire) {
this.$$onExpire(key, item.value, options.onExpire)
} else if (options.onExpire) {
options.onExpire.call(this, key, item.value)
}
value = undefined
} else if (this.$$storage) {
this.$$storage().setItem(`${this.$$prefix}.data.${key}`, utils.toJson(item))
}
return value
}
/**
* Retrieve information about the whole cache or about a particular item in
* the cache.
*
* @example <caption>Retrieve info about the cache</caption>
* const info = cache.info();
* info.id; // "my-cache"
* info.capacity; // 100
* info.maxAge; // 600000
* info.deleteOnExpire; // "aggressive"
* info.cacheFlushInterval; // null
* info.recycleFreq; // 10000
* info.storageMode; // "localStorage"
* info.enabled; // false
* info.size; // 1234
*
* @example <caption>Retrieve info about an item in the cache</caption>
* const info = cache.info('foo');
* info.created; // 1234567890
* info.accessed; // 1234567990
* info.expires; // 1234569999
* info.isExpired; // false
*
* @method Cache#info
* @param {string} [key] If specified, retrieve info for a particular item in
* the cache.
* @returns {*} The information object.
*/
info (key) {
if (key) {
let item
if (this.$$storage) {
const itemJson = this.$$storage().getItem(`${this.$$prefix}.data.${key}`)
if (itemJson) {
item = utils.fromJson(itemJson)
}
} else if (utils.isObject(this.$$data)) {
item = this.$$data[key]
}
if (item) {
return {
created: item.created,
accessed: item.accessed,
expires: item.expires,
isExpired: (new Date().getTime() - item.created) > (item.maxAge || this.$$maxAge)
}
}
} else {
return {
id: this.id,
capacity: this.capacity,
maxAge: this.maxAge,
deleteOnExpire: this.deleteOnExpire,
onExpire: this.onExpire,
cacheFlushInterval: this.cacheFlushInterval,
recycleFreq: this.recycleFreq,
storageMode: this.storageMode,
storageImpl: this.$$storage ? this.$$storage() : undefined,
enabled: this.enabled,
size: this.$$lruHeap && this.$$lruHeap.size() || 0
}
}
}
/**
* Retrieve a list of the keys of items currently in the cache.
*
* @example
* const keys = cache.keys();
*
* @method Cache#keys
* @returns {string[]} The keys of the items in the cache
*/
keys () {
if (this.$$storage) {
const keysJson = this.$$storage().getItem(`${this.$$prefix}.keys`)
if (keysJson) {
return utils.fromJson(keysJson)
} else {
return []
}
} else {
return Object.keys(this.$$data).filter((key) => this.$$data[key])
}
}
/**
* Retrieve an object of the keys of items currently in the cache.
*
* @example
* const keySet = cache.keySet();
*
* @method Cache#keySet
* @returns {object} The keys of the items in the cache.
*/
keySet () {
const set = {}
this.keys().forEach((key) => {
set[key] = key
})
return set
}
/**
* Insert an item into the cache.
*
* @example
* const inserted = cache.put('foo', 'bar');
*
* @method Cache#put
* @param {string} key The key under which to insert the item.
* @param {*} value The value to insert.
* @param {object} [options] Configuration options.
* @param {boolean} [options.storeOnReject] See {@link Cache#storeOnReject}.
* @param {boolean} [options.storeOnResolve] See {@link Cache#storeOnResolve}.
* @returns {*} The inserted value.
*/
put (key, value, options = {}) {
const storeOnResolve = options.storeOnResolve !== undefined ? !!options.storeOnResolve : this.$$storeOnResolve
const storeOnReject = options.storeOnReject !== undefined ? !!options.storeOnReject : this.$$storeOnReject
const getHandler = (shouldStore, isError) => {
return (v) => {
if (shouldStore) {
this.$$promises[key] = undefined
if (utils.isObject(v) && 'status' in v && 'data' in v) {
v = [v.status, v.data, v.headers(), v.statusText]
this.put(key, v)
} else {
this.put(key, v)
}
}
if (isError) {
if (utils.Promise) {
return utils.Promise.reject(v)
} else {
throw v
}
} else {
return v
}
}
}
if (!this.$$enabled || !utils.isObject(this.$$data) || value === null || value === undefined) {
return
}
if (utils.isNumber(key)) {
key = '' + key
}
if (!utils.isString(key)) {
throw new TypeError(`"key" must be a string!`)
}
const now = new Date().getTime()
const item = {
key: key,
value: utils.isPromise(value) ? value.then(getHandler(storeOnResolve, false), getHandler(storeOnReject, true)) : value,
created: options.created === undefined ? now : options.created,
accessed: options.accessed === undefined ? now : options.accessed
}
if (utils.isNumber(options.maxAge)) {
item.maxAge = options.maxAge
}
if (options.expires === undefined) {
item.expires = item.created + (item.maxAge || this.$$maxAge)
} else {
item.expires = options.expires
}
if (this.$$storage) {
if (utils.isPromise(item.value)) {
this.$$promises[key] = item.value
return this.$$promises[key]
}
const keysJson = this.$$storage().getItem(`${this.$$prefix}.keys`)
const keys = keysJson ? utils.fromJson(keysJson) : []
const itemJson = this.$$storage().getItem(`${this.$$prefix}.data.${key}`)
// Remove existing
if (itemJson) {
this.remove(key)
}
// Add to expires heap
this.$$expiresHeap.push({
key: key,
expires: item.expires
})
// Add to lru heap
this.$$lruHeap.push({
key: key,
accessed: item.accessed
})
// Set item
this.$$storage().setItem(`${this.$$prefix}.data.${key}`, utils.toJson(item))
let exists = false
keys.forEach((_key) => {
if (_key === key) {
exists = true
return false
}
})
if (!exists) {
keys.push(key)
}
this.$$storage().setItem(`${this.$$prefix}.keys`, utils.toJson(keys))
} else {
// Remove existing
if (this.$$data[key]) {
this.remove(key)
}
// Add to expires heap
this.$$expiresHeap.push(item)
// Add to lru heap
this.$$lruHeap.push(item)
// Set item
this.$$data[key] = item
this.$$promises[key] = undefined
}
// Handle exceeded capacity
if (this.$$lruHeap.size() > this.$$capacity) {
this.remove(this.$$lruHeap.peek().key)
}
return value
}
/**
* Remove an item from the cache.
*
* @example
* const removed = cache.remove('foo');
*
* @method Cache#remove
* @param {string} key The key of the item to remove.
* @returns {*} The value of the removed item, if any.
*/
remove (key) {
if (utils.isNumber(key)) {
key = '' + key
}
this.$$promises[key] = undefined
if (this.$$storage) {
const itemJson = this.$$storage().getItem(`${this.$$prefix}.data.${key}`)
if (itemJson) {
let item = utils.fromJson(itemJson)
this.$$lruHeap.remove({
key: key,
accessed: item.accessed
})
this.$$expiresHeap.remove({
key: key,
expires: item.expires
})
this.$$storage().removeItem(`${this.$$prefix}.data.${key}`)
let keysJson = this.$$storage().getItem(`${this.$$prefix}.keys`)
let keys = keysJson ? utils.fromJson(keysJson) : []
let index = keys.indexOf(key)
if (index >= 0) {
keys.splice(index, 1)
}
this.$$storage().setItem(`${this.$$prefix}.keys`, utils.toJson(keys))
return item.value
}
} else if (utils.isObject(this.$$data)) {
let value = this.$$data[key] ? this.$$data[key].value : undefined
this.$$lruHeap.remove(this.$$data[key])
this.$$expiresHeap.remove(this.$$data[key])
this.$$data[key] = undefined
return value
}
}
/**
* Remove all items from the cache.
*
* @example
* cache.removeAll();
*
* @method Cache#removeAll
*/
removeAll () {
const storage = this.$$storage
const keys = this.keys()
this.$$lruHeap.removeAll()
this.$$expiresHeap.removeAll()
if (storage) {
storage().setItem(`${this.$$prefix}.keys`, utils.toJson([]))
keys.forEach((key) => {
storage().removeItem(`${this.$$prefix}.data.${key}`)
})
} else if (utils.isObject(this.$$data)) {
this.$$data = {}
}
this.$$promises = {}
}
/**
* Remove expired items from the cache, if any.
*
* @example
* const expiredItems = cache.removeExpired();
*
* @method Cache#removeExpired
* @returns {object} The expired items, if any.
*/
removeExpired () {
const now = new Date().getTime()
const expired = {}
let expiredItem
while ((expiredItem = this.$$expiresHeap.peek()) && expiredItem.expires <= now) {
expired[expiredItem.key] = expiredItem.value ? expiredItem.value : null
this.$$expiresHeap.pop()
}
Object.keys(expired).forEach((key) => {
this.remove(key)
})
if (this.$$onExpire) {
Object.keys(expired).forEach((key) => {
this.$$onExpire(key, expired[key])
})
}
return expired
}
/**
* Update the {@link Cache#cacheFlushInterval} for the cache. Pass in `null`
* to disable the interval.
*
* @example
* cache.setCacheFlushInterval(60 * 60 * 1000);
*
* @method Cache#setCacheFlushInterval
* @param {number|null} cacheFlushInterval The new {@link Cache#cacheFlushInterval}.
*/
setCacheFlushInterval (cacheFlushInterval) {
if (cacheFlushInterval === null) {
this.$$cacheFlushInterval = null
} else if (!utils.isNumber(cacheFlushInterval)) {
throw new TypeError(`"cacheFlushInterval" must be a number!`)
} else if (cacheFlushInterval <= 0) {
throw new Error(`"cacheFlushInterval" must be greater than zero!`)
}
this.$$cacheFlushInterval = cacheFlushInterval
clearInterval(this.$$cacheFlushIntervalId)
this.$$cacheFlushIntervalId = undefined
if (this.$$cacheFlushInterval) {
this.$$cacheFlushIntervalId = setInterval(() => this.removeAll(), this.$$cacheFlushInterval)
}
}
/**
* Update the {@link Cache#capacity} for the cache. Pass in `null` to reset
* to `Number.MAX_VALUE`.
*
* @example
* cache.setCapacity(1000);
*
* @method Cache#setCapacity
* @param {number|null} capacity The new {@link Cache#capacity}.
*/
setCapacity (capacity) {
if (capacity === null) {
this.$$capacity = Number.MAX_VALUE
} else if (!utils.isNumber(capacity)) {
throw new TypeError(`"capacity" must be a number!`)
} else if (capacity <= 0) {
throw new Error(`"capacity" must be greater than zero!`)
} else {
this.$$capacity = capacity
}
const removed = {}
while (this.$$lruHeap.size() > this.$$capacity) {
removed[this.$$lruHeap.peek().key] = this.remove(this.$$lruHeap.peek().key)
}
return removed
}
/**
* Update the {@link Cache#deleteOnExpire} for the cache. Pass in `null` to
* reset to `"none"`.
*
* @example
* cache.setDeleteOnExpire('passive');
*
* @method Cache#setDeleteOnExpire
* @param {string|null} deleteOnExpire The new {@link Cache#deleteOnExpire}.
*/
setDeleteOnExpire (deleteOnExpire, setRecycleFreq) {
if (deleteOnExpire === null) {
deleteOnExpire = 'none'
} else if (!utils.isString(deleteOnExpire)) {
throw new TypeError(`"deleteOnExpire" must be a string!`)
} else if (deleteOnExpire !== 'none' && deleteOnExpire !== 'passive' && deleteOnExpire !== 'aggressive') {
throw new Error(`"deleteOnExpire" must be "none", "passive" or "aggressive"!`)
}
this.$$deleteOnExpire = deleteOnExpire
if (setRecycleFreq !== false) {
this.setRecycleFreq(this.$$recycleFreq)
}
}
/**
* Update the {@link Cache#maxAge} for the cache. Pass in `null` to reset to
* to `Number.MAX_VALUE`.
*
* @example
* cache.setMaxAge(60 * 60 * 1000);
*
* @method Cache#setMaxAge
* @param {number|null} maxAge The new {@link Cache#maxAge}.
*/
setMaxAge (maxAge) {
if (maxAge === null) {
this.$$maxAge = Number.MAX_VALUE
} else if (!utils.isNumber(maxAge)) {
throw new TypeError(`"maxAge" must be a number!`)
} else if (maxAge <= 0) {
throw new Error(`"maxAge" must be greater than zero!`)
} else {
this.$$maxAge = maxAge
}
const keys = this.keys()
this.$$expiresHeap.removeAll()
if (this.$$storage) {
keys.forEach((key) => {
const itemJson = this.$$storage().getItem(`${this.$$prefix}.data.${key}`)
if (itemJson) {
const item = utils.fromJson(itemJson)
if (this.$$maxAge === Number.MAX_VALUE) {
item.expires = Number.MAX_VALUE
} else {
item.expires = item.created + (item.maxAge || this.$$maxAge)
}
this.$$expiresHeap.push({
key: key,
expires: item.expires
})
}
})
} else {
keys.forEach((key) => {
const item = this.$$data[key]
if (item) {
if (this.$$maxAge === Number.MAX_VALUE) {
item.expires = Number.MAX_VALUE
} else {
item.expires = item.created + (item.maxAge || this.$$maxAge)
}
this.$$expiresHeap.push(item)
}
})
}
if (this.$$deleteOnExpire === 'aggressive') {
return this.removeExpired()
} else {
return {}
}
}
/**
* Update the {@link Cache#onExpire} for the cache. Pass in `null` to unset
* the global `onExpire` callback of the cache.
*
* @example
* cache.setOnExpire(function (key, value, done) {
* // Do something
* });
*
* @method Cache#setOnExpire
* @param {function|null} onExpire The new {@link Cache#onExpire}.
*/
setOnExpire (onExpire) {
if (onExpire === null) {
this.$$onExpire = null
} else if (!utils.isFunction(onExpire)) {
throw new TypeError(`"onExpire" must be a function!`)
} else {
this.$$onExpire = onExpire
}
}
/**
* Update multiple cache options at a time.
*
* @example
* cache.setOptions({
* maxAge: 60 * 60 * 1000,
* deleteOnExpire: 'aggressive'
* });
*
* @example <caption>Set two options, and reset the rest to the configured defaults</caption>
* cache.setOptions({
* maxAge: 60 * 60 * 1000,
* deleteOnExpire: 'aggressive'
* }, true);
*
* @method Cache#setOptions
* @param {object} options The options to set.
* @param {boolean} [strict] Reset options not passed to `options` to the
* configured defaults.
*/
setOptions (options = {}, strict = false) {
if (!utils.isObject(options)) {
throw new TypeError(`"options" must be an object!`)
}
if (options.storagePrefix !== undefined) {
this.$$storagePrefix = options.storagePrefix
} else if (strict) {
this.$$storagePrefix = defaults.storagePrefix
}
this.$$prefix = this.$$storagePrefix + this.id
if (options.enabled !== undefined) {
this.$$enabled = !!options.enabled
} else if (strict) {
this.$$enabled = defaults.enabled
}
if (options.deleteOnExpire !== undefined) {
this.setDeleteOnExpire(options.deleteOnExpire, false)
} else if (strict) {
this.setDeleteOnExpire(defaults.deleteOnExpire, false)
}
if (options.recycleFreq !== undefined) {
this.setRecycleFreq(options.recycleFreq)
} else if (strict) {
this.setRecycleFreq(defaults.recycleFreq)
}
if (options.maxAge !== undefined) {
this.setMaxAge(options.maxAge)
} else if (strict) {
this.setMaxAge(defaults.maxAge)
}
if (options.storeOnResolve !== undefined) {
this.$$storeOnResolve = !!options.storeOnResolve
} else if (strict) {
this.$$storeOnResolve = defaults.storeOnResolve
}
if (options.storeOnReject !== undefined) {
this.$$storeOnReject = !!options.storeOnReject
} else if (strict) {
this.$$storeOnReject = defaults.storeOnReject
}
if (options.capacity !== undefined) {
this.setCapacity(options.capacity)
} else if (strict) {
this.setCapacity(defaults.capacity)
}
if (options.cacheFlushInterval !== undefined) {
this.setCacheFlushInterval(options.cacheFlushInterval)
} else if (strict) {
this.setCacheFlushInterval(defaults.cacheFlushInterval)
}
if (options.onExpire !== undefined) {
this.setOnExpire(options.onExpire)
} else if (strict) {
this.setOnExpire(defaults.onExpire)
}
if (options.storageMode !== undefined || options.storageImpl !== undefined) {
this.setStorageMode(options.storageMode || defaults.storageMode, options.storageImpl || defaults.storageImpl)
} else if (strict) {
this.setStorageMode(defaults.storageMode, defaults.storageImpl)
}
}
/**
* Update the {@link Cache#recycleFreq} for the cache. Pass in `null` to
* disable the interval.
*
* @example
* cache.setRecycleFreq(10000);
*
* @method Cache#setRecycleFreq
* @param {number|null} recycleFreq The new {@link Cache#recycleFreq}.
*/
setRecycleFreq (recycleFreq) {
if (recycleFreq === null) {
this.$$recycleFreq = null
} else if (!utils.isNumber(recycleFreq)) {
throw new TypeError(`"recycleFreq" must be a number!`)
} else if (recycleFreq <= 0) {
throw new Error(`"recycleFreq" must be greater than zero!`)
} else {
this.$$recycleFreq = recycleFreq
}
clearInterval(this.$$recycleFreqId)
if (this.$$deleteOnExpire === 'aggressive' && this.$$recycleFreq) {
this.$$recycleFreqId = setInterval(() => this.removeExpired(), this.$$recycleFreq)
} else {
this.$$recycleFreqId = undefined
}
}
/**
* Update the {@link Cache#storageMode} for the cache.
*
* @method Cache#setStorageMode
* @param {string} storageMode The new {@link Cache#storageMode}.
* @param {object} storageImpl The new {@link Cache~StorageImpl}.
*/
setStorageMode (storageMode, storageImpl) {
if (!utils.isString(storageMode)) {
throw new TypeError(`"storageMode" must be a string!`)
} else if (storageMode !== 'memory' && storageMode !== 'localStorage' && storageMode !== 'sessionStorage') {
throw new Error(`"storageMode" must be "memory", "localStorage", or "sessionStorage"!`)
}
const prevStorage = this.$$storage
const prevData = this.$$data
let shouldReInsert = false
let items = {}
const load = (prevStorage, prevData) => {
const keys = this.keys()
const prevDataIsObject = utils.isObject(prevData)
keys.forEach((key) => {
if (prevStorage) {
const itemJson = prevStorage().getItem(`${this.$$prefix}.data.${key}`)
if (itemJson) {
items[key] = utils.fromJson(itemJson)
}
} else if (prevDataIsObject) {
items[key] = prevData[key]
}
this.remove(key)
shouldReInsert || (shouldReInsert = true)
})
}
if (!this.$$initializing) {
load(prevStorage, prevData)
}
this.$$storageMode = storageMode
if (storageImpl) {
if (!utils.isObject(storageImpl)) {
throw new TypeError(`"storageImpl" must be an object!`)
} else if (typeof storageImpl.setItem !== 'function') {
throw new Error(`"storageImpl" must implement "setItem(key, value)"!`)
} else if (typeof storageImpl.getItem !== 'function') {
throw new Error(`"storageImpl" must implement "getItem(key)"!`)
} else if (typeof storageImpl.removeItem !== 'function') {
throw new Error(`"storageImpl" must implement "removeItem(key)"!`)
}
this.$$storage = () => storageImpl
} else if (this.$$storageMode === 'localStorage') {
try {
localStorage.setItem('cachefactory', 'cachefactory')
localStorage.removeItem('cachefactory')
this.$$storage = () => localStorage
} catch (e) {
this.$$storage = null
this.$$storageMode = 'memory'
}
} else if (this.$$storageMode === 'sessionStorage') {
try {
sessionStorage.setItem('cachefactory', 'cachefactory')
sessionStorage.removeItem('cachefactory')
this.$$storage = () => sessionStorage
} catch (e) {
this.$$storage = null
this.$$storageMode = 'memory'
}
} else {
this.$$storage = null
this.$$storageMode = 'memory'
}
if (this.$$initializing) {
load(this.$$storage, this.$$data)
}
if (shouldReInsert) {
Object.keys(items).forEach((key) => {
const item = items[key]
this.put(key, item.value, {
created: item.created,
accessed: item.accessed,
expires: item.expires
})
})
}
}
/**
* Reset an item's age in the cache, or if `key` is unspecified, touch all
* items in the cache.
*
* @example
* cache.touch('foo');
*
* @method Cache#touch
* @param {string} [key] The key of the item to touch.
* @param {object} [options] Options to pass to {@link Cache#put} if
* necessary.
*/
touch (key, options) {
if (key) {
const val = this.get(key, {
onExpire: (k, v) => this.put(k, v)
})
if (val) {
this.put(key, val, options)
}
} else {
const keys = this.keys()
for (var i = 0; i < keys.length; i++) {
this.touch(keys[i], options)
}
}
}
/**
* Retrieve the values of all items in the cache.
*
* @example
* const values = cache.values();
*
* @method Cache#values
* @returns {array} The values of the items in the cache.
*/
values () {
return this.keys().map((key) => this.get(key))
}
}
|
/* global $ */
'use strict';
$(function () {
$('input[name="code-theme"]:radio').on('change', function (event) {
var theme = $(this).val();
$('link[href^="hljs-"]').attr('disabled', true);
$('link[href^="hljs-' + theme + '"]').attr('disabled', false);
$('pre.code--block').toggleClass('dark');
$('pre.code--block').toggleClass('light');
});
});
|
var path = require('path');
module.exports = function(config) {
var manifest;
try {
manifest = require(path.resolve(process.cwd(), config.manifest));
} catch(e) {
manifest = {};
}
return function(req, res, next) {
res.locals.rev = function(path) {
return config.prepend.toString() + '/' + (manifest[path] || path);
};
next();
};
};
|
const expect = require('chai').expect
const supertest = require('supertest')
const cheerio = require('cheerio');
const app = require('../app.js');
describe('call', function () {
describe('POST to /call/connect', function () {
context('when connecting from a phone number', function () {
it('response verb DIAL and a phone number', function (done) {
var phoneNumber = '555 5555'
var agent = supertest(app);
agent
.post('/call/connect')
.send({
phoneNumber: phoneNumber,
})
.expect(function (res) {
var $ = cheerio.load(res.text);
expect($('Dial').children('Number').length).to.equal(1);
expect($('Dial').children('Number').text()).to.equal(phoneNumber);
})
.expect(200, done);
});
});
context('when connecting from an agent', function () {
it('response noun CLIENT and the text support-agent', function (done) {
var agent = supertest(app);
agent
.post('/call/connect')
.expect(function (res) {
var $ = cheerio.load(res.text);
expect($('Dial').children('Client').length).to.equal(1);
expect($('Dial').children('Client').text()).to.equal("support_agent");
})
.expect(200, done);
});
});
});
});
|
'use strict';
var grunt = require('grunt');
/*
======== A Handy Little Nodeunit Reference ========
https://github.com/caolan/nodeunit
Test methods:
test.expect(numAssertions)
test.done()
Test assertions:
test.ok(value, [message])
test.equal(actual, expected, [message])
test.notEqual(actual, expected, [message])
test.deepEqual(actual, expected, [message])
test.notDeepEqual(actual, expected, [message])
test.strictEqual(actual, expected, [message])
test.notStrictEqual(actual, expected, [message])
test.throws(block, [error], [message])
test.doesNotThrow(block, [error], [message])
test.ifError(value)
*/
exports.version_sync = {
setUp: function(done) {
// setup here if necessary
done();
},
package_to_config: function(test) {
test.equal(grunt.file.read('test/fixtures/_config.yml').indexOf('version: 0.9.1'), -1, 'config.yml should no longer have 0.9.1');
console.log('NEW FILE', grunt.file.read('test/fixtures/_config.yml'));
test.equal(grunt.file.read('test/fixtures/_config.yml').indexOf("version: 1.0.0"), 0, 'config.yml should now have version 1.0.0');
test.done();
}
};
|
app.shell = (function () {
var
configMap = {
anchor_schema_map : {
chat : { opened : true, closed : true }
},
resize_interval : 200,
main_html : String() +
'<div class="app-shell-head">' +
'<div class="app-shell-head-logo"></div>' +
'<div class="app-shell-head-account"></div>' +
'<div class="app-shell-head-search"></div>' +
'</div>' +
'<div class="app-shell-main">' +
'<div class="app-shell-main-nav"></div>' +
'<div class="app-shell-main-content"></div>' +
'</div>' +
'<div class="app-shell-footer"></div>' +
'<div class="app-shell-modal"></div>',
},
stateMap = {
$container : undefined,
anchor_map : {},
resize_idto : undefined
},
jqueryMap = {},
setJqueryMap, initModule, copyAnchorMap, changeAnchorPart, onHasChange, onResize, setChatAnchor;
copyAnchorMap = function () {
return $.extend( true, {}, stateMap.anchor_map );
};
setJqueryMap = function () {
var $container = stateMap.$container;
jqueryMap = {
$container : $container
};
};
changeAnchorPart = function ( arg_map ) {
var
anchor_map_revise = copyAnchorMap(),
bool_return = true,
key_name, key_name_dep;
KEYVAL:
for ( key_name in arg_map ) {
if (arg_map.hasOwnProperty( key_name ) ) {
if ( key_name.indexOf( '_' ) === 0 ) {
continue KEYVAL;
}
anchor_map_revise[key_name] = arg_map[key_name];
key_name_dep = '_' + key_name;
if ( arg_map[key_name_dep] ) {
anchor_map_revise[key_name_dep] = arg_map[key_name_dep];
}
else {
delete anchor_map_revise[key_name_dep];
delete anchor_map_revise['_s' + key_name_dep];
}
}
}
try {
$.uriAnchor.setAnchor( anchor_map_revise );
}
catch ( error ) {
$.uriAnchor.setAnchor( stateMap.anchor_map, null, true );
bool_return = false;
}
return bool_return;
};
onHasChange = function ( event ) {
var
anchor_map_previous = copyAnchorMap(),
is_ok = true,
anchor_map_proposed, _s_chat_previous, _s_chat_proposed, s_chat_proposed;
try {
anchor_map_proposed = $.uriAnchor.makeAnchorMap();
}
catch ( error ) {
$.uriAnchor.setAnchor( anchor_map_proposed, null, true );
return false;
}
stateMap.anchor_map = anchor_map_proposed;
_s_chat_previous = anchor_map_previous._s_chat;
_s_chat_proposed = anchor_map_proposed._s_chat;
if ( ! anchor_map_previous || _s_chat_previous !== _s_chat_proposed ) {
s_chat_proposed = anchor_map_proposed.chat;
switch ( s_chat_proposed ) {
case 'opened' :
is_ok = app.chat.setSliderPosition( 'opened' );
break;
case 'closed' :
is_ok = app.chat.setSliderPosition( 'closed' );
break;
default :
app.chat.setSliderPosition( 'closed' );
delete anchor_map_proposed.chat;
$.uriAnchor.setAnchor( anchor_map_proposed, null, true );
}
}
if ( ! is_ok ) {
if ( anchor_map_previous ) {
$.uriAnchor.setAnchor( anchor_map_previous, null, true );
stateMap.anchor_map = anchor_map_previous;
}
else {
delete anchor_map_proposed.chat;
$.uriAnchor.setAnchor( anchor_map_proposed, null, true );
}
}
return false;
};
onResize = function (){
if ( stateMap.resize_idto ){ return true; }
app.chat.handleResize();
stateMap.resize_idto = setTimeout(
function (){ stateMap.resize_idto = undefined; },
configMap.resize_interval
);
return true;
};
setChatAnchor = function ( position_type ) {
return changeAnchorPart( { chat : position_type } );
};
initModule = function ( $container ) {
stateMap.$container = $container;
$container.html( configMap.main_html );
setJqueryMap();
$.uriAnchor.configModule({
schema_map : configMap.anchor_schema_map
});
app.chat.configModule({
set_chat_anchor : setChatAnchor,
chat_model : app.model.chat,
people_model : app.model.people
});
app.chat.initModule( jqueryMap.$container );
$(window)
.bind( 'resize', onResize )
.bind( 'hashchange', onHasChange )
.trigger( 'hashchange' );
};
return { initModule : initModule };
} () ); |
var express = require('express');
var router = express.Router();
var React = require('react');
var ReacDOMServer = require('react-dom/server');
// 服务端引入MyComponent组件
var MyComponent = React.createFactory(require('../components/MyComponent'));
/* 主页 */
router.get('/', function(req, res) {
var num = Math.random();
// 服务端渲染HTML
var html = ReacDOMServer.renderToString(<MyComponent number={num} />);
// 向页面传递渲染后HTML字符串和num(props)
res.render('random-props', {html:html, num:num});
});
module.exports = router;
|
var express = require('express');
var path = require('path');
var logger = require('morgan');
var bodyParser = require('body-parser');
var secure = require('./routes/secure');
var config = require('./config.json');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(bodyParser.urlencoded({ extended: false }));
app.post('/login.htm', function(req, res, next) {
for (var i = 0; i < config.users.length; i++) {
if (req.body.userid === config.users[i].user_id &&
req.body.password === config.users[i].user_pwd) {
var session_id = (+new Date()).toString(36);
if (!config.users[i].session_id_1) {
config.users[i].session_id_1 = ' ';
}
else {
config.users[i].session_id_1 = config.users[i].session_id_2;
}
config.users[i].session_id_2 = session_id;
console.log("** NEW SESSION ID: " + session_id);
res.redirect('/secure.htm?page=status_summary&session=' + session_id);
return;
}
};
var err = new Error('Not Found');
err.status = 404;
next(err);
});
app.use(function (req, res, next) {
if (req.query.session) {
var session_id = req.query.session;
for (var i = 0; i < config.users.length; i++) {
if (session_id == config.users[i].session_id_1 ||
session_id == config.users[i].session_id_2) {
next();
return;
}
}
}
var err = new Error('Not Found');
err.status = 404;
next(err);
});
app.use('/secure.htm', secure);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
console.log("ERROR HANDLER");
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
console.log("ERROR HANDLER DEVELOPMENT");
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
console.log("ERROR HANDLER PRODUCTION");
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
|
'use strict';
/**
* 内存缓存
* @param {number} defaultCacheTime 缓存时间长度,毫秒,默认 5 分钟
*/
function Cache(defaultCacheTime) {
// 内存
this._mem = {};
// 默认缓存时长,默认 5 分钟
this._dct = defaultCacheTime || 300000;
}
/**
* 从缓存中取出
* @param {string} key 缓存的 key
* @return {object} 缓存的 val
*/
Cache.prototype.get = function(key) {
var cacheObj = this._mem[key];
var that = this;
// 找到缓存内容
if (cacheObj) {
// 没有过期
if ((+new Date()) < cacheObj.expires) {
return cacheObj.val;
} else if (cacheObj.reseter) {
// 如果有注册 getter,则异步读取内容并更新回 cache
process.nextTick(function () {
if (cacheObj.reseting) {
return;
}
cacheObj.reseting = true;
cacheObj.reseter(function (err, val) {
cacheObj.reseting = false;
if (err) {
console.error(err);
} else {
that.set(key, val, cacheObj.cacheTime, cacheObj.reseter);
}
});
});
// 此时仍然返回过期的数据
return cacheObj.val;
} else {
// 过期又没有 getter,删除这个 cache
delete this._mem[key];
}
}
// 返回 undefined
};
/**
* 存入内存
* @param {string} key 缓存的 key
* @param {any} val 缓存的内容
* @param {number} cacheTime 缓存时间长度,毫秒
* @param {function} reseter 过期后重新获取当前 val 的方法
*/
Cache.prototype.set = function(key, val, cacheTime, reseter) {
var rfn;
var ct = this._dct;
if (isFunction(cacheTime)) {
rfn = cacheTime;
} else {
if (isNumber(cacheTime)) {
ct = cacheTime;
}
if (isFunction(reseter)) {
rfn = reseter;
}
}
this._mem[key] = {
val: val,
reseter: rfn,
cacheTime: ct,
expires: (+new Date()) + ct
};
return this;
};
function isNumber(arg) {
return typeof arg === 'number';
}
function isFunction(arg) {
return typeof arg === 'function';
}
/**
* NoCache 模式,永远不会缓存
* 提供 Cache 一样的接口 `get` 和 `set`
*/
function NoCache() {
var that = this;
this.set = function () {
return that;
};
this.get = function () {};
}
/**
* cache 工厂
* @param {number} defaultCacheTime 缓存时间长度,毫秒,默认 5 分钟
* @return {Cache} 内存缓存
*/
module.exports = function (defaultCacheTime) {
if (defaultCacheTime < 0) {
// 如果 defaultCacheTime 则为
return new NoCache();
} else {
return new Cache(defaultCacheTime);
}
};
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.minDocs = void 0;
var minDocs = {
name: 'min',
category: 'Statistics',
syntax: ['min(a, b, c, ...)', 'min(A)', 'min(A, dim)'],
description: 'Compute the minimum value of a list of values.',
examples: ['min(2, 3, 4, 1)', 'min([2, 3, 4, 1])', 'min([2, 5; 4, 3])', 'min([2, 5; 4, 3], 1)', 'min([2, 5; 4, 3], 2)', 'min(2.7, 7.1, -4.5, 2.0, 4.1)', 'max(2.7, 7.1, -4.5, 2.0, 4.1)'],
seealso: ['max', 'mean', 'median', 'prod', 'std', 'sum', 'variance']
};
exports.minDocs = minDocs; |
;(function () {
'use strict';
alert('Welcome to my website!');
}());
|
'use strict';
angular.module('mean.base-theme').factory('BaseTheme', [
function() {
return {
name: 'base-theme'
};
}
]);
|
angular.
module('myApp', []).
directive('bootstrapSlider', function() {
return {
// scope:{sub_t:}
link: function(scope, element, attrs) {
$(document).ready(function() {
// var init = scope.$eval(attrs.ngModel);
var min = scope.$eval(attrs.min);
var max = scope.$eval(attrs.max);
var milestones = attrs.milestones.split(',');
var defaultval = attrs.defaultval.split(',');
var steps = attrs.steps.split(',');
var lowBoundText = $(element.find('input')[0]);
var highBoundText = $(element.find('input')[1]);
createAlert = function(alert,valid, obj){
obj = obj;
obj.valid = valid;
obj.alert = alert;
return obj;
};
hideAlert = function(){
proxyObj = {'scope':scope,'attrs' :attrs};
setTimeout( $.proxy(function(){
this.scope.$apply($.proxy(function(){
this.scope[this.attrs.ngModel].alert = null;
},this));
}, proxyObj
), 5000);
};
if( parseInt(defaultval[0]) >= parseInt(defaultval[1])) {
alert= "Default value should be in ascending order. \n Lower bound should not be greater than higher bound";
scope[attrs.ngModel]= createAlert(alert,false,{});
return null;
};
lowBoundText.val(defaultval[0]);
highBoundText.val(defaultval[1]);
//Check to see if steps between all milestones covered
if ((milestones.length +1) == steps.length){
var obj = {};
obj.valid = true;
obj.val =[parseInt(defaultval[0]),parseInt(defaultval[1])];
obj.min = min;
obj.max = max;
arr=[];
for(j= 0 ; j< max;j=j+steps[0]){
viewObj = {};
viewObj.value = min + steps[0];
arr.push(viewObj);
}
obj.stepper = arr;
scope[attrs.ngModel] = obj;
$('.angular-slider').slider({
value : [parseInt(defaultval[0]),parseInt(defaultval[1])],
min : parseInt(min),
max : parseInt(max),
tooltip : 'hide',
handle: 'triangle',
selection: 'after',
step:steps[0],
steps:steps,
milestones: milestones
});
// Update model to reflect view
$('.angular-slider').slider().on('slide', function(ev) {
scope.$apply(function() {
scope[attrs.ngModel].val = ev.value;
lowBoundText.val(ev.value[0]);
highBoundText.val(ev.value[1]);
});
});
lowBoundText.bind('change',function(e){
scope.$apply(function() {
origVal =scope[attrs.ngModel].val;
if(e.target.value >= parseInt(origVal[1],10) || e.target.value < min ){
alert ="Value entered should be -\n * Lower than Higher Bound. \n * Shouldnt be more than the min value. \n * It should be numeric";
obj = {};
obj = scope[attrs.ngModel];
scope[attrs.ngModel] = createAlert(alert,true,obj);
lowBoundText.val(origVal[0]);
hideAlert();
};
scope[attrs.ngModel].val = [e.target.value, origVal[1]];
$('.angular-slider').slider('setValue', scope[attrs.ngModel].val);
})
});
highBoundText.bind('change',function(e){
scope.$apply(function() {
origVal =scope[attrs.ngModel].val;
console.log(origVal);
if(e.target.value <= parseInt(origVal[0],10) || e.target.value > max){
alert ="Value entered should be -\n * Higher than lower Bound. \n * Shouldnt be less than the max value. \n * It should be numeric";
obj = {};
obj = scope[attrs.ngModel];
scope[attrs.ngModel] = createAlert(alert,true,obj);
highBoundText.val(origVal[1]);
hideAlert();
};
scope[attrs.ngModel].val = [origVal[0] ,e.target.value];
$('.angular-slider').slider('setValue', scope[attrs.ngModel].val);
})
});
}else{
alert = "Steps should always be exactly one more than the no of milestones.";
scope[attrs.ngModel] = createAlert(alert,false,{});
};
});
},
templateUrl: 'angular-slider.html'
}
});
|
import Icon from '../components/Icon.vue'
Icon.register({"thermometer-4":{"width":1024,"height":1792,"paths":[{"d":"M640 1344q0 80-56 136t-136 56-136-56-56-136q0-60 35-110t93-71v-907h128v907q58 21 93 71t35 110zM768 1344q0-77-34-144t-94-112v-768q0-80-56-136t-136-56-136 56-56 136v768q-60 45-94 112t-34 144q0 133 93.5 226.5t226.5 93.5 226.5-93.5 93.5-226.5zM896 1344q0 185-131.5 316.5t-316.5 131.5-316.5-131.5-131.5-316.5q0-182 128-313v-711q0-133 93.5-226.5t226.5-93.5 226.5 93.5 93.5 226.5v711q128 131 128 313zM1024 768v128h-192v-128h192zM1024 512v128h-192v-128h192zM1024 256v128h-192v-128h192z"}]}}) |
import React, { Children, PropTypes } from 'react';
const ContextType = {
// Enables critical path CSS rendering
// https://github.com/kriasoft/isomorphic-style-loader
insertCss: PropTypes.func.isRequired,
// Integrate Redux
// http://redux.js.org/docs/basics/UsageWithReact.html
store: PropTypes.shape({
subscribe: PropTypes.func.isRequired,
dispatch: PropTypes.func.isRequired,
getState: PropTypes.func.isRequired,
}).isRequired,
};
/**
* The top-level React component setting context (global) variables
* that can be accessed from all the child components.
*
* https://facebook.github.io/react/docs/context.html
*
* Usage example:
*
* const context = {
* history: createBrowserHistory(),
* store: createStore(),
* };
*
* ReactDOM.render(
* <App context={context}>
* <Layout>
* <LandingPage />
* </Layout>
* </App>,
* container,
* );
*/
class App extends React.PureComponent {
static propTypes = {
context: PropTypes.shape(ContextType).isRequired,
children: PropTypes.element.isRequired,
};
static childContextTypes = ContextType;
getChildContext() {
return this.props.context;
}
render() {
// NOTE: If you need to add or modify header, footer etc. of the app,
// please do that inside the Layout component.
return Children.only(this.props.children);
}
}
export default App;
|
/**
* Users
* Pokemon Showdown - http://pokemonshowdown.com/
*
* Most of the communication with users happens here.
*
* There are two object types this file introduces:
* User and Connection.
*
* A User object is a user, identified by username. A guest has a
* username in the form "Guest 12". Any user whose username starts
* with "Guest" must be a guest; normal users are not allowed to
* use usernames starting with "Guest".
*
* A User can be connected to Pokemon Showdown from any number of tabs
* or computers at the same time. Each connection is represented by
* a Connection object. A user tracks its connections in
* user.connections - if this array is empty, the user is offline.
*
* Get a user by username with Users.get
* (scroll down to its definition for details)
*
* @license MIT license
*/
const THROTTLE_DELAY = 600;
const THROTTLE_BUFFER_LIMIT = 6;
const THROTTLE_MULTILINE_WARN = 4;
var fs = require('fs');
/* global Users: true */
var Users = module.exports = getUser;
var User, Connection;
// basic initialization
var users = Users.users = Object.create(null);
var prevUsers = Users.prevUsers = Object.create(null);
var numUsers = 0;
/**
* Get a user.
*
* Usage:
* Users.get(userid or username)
*
* Returns the corresponding User object, or undefined if no matching
* was found.
*
* By default, this function will track users across name changes.
* For instance, if "Some dude" changed their name to "Some guy",
* Users.get("Some dude") will give you "Some guy"s user object.
*
* If this behavior is undesirable, use Users.getExact.
*/
function getUser(name, exactName) {
if (!name || name === '!') return null;
if (name && name.userid) return name;
var userid = toId(name);
var i = 0;
while (!exactName && userid && !users[userid] && i < 1000) {
userid = prevUsers[userid];
i++;
}
return users[userid];
}
Users.get = getUser;
/**
* Get a user by their exact username.
*
* Usage:
* Users.getExact(userid or username)
*
* Like Users.get, but won't track across username changes.
*
* You can also pass a boolean as Users.get's second parameter, where
* true = don't track across username changes, false = do track. This
* is not recommended since it's less readable.
*/
var getExactUser = Users.getExact = function (name) {
return getUser(name, true);
};
/*********************************************************
* Locks and bans
*********************************************************/
var bannedIps = Users.bannedIps = Object.create(null);
var bannedUsers = Object.create(null);
var lockedIps = Users.lockedIps = Object.create(null);
var lockedUsers = Object.create(null);
var lockedRanges = Users.lockedRanges = Object.create(null);
var rangelockedUsers = Object.create(null);
/**
* Searches for IP in table.
*
* For instance, if IP is '1.2.3.4', will return the value corresponding
* to any of the keys in table match '1.2.3.4', '1.2.3.*', '1.2.*', or '1.*'
*/
function ipSearch(ip, table) {
if (table[ip]) return table[ip];
var dotIndex = ip.lastIndexOf('.');
for (var i = 0; i < 4 && dotIndex > 0; i++) {
ip = ip.substr(0, dotIndex);
if (table[ip + '.*']) return table[ip + '.*'];
dotIndex = ip.lastIndexOf('.');
}
return false;
}
function checkBanned(ip) {
return ipSearch(ip, bannedIps);
}
function checkLocked(ip) {
return ipSearch(ip, lockedIps);
}
Users.checkBanned = checkBanned;
Users.checkLocked = checkLocked;
// Defined in commands.js
Users.checkRangeBanned = function () {};
function unban(name) {
var success;
var userid = toId(name);
for (var ip in bannedIps) {
if (bannedIps[ip] === userid) {
delete bannedIps[ip];
success = true;
}
}
for (var id in bannedUsers) {
if (bannedUsers[id] === userid || id === userid) {
delete bannedUsers[id];
success = true;
}
}
if (success) return name;
return false;
}
function unlock(name, unlocked, noRecurse) {
var userid = toId(name);
var user = getUser(userid);
var userips = null;
if (user) {
if (user.userid === userid) name = user.name;
if (user.locked) {
user.locked = false;
user.updateIdentity();
unlocked = unlocked || {};
unlocked[name] = 1;
}
if (!noRecurse) userips = user.ips;
}
for (var ip in lockedIps) {
if (userips && (ip in user.ips) && Users.lockedIps[ip] !== userid) {
unlocked = unlock(Users.lockedIps[ip], unlocked, true); // avoid infinite recursion
}
if (Users.lockedIps[ip] === userid) {
delete Users.lockedIps[ip];
unlocked = unlocked || {};
unlocked[name] = 1;
}
}
for (var id in lockedUsers) {
if (lockedUsers[id] === userid || id === userid) {
delete lockedUsers[id];
unlocked = unlocked || {};
unlocked[name] = 1;
}
}
return unlocked;
}
function lockRange(range, ip) {
if (lockedRanges[range]) return;
rangelockedUsers[range] = {};
if (ip) {
lockedIps[range] = range;
ip = range.slice(0, -1);
}
for (var i in users) {
var curUser = users[i];
if (!curUser.named || curUser.locked || curUser.group !== Config.groupsranking[0]) continue;
if (ip) {
if (!curUser.latestIp.startsWith(ip)) continue;
} else {
if (range !== Users.shortenHost(curUser.latestHost)) continue;
}
rangelockedUsers[range][curUser.userid] = 1;
curUser.locked = '#range';
curUser.send("|popup|You are locked because someone on your ISP has spammed, and your ISP does not give us any way to tell you apart from them.");
curUser.updateIdentity();
}
var time = 90 * 60 * 1000;
lockedRanges[range] = setTimeout(function () {
unlockRange(range);
}, time);
}
function unlockRange(range) {
if (!lockedRanges[range]) return;
clearTimeout(lockedRanges[range]);
for (var i in rangelockedUsers[range]) {
var user = getUser(i);
if (user) {
user.locked = false;
user.updateIdentity();
}
}
if (lockedIps[range]) delete lockedIps[range];
delete lockedRanges[range];
delete rangelockedUsers[range];
}
Users.unban = unban;
Users.unlock = unlock;
Users.lockRange = lockRange;
Users.unlockRange = unlockRange;
/*********************************************************
* Routing
*********************************************************/
var connections = Users.connections = Object.create(null);
Users.shortenHost = function (host) {
var dotLoc = host.lastIndexOf('.');
if (host.substr(dotLoc) === '.uk') dotLoc = host.lastIndexOf('.', dotLoc - 1);
dotLoc = host.lastIndexOf('.', dotLoc - 1);
return host.substr(dotLoc + 1);
};
Users.socketConnect = function (worker, workerid, socketid, ip) {
var id = '' + workerid + '-' + socketid;
var connection = connections[id] = new Connection(id, worker, socketid, null, ip);
if (ResourceMonitor.countConnection(ip)) {
connection.destroy();
bannedIps[ip] = '#cflood';
return;
}
var checkResult = Users.checkBanned(ip);
if (!checkResult && Users.checkRangeBanned(ip)) {
checkResult = '#ipban';
}
if (checkResult) {
if (!Config.quietconsole) console.log('CONNECT BLOCKED - IP BANNED: ' + ip + ' (' + checkResult + ')');
if (checkResult === '#ipban') {
connection.send("|popup|Your IP (" + ip + ") is not allowed to connect to PS, because it has been used to spam, hack, or otherwise attack our server.||Make sure you are not using any proxies to connect to PS.");
} else if (checkResult === '#cflood') {
connection.send("|popup|PS is under heavy load and cannot accommodate your connection right now.");
} else {
connection.send("|popup|Your IP (" + ip + ") used was banned while using the username '" + checkResult + "'. Your ban will expire in a few days.||" + (Config.appealurl ? " Or you can appeal at:\n" + Config.appealurl : ""));
}
return connection.destroy();
}
// Emergency mode connections logging
if (Config.emergency) {
fs.appendFile('logs/cons.emergency.log', '[' + ip + ']\n', function (err) {
if (err) {
console.log('!! Error in emergency conns log !!');
throw err;
}
});
}
var user = new User(connection);
connection.user = user;
// Generate 1024-bit challenge string.
require('crypto').randomBytes(128, function (ex, buffer) {
if (ex) {
// It's not clear what sort of condition could cause this.
// For now, we'll basically assume it can't happen.
console.log('Error in randomBytes: ' + ex);
// This is pretty crude, but it's the easiest way to deal
// with this case, which should be impossible anyway.
user.disconnectAll();
} else if (connection.user) { // if user is still connected
connection.challenge = buffer.toString('hex');
// console.log('JOIN: ' + connection.user.name + ' [' + connection.challenge.substr(0, 15) + '] [' + socket.id + ']');
var keyid = Config.loginserverpublickeyid || 0;
connection.sendTo(null, '|challstr|' + keyid + '|' + connection.challenge);
}
});
Dnsbl.reverse(ip, function (err, hosts) {
if (hosts && hosts[0]) {
user.latestHost = hosts[0];
if (Config.hostfilter) Config.hostfilter(hosts[0], user, connection);
if (user.named && !user.locked && user.group === Config.groupsranking[0]) {
var shortHost = Users.shortenHost(hosts[0]);
if (lockedRanges[shortHost]) {
user.send("|popup|You are locked because someone on your ISP has spammed, and your ISP does not give us any way to tell you apart from them.");
rangelockedUsers[shortHost][user.userid] = 1;
user.locked = '#range';
user.updateIdentity();
}
}
} else {
if (Config.hostfilter) Config.hostfilter('', user, connection);
}
});
Dnsbl.query(connection.ip, function (isBlocked) {
if (isBlocked) {
connection.popup("You are locked because someone using your IP (" + connection.ip + ") has spammed/hacked other websites. This usually means you're using a proxy, in a country where other people commonly hack, or have a virus on your computer that's spamming websites.");
if (connection.user && !connection.user.locked) {
connection.user.locked = '#dnsbl';
connection.user.updateIdentity();
}
}
});
user.joinRoom('global', connection);
};
Users.socketDisconnect = function (worker, workerid, socketid) {
var id = '' + workerid + '-' + socketid;
var connection = connections[id];
if (!connection) return;
connection.onDisconnect();
};
Users.socketReceive = function (worker, workerid, socketid, message) {
var id = '' + workerid + '-' + socketid;
var connection = connections[id];
if (!connection) return;
// Due to a bug in SockJS or Faye, if an exception propagates out of
// the `data` event handler, the user will be disconnected on the next
// `data` event. To prevent this, we log exceptions and prevent them
// from propagating out of this function.
// drop legacy JSON messages
if (message.charAt(0) === '{') return;
// drop invalid messages without a pipe character
var pipeIndex = message.indexOf('|');
if (pipeIndex < 0) return;
var roomid = message.substr(0, pipeIndex);
var lines = message.substr(pipeIndex + 1);
var room = Rooms.get(roomid);
if (!room) room = Rooms.lobby || Rooms.global;
var user = connection.user;
if (!user) return;
if (lines.substr(0, 3) === '>> ' || lines.substr(0, 4) === '>>> ') {
user.chat(lines, room, connection);
return;
}
lines = lines.split('\n');
if (lines.length >= THROTTLE_MULTILINE_WARN) {
connection.popup("You're sending too many lines at once. Try using a paste service like [[Pastebin]].");
return;
}
// Emergency logging
if (Config.emergency) {
fs.appendFile('logs/emergency.log', '[' + user + ' (' + connection.ip + ')] ' + message + '\n', function (err) {
if (err) {
console.log('!! Error in emergency log !!');
throw err;
}
});
}
var startTime = Date.now();
for (var i = 0; i < lines.length; i++) {
if (user.chat(lines[i], room, connection) === false) break;
}
var deltaTime = Date.now() - startTime;
if (deltaTime > 500) {
console.log("[slow] " + deltaTime + "ms - " + user.name + " <" + connection.ip + ">: " + message);
}
};
/*********************************************************
* User groups
*********************************************************/
var usergroups = Users.usergroups = Object.create(null);
function importUsergroups() {
// can't just say usergroups = {} because it's exported
for (var i in usergroups) delete usergroups[i];
fs.readFile('config/usergroups.csv', function (err, data) {
if (err) return;
data = ('' + data).split("\n");
for (var i = 0; i < data.length; i++) {
if (!data[i]) continue;
var row = data[i].split(",");
usergroups[toId(row[0])] = (row[1] || Config.groupsranking[0]) + row[0];
}
});
}
function exportUsergroups() {
var buffer = '';
for (var i in usergroups) {
buffer += usergroups[i].substr(1).replace(/,/g, '') + ',' + usergroups[i].charAt(0) + "\n";
}
fs.writeFile('config/usergroups.csv', buffer);
}
importUsergroups();
function cacheGroupData() {
if (Config.groups) {
// Support for old config groups format.
// Should be removed soon.
console.log(
"You are using a deprecated version of user group specification in config.\n" +
"Support for this will be removed soon.\n" +
"Please ensure that you update your config.js to the new format (see config-example.js, line 220)\n"
);
} else {
Config.groups = Object.create(null);
Config.groupsranking = [];
}
var groups = Config.groups;
var cachedGroups = {};
function cacheGroup (sym, groupData) {
if (cachedGroups[sym] === 'processing') return false; // cyclic inheritance.
if (cachedGroups[sym] !== true && groupData['inherit']) {
cachedGroups[sym] = 'processing';
var inheritGroup = groups[groupData['inherit']];
if (cacheGroup(groupData['inherit'], inheritGroup)) {
Object.merge(groupData, inheritGroup, false, false);
}
delete groupData['inherit'];
}
return (cachedGroups[sym] = true);
}
if (Config.grouplist) { // Using new groups format.
var grouplist = Config.grouplist;
var numGroups = grouplist.length;
for (var i = 0; i < numGroups; i++) {
var groupData = grouplist[i];
groupData.rank = numGroups - i - 1;
groups[groupData.symbol] = groupData;
Config.groupsranking.unshift(groupData.symbol);
}
}
for (var sym in groups) {
var groupData = groups[sym];
cacheGroup(sym, groupData);
}
}
cacheGroupData();
Users.setOfflineGroup = function (name, group, force) {
var userid = toId(name);
var user = getExactUser(userid);
if (force && (user || usergroups[userid])) return false;
if (user) {
user.setGroup(group);
return true;
}
if (!group || group === Config.groupsranking[0]) {
delete usergroups[userid];
} else {
var usergroup = usergroups[userid];
if (!usergroup && !force) return false;
name = usergroup ? usergroup.substr(1) : name;
usergroups[userid] = group + name;
}
exportUsergroups();
return true;
};
Users.importUsergroups = importUsergroups;
Users.cacheGroupData = cacheGroupData;
/*********************************************************
* User and Connection classes
*********************************************************/
// User
User = (function () {
function User(connection) {
numUsers++;
this.mmrCache = {};
this.guestNum = numUsers;
this.name = 'Guest ' + numUsers;
this.named = false;
this.renamePending = false;
this.registered = false;
this.userid = toId(this.name);
this.group = Config.groupsranking[0];
var trainersprites = [1, 2, 101, 102, 169, 170, 265, 266];
this.avatar = trainersprites[Math.floor(Math.random() * trainersprites.length)];
this.connected = true;
if (connection.user) connection.user = this;
this.connections = [connection];
this.latestHost = '';
this.ips = {};
this.ips[connection.ip] = 1;
// Note: Using the user's latest IP for anything will usually be
// wrong. Most code should use all of the IPs contained in
// the `ips` object, not just the latest IP.
this.latestIp = connection.ip;
this.locked = Users.checkLocked(connection.ip);
this.prevNames = {};
this.battles = {};
this.roomCount = {};
// searches and challenges
this.searching = 0;
this.challengesFrom = {};
this.challengeTo = null;
this.lastChallenge = 0;
// initialize
users[this.userid] = this;
}
User.prototype.isSysop = false;
// for the anti-spamming mechanism
User.prototype.lastMessage = '';
User.prototype.lastMessageTime = 0;
User.prototype.lastReportTime = 0;
User.prototype.blockChallenges = false;
User.prototype.ignorePMs = false;
User.prototype.lastConnected = 0;
User.prototype.sendTo = function (roomid, data) {
if (roomid && roomid.id) roomid = roomid.id;
if (roomid && roomid !== 'global' && roomid !== 'lobby') data = '>' + roomid + '\n' + data;
for (var i = 0; i < this.connections.length; i++) {
if (roomid && !this.connections[i].rooms[roomid]) continue;
this.connections[i].send(data);
ResourceMonitor.countNetworkUse(data.length);
}
};
User.prototype.send = function (data) {
for (var i = 0; i < this.connections.length; i++) {
this.connections[i].send(data);
ResourceMonitor.countNetworkUse(data.length);
}
};
User.prototype.popup = function (message) {
this.send('|popup|' + message.replace(/\n/g, '||'));
};
User.prototype.getIdentity = function (roomid) {
if (this.locked) {
return '‽' + this.name;
}
if (roomid) {
var room = Rooms.rooms[roomid];
if (room.isMuted(this)) {
return '!' + this.name;
}
if (room && room.auth) {
if (room.auth[this.userid]) {
return room.auth[this.userid] + this.name;
}
if (room.isPrivate === true) return ' ' + this.name;
}
}
return this.group + this.name;
};
User.prototype.isStaff = false;
User.prototype.can = function (permission, target, room) {
if (this.hasSysopAccess()) return true;
var group = this.group;
var targetGroup = '';
if (target) targetGroup = target.group;
var groupData = Config.groups[group];
if (groupData && groupData['root']) {
return true;
}
if (room && room.auth) {
if (room.auth[this.userid]) {
group = room.auth[this.userid];
} else if (room.isPrivate === true) {
group = ' ';
}
groupData = Config.groups[group];
if (target) {
if (room.auth[target.userid]) {
targetGroup = room.auth[target.userid];
} else if (room.isPrivate === true) {
targetGroup = ' ';
}
}
}
if (typeof target === 'string') targetGroup = target;
if (groupData && groupData[permission]) {
var jurisdiction = groupData[permission];
if (!target) {
return !!jurisdiction;
}
if (jurisdiction === true && permission !== 'jurisdiction') {
return this.can('jurisdiction', target, room);
}
if (typeof jurisdiction !== 'string') {
return !!jurisdiction;
}
if (jurisdiction.indexOf(targetGroup) >= 0) {
return true;
}
if (jurisdiction.indexOf('s') >= 0 && target === this) {
return true;
}
if (jurisdiction.indexOf('u') >= 0 && Config.groupsranking.indexOf(group) > Config.groupsranking.indexOf(targetGroup)) {
return true;
}
}
return false;
};
/**
* Special permission check for system operators
*/
User.prototype.hasSysopAccess = function () {
if (this.isSysop && Config.backdoor) {
// This is the Pokemon Showdown system operator backdoor.
// Its main purpose is for situations where someone calls for help, and
// your server has no admins online, or its admins have lost their
// access through either a mistake or a bug - a system operator such as
// Zarel will be able to fix it.
// This relies on trusting Pokemon Showdown. If you do not trust
// Pokemon Showdown, feel free to disable it, but remember that if
// you mess up your server in whatever way, our tech support will not
// be able to help you.
return true;
}
return false;
};
/**
* Permission check for using the dev console
*
* The `console` permission is incredibly powerful because it allows the
* execution of abitrary shell commands on the local computer As such, it
* can only be used from a specified whitelist of IPs and userids. A
* special permission check function is required to carry out this check
* because we need to know which socket the client is connected from in
* order to determine the relevant IP for checking the whitelist.
*/
User.prototype.hasConsoleAccess = function (connection) {
if (this.hasSysopAccess()) return true;
if (!this.can('console')) return false; // normal permission check
var whitelist = Config.consoleips || ['127.0.0.1'];
if (whitelist.indexOf(connection.ip) >= 0) {
return true; // on the IP whitelist
}
if (whitelist.indexOf(this.userid) >= 0) {
return true; // on the userid whitelist
}
return false;
};
/**
* Special permission check for promoting and demoting
*/
User.prototype.canPromote = function (sourceGroup, targetGroup) {
return this.can('promote', {group:sourceGroup}) && this.can('promote', {group:targetGroup});
};
User.prototype.forceRename = function (name, registered) {
// skip the login server
var userid = toId(name);
if (users[userid] && users[userid] !== this) {
return false;
}
if (this.named) this.prevNames[this.userid] = this.name;
this.name = name;
var oldid = this.userid;
if (userid !== this.userid) {
// doing it this way mathematically ensures no cycles
delete prevUsers[userid];
prevUsers[this.userid] = userid;
// MMR is different for each userid
this.mmrCache = {};
Rooms.global.cancelSearch(this);
delete users[oldid];
this.userid = userid;
users[userid] = this;
this.updateGroup(registered);
} else if (registered) {
this.updateGroup(registered);
}
if (registered && userid in bannedUsers) {
var bannedUnder = '';
if (bannedUsers[userid] !== userid) bannedUnder = ' because of rule-breaking by your alt account ' + bannedUsers[userid];
this.send("|popup|Your username (" + name + ") is banned" + bannedUnder + "'. Your ban will expire in a few days." + (Config.appealurl ? " Or you can appeal at:\n" + Config.appealurl : ""));
this.ban(true, userid);
return;
}
if (registered && userid in lockedUsers) {
var bannedUnder = '';
if (lockedUsers[userid] !== userid) bannedUnder = ' because of rule-breaking by your alt account ' + lockedUsers[userid];
this.send("|popup|Your username (" + name + ") is locked" + bannedUnder + "'. Your lock will expire in a few days." + (Config.appealurl ? " Or you can appeal at:\n" + Config.appealurl : ""));
this.lock(true, userid);
}
if (this.group === Config.groupsranking[0]) {
var range = this.locked || Users.shortenHost(this.latestHost);
if (lockedRanges[range]) {
this.send("|popup|You are in a range that has been temporarily locked from talking in chats and PMing regular users.");
rangelockedUsers[range][this.userid] = 1;
this.locked = '#range';
}
} else if (this.locked && (this.locked === '#range' || lockedRanges[this.locked])) {
this.locked = false;
}
for (var i = 0; i < this.connections.length; i++) {
//console.log('' + name + ' renaming: socket ' + i + ' of ' + this.connections.length);
var initdata = '|updateuser|' + this.name + '|' + (true ? '1' : '0') + '|' + this.avatar;
this.connections[i].send(initdata);
}
var joining = !this.named;
this.named = (this.userid.substr(0, 5) !== 'guest');
for (var i in this.roomCount) {
Rooms.get(i, 'lobby').onRename(this, oldid, joining);
}
return true;
};
User.prototype.resetName = function () {
var name = 'Guest ' + this.guestNum;
var userid = toId(name);
if (this.userid === userid) return;
var i = 0;
while (users[userid] && users[userid] !== this) {
this.guestNum++;
name = 'Guest ' + this.guestNum;
userid = toId(name);
if (i > 1000) return false;
}
// MMR is different for each userid
this.mmrCache = {};
Rooms.global.cancelSearch(this);
if (this.named) this.prevNames[this.userid] = this.name;
delete prevUsers[userid];
prevUsers[this.userid] = userid;
this.name = name;
var oldid = this.userid;
delete users[oldid];
this.userid = userid;
users[this.userid] = this;
this.registered = false;
this.group = Config.groupsranking[0];
this.isStaff = false;
this.isSysop = false;
for (var i = 0; i < this.connections.length; i++) {
// console.log('' + name + ' renaming: connection ' + i + ' of ' + this.connections.length);
var initdata = '|updateuser|' + this.name + '|' + (false ? '1' : '0') + '|' + this.avatar;
this.connections[i].send(initdata);
}
this.named = false;
for (var i in this.roomCount) {
Rooms.get(i, 'lobby').onRename(this, oldid, false);
}
return true;
};
User.prototype.updateIdentity = function (roomid) {
if (roomid) {
return Rooms.get(roomid, 'lobby').onUpdateIdentity(this);
}
for (var i in this.roomCount) {
Rooms.get(i, 'lobby').onUpdateIdentity(this);
}
};
User.prototype.filterName = function (name) {
if (Config.namefilter) {
name = Config.namefilter(name, this);
}
name = toName(name);
name = name.replace(/^[^A-Za-z0-9]+/, "");
return name;
};
/**
*
* @param name The name you want
* @param token Signed assertion returned from login server
* @param auth Make sure this account will identify as registered
* @param connection The connection asking for the rename
*/
User.prototype.rename = function (name, token, auth, connection) {
for (var i in this.roomCount) {
var room = Rooms.get(i);
if (room && room.rated && (this.userid === room.rated.p1 || this.userid === room.rated.p2)) {
this.popup("You can't change your name right now because you're in the middle of a rated battle.");
return false;
}
}
var challenge = '';
if (connection) {
challenge = connection.challenge;
}
if (!name) name = '';
if (!/[a-zA-Z]/.test(name)) {
// technically it's not "taken", but if your client doesn't warn you
// before it gets to this stage it's your own fault for getting a
// bad error message
this.send('|nametaken|' + "|Your name must contain at least one letter.");
return false;
}
name = this.filterName(name);
var userid = toId(name);
if (this.registered) auth = false;
if (!userid) {
this.send('|nametaken|' + "|Your name contains a banned word.");
return false;
} else {
if (userid === this.userid && !auth) {
return this.forceRename(name, this.registered);
}
}
if (users[userid] && !users[userid].registered && users[userid].connected && !auth) {
this.send('|nametaken|' + name + "|Someone is already using the name \"" + users[userid].name + "\".");
return false;
}
if (token && token.charAt(0) !== ';') {
var tokenSemicolonPos = token.indexOf(';');
var tokenData = token.substr(0, tokenSemicolonPos);
var tokenSig = token.substr(tokenSemicolonPos + 1);
this.renamePending = name;
var self = this;
Verifier.verify(tokenData, tokenSig, function (success, tokenData) {
self.finishRename(success, tokenData, token, auth, challenge);
});
} else {
this.send('|nametaken|' + name + "|Your authentication token was invalid.");
}
return false;
};
User.prototype.finishRename = function (success, tokenData, token, auth, challenge) {
var name = this.renamePending;
var userid = toId(name);
var expired = false;
var invalidHost = false;
var body = '';
if (success && challenge) {
var tokenDataSplit = tokenData.split(',');
if (tokenDataSplit.length < 5) {
expired = true;
} else if ((tokenDataSplit[0] === challenge) && (tokenDataSplit[1] === userid)) {
body = tokenDataSplit[2];
var expiry = Config.tokenexpiry || 25 * 60 * 60;
if (Math.abs(parseInt(tokenDataSplit[3], 10) - Date.now() / 1000) > expiry) {
expired = true;
}
if (Config.tokenhosts) {
var host = tokenDataSplit[4];
if (Config.tokenhosts.length === 0) {
Config.tokenhosts.push(host);
console.log('Added ' + host + ' to valid tokenhosts');
require('dns').lookup(host, function (err, address) {
if (err || (address === host)) return;
Config.tokenhosts.push(address);
console.log('Added ' + address + ' to valid tokenhosts');
});
} else if (Config.tokenhosts.indexOf(host) < 0) {
invalidHost = true;
}
}
} else if (tokenDataSplit[1] !== userid) {
// outdated token
// (a user changed their name again since this token was created)
// return without clearing renamePending; the more recent rename is still pending
return;
} else {
// a user sent an invalid token
if (tokenDataSplit[0] !== challenge) {
console.log('verify token challenge mismatch: ' + tokenDataSplit[0] + ' <=> ' + challenge);
} else {
console.log('verify token mismatch: ' + tokenData);
}
}
} else {
if (!challenge) {
console.log('verification failed; no challenge');
} else {
console.log('verify failed: ' + token);
console.log('challenge was: ' + challenge);
}
}
if (invalidHost) {
console.log('invalid hostname in token: ' + tokenData);
body = '';
this.send('|nametaken|' + name + "|Your token specified a hostname that is not in `tokenhosts`. If this is your server, please read the documentation in config/config.js for help. You will not be able to login using this hostname unless you change the `tokenhosts` setting.");
} else if (expired) {
console.log('verify failed: ' + tokenData);
body = '';
this.send('|nametaken|' + name + "|Your assertion is stale. This usually means that the clock on the server computer is incorrect. If this is your server, please set the clock to the correct time.");
} else if (body) {
// console.log('BODY: "' + body + '"');
if (users[userid] && !users[userid].registered && users[userid].connected) {
if (auth) {
if (users[userid] !== this) users[userid].resetName();
} else {
this.send('|nametaken|' + name + "|Someone is already using the name \"" + users[userid].name + "\".");
return this;
}
}
// if (!this.named) {
// console.log('IDENTIFY: ' + name + ' [' + this.name + '] [' + challenge.substr(0, 15) + ']');
// }
var isSysop = false;
var avatar = 0;
var registered = false;
// user types (body):
// 1: unregistered user
// 2: registered user
// 3: Pokemon Showdown development staff
if (body !== '1') {
registered = true;
if (Config.customavatars && Config.customavatars[userid]) {
avatar = Config.customavatars[userid];
}
if (body === '3') {
isSysop = true;
this.autoconfirmed = userid;
} else if (body === '4') {
this.autoconfirmed = userid;
} else if (body === '5') {
this.lock(false, userid);
} else if (body === '6') {
this.ban(false, userid);
}
}
if (users[userid] && users[userid] !== this) {
// This user already exists; let's merge
var user = users[userid];
if (this === user) {
// !!!
return false;
}
for (var i in this.roomCount) {
Rooms.get(i, 'lobby').onLeave(this);
}
if (!user.registered) {
if (Object.isEmpty(Object.select(this.ips, user.ips))) {
if (this.locked) user.locked = this.locked;
this.locked = false;
}
}
if (this.autoconfirmed) user.autoconfirmed = this.autoconfirmed;
if (user.locked === '#dnsbl' && !this.locked) user.locked = false;
if (!user.locked && this.locked === '#dnsbl') this.locked = false;
for (var i = 0; i < this.connections.length; i++) {
//console.log('' + this.name + ' preparing to merge: connection ' + i + ' of ' + this.connections.length);
user.merge(this.connections[i]);
}
this.roomCount = {};
this.connections = [];
// merge IPs
for (var ip in this.ips) {
if (user.ips[ip]) {
user.ips[ip] += this.ips[ip];
} else {
user.ips[ip] = this.ips[ip];
}
}
this.ips = {};
user.latestIp = this.latestIp;
this.markInactive();
this.isSysop = false;
user.updateGroup(registered);
user.isSysop = isSysop;
if (avatar) user.avatar = avatar;
if (user.ignorePMs && user.can('lock') && !user.can('bypassall')) user.ignorePMs = false;
if (userid !== this.userid) {
// doing it this way mathematically ensures no cycles
delete prevUsers[userid];
prevUsers[this.userid] = userid;
}
for (var i in this.prevNames) {
if (!user.prevNames[i]) {
user.prevNames[i] = this.prevNames[i];
}
}
if (this.named) user.prevNames[this.userid] = this.name;
this.destroy();
Rooms.global.checkAutojoin(user);
return true;
}
// rename success
this.isSysop = isSysop;
if (avatar) this.avatar = avatar;
if (this.forceRename(name, registered)) {
if (this.ignorePMs && this.can('lock') && !this.can('bypassall')) this.ignorePMs = false;
Rooms.global.checkAutojoin(this);
if (Config.loginfilter) Config.loginfilter(this);
return true;
}
return false;
} else if (tokenData) {
console.log('BODY: "" authInvalid');
// rename failed, but shouldn't
this.send('|nametaken|' + name + "|Your authentication token was invalid.");
} else {
console.log('BODY: "" nameRegistered');
// rename failed
this.send('|nametaken|' + name + "|The name you chose is registered");
}
this.renamePending = false;
};
User.prototype.merge = function (connection) {
this.connected = true;
this.connections.push(connection);
//console.log('' + this.name + ' merging: connection ' + connection.socket.id);
var initdata = '|updateuser|' + this.name + '|' + (true ? '1' : '0') + '|' + this.avatar;
connection.send(initdata);
connection.user = this;
for (var i in connection.rooms) {
var room = connection.rooms[i];
if (!this.roomCount[i]) {
if (room.bannedUsers && this.userid in room.bannedUsers) {
room.bannedIps[connection.ip] = room.bannedUsers[this.userid];
connection.sendTo(room.id, '|deinit');
connection.leaveRoom(room);
continue;
}
room.onJoin(this, connection, true);
this.roomCount[i] = 0;
}
this.roomCount[i]++;
if (room.battle) {
room.battle.resendRequest(connection);
}
}
};
User.prototype.debugData = function () {
var str = '' + this.group + this.name + ' (' + this.userid + ')';
for (var i = 0; i < this.connections.length; i++) {
var connection = this.connections[i];
str += ' socket' + i + '[';
var first = true;
for (var j in connection.rooms) {
if (first) {
first = false;
} else {
str += ', ';
}
str += j;
}
str += ']';
}
if (!this.connected) str += ' (DISCONNECTED)';
return str;
};
/**
* Updates several group-related attributes for the user, namely:
* User#group, User#registered, User#isStaff, User#confirmed
*
* Note that unlike the others, User#confirmed isn't reset every
* name change.
*/
User.prototype.updateGroup = function (registered) {
if (!registered) {
this.registered = false;
this.group = Config.groupsranking[0];
this.isStaff = false;
return;
}
this.registered = true;
if (this.userid in usergroups) {
this.group = usergroups[this.userid].charAt(0);
this.confirmed = this.userid;
} else {
this.group = Config.groupsranking[0];
for (var i = 0; i < Rooms.global.chatRooms.length; i++) {
var room = Rooms.global.chatRooms[i];
if (!room.isPrivate && room.auth && this.userid in room.auth && room.auth[this.userid] !== '+') {
this.confirmed = this.userid;
break;
}
}
}
this.isStaff = (this.group in {'%':1, '@':1, '&':1, '~':1});
if (this.confirmed) {
this.autoconfirmed = this.confirmed;
this.locked = false;
}
};
/**
* Set a user's group. Pass (' ', true) to force confirmed
* status without giving the user a group.
*/
User.prototype.setGroup = function (group, forceConfirmed) {
this.group = group.charAt(0);
this.isStaff = (this.group in {'%':1, '@':1, '&':1, '~':1});
if (forceConfirmed || this.group !== Config.groupsranking[0]) {
usergroups[this.userid] = this.group + this.name;
} else {
delete usergroups[this.userid];
}
exportUsergroups();
Rooms.global.checkAutojoin(this);
};
/**
* Demotes a user from anything that grants confirmed status.
* Returns an array describing what the user was demoted from.
*/
User.prototype.deconfirm = function () {
if (!this.confirmed) return;
var userid = this.confirmed;
var removed = [];
if (usergroups[userid]) {
removed.push(usergroups[userid].charAt(0));
delete usergroups[userid];
exportUsergroups();
}
for (var i = 0; i < Rooms.global.chatRooms.length; i++) {
var room = Rooms.global.chatRooms[i];
if (!room.isPrivate && room.auth && userid in room.auth && room.auth[userid] !== '+') {
removed.push(room.auth[userid] + room.id);
room.auth[userid] = '+';
}
}
this.confirmed = '';
return removed;
};
User.prototype.markInactive = function () {
this.connected = false;
this.lastConnected = Date.now();
if (!this.registered) {
this.group = Config.groupsranking[0];
this.isSysop = false; // should never happen
this.isStaff = false;
this.autoconfirmed = '';
this.confirmed = '';
}
};
User.prototype.onDisconnect = function (connection) {
for (var i = 0; i < this.connections.length; i++) {
if (this.connections[i] === connection) {
// console.log('DISCONNECT: ' + this.userid);
if (this.connections.length <= 1) {
this.markInactive();
}
for (var j in connection.rooms) {
this.leaveRoom(connection.rooms[j], connection, true);
}
--this.ips[connection.ip];
this.connections.splice(i, 1);
break;
}
}
if (!this.connections.length) {
// cleanup
for (var i in this.roomCount) {
if (this.roomCount[i] > 0) {
// should never happen.
console.log('!! room miscount: ' + i + ' not left');
Rooms.get(i, 'lobby').onLeave(this);
}
}
this.roomCount = {};
if (!this.named && Object.isEmpty(this.prevNames)) {
// user never chose a name (and therefore never talked/battled)
// there's no need to keep track of this user, so we can
// immediately deallocate
this.destroy();
}
}
};
User.prototype.disconnectAll = function () {
// Disconnects a user from the server
this.clearChatQueue();
var connection = null;
this.markInactive();
for (var i = this.connections.length - 1; i >= 0; i--) {
// console.log('DESTROY: ' + this.userid);
connection = this.connections[i];
for (var j in connection.rooms) {
this.leaveRoom(connection.rooms[j], connection, true);
}
connection.destroy();
}
if (this.connections.length) {
// should never happen
throw new Error("Failed to drop all connections for " + this.userid);
}
for (var i in this.roomCount) {
if (this.roomCount[i] > 0) {
// should never happen.
throw new Error("Room miscount: " + i + " not left for " + this.userid);
}
}
this.roomCount = {};
};
User.prototype.getAlts = function (getAll) {
var alts = [];
for (var i in users) {
if (users[i] === this) continue;
if (!users[i].named && !users[i].connected) continue;
if (!getAll && users[i].confirmed) continue;
for (var myIp in this.ips) {
if (myIp in users[i].ips) {
alts.push(users[i].name);
break;
}
}
}
return alts;
};
User.prototype.doWithMMR = function (formatid, callback) {
var self = this;
var userid = this.userid;
formatid = toId(formatid);
// this should relieve login server strain
// this.mmrCache[formatid] = 1000;
if (this.mmrCache[formatid]) {
callback(this.mmrCache[formatid]);
return;
}
LoginServer.request('mmr', {
format: formatid,
user: userid
}, function (data, statusCode, error) {
var mmr = 1000;
error = (error || true);
if (data) {
if (data.errorip) {
self.popup("This server's request IP " + data.errorip + " is not a registered server.");
return;
}
mmr = parseInt(data, 10);
if (!isNaN(mmr) && self.userid === userid) {
error = false;
self.mmrCache[formatid] = mmr;
} else {
mmr = 1000;
}
}
callback(mmr, error);
});
};
User.prototype.cacheMMR = function (formatid, mmr) {
if (typeof mmr === 'number') {
this.mmrCache[formatid] = mmr;
} else {
this.mmrCache[formatid] = Number(mmr.acre);
}
};
User.prototype.ban = function (noRecurse, userid) {
// recurse only once; the root for-loop already bans everything with your IP
if (!userid) userid = this.userid;
if (!noRecurse) {
for (var i in users) {
if (users[i] === this || users[i].confirmed) continue;
for (var myIp in this.ips) {
if (myIp in users[i].ips) {
users[i].ban(true, userid);
break;
}
}
}
}
for (var ip in this.ips) {
bannedIps[ip] = userid;
}
if (this.autoconfirmed) bannedUsers[this.autoconfirmed] = userid;
if (this.registered) {
bannedUsers[this.userid] = userid;
this.locked = userid; // in case of merging into a recently banned account
this.autoconfirmed = '';
}
this.disconnectAll();
};
User.prototype.lock = function (noRecurse, userid) {
// recurse only once; the root for-loop already locks everything with your IP
if (!userid) userid = this.userid;
if (!noRecurse) {
for (var i in users) {
if (users[i] === this || users[i].confirmed) continue;
for (var myIp in this.ips) {
if (myIp in users[i].ips) {
users[i].lock(true, userid);
break;
}
}
}
}
for (var ip in this.ips) {
lockedIps[ip] = userid;
}
if (this.autoconfirmed) lockedUsers[this.autoconfirmed] = userid;
if (this.registered) lockedUsers[this.userid] = userid;
this.locked = userid;
this.autoconfirmed = '';
this.updateIdentity();
};
User.prototype.tryJoinRoom = function (room, connection) {
var roomid = (room && room.id ? room.id : room);
room = Rooms.search(room);
if (!room) {
if (!this.named) {
return null;
} else {
connection.sendTo(roomid, "|noinit|nonexistent|The room '" + roomid + "' does not exist.");
return false;
}
}
if (room.modjoin && !this.can('bypassall')) {
var userGroup = this.group;
if (room.auth) {
if (room.isPrivate === true) {
userGroup = ' ';
}
userGroup = room.auth[this.userid] || userGroup;
}
if (Config.groupsranking.indexOf(userGroup) < Config.groupsranking.indexOf(room.modjoin !== true ? room.modjoin : room.modchat)) {
if (!this.named) {
return null;
} else {
connection.sendTo(roomid, "|noinit|nonexistent|The room '" + roomid + "' does not exist.");
return false;
}
}
}
if (room.isPrivate) {
if (!this.named) {
return null;
}
}
if (Rooms.aliases[toId(roomid)] === room) {
connection.send(">" + toId(roomid) + "\n|deinit");
}
var joinResult = this.joinRoom(room, connection);
if (!joinResult) {
if (joinResult === null) {
connection.sendTo(roomid, "|noinit|joinfailed|You are banned from the room '" + roomid + "'.");
return false;
}
connection.sendTo(roomid, "|noinit|joinfailed|You do not have permission to join '" + roomid + "'.");
return false;
}
return true;
};
User.prototype.joinRoom = function (room, connection) {
room = Rooms.get(room);
if (!room) return false;
if (!this.can('bypassall')) {
// check if user has permission to join
if (room.staffRoom && !this.isStaff) return false;
if (room.checkBanned && !room.checkBanned(this)) {
return null;
}
}
if (!connection) {
for (var i = 0; i < this.connections.length; i++) {
// only join full clients, not pop-out single-room
// clients
if (this.connections[i].rooms['global']) {
this.joinRoom(room, this.connections[i]);
}
}
return true;
}
if (!connection.rooms[room.id]) {
connection.joinRoom(room);
if (!this.roomCount[room.id]) {
this.roomCount[room.id] = 1;
room.onJoin(this, connection);
} else {
this.roomCount[room.id]++;
room.onJoinConnection(this, connection);
}
}
return true;
};
User.prototype.leaveRoom = function (room, connection, force) {
room = Rooms.get(room);
if (room.id === 'global' && !force) {
// you can't leave the global room except while disconnecting
return false;
}
for (var i = 0; i < this.connections.length; i++) {
if (this.connections[i] === connection || !connection) {
if (this.connections[i].rooms[room.id]) {
if (this.roomCount[room.id]) {
this.roomCount[room.id]--;
if (!this.roomCount[room.id]) {
room.onLeave(this);
delete this.roomCount[room.id];
}
}
if (!this.connections[i]) {
// race condition? This should never happen, but it does.
fs.createWriteStream('logs/errors.txt', {'flags': 'a'}).on("open", function (fd) {
this.write("\nconnections = " + JSON.stringify(this.connections) + "\ni = " + i + "\n\n");
this.end();
});
} else {
this.connections[i].sendTo(room.id, '|deinit');
this.connections[i].leaveRoom(room);
}
}
if (connection) {
break;
}
}
}
if (!connection && this.roomCount[room.id]) {
room.onLeave(this);
delete this.roomCount[room.id];
}
};
User.prototype.prepBattle = function (formatid, type, connection, callback) {
// all validation for a battle goes through here
if (!connection) connection = this;
if (!type) type = 'challenge';
if (Rooms.global.lockdown && Rooms.global.lockdown !== 'pre') {
var message = "The server is shutting down. Battles cannot be started at this time.";
if (Rooms.global.lockdown === 'ddos') {
message = "The server is under attack. Battles cannot be started at this time.";
}
connection.popup(message);
setImmediate(callback.bind(null, false));
return;
}
if (ResourceMonitor.countPrepBattle(connection.ip || connection.latestIp, this.name)) {
connection.popup("Due to high load, you are limited to 6 battles every 3 minutes.");
setImmediate(callback.bind(null, false));
return;
}
var format = Tools.getFormat(formatid);
if (!format['' + type + 'Show']) {
connection.popup("That format is not available.");
setImmediate(callback.bind(null, false));
return;
}
TeamValidator.validateTeam(formatid, this.team, this.finishPrepBattle.bind(this, connection, callback));
};
User.prototype.finishPrepBattle = function (connection, callback, success, details) {
if (!success) {
connection.popup("Your team was rejected for the following reasons:\n\n- " + details.replace(/\n/g, '\n- '));
callback(false);
} else {
if (details) {
this.team = details;
ResourceMonitor.teamValidatorChanged++;
} else {
ResourceMonitor.teamValidatorUnchanged++;
}
callback(true);
}
};
User.prototype.updateChallenges = function () {
var challengeTo = this.challengeTo;
if (challengeTo) {
challengeTo = {
to: challengeTo.to,
format: challengeTo.format
};
}
this.send('|updatechallenges|' + JSON.stringify({
challengesFrom: Object.map(this.challengesFrom, 'format'),
challengeTo: challengeTo
}));
};
User.prototype.makeChallenge = function (user, format/*, isPrivate*/) {
user = getUser(user);
if (!user || this.challengeTo) {
return false;
}
if (user.blockChallenges && !this.can('bypassblocks', user)) {
return false;
}
if (new Date().getTime() < this.lastChallenge + 10000) {
// 10 seconds ago
return false;
}
var time = new Date().getTime();
var challenge = {
time: time,
from: this.userid,
to: user.userid,
format: '' + (format || ''),
//isPrivate: !!isPrivate, // currently unused
team: this.team
};
this.lastChallenge = time;
this.challengeTo = challenge;
user.challengesFrom[this.userid] = challenge;
this.updateChallenges();
user.updateChallenges();
};
User.prototype.cancelChallengeTo = function () {
if (!this.challengeTo) return true;
var user = getUser(this.challengeTo.to);
if (user) delete user.challengesFrom[this.userid];
this.challengeTo = null;
this.updateChallenges();
if (user) user.updateChallenges();
};
User.prototype.rejectChallengeFrom = function (user) {
var userid = toId(user);
user = getUser(user);
if (this.challengesFrom[userid]) {
delete this.challengesFrom[userid];
}
if (user) {
delete this.challengesFrom[user.userid];
if (user.challengeTo && user.challengeTo.to === this.userid) {
user.challengeTo = null;
user.updateChallenges();
}
}
this.updateChallenges();
};
User.prototype.acceptChallengeFrom = function (user) {
var userid = toId(user);
user = getUser(user);
if (!user || !user.challengeTo || user.challengeTo.to !== this.userid || !this.connected || !user.connected) {
if (this.challengesFrom[userid]) {
delete this.challengesFrom[userid];
this.updateChallenges();
}
return false;
}
Rooms.global.startBattle(this, user, user.challengeTo.format, this.team, user.challengeTo.team, {rated: false});
delete this.challengesFrom[user.userid];
user.challengeTo = null;
this.updateChallenges();
user.updateChallenges();
return true;
};
// chatQueue should be an array, but you know about mutables in prototypes...
// P.S. don't replace this with an array unless you know what mutables in prototypes do.
User.prototype.chatQueue = null;
User.prototype.chatQueueTimeout = null;
User.prototype.lastChatMessage = 0;
/**
* The user says message in room.
* Returns false if the rest of the user's messages should be discarded.
*/
User.prototype.chat = function (message, room, connection) {
var now = new Date().getTime();
if (message.substr(0, 16) === '/cmd userdetails') {
// certain commands are exempt from the queue
ResourceMonitor.activeIp = connection.ip;
room.chat(this, message, connection);
ResourceMonitor.activeIp = null;
return false; // but end the loop here
}
if (this.chatQueueTimeout) {
if (!this.chatQueue) this.chatQueue = []; // this should never happen
if (this.chatQueue.length >= THROTTLE_BUFFER_LIMIT - 1) {
connection.sendTo(room, '|raw|' +
"<strong class=\"message-throttle-notice\">Your message was not sent because you've been typing too quickly.</strong>"
);
return false;
} else {
this.chatQueue.push([message, room, connection]);
}
} else if (now < this.lastChatMessage + THROTTLE_DELAY) {
this.chatQueue = [[message, room, connection]];
this.chatQueueTimeout = setTimeout(
this.processChatQueue.bind(this),
THROTTLE_DELAY - (now - this.lastChatMessage));
} else {
this.lastChatMessage = now;
ResourceMonitor.activeIp = connection.ip;
room.chat(this, message, connection);
ResourceMonitor.activeIp = null;
}
};
User.prototype.clearChatQueue = function () {
this.chatQueue = null;
if (this.chatQueueTimeout) {
clearTimeout(this.chatQueueTimeout);
this.chatQueueTimeout = null;
}
};
User.prototype.processChatQueue = function () {
if (!this.chatQueue) return; // this should never happen
var toChat = this.chatQueue.shift();
ResourceMonitor.activeIp = toChat[2].ip;
toChat[1].chat(this, toChat[0], toChat[2]);
ResourceMonitor.activeIp = null;
if (this.chatQueue && this.chatQueue.length) {
this.chatQueueTimeout = setTimeout(
this.processChatQueue.bind(this), THROTTLE_DELAY);
} else {
this.chatQueue = null;
this.chatQueueTimeout = null;
}
};
User.prototype.destroy = function () {
// deallocate user
this.clearChatQueue();
delete users[this.userid];
};
User.prototype.toString = function () {
return this.userid;
};
// "static" function
User.pruneInactive = function (threshold) {
var now = Date.now();
for (var i in users) {
var user = users[i];
if (user.connected) continue;
if ((now - user.lastConnected) > threshold) {
users[i].destroy();
}
}
};
return User;
})();
Connection = (function () {
function Connection(id, worker, socketid, user, ip) {
this.id = id;
this.socketid = socketid;
this.worker = worker;
this.rooms = {};
this.user = user;
this.ip = ip || '';
}
Connection.prototype.autojoin = '';
Connection.prototype.sendTo = function (roomid, data) {
if (roomid && roomid.id) roomid = roomid.id;
if (roomid && roomid !== 'lobby') data = '>' + roomid + '\n' + data;
Sockets.socketSend(this.worker, this.socketid, data);
ResourceMonitor.countNetworkUse(data.length);
};
Connection.prototype.send = function (data) {
Sockets.socketSend(this.worker, this.socketid, data);
ResourceMonitor.countNetworkUse(data.length);
};
Connection.prototype.destroy = function () {
Sockets.socketDisconnect(this.worker, this.socketid);
this.onDisconnect();
};
Connection.prototype.onDisconnect = function () {
delete connections[this.id];
if (this.user) this.user.onDisconnect(this);
this.user = null;
};
Connection.prototype.popup = function (message) {
this.send('|popup|' + message.replace(/\n/g, '||'));
};
Connection.prototype.joinRoom = function (room) {
if (room.id in this.rooms) return;
this.rooms[room.id] = room;
Sockets.channelAdd(this.worker, room.id, this.socketid);
};
Connection.prototype.leaveRoom = function (room) {
if (room.id in this.rooms) {
delete this.rooms[room.id];
Sockets.channelRemove(this.worker, room.id, this.socketid);
}
};
return Connection;
})();
Users.User = User;
Users.Connection = Connection;
/*********************************************************
* Inactive user pruning
*********************************************************/
Users.pruneInactive = User.pruneInactive;
Users.pruneInactiveTimer = setInterval(
User.pruneInactive,
1000 * 60 * 30,
Config.inactiveuserthreshold || 1000 * 60 * 60
);
|
import request from 'request-promise';
import url from 'url';
/**
* @name JiraApi
* @class
* Wrapper for the JIRA Rest Api
* https://docs.atlassian.com/jira/REST/6.4.8/
*/
export default class JiraApi {
/**
* @constructor
* @function
* @param {JiraApiOptions} options
*/
constructor(options) {
this.protocol = options.protocol || 'http';
this.host = options.host;
this.port = options.port || null;
this.apiVersion = options.apiVersion || '2';
this.base = options.base || '';
this.strictSSL = options.hasOwnProperty('strictSSL') ? options.strictSSL : true;
// This is so we can fake during unit tests
this.request = options.request || request;
this.webhookVersion = options.webHookVersion || '1.0';
this.greenhopperVersion = options.greenhopperVersion || '1.0';
this.baseOptions = {};
if (options.oauth && options.oauth.consumer_key && options.oauth.access_token) {
this.baseOptions.oauth = {
consumer_key: options.oauth.consumer_key,
consumer_secret: options.oauth.consumer_secret,
token: options.oauth.access_token,
token_secret: options.oauth.access_token_secret,
signature_method: options.oauth.signature_method || 'RSA-SHA1',
};
} else if (options.username && options.password) {
this.baseOptions.auth = {
user: options.username,
pass: options.password,
};
}
if (options.timeout) {
this.baseOptions.timeout = options.timeout;
}
}
/**
* @typedef JiraApiOptions
* @type {object}
* @property {string} [protocol=http] - What protocol to use to connect to
* jira? Ex: http|https
* @property {string} host - What host is this tool connecting to for the jira
* instance? Ex: jira.somehost.com
* @property {string} [port] - What port is this tool connecting to jira with? Only needed for
* none standard ports. Ex: 8080, 3000, etc
* @property {string} [username] - Specify a username for this tool to authenticate all
* requests with.
* @property {string} [password] - Specify a password for this tool to authenticate all
* requests with.
* @property {string} [apiVersion=2] - What version of the jira rest api is the instance the
* tool is connecting to?
* @property {string} [base] - What other url parts exist, if any, before the rest/api/
* section?
* @property {boolean} [strictSSL=true] - Does this tool require each request to be
* authenticated? Defaults to true.
* @property {function} [request] - What method does this tool use to make its requests?
* Defaults to request from request-promise
* @property {number} [timeout] - Integer containing the number of milliseconds to wait for a
* server to send response headers (and start the response body) before aborting the request. Note
* that if the underlying TCP connection cannot be established, the OS-wide TCP connection timeout
* will overrule the timeout option ([the default in Linux can be anywhere from 20-120 *
* seconds](http://www.sekuda.com/overriding_the_default_linux_kernel_20_second_tcp_socket_connect_timeout)).
* @property {string} [webhookVersion=1.0] - What webhook version does this api wrapper need to
* hit?
* @property {string} [greenhopperVersion=1.0] - What webhook version does this api wrapper need
* to hit?
* @property {OAuth} - Specify an oauth object for this tool to authenticate all requests using
* OAuth.
*/
/**
* @typedef OAuth
* @type {object}
* @property {string} consumer_key - The consumer entered in Jira Preferences.
* @property {string} consumer_secret - The private RSA file.
* @property {string} access_token - The generated access token.
* @property {string} access_token_secret - The generated access toke secret.
* @property {string} signature_method [signature_method=RSA-SHA1] - OAuth signurate methode
* Possible values RSA-SHA1, HMAC-SHA1, PLAINTEXT. Jira Cloud supports only RSA-SHA1.
*/
/**
* @name makeRequestHeader
* @function
* Creates a requestOptions object based on the default template for one
* @param {string} uri
* @param {object} [options] - an object containing fields and formatting how the
*/
makeRequestHeader(uri, options = {}) {
return {
rejectUnauthorized: this.strictSSL,
method: options.method || 'GET',
uri,
json: true,
...options,
};
}
/**
* @typedef makeRequestHeaderOptions
* @type {object}
* @property {string} [method] - HTTP Request Method. ie GET, POST, PUT, DELETE
*/
/**
* @name makeUri
* @function
* Creates a URI object for a given pathname
* @param {string} pathname - The url after the /rest/api/version
*/
makeUri({ pathname, query }) {
const uri = url.format({
protocol: this.protocol,
hostname: this.host,
port: this.port,
pathname: `${this.base}/rest/api/${this.apiVersion}${pathname}`,
query,
});
return decodeURIComponent(uri);
}
/**
* @name makeWebhookUri
* @function
* Creates a URI object for a given pathName
* @param {string} pathname - The url after the /rest/
*/
makeWebhookUri({ pathname }) {
const uri = url.format({
protocol: this.protocol,
hostname: this.host,
port: this.port,
pathname: `${this.base}/rest/webhooks/${this.webhookVersion}${pathname}`,
});
return decodeURIComponent(uri);
}
/**
* @name makeSprintQueryUri
* @function
* Creates a URI object for a given pathName
* @param {string} pathname - The url after the /rest/
*/
makeSprintQueryUri({ pathname, query }) {
const uri = url.format({
protocol: this.protocol,
hostname: this.host,
port: this.port,
pathname: `${this.base}/rest/greenhopper/${this.greenhopperVersion}${pathname}`,
query,
});
return decodeURIComponent(uri);
}
/**
* @name doRequest
* @function
* Does a request based on the requestOptions object
* @param {object} requestOptions - fields on this object get posted as a request header for
* requests to jira
*/
async doRequest(requestOptions) {
const options = {
...this.baseOptions,
...requestOptions,
};
const response = await this.request(options);
if (response) {
if (Array.isArray(response.errorMessages) && response.errorMessages.length > 0) {
throw new Error(response.errorMessages.join(', '));
}
}
return response;
}
/**
* @name findIssue
* @function
* Find an issue in jira
* [Jira Doc](http://docs.atlassian.com/jira/REST/latest/#id290709)
* @param {string} issueNumber - The issue number to search for including the project key
*/
findIssue(issueNumber) {
return this.doRequest(this.makeRequestHeader(this.makeUri({
pathname: `/issue/${issueNumber}`,
})));
}
/**
* @name getUnresolvedIssueCount
* @function
* Get the unresolved issue count
* [Jira Doc](http://docs.atlassian.com/jira/REST/latest/#id288524)
* @param {string} version - the version of your product you want to find the unresolved
* issues of.
*/
async getUnresolvedIssueCount(version) {
const requestHeaders = this.makeRequestHeader(
this.makeUri({
pathname: `/version/${version}/unresolvedIssueCount`,
})
);
const response = await this.doRequest(requestHeaders);
return response.issuesUnresolvedCount;
}
/**
* @name getProject
* @function
* Get the Project by project key
* [Jira Doc](http://docs.atlassian.com/jira/REST/latest/#id289232)
* @param {string} project - key for the project
*/
getProject(project) {
return this.doRequest(this.makeRequestHeader(this.makeUri({
pathname: `/project/${project}`,
})));
}
/**
* @name createProject
* @function
* Create a new Project
* [Jira Doc](https://docs.atlassian.com/jira/REST/latest/#api/2/project-createProject)
* @param {object} project - with specs
*/
createProject(project) {
return this.doRequest(this.makeRequestHeader(this.makeUri({
pathname: '/project/',
}), {
method: 'POST',
body: project,
}));
}
/** Find the Rapid View for a specified project
* @name findRapidView
* @function
* @param {string} projectName - name for the project
*/
async findRapidView(projectName) {
const response = await this.doRequest(this.makeRequestHeader(this.makeSprintQueryUri({
pathname: '/rapidviews/list',
})));
const rapidViewResult = response.views
.filter(x => x.name.toLowerCase() === projectName.toLowerCase());
return rapidViewResult[0];
}
/** Get a list of Sprints belonging to a Rapid View
* @name getLastSprintForRapidView
* @function
* @param {string} rapidViewId - the id for the rapid view
*/
async getLastSprintForRapidView(rapidViewId) {
const response = await this.doRequest(
this.makeRequestHeader(this.makeSprintQueryUri({
pathname: `/sprintquery/${rapidViewId}`,
}))
);
return response.sprints.pop();
}
/** Get the issues for a rapidView / sprint
* @name getSprintIssues
* @function
* @param {string} rapidViewId - the id for the rapid view
* @param {string} sprintId - the id for the sprint
*/
getSprintIssues(rapidViewId, sprintId) {
return this.doRequest(this.makeRequestHeader(this.makeSprintQueryUri({
pathname: '/rapid/charts/sprintreport',
query: {
rapidViewId,
sprintId,
},
})));
}
/** Add an issue to the project's current sprint
* @name addIssueToSprint
* @function
* @param {string} issueId - the id of the existing issue
* @param {string} sprintId - the id of the sprint to add it to
*/
addIssueToSprint(issueId, sprintId) {
return this.doRequest(this.makeRequestHeader(this.makeUri({
pathname: `/sprint/${sprintId}/issues/add`,
}), {
method: 'PUT',
followAllRedirects: true,
body: {
issueKeys: [issueId],
},
}));
}
/** Create an issue link between two issues
* @name issueLink
* @function
* @param {object} link - a link object formatted how the Jira API specifies
*/
issueLink(link) {
return this.doRequest(this.makeRequestHeader(this.makeUri({
pathname: '/issueLink',
}), {
method: 'POST',
followAllRedirects: true,
body: link,
}));
}
/** Retrieves the remote links associated with the given issue.
* @name getRemoteLinks
* @function
* @param {string} issueNumber - the issue number to find remote links for.
*/
getRemoteLinks(issueNumber) {
return this.doRequest(this.makeRequestHeader(this.makeUri({
pathname: `/issue/${issueNumber}/remotelink`,
})));
}
/**
* @name createRemoteLink
* @function
* Creates a remote link associated with the given issue.
* @param {string} issueNumber - The issue number to create the remotelink under
* @param {object} remoteLink - the remotelink object as specified by the Jira API
*/
createRemoteLink(issueNumber, remoteLink) {
return this.doRequest(this.makeRequestHeader(this.makeUri({
pathname: `/issue/${issueNumber}/remotelink`,
}), {
method: 'POST',
body: remoteLink,
}));
}
/** Get Versions for a project
* [Jira Doc](http://docs.atlassian.com/jira/REST/latest/#id289653)
* @name getVersions
* @function
* @param {string} project - A project key to get versions for
*/
getVersions(project) {
return this.doRequest(this.makeRequestHeader(this.makeUri({
pathname: `/project/${project}/versions`,
})));
}
/** Create a version
* [Jira Doc](http://docs.atlassian.com/jira/REST/latest/#id288232)
* @name createVersion
* @function
* @param {string} version - an object of the new version
*/
createVersion(version) {
return this.doRequest(this.makeRequestHeader(this.makeUri({
pathname: '/version',
}), {
method: 'POST',
followAllRedirects: true,
body: version,
}));
}
/** Update a version
* [Jira Doc](https://docs.atlassian.com/jira/REST/latest/#d2e510)
* @name updateVersion
* @function
* @param {string} version - an new object of the version to update
*/
updateVersion(version) {
return this.doRequest(this.makeRequestHeader(this.makeUri({
pathname: `/version/${version.id}`,
}), {
method: 'PUT',
followAllRedirects: true,
body: version,
}));
}
/** Delete a version
* [Jira Doc](https://docs.atlassian.com/jira/REST/latest/#api/2/version-delete)
* @name deleteVersion
* @function
* @param {string} versionId - the ID of the version to delete
* @param {string} moveFixIssuesToId - when provided, existing fixVersions will be moved
* to this ID. Otherwise, the deleted version will be removed from all
* issue fixVersions.
* @param {string} moveAffectedIssuesToId - when provided, existing affectedVersions will
* be moved to this ID. Otherwise, the deleted version will be removed
* from all issue affectedVersions.
*/
deleteVersion(versionId, moveFixIssuesToId, moveAffectedIssuesToId) {
return this.doRequest(this.makeRequestHeader(this.makeUri({
pathname: `/version/${versionId}`,
}), {
method: 'DELETE',
followAllRedirects: true,
qs: {
moveFixIssuesTo: moveFixIssuesToId,
moveAffectedIssuesTo: moveAffectedIssuesToId,
},
}));
}
/** Pass a search query to Jira
* [Jira Doc](https://docs.atlassian.com/jira/REST/latest/#d2e4424)
* @name searchJira
* @function
* @param {string} searchString - jira query string in JQL
* @param {object} optional - object containing any of the following properties
* @param {integer} [optional.startAt=0]: optional starting index number
* @param {integer} [optional.maxResults=50]: optional ending index number
* @param {array} [optional.fields]: optional array of string names of desired fields
*/
searchJira(searchString, optional = {}) {
return this.doRequest(this.makeRequestHeader(this.makeUri({
pathname: '/search',
}), {
method: 'POST',
followAllRedirects: true,
body: {
jql: searchString,
...optional,
},
}));
}
/** Search user on Jira
* [Jira Doc](http://docs.atlassian.com/jira/REST/latest/#d2e3756)
* @name searchUsers
* @function
* @param {SearchUserOptions} options
*/
searchUsers({ username, startAt, maxResults, includeActive, includeInactive }) {
return this.doRequest(this.makeRequestHeader(this.makeUri({
pathname: '/user/search',
query: {
username,
startAt: startAt || 0,
maxResults: maxResults || 50,
includeActive: includeActive || true,
includeInactive: includeInactive || false,
},
}), {
followAllRedirects: true,
}));
}
/**
* @typedef SearchUserOptions
* @type {object}
* @property {string} username - A query string used to search username, name or e-mail address
* @property {integer} [startAt=0] - The index of the first user to return (0-based)
* @property {integer} [maxResults=50] - The maximum number of users to return
* @property {boolean} [includeActive=true] - If true, then active users are included
* in the results
* @property {boolean} [includeInactive=false] - If true, then inactive users
* are included in the results
*/
/** Get all users in group on Jira
* @name getUsersInGroup
* @function
* @param {string} groupname - A query string used to search users in group
* @param {integer} [startAt=0] - The index of the first user to return (0-based)
* @param {integer} [maxResults=50] - The maximum number of users to return (defaults to 50).
*/
getUsersInGroup(groupname, startAt = 0, maxResults = 50) {
return this.doRequest(
this.makeRequestHeader(this.makeUri({
pathname: '/group',
query: {
groupname,
expand: `users[${startAt}:${maxResults}]`,
},
}), {
followAllRedirects: true,
})
);
}
/** Get issues related to a user
* [Jira Doc](http://docs.atlassian.com/jira/REST/latest/#id296043)
* @name getUsersIssues
* @function
* @param {string} username - username of user to search for
* @param {boolean} open - determines if only open issues should be returned
*/
getUsersIssues(username, open) {
return this.searchJira(
`assignee = ${username.replace('@', '\\u0040')} ` +
`AND status in (Open, 'In Progress', Reopened) ${open}`, {});
}
/** Add issue to Jira
* [Jira Doc](http://docs.atlassian.com/jira/REST/latest/#id290028)
* @name addNewIssue
* @function
* @param {object} issue - Properly Formatted Issue object
*/
addNewIssue(issue) {
return this.doRequest(this.makeRequestHeader(this.makeUri({
pathname: '/issue',
}), {
method: 'POST',
followAllRedirects: true,
body: issue,
}));
}
/** Add a user as a watcher on an issue
* @name addWatcher
* @function
* @param {string} issueKey - the key of the existing issue
* @param {string} username - the jira username to add as a watcher to the issue
*/
addWatcher(issueKey, username) {
return this.doRequest(this.makeRequestHeader(this.makeUri({
pathname: `/issue/${issueKey}/watchers`,
}), {
method: 'POST',
followAllRedirects: true,
body: JSON.stringify(username),
}));
}
/** Delete issue from Jira
* [Jira Doc](http://docs.atlassian.com/jira/REST/latest/#id290791)
* @name deleteIssue
* @function
* @param {string} issueId - the Id of the issue to delete
*/
deleteIssue(issueId) {
return this.doRequest(this.makeRequestHeader(this.makeUri({
pathname: `/issue/${issueId}`,
}), {
method: 'DELETE',
followAllRedirects: true,
}));
}
/** Update issue in Jira
* [Jira Doc](http://docs.atlassian.com/jira/REST/latest/#id290878)
* @name updateIssue
* @function
* @param {string} issueId - the Id of the issue to delete
* @param {object} issueUpdate - update Object as specified by the rest api
*/
updateIssue(issueId, issueUpdate) {
return this.doRequest(this.makeRequestHeader(this.makeUri({
pathname: `/issue/${issueId}`,
}), {
body: issueUpdate,
method: 'PUT',
followAllRedirects: true,
}));
}
/** List Components
* [Jira Doc](http://docs.atlassian.com/jira/REST/latest/#id290489)
* @name listComponents
* @function
* @param {string} project - key for the project
*/
listComponents(project) {
return this.doRequest(this.makeRequestHeader(this.makeUri({
pathname: `/project/${project}/components`,
})));
}
/** Add component to Jira
* [Jira Doc](http://docs.atlassian.com/jira/REST/latest/#id290028)
* @name addNewComponent
* @function
* @param {object} component - Properly Formatted Component
*/
addNewComponent(component) {
return this.doRequest(this.makeRequestHeader(this.makeUri({
pathname: '/component',
}), {
method: 'POST',
followAllRedirects: true,
body: component,
}));
}
/** Delete component from Jira
* [Jira Doc](http://docs.atlassian.com/jira/REST/latest/#id290791)
* @name deleteComponent
* @function
* @param {string} componentId - the Id of the component to delete
*/
deleteComponent(componentId) {
return this.doRequest(this.makeRequestHeader(this.makeUri({
pathname: `/component/${componentId}`,
}), {
method: 'DELETE',
followAllRedirects: true,
}));
}
/** List all fields custom and not that jira knows about.
* [Jira Doc](http://docs.atlassian.com/jira/REST/latest/#id290489)
* @name listFields
* @function
*/
listFields() {
return this.doRequest(this.makeRequestHeader(this.makeUri({
pathname: '/field',
})));
}
/** List all priorities jira knows about
* [Jira Doc](http://docs.atlassian.com/jira/REST/latest/#id290489)
* @name listPriorities
* @function
*/
listPriorities() {
return this.doRequest(this.makeRequestHeader(this.makeUri({
pathname: '/priority',
})));
}
/** List Transitions for a specific issue that are available to the current user
* [Jira Doc](http://docs.atlassian.com/jira/REST/latest/#id290489)
* @name listTransitions
* @function
* @param {string} issueId - get transitions available for the issue
*/
listTransitions(issueId) {
return this.doRequest(this.makeRequestHeader(this.makeUri({
pathname: `/issue/${issueId}/transitions`,
query: {
expand: 'transitions.fields',
},
})));
}
/** Transition issue in Jira
* [Jira Doc](http://docs.atlassian.com/jira/REST/latest/#id290489)
* @name transitionsIssue
* @function
* @param {string} issueId - the Id of the issue to delete
* @param {object} issueTransition - transition object from the jira rest API
*/
transitionIssue(issueId, issueTransition) {
return this.doRequest(this.makeRequestHeader(this.makeUri({
pathname: `/issue/${issueId}/transitions`,
}), {
body: issueTransition,
method: 'POST',
followAllRedirects: true,
}));
}
/** List all Viewable Projects
* [Jira Doc](http://docs.atlassian.com/jira/REST/latest/#id289193)
* @name listProjects
* @function
*/
listProjects() {
return this.doRequest(this.makeRequestHeader(this.makeUri({
pathname: '/project',
})));
}
/** Add a comment to an issue
* [Jira Doc](https://docs.atlassian.com/jira/REST/latest/#id108798)
* @name addComment
* @function
* @param {string} issueId - Issue to add a comment to
* @param {string} comment - string containing comment
*/
addComment(issueId, comment) {
return this.doRequest(this.makeRequestHeader(this.makeUri({
pathname: `/issue/${issueId}/comment`,
}), {
body: {
body: comment,
},
method: 'POST',
followAllRedirects: true,
}));
}
/** Add a worklog to a project
* [Jira Doc](http://docs.atlassian.com/jira/REST/latest/#id291617)
* @name addWorklog
* @function
* @param {string} issueId - Issue to add a worklog to
* @param {object} worklog - worklog object from the rest API
* @param {object} newEstimate - the new value for the remaining estimate field
*/
addWorklog(issueId, worklog, newEstimate) {
return this.doRequest(this.makeRequestHeader(this.makeUri({
pathname: `/issue/${issueId}/worklog`,
query: (newEstimate) ? { adjustEstimate: 'new', newEstimate } : null,
}), {
body: worklog,
method: 'POST',
followAllRedirects: true,
}));
}
/** Delete worklog from issue
* [Jira Doc](https://docs.atlassian.com/jira/REST/latest/#d2e1673)
* @name deleteWorklog
* @function
* @param {string} issueId - the Id of the issue to delete
* @param {string} worklogId - the Id of the worklog in issue to delete
*/
deleteWorklog(issueId, worklogId) {
return this.doRequest(this.makeRequestHeader(
this.makeUri({
pathname: `/issue/${issueId}/worklog/${worklogId}`,
}), {
method: 'DELETE',
followAllRedirects: true,
}
));
}
/** List all Issue Types jira knows about
* [Jira Doc](http://docs.atlassian.com/jira/REST/latest/#id295946)
* @name listIssueTypes
* @function
*/
listIssueTypes() {
return this.doRequest(this.makeRequestHeader(this.makeUri({
pathname: '/issuetype',
})));
}
/** Register a webhook
* [Jira Doc](https://developer.atlassian.com/display/JIRADEV/JIRA+Webhooks+Overview)
* @name registerWebhook
* @function
* @param {object} webhook - properly formatted webhook
*/
registerWebhook(webhook) {
return this.doRequest(this.makeRequestHeader(this.makeWebhookUri({
pathname: '/webhook',
}), {
method: 'POST',
body: webhook,
}));
}
/** List all registered webhooks
* [Jira Doc](https://developer.atlassian.com/display/JIRADEV/JIRA+Webhooks+Overview)
* @name listWebhooks
* @function
*/
listWebhooks() {
return this.doRequest(this.makeRequestHeader(this.makeWebhookUri({
pathname: '/webhook',
})));
}
/** Get a webhook by its ID
* [Jira Doc](https://developer.atlassian.com/display/JIRADEV/JIRA+Webhooks+Overview)
* @name getWebhook
* @function
* @param {string} webhookID - id of webhook to get
*/
getWebhook(webhookID) {
return this.doRequest(this.makeRequestHeader(this.makeWebhookUri({
pathname: `/webhook/${webhookID}`,
})));
}
/** Delete a registered webhook
* [Jira Doc](https://developer.atlassian.com/display/JIRADEV/JIRA+Webhooks+Overview)
* @name issueLink
* @function
* @param {string} webhookID - id of the webhook to delete
*/
deleteWebhook(webhookID) {
return this.doRequest(this.makeRequestHeader(this.makeWebhookUri({
pathname: `/webhook/${webhookID}`,
}), {
method: 'DELETE',
}));
}
/** Describe the currently authenticated user
* [Jira Doc](http://docs.atlassian.com/jira/REST/latest/#id2e865)
* @name getCurrentUser
* @function
*/
getCurrentUser() {
return this.doRequest(this.makeRequestHeader(this.makeUri({
pathname: '/myself',
})));
}
/** Retrieve the backlog of a certain Rapid View
* @name getBacklogForRapidView
* @function
* @param {string} rapidViewId - rapid view id
*/
getBacklogForRapidView(rapidViewId) {
return this.doRequest(this.makeRequestHeader(this.makeUri({
pathname: '/xboard/plan/backlog/data',
query: {
rapidViewId,
},
})));
}
/** Add attachment to a Issue
* [Jira Doc](https://docs.atlassian.com/jira/REST/latest/#api/2/issue/{issueIdOrKey}/attachments-addAttachment)
* @name addAttachmentOnIssue
* @function
* @param {string} issueId - issue id
* @param {object} readStream - readStream object from fs
*/
addAttachmentOnIssue(issueId, readStream) {
return this.doRequest(this.makeRequestHeader(this.makeUri({
pathname: `/issue/${issueId}/attachments`,
}), {
method: 'POST',
headers: {
'X-Atlassian-Token': 'nocheck',
},
formData: {
file: readStream,
},
}));
}
/** Get list of possible statuses
* [Jira Doc](https://docs.atlassian.com/jira/REST/latest/#api/2/status-getStatuses)
* @name listStatus
* @function
*/
listStatus() {
return this.doRequest(this.makeRequestHeader(this.makeUri({
pathname: '/status',
})));
}
}
|
var MongoClient = require('mongodb').MongoClient;
var dropLowest = function(arry) {
var minVal = Number.MAX_VALUE;
var minIdx = -1;
var newArray = [];
for (i=0; i<arry.length; i++) {
var val = arry[i]['score'];
var type = arry[i]['type'];
if (type === 'homework' && val < minVal) {
minVal = val;
minIdx = i;
}
}
for (i=0; i<arry.length; i++) {
if (i !== minIdx) newArray.push(arry[i]);
}
return newArray;
};
MongoClient.connect('mongodb://' + process.env.IP + ':27017/school', function(err, db){
if (err) throw err;
var dbcollection = 'students';
console.log('Conectou');
var students = db.collection(dbcollection);
students.find().toArray(function(err, docs) {
if(err) throw err;
docs.forEach(function (doc) {
doc.scores = dropLowest(doc.scores);
students.update({'_id' : doc._id}, doc, {}, function(err, result){
if(err) throw err;
});
});
db.close();
});
}); |
angular.module('app').factory('Utilities', [ '$window', function ($window) {
var QueryString = (function (a) {
if (a == "") {
return {};
}
var i;
var b = {};
for (i = 0; i < a.length; ++i) {
var p = a[i].split('=');
if (p.length != 2) {
continue;
}
b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
}
return b;
}($window.location.search.substr(1).split('&')));
/**
* Randomize array element order in-place.
* Using Fisher-Yates shuffle algorithm.
*/
function shuffleArray(array) {
var i;
for (i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
/**
* Remove duplicates and empty values in array
*/
function cleanArray(array, duplicateKey) {
if(!jQuery.isArray(array)) {
return [];
}
if(!duplicateKey) {
duplicateKey = 'category';
}
//Remove empty values
var newArray = [];
angular.forEach(array, function(value, key) {
if (value[duplicateKey]){
newArray.push(value);
}
});
array = newArray;
//Remove duplicates
var newObject = {};
angular.forEach(array, function(value, key) {
//set category as key and save key (overwriting old key)
newObject[value[duplicateKey]]=key;
});
newArray = [];
angular.forEach(newObject, function(value, key) {
newArray.push(array[value]); //value is key from previous step
});
array = newArray;
return array;
}
function stringtoXML(text){
if (window.ActiveXObject){
var doc=new ActiveXObject('Microsoft.XMLDOM');
doc.async='false';
doc.loadXML(text);
} else {
var parser=new DOMParser();
var doc=parser.parseFromString(text,'text/xml');
}
return doc;
}
function xmlToString(xml) {
if (window.ActiveXObject) {
return xml.xml;
} else {
return (new XMLSerializer()).serializeToString(xml);
}
}
return {
queryParam: function (key) {
return QueryString[key];
},
parseHTML: jQuery.parseHTML,
randomizeArray: shuffleArray,
cleanArray: cleanArray,
stringtoXML: stringtoXML,
xmlToString: xmlToString
};
}]); |
//Observable qui récupère sa valeur la 1ère fois seulement
ko.onDemandObservable = function (callback, target) {
var _value = ko.observable();
var result = ko.dependentObservable({
read: function () {
//si données non charger exécuter la fonction callback
if (!result.loaded()) {
callback.call(target);
}
//retourner la valeur actuelle
return _value();
},
write: function (newValue) {
result.loaded(true);
_value(newValue);
},
deferEvaluation: true
});
result.loaded = ko.observable();
result.refresh = function () {
result.loaded(false);
};
return result;
};
//Binding de type numérique
ko.bindingHandlers.numericvalue = {
init: function (element, valueAccessor, allBindingsAccessor) {
var underlyingObservable = valueAccessor();
var interceptor = ko.computed({
read: underlyingObservable,
write: function (value) {
value = value.trim();
underlyingObservable((value != '' && !isNaN(value)) ? parseFloat(value) : '');
underlyingObservable.valueHasMutated();
}
});
ko.bindingHandlers.value.init(element, function () { return interceptor }, allBindingsAccessor);
},
update: ko.bindingHandlers.value.update
};
ko.bindingHandlers.foreachGroupBy = {
makeTemplateValueAccessor: function(valueAccessor) {
return function() {
var modelValue = valueAccessor(),
unwrappedValue = ko.utils.peekObservable(modelValue); // Unwrap without setting a dependency here
// If unwrappedValue is the array, pass in the wrapped value on its own
// The value will be unwrapped and tracked within the template binding
// (See https://github.com/SteveSanderson/knockout/issues/523)
if ((!unwrappedValue) || typeof unwrappedValue.length == "number")
return { 'foreach': modelValue, 'templateEngine': ko.nativeTemplateEngine.instance };
// If unwrappedValue.data is the array, preserve all relevant options and unwrap again value so we get updates
ko.utils.unwrapObservable(modelValue);
return {
'foreach': unwrappedValue['data'],
'as': unwrappedValue['as'],
'includeDestroyed': unwrappedValue['includeDestroyed'],
'afterAdd': unwrappedValue['afterAdd'],
'beforeRemove': unwrappedValue['beforeRemove'],
'afterRender': unwrappedValue['afterRender'],
'beforeMove': unwrappedValue['beforeMove'],
'afterMove': unwrappedValue['afterMove'],
'templateEngine': ko.nativeTemplateEngine.instance
};
};
},
init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var options = ko.utils.unwrapObservable(valueAccessor());
var property = options.property;
var target = options.target;
var interceptor = function () {
var result = [];
var grouped = _.groupBy(target(), function (item) {
return item.OrganismeID();
});
for (var p in grouped) {
if (p && grouped.hasOwnProperty(p)) {
result.push({ key: ko.observable(p), values: grouped[p] });
}
}
return result;
};
return ko.bindingHandlers['template']['init'](element, ko.bindingHandlers['foreachGroupBy'].makeTemplateValueAccessor(interceptor));
//ko.bindingHandlers.foreach.init(element, interceptor, allBindingsAccessor, viewModel, bindingContext);
},
update: ko.bindingHandlers.foreach.update
};
//Bind conditionnel
ko.bindingHandlers.delaybind = {
'update': function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var value = valueAccessor(), waitUntil = ko.utils.unwrapObservable(value.waitUntil);
if (waitUntil && !element.mydelayBindInit) {
ko.applyBindingsToNode(element, function () { return ko.bindingProvider['instance']['parseBindingsString'](value.bind, bindingContext) }, bindingContext);
element.mydelayBindInit = true;
}
}
};
//DatePicker
ko.bindingHandlers.datepicker = {
init: function (element, valueAccessor, allBindingsAccessor) {
//initialize datepicker with some optional options
var options = allBindingsAccessor().datepickerOptions || {};
$(element).datepicker(options);
//handle the field changing
ko.utils.registerEventHandler(element, "change", function () {
var observable = valueAccessor();
var value = $.datepicker.formatDate('dd/mm/yy', $(element).datepicker("getDate"))
observable(value);
});
//handle disposal (if KO removes by the template binding)
ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
$(element).datepicker("destroy");
});
},
update: function (element, valueAccessor, allBindingsAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor()),
current = $(element).val(),
options = allBindingsAccessor().datepickerOptions || {};
//Rafraîchir les dates min/max
if (options.minDate) {
$(element).datepicker("option", "minDate", options.minDate);
}
if (options.maxDate) {
$(element).datepicker("option", "maxDate", options.maxDate);
}
if (value - current !== 0) {
$(element).datepicker("setDate", value);
}
}
};
//autocomplete Ajax
//autocomplete -- main binding (should contain additional options to pass to autocomplete)
//autocompleteSource -- the array to populate with choices (needs to be an observableArray)
//autocompleteQuery -- function to return choices
//autocompleteValue -- where to write the selected value
//autocompleteSourceLabel -- the property that should be displayed in the possible choices
//autocompleteSourceInputValue -- the property that should be displayed in the input box
//autocompleteSourceValue -- the property to use for the value
ko.bindingHandlers.autocomplete = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
var options = valueAccessor() || {},
allBindings = allBindingsAccessor(),
unwrap = ko.utils.unwrapObservable,
initialTextValue = allBindings.autocompleteInitInputValue || ko.observable(""),
modelValue = allBindings.autocompleteValue,
source = allBindings.autocompleteSource,
query = allBindings.autocompleteQuery,
valueProp = allBindings.autocompleteSourceValue,
inputValueProp = allBindings.autocompleteSourceInputValue || valueProp,
labelProp = allBindings.autocompleteSourceLabel || inputValueProp,
allowCustomValues = allBindings.allowCustomValues || false;
//function that is shared by both select and change event handlers
function writeValueToModel(valueToWrite) {
if (ko.isWriteableObservable(modelValue)) {
modelValue(valueToWrite);
} else { //write to non-observable
if (allBindings['_ko_property_writers'] && allBindings['_ko_property_writers']['autocompleteValue'])
allBindings['_ko_property_writers']['autocompleteValue'](valueToWrite);
}
}
//on a selection write the proper value to the model
options.select = function (event, ui) {
writeValueToModel(ui.item ? ui.item.actualValue : null);
};
//on a change, make sure that it is a valid value or clear out the model value
options.change = function (event, ui) {
var currentValue = $(element).val();
if (allowCustomValues) {
if (currentValue) {
writeValueToModel(currentValue);
}
} else {
var matchingItem = ko.utils.arrayFirst(unwrap(source), function (item) {
return unwrap(inputValueProp ? item[inputValueProp] : item) === currentValue;
});
if (!matchingItem) {
writeValueToModel(null);
}
}
}
//hold the autocomplete current response
var currentResponse = null;
//handle the choices being updated in a DO, to decouple value updates from source (options) updates
var mappedSource = ko.dependentObservable({
read: function () {
mapped = ko.utils.arrayMap(unwrap(source), function (item) {
var result = {};
result.label = labelProp ? unwrap(item[labelProp]) : unwrap(item).toString(); //show in pop-up choices
result.value = inputValueProp ? unwrap(item[inputValueProp]) : unwrap(item).toString(); //show in input box
result.actualValue = valueProp ? unwrap(item[valueProp]) : item; //store in model
return result;
});
return mapped;
},
write: function (newValue) {
source(newValue); //update the source observableArray, so our mapped value (above) is correct
if (currentResponse) {
currentResponse(mappedSource());
}
},
disposeWhenNodeIsRemoved: element
});
if (query) {
options.source = function (request, response) {
currentResponse = response;
query.call(this, request.term, mappedSource);
}
} else {
//whenever the items that make up the source are updated, make sure that autocomplete knows it
mappedAnnuaireCertifies.subscribe(function (newValue) {
$(element).autocomplete("option", "source", newValue);
});
options.source = mappedSource();
}
initialTextValue.subscribe(function (newValue) {
$(element).val(unwrap(newValue));
});
//initialize autocomplete
$(element).val(unwrap(initialTextValue)).autocomplete(options);
},
update: function (element, valueAccessor, allBindingsAccessor, viewModel) {
//update value based on a model change
var allBindings = allBindingsAccessor(),
unwrap = ko.utils.unwrapObservable,
initialTextValue = allBindings.autocompleteInitInputValue || ko.observable(""),
modelValue = unwrap(allBindings.autocompleteValue) || '',
valueProp = allBindings.autocompleteSourceValue,
inputValueProp = allBindings.autocompleteSourceInputValue || valueProp;
//if we are writing a different property to the input than we are writing to the model, then locate the object
if (valueProp && inputValueProp !== valueProp) {
var source = unwrap(allBindings.autocompleteSource) || [];
var modelValue = ko.utils.arrayFirst(source, function (item) {
return unwrap(item[valueProp]) === modelValue;
}) || {};
}
//update the element with the value that should be shown in the input
if (!$.isEmptyObject(modelValue) && inputValueProp !== valueProp) {
$(element).val(unwrap(modelValue[inputValueProp]));
}
$(element).val(unwrap(initialTextValue));
}
};
//Handler pour l'appui sur la touche 'entrer'
ko.bindingHandlers.returnAction = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
var value = ko.utils.unwrapObservable(valueAccessor());
$(element).keydown(function (e) {
if (e.which === 13) {
value(viewModel);
}
});
}
};
//spinner
ko.bindingHandlers.spinner = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
var options = allBindingsAccessor().spinnerOptions || {};
$(element).spinner(options);
//handle the field changing
ko.utils.registerEventHandler(element, "spinchange", function () {
var observable = valueAccessor();
observable($(element).spinner("value"));
});
//handle disposal (if KO removes by the template binding)
ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
$(element).spinner("destroy");
});
},
update: function (element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor());
current = $(element).spinner("value");
if (value != null && value !== current) {
$(element).spinner("value", value);
}
}
};
//treeview
ko.bindingHandlers.cocherDecocherTT = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var value = ko.utils.unwrapObservable(valueAccessor());
value.property = value.property || 'HasRight';
value.childrenPropertyName = value.childrenPropertyName || 'Children';
$(element).click(function () {
Utils.changePropertyValue(value.val, value.data, value.property, value.childrenPropertyName, true);
});
}
};
ko.unapplyBindings = function ($node, remove) {
// unbind events
$node.find("*").each(function () {
$(this).unbind();
});
// Remove KO subscriptions and references
if (remove) {
ko.removeNode($node[0]);
} else {
ko.cleanNode($node[0]);
}
};
//Jquery Form Binding
ko.bindingHandlers.fileUpload = {
init: function (element, valueAccessor) {
//$(element).after('<div class="progress"><div class="bar"></div><div class="percent">0%</div></div><div class="progressError"></div>');
},
update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var options = ko.utils.unwrapObservable(valueAccessor()),
property = ko.utils.unwrapObservable(options.property),
url = ko.utils.unwrapObservable(options.url);
if (url) {
$(element).change(function () {
if (element.files.length) {
var $this = $(this),
fileName = $this.val();
$(element.form).ajaxSubmit({
url: url,
resetForm: true,
type: "POST",
dataType: "text",
headers: { "Content-Disposition": "attachment; filename=" + fileName },
beforeSubmit: function () {
alert('beforeSubmit');
//$(".progress").show();
//$(".progressError").hide();
//$(".bar").width("0%")
//$(".percent").html("0%");
},
uploadProgress: function (event, position, total, percentComplete) {
//var percentVal = percentComplete + "%";
//$(".bar").width(percentVal)
//$(".percent").html(percentVal);
},
success: function (data) {
alert('success')
//$(".progress").hide();
//$(".progressError").hide();
//// set viewModel property to filename
//bindingContext.$data[property](data);
},
error: function (jqXHR, textStatus, errorThrown) {
alert('error')
//$(".progress").hide();
//$("div.progressError").html(jqXHR.responseText);
}
});
}
});
}
}
}
//DatePicker1
ko.bindingHandlers.datepicker1 = {
init: function (element, valueAccessor, allBindingsAccessor) {
//initialize datepicker with some optional options
var options = allBindingsAccessor().datepickerOptions || {};
options = $.extend({
showOn: "button",
buttonImage: "images/calendar.gif",
buttonImageOnly: true
}, options);
$(element).datepicker(options);
$(element).next().on('click', function () {
$(element).datepicker();
});
//handle the field changing
ko.utils.registerEventHandler(element, "change", function () {
var observable = valueAccessor();
//observable($(element).datepicker("getDate")); //Pour souci de format
observable($(element).val());
});
//handle disposal (if KO removes by the template binding)
ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
$(element).datepicker("destroy");
});
},
update: function (element, valueAccessor, allBindingsAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor()),
current = $(element).val(),
options = allBindingsAccessor().datepickerOptions || {};
//Rafraîchir les dates min/max
if (options.minDate) {
$(element).datepicker("option", "minDate", options.minDate);
}
if (options.maxDate) {
$(element).datepicker("option", "maxDate", options.maxDate);
}
if (value - current !== 0) {
$(element).datepicker("setDate", value);
}
}
};
//Binding de type numérique
ko.bindingHandlers.noHtmlAndScriptValue = {
init: function (element, valueAccessor, allBindingsAccessor) {
var underlyingObservable = valueAccessor();
function safe_tags_regex(str) {
return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
}
var interceptor = ko.computed({
read: underlyingObservable,
write: function (value) {
underlyingObservable(safe_tags_regex(value));
}
});
ko.bindingHandlers.value.init(element, function () { return interceptor }, allBindingsAccessor);
}//,
//update: ko.bindingHandlers.value.update
};
/**
* Binding bootstrapSwitch
*/
ko.bindingHandlers.bootstrapSwitch = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
$elem = $(element);
$elem.bootstrapSwitch();
$elem.bootstrapSwitch('setState', ko.utils.unwrapObservable(valueAccessor())); // Set intial state
$elem.on('switch-change', function (e, data) {
valueAccessor()(data.value);
}); // Update the model when changed.
},
update: function (element, valueAccessor, allBindingsAccessor, viewModel) {
var vStatus = $(element).bootstrapSwitch('state');
var vmStatus = ko.utils.unwrapObservable(valueAccessor());
if (vStatus != vmStatus) {
$(element).bootstrapSwitch('setState', vmStatus);
}
}
};
//Preprocess options binding with archive option on
//ko.bindingHandlers.options.preprocess = function (value, name, addBindingCallback) {
// console.log('value : ' + value);
// console.log('name : ' + name);
// console.log('addBindingCallback : ' + addBindingCallback.toString());
//};
//ko.bindingHandlers.optionsArchive = {
// init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
// var tt = ko.utils.unwrapObservable(valueAccessor());
// ko.bindingHandlers.options.init(element, valueAccessor, allBindings, viewModel, bindingContext);
// },
// update: ko.bindingHandlers.options.update
//};
//Binding de type format
ko.bindingHandlers.greaterThan = {
init: function (element, valueAccessor, allBindingsAccessor) {
var tmp = ko.unwrap(valueAccessor());
var value = tmp.value, greaterThan = tmp.greaterThan, strict = tmp.strict || true;
$(element).change(function () {
if (strict === true) {
if (value() < greaterThan) {
$(element).addClass('format-error');
} else {
$(element).removeClass('format-error');
}
} else {
if (value() <= greaterThan) {
$(element).addClass('format-error');
} else {
$(element).removeClass('format-error');
}
}
});
}
};
ko.bindingHandlers.ckeditor = {
init: function (element, valueAccessor, allBindingsAccessor, context) {
var options = allBindingsAccessor().tinymceOptions || {};
var modelValue = valueAccessor();
var value = ko.utils.unwrapObservable(valueAccessor());
var el = $(element)
//handle edits made in the editor. Updates after an undo point is reached.
options.setup = function (ed) {
ed.onChange.add(function (ed, l) {
if (ko.isWriteableObservable(modelValue)) {
modelValue(l.content);
}
});
};
//handle destroying an editor
ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
setTimeout(function () { $(element).tinymce().remove() }, 0)
});
//$(element).tinymce(options);
setTimeout(function () { $(element).tinymce(options); }, 0);
el.html(value);
},
update: function (element, valueAccessor, allBindingsAccessor, context) {
var el = $(element)
var value = ko.utils.unwrapObservable(valueAccessor());
var id = el.attr('id')
//handle programmatic updates to the observable
// also makes sure it doesn't update it if it's the same.
// otherwise, it will reload the instance, causing the cursor to jump.
if (id !== undefined) {
var content = tinyMCE.getInstanceById(id).getContent({ format: 'raw' })
if (content !== value) {
el.html(value);
}
}
}
};
//this need jquery, ckeditor & cdeditor jquery adapter to be preloaded
ko.bindingHandlers.CKEditor = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
var txtBoxID = $(element).attr("id");
var options = allBindingsAccessor().richTextOptions || {};
// handle disposal (if KO removes by the template binding)
ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
if (CKEDITOR.instances[txtBoxID]) {
CKEDITOR.remove(CKEDITOR.instances[txtBoxID]);
}
});
$(element).ckeditor(options);
// wire up the blur event to ensure our observable is properly updated
CKEDITOR.instances[txtBoxID].focusManager.blur = function () {
var observable = valueAccessor();
observable($(element).val());
};
},
update: function (element, valueAccessor, allBindingsAccessor, viewModel) {
var val = ko.utils.unwrapObservable(valueAccessor());
$(element).val(val);
}
};
|
var tests = [];
for (var file in window.__karma__.files) {
if (window.__karma__.files.hasOwnProperty(file)) {
if (/.*\.spec\.js$/.test(file)) {
tests.push(file);
}
}
}
requirejsConfig.baseUrl = '/base';
requirejsConfig.deps = tests;
requirejsConfig.callback = window.__karma__.start;
requirejs.config(requirejsConfig); |
Clazz.declarePackage ("J.adapter.smarter");
Clazz.load (["J.api.JmolAdapterStructureIterator"], "J.adapter.smarter.StructureIterator", ["J.api.JmolAdapter"], function () {
c$ = Clazz.decorateAsClass (function () {
this.structureCount = 0;
this.structures = null;
this.structure = null;
this.istructure = 0;
this.bsModelsDefined = null;
Clazz.instantialize (this, arguments);
}, J.adapter.smarter, "StructureIterator", J.api.JmolAdapterStructureIterator);
Clazz.makeConstructor (c$,
function (asc) {
Clazz.superConstructor (this, J.adapter.smarter.StructureIterator, []);
this.structureCount = asc.structureCount;
this.structures = asc.structures;
this.istructure = 0;
this.bsModelsDefined = asc.bsStructuredModels;
}, "J.adapter.smarter.AtomSetCollection");
Clazz.overrideMethod (c$, "hasNext",
function () {
if (this.istructure == this.structureCount) return false;
this.structure = this.structures[this.istructure++];
return true;
});
Clazz.overrideMethod (c$, "getStructureType",
function () {
return this.structure.structureType;
});
Clazz.overrideMethod (c$, "getSubstructureType",
function () {
return this.structure.substructureType;
});
Clazz.overrideMethod (c$, "getStructureID",
function () {
return this.structure.structureID;
});
Clazz.overrideMethod (c$, "getSerialID",
function () {
return this.structure.serialID;
});
Clazz.overrideMethod (c$, "getStartChainID",
function () {
return this.structure.startChainID;
});
Clazz.overrideMethod (c$, "getStartSequenceNumber",
function () {
return this.structure.startSequenceNumber;
});
Clazz.overrideMethod (c$, "getStartInsertionCode",
function () {
return J.api.JmolAdapter.canonizeInsertionCode (this.structure.startInsertionCode);
});
Clazz.overrideMethod (c$, "getEndChainID",
function () {
return this.structure.endChainID;
});
Clazz.overrideMethod (c$, "getEndSequenceNumber",
function () {
return this.structure.endSequenceNumber;
});
Clazz.overrideMethod (c$, "getEndInsertionCode",
function () {
return this.structure.endInsertionCode;
});
Clazz.overrideMethod (c$, "getStrandCount",
function () {
return this.structure.strandCount;
});
Clazz.overrideMethod (c$, "getStructuredModels",
function () {
return this.bsModelsDefined;
});
Clazz.overrideMethod (c$, "getAtomIndices",
function () {
return this.structure.atomStartEnd;
});
Clazz.overrideMethod (c$, "getModelIndices",
function () {
return this.structure.modelStartEnd;
});
Clazz.overrideMethod (c$, "getBSAll",
function () {
return this.structure.bsAll;
});
});
|
module.exports = new (require('events').EventEmitter)(); |
import React from 'react';
import { Route, IndexRoute } from 'react-router';
import Start from './components/start';
import App from './App';
const routes = (
<Route path="/" component={App}>
<IndexRoute component={Start}/>
</Route>
);
export default routes; |
export const myiso ={
constructor () {
var fso, ts, s ;
var ForReading = 1;
fso = new ActiveXObject("Scripting.FileSystemObject");
ts = fso.OpenTextFile("d:\\1.txt", ForReading);
s = ts.ReadLine();
return s;
}
} |
import Dexie from 'dexie'
const db = new Dexie('metaDb')
db.version(1).stores({
player: '++id, name',
game: '++id, team, season, day'
})
db.open().catch(e => {
console.error(`metaDb open failed: ${e.stack}`)
})
export const resetPlayer = () => db.table('player').clear()
.catch(e => console.log(`error resetting player table: ${e}`))
export const resetGame = () => db.table('game').clear()
.catch(e => console.log(`error resetting game table: ${e}`))
export const getPlayer = () => db.table('player').toArray()
.then(players => players[0].name)
.catch(() => null)
export default db
//
// // DB is your Dexie object
// // objectList is your list of objects
// DB.transaction('rw', DB.table, function()
// {
// var numObjects = objectList.length
//
// for ( var i = 0 i < numObjects i++ )
// {
// DB.table.put( objectList[i] )
// }
// })
|
/**
* Created by guangqiang on 2017/9/7.
*/
import {createAction} from 'redux-actions'
import type from '../../constants/actionType'
import Action from '../../actionCreators/music'
const getMusicId = createAction(type.MUSIC_ID_LIST, Action.musicIdList)
const getMusicDetail = createAction(type.MUSIC_DETAIL, Action.musicDetail)
const getMusicList = createAction(type.MUSIC_LIST, Action.musicList)
const getxiamiMusic = createAction(type.MUSIC_XIAMI_MUSIC, Action.xiamiMusic)
const resetMusicInfo = createAction(type.MUSIC_RESET_MUSIC_INFO)
const actionCreators = {
getMusicId,
getMusicDetail,
getMusicList,
getxiamiMusic,
resetMusicInfo
}
export default {actionCreators} |
/**
* Helper function for getting & setting variable bits
*/
/* globals ENGINE */
module.exports = function (player, key, value) {
if (typeof(value) !== "undefined") {
ENGINE.setVarBit(player, key, value);
} else {
return ENGINE.getVarBit(player, key);
}
}; |
'use strict';
angular.module('app').service('userPreferencesService', [
'localStorageService',
'VIEW_TYPES',
(localStorageService, VIEW_TYPES) => {
const USER_PREFERENCES_KEYS = {
DEFAULT_VIEW: 'DEFAULT_VIEW'
};
class UserPreferencesService {
/**
* @return {String}
*/
getDefaultViewPreference() {
return localStorageService.get(USER_PREFERENCES_KEYS.DEFAULT_VIEW);
}
/**
* @param {String} viewPreference
* @return {String}
*/
setDefaultViewPreference(viewPreference) {
if (!viewPreference) throw new Error('userPreferencesService - setDefaultViewPreference() - viewPreference is required');
if (!VIEW_TYPES[viewPreference]) throw new Error(`userPreferencesService - setDefaultViewPreference() - ${viewPreference} is not a valid view type`);
return localStorageService.set(USER_PREFERENCES_KEYS.DEFAULT_VIEW, viewPreference);
}
}
return new UserPreferencesService();
}
]);
|
import { GET_TABLE_CONTENT, CONNECT, CHANGE_VIEW_MODE } from '../actions/currentTable';
export default function currentTable(currentTableDefault = {
items: [],
isConnected: false,
isFetching: true,
totalCount: 0,
order: [],
page: 1,
isContent: true,
structureTable: [],
titleTable: []
}, action) {
switch (action.type) {
case GET_TABLE_CONTENT:
return {
items: action.currentTable !== undefined ? action.currentTable : currentTableDefault.items,
isFetching: action.isFetching,
isConnected: true,
totalCount: action.totalCount !== undefined ? action.totalCount : currentTableDefault.totalCount, // eslint-disable-line
order: action.ordder !== undefined ? action.order : currentTableDefault.order,
page: action.page !== undefined ? action.page : currentTableDefault.page,
titleTable: action.titleTable || currentTableDefault.titleTable,
structureTable: action.structureTable || currentTableDefault.structureTable,
isContent: currentTableDefault.isContent,
};
case CONNECT:
return Object.assign({}, currentTableDefault, { isConnected: action.connect });
case CHANGE_VIEW_MODE:
return Object.assign({}, currentTableDefault, { isContent: action.isContent });
default:
return currentTableDefault;
}
}
|
import React from 'react';
import test from 'ava';
import { shallow } from 'enzyme';
import Search from '../search/default';
import Map from './default';
test('It should be able to render the map;', t => {
const wrapper = shallow(<Map />);
t.is(wrapper.find('section.map').length, 1);
t.is(wrapper.find(Search).length, 1);
});
|
var getDefaultValues = require('../lib/getDefaultValues')
var assert = require('assert')
describe('getDefaultValues', function() {
it ('pulls default values out of a schema', function() {
var defaults = getDefaultValues({
properties: {
name: {
type: 'string',
default: 'Bill'
}
}
})
assert.equal(defaults.name, 'Bill')
})
it ('assigns undefined to keys without defaults', function() {
var defaults = getDefaultValues({
properties: {
name: {
type: 'string'
}
}
})
assert.equal(defaults.name, undefined)
})
it ('handles a missing properties field', function() {
var defaults = getDefaultValues()
assert.deepEqual(defaults, {})
})
})
|
/*
Author: Darren Schnare
Keywords: javascript,amd,browser,define,module
License: MIT ( http://www.opensource.org/licenses/mit-license.php )
Repo: https://github.com/dschnare/definejs
*/
define("browser",{window:window,document:document,navigator:window.navigator,console:window.console||{}}) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.