text
stringlengths 3
1.05M
|
|---|
import {spawn} from 'child_process'
import {Observable} from 'rxjs/Observable'
import {mergeMap} from 'rxjs/operator/mergeMap'
import {retryWhen} from 'rxjs/operator/retryWhen'
import {getTmp} from './cache'
import * as util from './util'
import * as config from './config'
import path from 'path'
import debuglog from './debuglog'
const log = debuglog('git')
function prefixGitArgs () {
return process.platform === 'win32' ? ['-c', 'core.longpaths=true'] : []
}
function spawnGit (args) {
log(`executing git with args ${args}`)
const fullArgs = prefixGitArgs().concat(args || [])
return spawn('git', fullArgs)
}
/**
* clone a git repository.
* @param {String} repo - git repository to clone.
* @param {String} ref - git reference to checkout.
* @return {Observable} - observable sequence that will be completed once
* the git repository has been cloned.
*/
export function clone (repo, ref) {
return Observable.create((observer) => {
const tmpDest = getTmp()
const completeHandler = () => {
observer.next(tmpDest)
observer.complete()
}
const errorHandler = (err) => {
log(`failed to clone repository from ${repo}`)
observer.error(err)
}
const args = ['clone', '-b', ref, repo, tmpDest, '--single-branch']
log(`cloning git repository from ${repo}`)
const git = spawnGit(args)
git.on('close', code => (code ? errorHandler() : completeHandler()))
})
}
/**
* extract a cloned git repository to destination.
* @param {String} dest - pathname into which the cloned repository should be
* extracted.
* @return {Observable} - observable sequence that will be completed once
* the cloned repository has been extracted.
*/
export function extract (dest) {
const {pkgJson, target} = this
const tmpDest = pkgJson.dist.path
const where = path.join(dest, target, 'package')
return util.rename(tmpDest, where)
::retryWhen((errors) => errors::mergeMap((error) => {
if (error.code !== 'ENOENT') {
throw error
}
return util.mkdirp(path.dirname(dest))
}))
}
|
import { Meteor } from 'meteor/meteor';
Meteor.methods({
setAvatarFromService(dataURI, contentType, service) {
check(dataURI, String);
check(contentType, Match.Optional(String));
check(service, Match.Optional(String));
if (!Meteor.userId()) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
method: 'setAvatarFromService',
});
}
if (!RocketChat.settings.get('Accounts_AllowUserAvatarChange')) {
throw new Meteor.Error('error-not-allowed', 'Not allowed', {
method: 'setAvatarFromService',
});
}
const user = Meteor.user();
return RocketChat.setUserAvatar(user, dataURI, contentType, service);
},
});
DDPRateLimiter.addRule({
type: 'method',
name: 'setAvatarFromService',
userId() {
return true;
},
}, 1, 5000);
|
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
* @format
*/
'use strict';
const BoundingDimensions = require('BoundingDimensions');
const Platform = require('Platform');
const Position = require('Position');
const React = require('React');
const ReactNative = require('ReactNative');
const StyleSheet = require('StyleSheet');
const TVEventHandler = require('TVEventHandler');
const UIManager = require('UIManager');
const View = require('View');
const keyMirror = require('fbjs/lib/keyMirror');
const normalizeColor = require('normalizeColor');
import type {PressEvent} from 'CoreEventTypes';
import type {EdgeInsetsProp} from 'EdgeInsetsPropType';
const extractSingleTouch = nativeEvent => {
const touches = nativeEvent.touches;
const changedTouches = nativeEvent.changedTouches;
const hasTouches = touches && touches.length > 0;
const hasChangedTouches = changedTouches && changedTouches.length > 0;
return !hasTouches && hasChangedTouches
? changedTouches[0]
: hasTouches
? touches[0]
: nativeEvent;
};
/**
* `Touchable`: Taps done right.
*
* You hook your `ResponderEventPlugin` events into `Touchable`. `Touchable`
* will measure time/geometry and tells you when to give feedback to the user.
*
* ====================== Touchable Tutorial ===============================
* The `Touchable` mixin helps you handle the "press" interaction. It analyzes
* the geometry of elements, and observes when another responder (scroll view
* etc) has stolen the touch lock. It notifies your component when it should
* give feedback to the user. (bouncing/highlighting/unhighlighting).
*
* - When a touch was activated (typically you highlight)
* - When a touch was deactivated (typically you unhighlight)
* - When a touch was "pressed" - a touch ended while still within the geometry
* of the element, and no other element (like scroller) has "stolen" touch
* lock ("responder") (Typically you bounce the element).
*
* A good tap interaction isn't as simple as you might think. There should be a
* slight delay before showing a highlight when starting a touch. If a
* subsequent touch move exceeds the boundary of the element, it should
* unhighlight, but if that same touch is brought back within the boundary, it
* should rehighlight again. A touch can move in and out of that boundary
* several times, each time toggling highlighting, but a "press" is only
* triggered if that touch ends while within the element's boundary and no
* scroller (or anything else) has stolen the lock on touches.
*
* To create a new type of component that handles interaction using the
* `Touchable` mixin, do the following:
*
* - Initialize the `Touchable` state.
*
* getInitialState: function() {
* return merge(this.touchableGetInitialState(), yourComponentState);
* }
*
* - Choose the rendered component who's touches should start the interactive
* sequence. On that rendered node, forward all `Touchable` responder
* handlers. You can choose any rendered node you like. Choose a node whose
* hit target you'd like to instigate the interaction sequence:
*
* // In render function:
* return (
* <View
* onStartShouldSetResponder={this.touchableHandleStartShouldSetResponder}
* onResponderTerminationRequest={this.touchableHandleResponderTerminationRequest}
* onResponderGrant={this.touchableHandleResponderGrant}
* onResponderMove={this.touchableHandleResponderMove}
* onResponderRelease={this.touchableHandleResponderRelease}
* onResponderTerminate={this.touchableHandleResponderTerminate}>
* <View>
* Even though the hit detection/interactions are triggered by the
* wrapping (typically larger) node, we usually end up implementing
* custom logic that highlights this inner one.
* </View>
* </View>
* );
*
* - You may set up your own handlers for each of these events, so long as you
* also invoke the `touchable*` handlers inside of your custom handler.
*
* - Implement the handlers on your component class in order to provide
* feedback to the user. See documentation for each of these class methods
* that you should implement.
*
* touchableHandlePress: function() {
* this.performBounceAnimation(); // or whatever you want to do.
* },
* touchableHandleActivePressIn: function() {
* this.beginHighlighting(...); // Whatever you like to convey activation
* },
* touchableHandleActivePressOut: function() {
* this.endHighlighting(...); // Whatever you like to convey deactivation
* },
*
* - There are more advanced methods you can implement (see documentation below):
* touchableGetHighlightDelayMS: function() {
* return 20;
* }
* // In practice, *always* use a predeclared constant (conserve memory).
* touchableGetPressRectOffset: function() {
* return {top: 20, left: 20, right: 20, bottom: 100};
* }
*/
/**
* Touchable states.
*/
const States = keyMirror({
NOT_RESPONDER: null, // Not the responder
RESPONDER_INACTIVE_PRESS_IN: null, // Responder, inactive, in the `PressRect`
RESPONDER_INACTIVE_PRESS_OUT: null, // Responder, inactive, out of `PressRect`
RESPONDER_ACTIVE_PRESS_IN: null, // Responder, active, in the `PressRect`
RESPONDER_ACTIVE_PRESS_OUT: null, // Responder, active, out of `PressRect`
RESPONDER_ACTIVE_LONG_PRESS_IN: null, // Responder, active, in the `PressRect`, after long press threshold
RESPONDER_ACTIVE_LONG_PRESS_OUT: null, // Responder, active, out of `PressRect`, after long press threshold
ERROR: null,
});
type State =
| typeof States.NOT_RESPONDER
| typeof States.RESPONDER_INACTIVE_PRESS_IN
| typeof States.RESPONDER_INACTIVE_PRESS_OUT
| typeof States.RESPONDER_ACTIVE_PRESS_IN
| typeof States.RESPONDER_ACTIVE_PRESS_OUT
| typeof States.RESPONDER_ACTIVE_LONG_PRESS_IN
| typeof States.RESPONDER_ACTIVE_LONG_PRESS_OUT
| typeof States.ERROR;
/*
* Quick lookup map for states that are considered to be "active"
*/
const baseStatesConditions = {
NOT_RESPONDER: false,
RESPONDER_INACTIVE_PRESS_IN: false,
RESPONDER_INACTIVE_PRESS_OUT: false,
RESPONDER_ACTIVE_PRESS_IN: false,
RESPONDER_ACTIVE_PRESS_OUT: false,
RESPONDER_ACTIVE_LONG_PRESS_IN: false,
RESPONDER_ACTIVE_LONG_PRESS_OUT: false,
ERROR: false,
};
const IsActive = {
...baseStatesConditions,
RESPONDER_ACTIVE_PRESS_OUT: true,
RESPONDER_ACTIVE_PRESS_IN: true,
};
/**
* Quick lookup for states that are considered to be "pressing" and are
* therefore eligible to result in a "selection" if the press stops.
*/
const IsPressingIn = {
...baseStatesConditions,
RESPONDER_INACTIVE_PRESS_IN: true,
RESPONDER_ACTIVE_PRESS_IN: true,
RESPONDER_ACTIVE_LONG_PRESS_IN: true,
};
const IsLongPressingIn = {
...baseStatesConditions,
RESPONDER_ACTIVE_LONG_PRESS_IN: true,
};
/**
* Inputs to the state machine.
*/
const Signals = keyMirror({
DELAY: null,
RESPONDER_GRANT: null,
RESPONDER_RELEASE: null,
RESPONDER_TERMINATED: null,
ENTER_PRESS_RECT: null,
LEAVE_PRESS_RECT: null,
LONG_PRESS_DETECTED: null,
});
type Signal =
| typeof Signals.DELAY
| typeof Signals.RESPONDER_GRANT
| typeof Signals.RESPONDER_RELEASE
| typeof Signals.RESPONDER_TERMINATED
| typeof Signals.ENTER_PRESS_RECT
| typeof Signals.LEAVE_PRESS_RECT
| typeof Signals.LONG_PRESS_DETECTED;
/**
* Mapping from States x Signals => States
*/
const Transitions = {
NOT_RESPONDER: {
DELAY: States.ERROR,
RESPONDER_GRANT: States.RESPONDER_INACTIVE_PRESS_IN,
RESPONDER_RELEASE: States.ERROR,
RESPONDER_TERMINATED: States.ERROR,
ENTER_PRESS_RECT: States.ERROR,
LEAVE_PRESS_RECT: States.ERROR,
LONG_PRESS_DETECTED: States.ERROR,
},
RESPONDER_INACTIVE_PRESS_IN: {
DELAY: States.RESPONDER_ACTIVE_PRESS_IN,
RESPONDER_GRANT: States.ERROR,
RESPONDER_RELEASE: States.NOT_RESPONDER,
RESPONDER_TERMINATED: States.NOT_RESPONDER,
ENTER_PRESS_RECT: States.RESPONDER_INACTIVE_PRESS_IN,
LEAVE_PRESS_RECT: States.RESPONDER_INACTIVE_PRESS_OUT,
LONG_PRESS_DETECTED: States.ERROR,
},
RESPONDER_INACTIVE_PRESS_OUT: {
DELAY: States.RESPONDER_ACTIVE_PRESS_OUT,
RESPONDER_GRANT: States.ERROR,
RESPONDER_RELEASE: States.NOT_RESPONDER,
RESPONDER_TERMINATED: States.NOT_RESPONDER,
ENTER_PRESS_RECT: States.RESPONDER_INACTIVE_PRESS_IN,
LEAVE_PRESS_RECT: States.RESPONDER_INACTIVE_PRESS_OUT,
LONG_PRESS_DETECTED: States.ERROR,
},
RESPONDER_ACTIVE_PRESS_IN: {
DELAY: States.ERROR,
RESPONDER_GRANT: States.ERROR,
RESPONDER_RELEASE: States.NOT_RESPONDER,
RESPONDER_TERMINATED: States.NOT_RESPONDER,
ENTER_PRESS_RECT: States.RESPONDER_ACTIVE_PRESS_IN,
LEAVE_PRESS_RECT: States.RESPONDER_ACTIVE_PRESS_OUT,
LONG_PRESS_DETECTED: States.RESPONDER_ACTIVE_LONG_PRESS_IN,
},
RESPONDER_ACTIVE_PRESS_OUT: {
DELAY: States.ERROR,
RESPONDER_GRANT: States.ERROR,
RESPONDER_RELEASE: States.NOT_RESPONDER,
RESPONDER_TERMINATED: States.NOT_RESPONDER,
ENTER_PRESS_RECT: States.RESPONDER_ACTIVE_PRESS_IN,
LEAVE_PRESS_RECT: States.RESPONDER_ACTIVE_PRESS_OUT,
LONG_PRESS_DETECTED: States.ERROR,
},
RESPONDER_ACTIVE_LONG_PRESS_IN: {
DELAY: States.ERROR,
RESPONDER_GRANT: States.ERROR,
RESPONDER_RELEASE: States.NOT_RESPONDER,
RESPONDER_TERMINATED: States.NOT_RESPONDER,
ENTER_PRESS_RECT: States.RESPONDER_ACTIVE_LONG_PRESS_IN,
LEAVE_PRESS_RECT: States.RESPONDER_ACTIVE_LONG_PRESS_OUT,
LONG_PRESS_DETECTED: States.RESPONDER_ACTIVE_LONG_PRESS_IN,
},
RESPONDER_ACTIVE_LONG_PRESS_OUT: {
DELAY: States.ERROR,
RESPONDER_GRANT: States.ERROR,
RESPONDER_RELEASE: States.NOT_RESPONDER,
RESPONDER_TERMINATED: States.NOT_RESPONDER,
ENTER_PRESS_RECT: States.RESPONDER_ACTIVE_LONG_PRESS_IN,
LEAVE_PRESS_RECT: States.RESPONDER_ACTIVE_LONG_PRESS_OUT,
LONG_PRESS_DETECTED: States.ERROR,
},
error: {
DELAY: States.NOT_RESPONDER,
RESPONDER_GRANT: States.RESPONDER_INACTIVE_PRESS_IN,
RESPONDER_RELEASE: States.NOT_RESPONDER,
RESPONDER_TERMINATED: States.NOT_RESPONDER,
ENTER_PRESS_RECT: States.NOT_RESPONDER,
LEAVE_PRESS_RECT: States.NOT_RESPONDER,
LONG_PRESS_DETECTED: States.NOT_RESPONDER,
},
};
// ==== Typical Constants for integrating into UI components ====
// var HIT_EXPAND_PX = 20;
// var HIT_VERT_OFFSET_PX = 10;
const HIGHLIGHT_DELAY_MS = 130;
const PRESS_EXPAND_PX = 20;
const LONG_PRESS_THRESHOLD = 500;
const LONG_PRESS_DELAY_MS = LONG_PRESS_THRESHOLD - HIGHLIGHT_DELAY_MS;
const LONG_PRESS_ALLOWED_MOVEMENT = 10;
// Default amount "active" region protrudes beyond box
/**
* By convention, methods prefixed with underscores are meant to be @private,
* and not @protected. Mixers shouldn't access them - not even to provide them
* as callback handlers.
*
*
* ========== Geometry =========
* `Touchable` only assumes that there exists a `HitRect` node. The `PressRect`
* is an abstract box that is extended beyond the `HitRect`.
*
* +--------------------------+
* | | - "Start" events in `HitRect` cause `HitRect`
* | +--------------------+ | to become the responder.
* | | +--------------+ | | - `HitRect` is typically expanded around
* | | | | | | the `VisualRect`, but shifted downward.
* | | | VisualRect | | | - After pressing down, after some delay,
* | | | | | | and before letting up, the Visual React
* | | +--------------+ | | will become "active". This makes it eligible
* | | HitRect | | for being highlighted (so long as the
* | +--------------------+ | press remains in the `PressRect`).
* | PressRect o |
* +----------------------|---+
* Out Region |
* +-----+ This gap between the `HitRect` and
* `PressRect` allows a touch to move far away
* from the original hit rect, and remain
* highlighted, and eligible for a "Press".
* Customize this via
* `touchableGetPressRectOffset()`.
*
*
*
* ======= State Machine =======
*
* +-------------+ <---+ RESPONDER_RELEASE
* |NOT_RESPONDER|
* +-------------+ <---+ RESPONDER_TERMINATED
* +
* | RESPONDER_GRANT (HitRect)
* v
* +---------------------------+ DELAY +-------------------------+ T + DELAY +------------------------------+
* |RESPONDER_INACTIVE_PRESS_IN|+-------->|RESPONDER_ACTIVE_PRESS_IN| +------------> |RESPONDER_ACTIVE_LONG_PRESS_IN|
* +---------------------------+ +-------------------------+ +------------------------------+
* + ^ + ^ + ^
* |LEAVE_ |ENTER_ |LEAVE_ |ENTER_ |LEAVE_ |ENTER_
* |PRESS_RECT |PRESS_RECT |PRESS_RECT |PRESS_RECT |PRESS_RECT |PRESS_RECT
* | | | | | |
* v + v + v +
* +----------------------------+ DELAY +--------------------------+ +-------------------------------+
* |RESPONDER_INACTIVE_PRESS_OUT|+------->|RESPONDER_ACTIVE_PRESS_OUT| |RESPONDER_ACTIVE_LONG_PRESS_OUT|
* +----------------------------+ +--------------------------+ +-------------------------------+
*
* T + DELAY => LONG_PRESS_DELAY_MS + DELAY
*
* Not drawn are the side effects of each transition. The most important side
* effect is the `touchableHandlePress` abstract method invocation that occurs
* when a responder is released while in either of the "Press" states.
*
* The other important side effects are the highlight abstract method
* invocations (internal callbacks) to be implemented by the mixer.
*
*
* @lends Touchable.prototype
*/
const TouchableMixin = {
componentDidMount: function() {
if (!Platform.isTV) {
return;
}
this._tvEventHandler = new TVEventHandler();
this._tvEventHandler.enable(this, function(cmp, evt) {
const myTag = ReactNative.findNodeHandle(cmp);
evt.dispatchConfig = {};
if (myTag === evt.tag) {
if (evt.eventType === 'focus') {
cmp.touchableHandleFocus(evt);
} else if (evt.eventType === 'blur') {
cmp.touchableHandleBlur(evt);
} else if (evt.eventType === 'select') {
cmp.touchableHandlePress &&
!cmp.props.disabled &&
cmp.touchableHandlePress(evt);
}
}
});
},
/**
* Clear all timeouts on unmount
*/
componentWillUnmount: function() {
if (this._tvEventHandler) {
this._tvEventHandler.disable();
delete this._tvEventHandler;
}
this.touchableDelayTimeout && clearTimeout(this.touchableDelayTimeout);
this.longPressDelayTimeout && clearTimeout(this.longPressDelayTimeout);
this.pressOutDelayTimeout && clearTimeout(this.pressOutDelayTimeout);
},
/**
* It's prefer that mixins determine state in this way, having the class
* explicitly mix the state in the one and only `getInitialState` method.
*
* @return {object} State object to be placed inside of
* `this.state.touchable`.
*/
touchableGetInitialState: function() {
return {
touchable: {touchState: undefined, responderID: null},
};
},
// ==== Hooks to Gesture Responder system ====
/**
* Must return true if embedded in a native platform scroll view.
*/
touchableHandleResponderTerminationRequest: function() {
return !this.props.rejectResponderTermination;
},
/**
* Must return true to start the process of `Touchable`.
*/
touchableHandleStartShouldSetResponder: function() {
return !this.props.disabled;
},
/**
* Return true to cancel press on long press.
*/
touchableLongPressCancelsPress: function() {
return true;
},
/**
* Place as callback for a DOM element's `onResponderGrant` event.
* @param {SyntheticEvent} e Synthetic event from event system.
*
*/
touchableHandleResponderGrant: function(e: PressEvent) {
const dispatchID = e.currentTarget;
// Since e is used in a callback invoked on another event loop
// (as in setTimeout etc), we need to call e.persist() on the
// event to make sure it doesn't get reused in the event object pool.
e.persist();
this.pressOutDelayTimeout && clearTimeout(this.pressOutDelayTimeout);
this.pressOutDelayTimeout = null;
this.state.touchable.touchState = States.NOT_RESPONDER;
this.state.touchable.responderID = dispatchID;
this._receiveSignal(Signals.RESPONDER_GRANT, e);
let delayMS =
this.touchableGetHighlightDelayMS !== undefined
? Math.max(this.touchableGetHighlightDelayMS(), 0)
: HIGHLIGHT_DELAY_MS;
delayMS = isNaN(delayMS) ? HIGHLIGHT_DELAY_MS : delayMS;
if (delayMS !== 0) {
this.touchableDelayTimeout = setTimeout(
this._handleDelay.bind(this, e),
delayMS,
);
} else {
this._handleDelay(e);
}
let longDelayMS =
this.touchableGetLongPressDelayMS !== undefined
? Math.max(this.touchableGetLongPressDelayMS(), 10)
: LONG_PRESS_DELAY_MS;
longDelayMS = isNaN(longDelayMS) ? LONG_PRESS_DELAY_MS : longDelayMS;
this.longPressDelayTimeout = setTimeout(
this._handleLongDelay.bind(this, e),
longDelayMS + delayMS,
);
},
/**
* Place as callback for a DOM element's `onResponderRelease` event.
*/
touchableHandleResponderRelease: function(e: PressEvent) {
this._receiveSignal(Signals.RESPONDER_RELEASE, e);
},
/**
* Place as callback for a DOM element's `onResponderTerminate` event.
*/
touchableHandleResponderTerminate: function(e: PressEvent) {
this._receiveSignal(Signals.RESPONDER_TERMINATED, e);
},
/**
* Place as callback for a DOM element's `onResponderMove` event.
*/
touchableHandleResponderMove: function(e: PressEvent) {
// Not enough time elapsed yet, wait for highlight -
// this is just a perf optimization.
if (
this.state.touchable.touchState === States.RESPONDER_INACTIVE_PRESS_IN
) {
return;
}
// Measurement may not have returned yet.
if (!this.state.touchable.positionOnActivate) {
return;
}
const positionOnActivate = this.state.touchable.positionOnActivate;
const dimensionsOnActivate = this.state.touchable.dimensionsOnActivate;
const pressRectOffset = this.touchableGetPressRectOffset
? this.touchableGetPressRectOffset()
: {
left: PRESS_EXPAND_PX,
right: PRESS_EXPAND_PX,
top: PRESS_EXPAND_PX,
bottom: PRESS_EXPAND_PX,
};
let pressExpandLeft = pressRectOffset.left;
let pressExpandTop = pressRectOffset.top;
let pressExpandRight = pressRectOffset.right;
let pressExpandBottom = pressRectOffset.bottom;
const hitSlop = this.touchableGetHitSlop
? this.touchableGetHitSlop()
: null;
if (hitSlop) {
pressExpandLeft += hitSlop.left;
pressExpandTop += hitSlop.top;
pressExpandRight += hitSlop.right;
pressExpandBottom += hitSlop.bottom;
}
const touch = extractSingleTouch(e.nativeEvent);
const pageX = touch && touch.pageX;
const pageY = touch && touch.pageY;
if (this.pressInLocation) {
const movedDistance = this._getDistanceBetweenPoints(
pageX,
pageY,
this.pressInLocation.pageX,
this.pressInLocation.pageY,
);
if (movedDistance > LONG_PRESS_ALLOWED_MOVEMENT) {
this._cancelLongPressDelayTimeout();
}
}
const isTouchWithinActive =
pageX > positionOnActivate.left - pressExpandLeft &&
pageY > positionOnActivate.top - pressExpandTop &&
pageX <
positionOnActivate.left +
dimensionsOnActivate.width +
pressExpandRight &&
pageY <
positionOnActivate.top +
dimensionsOnActivate.height +
pressExpandBottom;
if (isTouchWithinActive) {
this._receiveSignal(Signals.ENTER_PRESS_RECT, e);
const curState = this.state.touchable.touchState;
if (curState === States.RESPONDER_INACTIVE_PRESS_IN) {
// fix for t7967420
this._cancelLongPressDelayTimeout();
}
} else {
this._cancelLongPressDelayTimeout();
this._receiveSignal(Signals.LEAVE_PRESS_RECT, e);
}
},
/**
* Invoked when the item receives focus. Mixers might override this to
* visually distinguish the `VisualRect` so that the user knows that it
* currently has the focus. Most platforms only support a single element being
* focused at a time, in which case there may have been a previously focused
* element that was blurred just prior to this.
*/
touchableHandleFocus: function(e: Event) {
this.props.onFocus && this.props.onFocus(e);
},
/**
* Invoked when the item loses focus. Mixers might override this to
* visually distinguish the `VisualRect` so that the user knows that it
* no longer has focus. Most platforms only support a single element being
* focused at a time, in which case the focus may have moved to another.
*/
touchableHandleBlur: function(e: Event) {
this.props.onBlur && this.props.onBlur(e);
},
// ==== Abstract Application Callbacks ====
/**
* Invoked when the item should be highlighted. Mixers should implement this
* to visually distinguish the `VisualRect` so that the user knows that
* releasing a touch will result in a "selection" (analog to click).
*
* @abstract
* touchableHandleActivePressIn: function,
*/
/**
* Invoked when the item is "active" (in that it is still eligible to become
* a "select") but the touch has left the `PressRect`. Usually the mixer will
* want to unhighlight the `VisualRect`. If the user (while pressing) moves
* back into the `PressRect` `touchableHandleActivePressIn` will be invoked
* again and the mixer should probably highlight the `VisualRect` again. This
* event will not fire on an `touchEnd/mouseUp` event, only move events while
* the user is depressing the mouse/touch.
*
* @abstract
* touchableHandleActivePressOut: function
*/
/**
* Invoked when the item is "selected" - meaning the interaction ended by
* letting up while the item was either in the state
* `RESPONDER_ACTIVE_PRESS_IN` or `RESPONDER_INACTIVE_PRESS_IN`.
*
* @abstract
* touchableHandlePress: function
*/
/**
* Invoked when the item is long pressed - meaning the interaction ended by
* letting up while the item was in `RESPONDER_ACTIVE_LONG_PRESS_IN`. If
* `touchableHandleLongPress` is *not* provided, `touchableHandlePress` will
* be called as it normally is. If `touchableHandleLongPress` is provided, by
* default any `touchableHandlePress` callback will not be invoked. To
* override this default behavior, override `touchableLongPressCancelsPress`
* to return false. As a result, `touchableHandlePress` will be called when
* lifting up, even if `touchableHandleLongPress` has also been called.
*
* @abstract
* touchableHandleLongPress: function
*/
/**
* Returns the number of millis to wait before triggering a highlight.
*
* @abstract
* touchableGetHighlightDelayMS: function
*/
/**
* Returns the amount to extend the `HitRect` into the `PressRect`. Positive
* numbers mean the size expands outwards.
*
* @abstract
* touchableGetPressRectOffset: function
*/
// ==== Internal Logic ====
/**
* Measures the `HitRect` node on activation. The Bounding rectangle is with
* respect to viewport - not page, so adding the `pageXOffset/pageYOffset`
* should result in points that are in the same coordinate system as an
* event's `globalX/globalY` data values.
*
* - Consider caching this for the lifetime of the component, or possibly
* being able to share this cache between any `ScrollMap` view.
*
* @sideeffects
* @private
*/
_remeasureMetricsOnActivation: function() {
const tag = this.state.touchable.responderID;
if (tag == null) {
return;
}
UIManager.measure(tag, this._handleQueryLayout);
},
_handleQueryLayout: function(
l: number,
t: number,
w: number,
h: number,
globalX: number,
globalY: number,
) {
//don't do anything UIManager failed to measure node
if (!l && !t && !w && !h && !globalX && !globalY) {
return;
}
this.state.touchable.positionOnActivate &&
Position.release(this.state.touchable.positionOnActivate);
this.state.touchable.dimensionsOnActivate &&
BoundingDimensions.release(this.state.touchable.dimensionsOnActivate);
this.state.touchable.positionOnActivate = Position.getPooled(
globalX,
globalY,
);
this.state.touchable.dimensionsOnActivate = BoundingDimensions.getPooled(
w,
h,
);
},
_handleDelay: function(e: PressEvent) {
this.touchableDelayTimeout = null;
this._receiveSignal(Signals.DELAY, e);
},
_handleLongDelay: function(e: PressEvent) {
this.longPressDelayTimeout = null;
const curState = this.state.touchable.touchState;
if (
curState !== States.RESPONDER_ACTIVE_PRESS_IN &&
curState !== States.RESPONDER_ACTIVE_LONG_PRESS_IN
) {
console.error(
'Attempted to transition from state `' +
curState +
'` to `' +
States.RESPONDER_ACTIVE_LONG_PRESS_IN +
'`, which is not supported. This is ' +
'most likely due to `Touchable.longPressDelayTimeout` not being cancelled.',
);
} else {
this._receiveSignal(Signals.LONG_PRESS_DETECTED, e);
}
},
/**
* Receives a state machine signal, performs side effects of the transition
* and stores the new state. Validates the transition as well.
*
* @param {Signals} signal State machine signal.
* @throws Error if invalid state transition or unrecognized signal.
* @sideeffects
*/
_receiveSignal: function(signal: Signal, e: PressEvent) {
const responderID = this.state.touchable.responderID;
const curState = this.state.touchable.touchState;
const nextState = Transitions[curState] && Transitions[curState][signal];
if (!responderID && signal === Signals.RESPONDER_RELEASE) {
return;
}
if (!nextState) {
throw new Error(
'Unrecognized signal `' +
signal +
'` or state `' +
curState +
'` for Touchable responder `' +
responderID +
'`',
);
}
if (nextState === States.ERROR) {
throw new Error(
'Touchable cannot transition from `' +
curState +
'` to `' +
signal +
'` for responder `' +
responderID +
'`',
);
}
if (curState !== nextState) {
this._performSideEffectsForTransition(curState, nextState, signal, e);
this.state.touchable.touchState = nextState;
}
},
_cancelLongPressDelayTimeout: function() {
this.longPressDelayTimeout && clearTimeout(this.longPressDelayTimeout);
this.longPressDelayTimeout = null;
},
_isHighlight: function(state: State) {
return (
state === States.RESPONDER_ACTIVE_PRESS_IN ||
state === States.RESPONDER_ACTIVE_LONG_PRESS_IN
);
},
_savePressInLocation: function(e: PressEvent) {
const touch = extractSingleTouch(e.nativeEvent);
const pageX = touch && touch.pageX;
const pageY = touch && touch.pageY;
const locationX = touch && touch.locationX;
const locationY = touch && touch.locationY;
this.pressInLocation = {pageX, pageY, locationX, locationY};
},
_getDistanceBetweenPoints: function(
aX: number,
aY: number,
bX: number,
bY: number,
) {
const deltaX = aX - bX;
const deltaY = aY - bY;
return Math.sqrt(deltaX * deltaX + deltaY * deltaY);
},
/**
* Will perform a transition between touchable states, and identify any
* highlighting or unhighlighting that must be performed for this particular
* transition.
*
* @param {States} curState Current Touchable state.
* @param {States} nextState Next Touchable state.
* @param {Signal} signal Signal that triggered the transition.
* @param {Event} e Native event.
* @sideeffects
*/
_performSideEffectsForTransition: function(
curState: State,
nextState: State,
signal: Signal,
e: PressEvent,
) {
const curIsHighlight = this._isHighlight(curState);
const newIsHighlight = this._isHighlight(nextState);
const isFinalSignal =
signal === Signals.RESPONDER_TERMINATED ||
signal === Signals.RESPONDER_RELEASE;
if (isFinalSignal) {
this._cancelLongPressDelayTimeout();
}
if (!IsActive[curState] && IsActive[nextState]) {
this._remeasureMetricsOnActivation();
}
if (IsPressingIn[curState] && signal === Signals.LONG_PRESS_DETECTED) {
this.touchableHandleLongPress && this.touchableHandleLongPress(e);
}
if (newIsHighlight && !curIsHighlight) {
this._startHighlight(e);
} else if (!newIsHighlight && curIsHighlight) {
this._endHighlight(e);
}
if (IsPressingIn[curState] && signal === Signals.RESPONDER_RELEASE) {
const hasLongPressHandler = !!this.props.onLongPress;
const pressIsLongButStillCallOnPress =
IsLongPressingIn[curState] && // We *are* long pressing.. // But either has no long handler
(!hasLongPressHandler || !this.touchableLongPressCancelsPress()); // or we're told to ignore it.
const shouldInvokePress =
!IsLongPressingIn[curState] || pressIsLongButStillCallOnPress;
if (shouldInvokePress && this.touchableHandlePress) {
if (!newIsHighlight && !curIsHighlight) {
// we never highlighted because of delay, but we should highlight now
this._startHighlight(e);
this._endHighlight(e);
}
if (Platform.OS === 'android') {
this._playTouchSound();
}
this.touchableHandlePress(e);
}
}
this.touchableDelayTimeout && clearTimeout(this.touchableDelayTimeout);
this.touchableDelayTimeout = null;
},
_playTouchSound: function() {
UIManager.playTouchSound();
},
_startHighlight: function(e: PressEvent) {
this._savePressInLocation(e);
this.touchableHandleActivePressIn && this.touchableHandleActivePressIn(e);
},
_endHighlight: function(e: PressEvent) {
if (this.touchableHandleActivePressOut) {
if (
this.touchableGetPressOutDelayMS &&
this.touchableGetPressOutDelayMS()
) {
this.pressOutDelayTimeout = setTimeout(() => {
this.touchableHandleActivePressOut(e);
}, this.touchableGetPressOutDelayMS());
} else {
this.touchableHandleActivePressOut(e);
}
}
},
};
const Touchable = {
Mixin: TouchableMixin,
TOUCH_TARGET_DEBUG: false, // Highlights all touchable targets. Toggle with Inspector.
/**
* Renders a debugging overlay to visualize touch target with hitSlop (might not work on Android).
*/
renderDebugView: ({
color,
hitSlop,
}: {
color: string | number,
hitSlop: EdgeInsetsProp,
}) => {
if (!Touchable.TOUCH_TARGET_DEBUG) {
return null;
}
if (!__DEV__) {
throw Error(
'Touchable.TOUCH_TARGET_DEBUG should not be enabled in prod!',
);
}
const debugHitSlopStyle = {};
hitSlop = hitSlop || {top: 0, bottom: 0, left: 0, right: 0};
for (const key in hitSlop) {
debugHitSlopStyle[key] = -hitSlop[key];
}
const normalizedColor = normalizeColor(color);
if (typeof normalizedColor !== 'number') {
return null;
}
const hexColor =
'#' + ('00000000' + normalizedColor.toString(16)).substr(-8);
return (
<View
pointerEvents="none"
style={[
styles.debug,
{
borderColor: hexColor.slice(0, -2) + '55', // More opaque
backgroundColor: hexColor.slice(0, -2) + '0F', // Less opaque
...debugHitSlopStyle,
},
]}
/>
);
},
};
const styles = StyleSheet.create({
debug: {
position: 'absolute',
borderWidth: 1,
borderStyle: 'dashed',
},
});
module.exports = Touchable;
|
/*
Copyright (c) 2016 VMware, Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
(function() {
'use strict';
angular
.module('harbor.loading.progress')
.directive('loadingProgress', loadingProgress);
function loadingProgress() {
var directive = {
'restrict': 'EA',
'scope': {
'toggleInProgress': '=',
'hideTarget': '@'
},
'link': link
};
return directive;
function link(scope, element, attrs) {
var spinner = $('<span class="loading-progress">');
function convertToBoolean(val) {
return val === 'true' ? true : false;
}
var hideTarget = convertToBoolean(scope.hideTarget);
console.log('loading-progress, toggleInProgress:' + scope.toggleInProgress + ', hideTarget:' + hideTarget);
var pristine = element.html();
scope.$watch('toggleInProgress', function(current) {
if(scope.toggleInProgress) {
element.attr('disabled', 'disabled');
if(hideTarget) {
element.html(spinner);
}else{
spinner = spinner.css({'margin-left': '5px'});
element.append(spinner);
}
}else{
if(hideTarget) {
element.html(pristine);
}else{
element.find('.loading-progress').remove();
}
element.removeAttr('disabled');
}
});
}
}
})();
|
export default class Player extends Phaser.GameObjects.Container {
constructor(scene, x, y) {
super(scene, x, y);
this.scene = scene;
scene.add.existing(this);
this.sprite = scene.add.sprite(0, 0, 'mouse', 0);
// this.sprite.setOrigin(0.5, 1.0);
// this.sprite.setScale(this.size);
// this.sprite.setTint(0x7777ff);
this.add(this.sprite);
this.setupAnimations();
this.walkSpeed = 10;
}
update(time, delta) {
let horInput = (-1 * this.scene.leftDown) + (1 * this.scene.rightDown);
if (horInput == 0) {
this.play('idle', true);
}
else {
this.play('walk', true);
this.scaleX = horInput;
}
this.x += horInput * this.walkSpeed;
}
play(key, ignoreIfPlaying=false) {
this.sprite.play(key, ignoreIfPlaying);
}
setupAnimations() {
this.scene.anims.create({
key: 'idle',
frames: [
{key: 'mouse', frame: 0, duration: 300},
{key: 'mouse', frame: 1, duration: 300},
],
repeat: -1
});
this.scene.anims.create({
key: 'walk',
frames: [
{key: 'mouse', frame: 2, duration: 100},
{key: 'mouse', frame: 3, duration: 100},
],
repeat: -1
});
}
}
|
const path = require('path')
const dotEnvPath = path.resolve('.env')
/**
* since mocha don't see enviroment variables we have to use dotenv
*/
require('dotenv').config({ path: dotEnvPath })
module.exports = {
development: {
'url': process.env.DATABASE_URL,
'dialect': 'mysql',
'define': {
'underscored': false
}
},
test: {
'url': process.env.DATABASE_URL_TEST,
'dialect': 'mysql',
'define': {
'underscored': false
}
},
staging: {
'url': process.env.DATABASE_URL_STAGING,
'dialect': 'mysql',
'define': {
'underscored': false
},
'ssl': true,
'dialectOptions': {
'ssl': {
'require': true
}
}
},
production: {
'url': process.env.DATABASE_URL_PRODUCTION,
'dialect': 'mysql',
'define': {
'underscored': false
}
// 'ssl': true,
// 'dialectOptions': {
// 'ssl': {
// 'require': true
// }
// }
}
}
|
"use strict";
/**
* @license
* Copyright 2017 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
Object.defineProperty(exports, "__esModule", { value: true });
var ArgMinMaxProgram = /** @class */ (function () {
function ArgMinMaxProgram(reduceInfo, op, firstPass) {
this.variableNames = ['A'];
var windowSize = reduceInfo.windowSize;
var batchSize = reduceInfo.batchSize;
var inSize = reduceInfo.inSize;
var outSize = Math.ceil(inSize / windowSize);
if (!firstPass) {
this.variableNames.push('bestIndicesA');
}
this.outputShape = [batchSize, outSize];
var compOp = (op === 'max') ? '>' : '<';
var indexSnippet = firstPass ?
'inOffset + i;' :
'round(getBestIndicesA(batch, inOffset + i));';
this.userCode = "\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = outIdx * " + windowSize + ";\n\n int bestIndex = inOffset;\n float bestValue = getA(batch, bestIndex);\n\n for (int i = 0; i < " + windowSize + "; i++) {\n int inIdx = " + indexSnippet + ";\n float candidate = getA(batch, inIdx);\n if (candidate " + compOp + " bestValue) {\n bestValue = candidate;\n bestIndex = inIdx;\n }\n }\n setOutput(float(bestIndex));\n }\n ";
}
return ArgMinMaxProgram;
}());
exports.ArgMinMaxProgram = ArgMinMaxProgram;
//# sourceMappingURL=argminmax_gpu.js.map
|
// args.apiDoc needs to be a js object. This file could be a json file, but we can't add
// comments in json files.
module.exports = {
swagger: '2.0',
// all routes will now have /v3 prefixed.
basePath: '/v3',
info: {
title: 'express-openapi sample project',
version: '3.0.0'
},
definitions: {
Error: {
additionalProperties: true
},
Foo: {
properties: {
name: {
type: 'string',
format: 'foo'
}
},
required: ['name']
}
},
// paths are derived from args.routes. These are filled in by fs-routes.
paths: {}
};
|
const Game = (io, games, utils, cardsPerPlayer, scoreToWin) => {
const Game = {
updatePlayerList: roomNum => {
const game = games[utils.getGameIndex(roomNum)];
io.to(roomNum).emit('UpdatePlayerList', game.players);
},
toggleReady: ({ room, userName },) => {
const gameIndex = utils.getGameIndex(room);
const playerIndex = games[gameIndex].players.findIndex(player => player.name == userName);
games[gameIndex].players[playerIndex].ready = !games[gameIndex].players[playerIndex].ready;
const readyPlayers = games[gameIndex].players.filter(player => player.ready == true);
if (readyPlayers.length == games[gameIndex].players.length && games[gameIndex].canStart == false && games[gameIndex].players.length > 1) {
games[gameIndex].canStart = true;
io.to(roomNum).emit('toggleAllowStart');
};
if (readyPlayers.length < games[gameIndex].players.length && games[gameIndex].canStart == true) {
games[gameIndex].canStart = false;
io.to(roomNum).emit('toggleAllowStart');
};
Game.updatePlayerList(room);
},
dealPhraseCards: (roomNum) => {
const gameIndex = utils.getGameIndex(roomNum);
const players = games[gameIndex].players;
players.forEach(player => {
if (!player.interviewer) {
const cardPack = games[gameIndex].phraseCards.slice(0, cardsPerPlayer);
games[gameIndex].phraseCards = games[gameIndex].phraseCards.slice(cardsPerPlayer);
io.to(player.socketId).emit('cardPack', cardPack);
};
});
},
dealJobCard: (roomNum) => {
const gameIndex = utils.getGameIndex(roomNum);
const card = games[gameIndex].jobCards[0];
games[gameIndex].jobCards = games[gameIndex].jobCards.slice(1);
console.log(card);
io.to(roomNum).emit('dealJobCard', card);
},
chooseNextInterviewee: (roomNum) => {
const game = games[utils.getGameIndex(roomNum)];
const availablePlayers = game.players.filter(player => !player.hasInterviewed && !player.interviewer);
if (availablePlayers.length > 0) {
const newIntervieweeRaw = availablePlayers[Math.floor(Math.random() * availablePlayers.length)];
return game.players.findIndex(player => player.socketId == newIntervieweeRaw.socketId);
} else {
io.to(roomNum).emit('employmentPhase', games[utils.getGameIndex(roomNum)].players)
return -1;
};
},
changeInterviewee: (roomNum) => {
const game = games[utils.getGameIndex(roomNum)];
let newIntervieweeIndex = -1;
newIntervieweeIndex = Game.chooseNextInterviewee(roomNum);
if (newIntervieweeIndex != -1) {
const newInterviewee = game.players[newIntervieweeIndex];
game.players.forEach(player => {
player.interviewee = false;
});
newInterviewee.interviewee = true;
newInterviewee.hasInterviewed = true;
io.to(roomNum).emit('setCurrentPlayer', newInterviewee);
io.to(roomNum).emit('interviewPhase');
};
},
nextInterviewer: (roomNum) => {
const game = games[utils.getGameIndex(roomNum)];
// Toggle interviewerStatus of the current interviewer (to false) on both client and server
io.to(game.players[game.interviewerIndex].socketId).emit('toggleInterviewer');
game.players[game.interviewerIndex].interviewer = false;
game.interviewerIndex += 1
if (game.interviewerIndex >= game.players.length) {
game.interviewerIndex = 0;
};
// Toggle interviewerStatus of the new interviewer (to true) on both client and server
io.to(game.players[game.interviewerIndex].socketId).emit('toggleInterviewer');
game.players[game.interviewerIndex].interviewer = true;
io.to(roomNum).emit('setCurrentInterviewer', game.players[game.interviewerIndex].name);
},
resetHasInterviewed: (game) => {
game.players.forEach(player => player.hasInterviewed = false);
},
resetPoints: game => {
game.players.forEach(player => player.points = 0);
},
checkForWinner: (game) => {
let winner;
game.players.forEach(player => {
if (player.points >= scoreToWin) {
winner = player.name;
console.log(`${winner} Wins!`);
};
});
return winner;
},
setInterviewerDisplay: (roomNum) => {
const game = games[utils.getGameIndex(roomNum)];
let interviewerName = '';
game.players.forEach(player => {
if (player.interviewer) {
interviewerName = player.name;
};
if (interviewerName != '') {
io.emit('setCurrentInterviewer', interviewerName);
};
});
},
nextRound: (room) => {
console.log(`Draw phase sent to room ${room}`);
io.to(room).emit('drawPhase');
Game.setInterviewerDisplay(room);
Game.resetHasInterviewed(games[utils.getGameIndex(room)]);
Game.changeInterviewee(room);
Game.dealPhraseCards(room);
Game.dealJobCard(room);
console.log(`Interview phase sent to room ${room}`);
io.to(room).emit('interviewPhase');
},
submissionPhaseSetup: room => {
const gameIndex = utils.getGameIndex(room);
console.log(`Submission phase sent to room ${room}`);
utils.resetPlayerReady(room);
const data = {
players: games[gameIndex].players
};
io.to(room).emit('submissionPhase', data);
},
resetGame: ({ room, newCards }) => {
const gameIndex = utils.getGameIndex(room);
const game = games[gameIndex];
Game.resetPoints(game);
if (newCards) {
game.jobCards = [];
game.phraseCards = [];
game.jobCardsOrig = [];
game.phraseCardsOrig = [];
Game.submissionPhaseSetup(room);
} else {
game.jobCards = game.jobCardsOrig;
game.phraseCards = game.phraseCardsOrig;
io.to(roomNum).emit("endSubmissionPhase");
}
}
};
return Game;
};
module.exports = Game;
|
!function(e){e.fn.richText=function(t){function a(e,t){"undefined"==typeof t&&(t=null),h(),"heading"===e&&r()?f("<"+t+">"+r()+"</"+t+">"):document.execCommand(e,!1,t)}function n(){var t=e("#"+te),a=t.html();b.useSingleQuotes===!0&&(a=u(a)),t.siblings(".richText-initial").val(a)}function i(){var t=e("#"+te),a=t.siblings(".richText-initial").val();t.html(a)}function o(t,a){if(9!==a.keyCode)return!1;var n;if(t.getSelection&&(n=t.getSelection(),n.rangeCount>0)){var i=null,r=null;if(a.shiftKey?(r="previous",i="TD"===n.focusNode.nodeName?null!=n.focusNode.previousSibling?n.focusNode.previousSibling:null!=n.focusNode.parentNode.previousSibling?n.focusNode.parentNode.previousSibling.childNodes[n.focusNode.parentNode.previousSibling.childNodes.length-1]:null:null!=n.focusNode.parentNode.previousSibling?n.focusNode.parentNode.previousSibling:null!=n.focusNode.parentNode.parentNode.previousSibling?n.focusNode.parentNode.parentNode.previousSibling.childNodes[n.focusNode.parentNode.parentNode.previousSibling.childNodes.length-1]:null):(r="next",i="TD"===n.focusNode.nodeName?null!=n.focusNode.nextSibling?n.focusNode.nextSibling:null!=n.focusNode.parentNode.nextSibling?n.focusNode.parentNode.nextSibling.childNodes[0]:null:null!=n.focusNode.parentNode.nextSibling?n.focusNode.parentNode.nextSibling:null!=n.focusNode.parentNode.parentNode.nextSibling?n.focusNode.parentNode.parentNode.nextSibling.childNodes[0]:null),null!=i)return n.collapse(i,Math.min(i.length,n.focusOffset+1)),null!=i.textContent&&n.selectAllChildren(i),a.preventDefault(),!0;if(null===i&&"next"===r&&"TD"===n.focusNode.nodeName){for(var l=e(n.focusNode).parents("table"),d=l.find("tr").first().children("td").length,s=e("<tr />"),c=e("<td />"),p=1;d>=p;p++)s.append(c.clone());l.append(s),o(window,{keyCode:9,shiftKey:!1,preventDefault:function(){}})}}return!1}function r(){var e;return window.getSelection?(e=window.getSelection(),e.toString()):document.selection.createRange?(e=document.selection.createRange(),e.text):!1}function l(){d(w.find("textarea").val()),N=y()}function d(e){ne.length-1>ie&&(ne.length=ie+1),ne[ne.length-1]!==e&&ne.push(e),ie=ne.length-1,s()}function s(){0>=ie?w.find(".richText-undo").addClass("is-disabled"):w.find(".richText-undo").removeClass("is-disabled"),ie>=ne.length-1||0===ne.length?w.find(".richText-redo").addClass("is-disabled"):w.find(".richText-redo").removeClass("is-disabled")}function c(){ie--;var e=ne[ie];w.find("textarea").val(e),w.find(".richText-editor").html(e),s()}function p(){ie++;var e=ne[ie];w.find("textarea").val(e),w.find(".richText-editor").html(e),s()}function h(){N&&C()}function f(e){var t,a;if(window.getSelection){if(t=window.getSelection(),t.getRangeAt&&t.rangeCount){a=t.getRangeAt(0),a.deleteContents();var n=document.createElement("div");n.innerHTML=e;for(var i,o,r=document.createDocumentFragment();i=n.firstChild;)o=r.appendChild(i);a.insertNode(r),o&&(a=a.cloneRange(),a.setStartAfter(o),a.collapse(!0),t.removeAllRanges(),t.addRange(a))}}else document.selection&&"Control"!==document.selection.type&&document.selection.createRange().pasteHTML(e)}function u(e){if(!e)return"";var t,a;return b.useSingleQuotes===!0?(t=/\s+(\w+\s*=\s*(["][^"]*["])|(['][^']*[']))+/g,a=e.replace(t,function(e,t,a){return a?e.replace(a,a.replace(/\"/g,"'")):e})):(t=/\s+(\w+\s*=\s*(['][^']*['])|(["][^"]*["]))+/g,a=e.replace(t,function(e,t,a){return a?e.replace(a,a.replace(/'/g,'"')):e})),a}function m(e){var t=[],a="";t["#FFFFFF"]="White",t["#000000"]="Black",t["#7F6000"]="Brown",t["#938953"]="Beige",t["#1F497D"]="Dark Blue",t.blue="Blue",t["#4F81BD"]="Light blue",t["#953734"]="Dark red",t.red="Red",t["#4F6128"]="Dark green",t.green="Green",t["#3F3151"]="Purple",t["#31859B"]="Dark Turquois",t["#4BACC6"]="Turquois",t["#E36C09"]="Dark orange",t["#F79646"]="Orange",t["#FFFF00"]="Yellow",b.colors&&b.colors.length>0&&(t=b.colors);for(var n in t)a+='<li class="inline"><a data-command="'+e+'" data-option="'+n+'" style="text-align:left;" title="'+t[n]+'"><span class="box-color" style="background-color:'+n+'"></span></a></li>';return a}function g(){w.find(".richText-editor").is(":visible")?(w.find(".richText-initial").show(),w.find(".richText-editor").hide(),e(".richText-toolbar").find(".richText-btn").each(function(){e(this).hasClass("fa-code")||e(this).parent("li").attr("data-disable","true")})):(w.find(".richText-initial").hide(),w.find(".richText-editor").show(),e(".richText-toolbar").find("li").removeAttr("data-disable"))}function v(e,t){var a=x(e),n=!1,i=!1;if(!a)return!1;t?"responsive"!==t?t=t.split("x"):(n=!0,t="640x360",t=t.split("x")):(t="640x360",t=t.split("x"));var o="<br><br>";n===!0&&(o+='<div style="position:relative;height:0;padding-bottom:56.25%">');var r="webkitallowfullscreen mozallowfullscreen allowfullscreen";return"YouTube"===a.platform?(o+='<iframe src="https://www.youtube.com/embed/'+a.id+'?ecver=2" width="'+t[0]+'" height="'+t[1]+'" frameborder="0"'+(n===!0?' style="position:absolute;width:100%;height:100%;left:0"':"")+" "+r+"></iframe>",i=!0):"Vimeo"===a.platform?(o+='<iframe src="https://player.vimeo.com/video/'+a.id+'" width="'+t[0]+'" height="'+t[1]+'" frameborder="0"'+(n===!0?' style="position:absolute;width:100%;height:100%;left:0"':"")+" "+r+"></iframe>",i=!0):"Facebook"===a.platform?(o+='<iframe src="https://www.facebook.com/plugins/video.php?href='+encodeURI(e)+"&show_text=0&width="+t[0]+'" width="'+t[0]+'" height="'+t[1]+'" style="'+(n===!0?'position:absolute;width:100%;height:100%;left:0;border:none;overflow:hidden"':"border:none;overflow:hidden")+'" scrolling="no" frameborder="0" allowTransparency="true" '+r+"></iframe>",i=!0):"Dailymotion"===a.platform&&(o+='<iframe frameborder="0" width="'+t[0]+'" height="'+t[1]+'" src="//www.dailymotion.com/embed/video/'+a.id+'"'+(n===!0?' style="position:absolute;width:100%;height:100%;left:0"':"")+" "+r+"></iframe>",i=!0),n===!0&&(o+="</div>"),o+="<br><br>",i?o:!1}function x(e){var t=/(?:http?s?:\/\/)?(?:www\.)?(?:vimeo\.com)\/?(.+)/,a=/^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/,n=/(?:http?s?:\/\/)?(?:www\.)?(?:facebook\.com)\/.*\/videos\/[0-9]+/,i=/(?:http?s?:\/\/)?(?:www\.)?(?:dailymotion\.com)\/video\/([a-zA-Z0-9]+)/,o=e.match(a),r=e.match(t),l=e.match(n),d=e.match(i);return o&&11===o[2].length?{platform:"YouTube",id:o[2]}:r&&r[1]?{platform:"Vimeo",id:r[1]}:l&&l[0]?{platform:"Facebook",id:l[0]}:d&&d[1]?{platform:"Dailymotion",id:d[1]}:!1}var b=e.extend({bold:!0,italic:!0,underline:!0,leftAlign:!0,centerAlign:!0,rightAlign:!0,ol:!0,ul:!0,heading:!0,fonts:!0,fontList:["Arial","Arial Black","Comic Sans MS","Courier New","Geneva","Georgia","Helvetica","Impact","Lucida Console","Tahoma","Times New Roman","Verdana"],fontColor:!0,imageUpload:!0,fileUpload:!0,videoEmbed:!0,urls:!0,table:!0,removeStyles:!0,code:!0,colors:[],fileHTML:"",imageHTML:"",useSingleQuotes:!1,height:0,heightPercentage:0,id:"","class":""},t),T=e(this);T.addClass("richText-initial");var w,y,C,N,R=e("<ul />"),S=e("<li />"),L=e("<a />",{"class":"richText-btn fa fa-bold","data-command":"bold"}),k=e("<a />",{"class":"richText-btn fa fa-italic","data-command":"italic"}),U=e("<a />",{"class":"richText-btn fa fa-underline","data-command":"underline"}),D=e("<a />",{"class":"richText-btn fa fa-align-left","data-command":"justifyLeft"}),A=e("<a />",{"class":"richText-btn fa fa-align-center","data-command":"justifyCenter"}),F=e("<a />",{"class":"richText-btn fa fa-align-right","data-command":"justifyRight"}),H=e("<a />",{"class":"richText-btn fa fa-list-ol","data-command":"insertOrderedList"}),E=e("<a />",{"class":"richText-btn fa fa-list","data-command":"insertUnorderedList"}),B=e("<a />",{"class":"richText-btn fa fa-header"}),I=e("<a />",{"class":"richText-btn fa fa-font"}),M=e("<a />",{"class":"richText-btn fa fa-paint-brush"}),W=e("<a />",{"class":"richText-btn fa fa-image"}),X=e("<a />",{"class":"richText-btn fa fa-video-camera"}),P=e("<a />",{"class":"richText-btn fa fa-file-text-o"}),Y=e("<a />",{"class":"richText-btn fa fa-link"}),Q=e("<a />",{"class":"richText-btn fa fa-table"}),z=e("<a />",{"class":"richText-btn fa fa-recycle","data-command":"removeFormat"}),_=e("<a />",{"class":"richText-btn fa fa-code","data-command":"toggleCode"}),V=e("<div />",{"class":"richText-dropdown-outer"}),G=e("<span />",{"class":"richText-dropdown-close",html:'<span class="fa fa-times"></span>'}),O=e("<ul />",{"class":"richText-dropdown"}),j=e("<div />",{"class":"richText-dropdown"}),q=e("<div />",{"class":"richText-form"}),K=e("<div />",{"class":"richText-form-item"}),Z=e("<label />"),$=e("<input />",{type:"text"}),J=(e("<input />",{type:"file"}),e("<select />")),ee=e("<button />",{text:"Einfügen","class":"btn"}),te="richText-"+Math.random().toString(36).substring(7),ae=null,ne=[],ie=0,oe=O.clone();oe.append(e("<li />",{html:'<a data-command="formatBlock" data-option="h1">Title #1</a>'})),oe.append(e("<li />",{html:'<a data-command="formatBlock" data-option="h2">Title #2</a>'})),oe.append(e("<li />",{html:'<a data-command="formatBlock" data-option="h3">Title #3</a>'})),oe.append(e("<li />",{html:'<a data-command="formatBlock" data-option="h4">Title #4</a>'})),B.append(V.clone().append(oe.prepend(G.clone())));for(var re=b.fontList,le=O.clone(),de=0;de<re.length;de++)le.append(e("<li />",{html:'<a style="font-family:'+re[de]+';" data-command="fontName" data-option="'+re[de]+'">'+re[de]+"</a>"}));I.append(V.clone().append(le.prepend(G.clone())));var se=O.clone();se.html(m("forecolor")),M.append(V.clone().append(se.prepend(G.clone())));var ce=j.clone(),pe=q.clone().attr("id","richText-URL").attr("data-editor",te);pe.append(K.clone().append(Z.clone().text("URL").attr("for","url")).append($.clone().attr("id","url"))),pe.append(K.clone().append(Z.clone().text("Text").attr("for","urlText")).append($.clone().attr("id","urlText"))),pe.append(K.clone().append(Z.clone().text("Open in").attr("for","openIn")).append(J.clone().attr("id","openIn").append(e("<option />",{value:"_self",text:"Same tab"})).append(e("<option />",{value:"_blank",text:"New tab"})))),pe.append(K.clone().append(ee.clone())),ce.append(pe),Y.append(V.clone().append(ce.prepend(G.clone())));var he=j.clone(),fe=q.clone().attr("id","richText-Video").attr("data-editor",te);fe.append(K.clone().append(Z.clone().text("URL").attr("for","videoURL")).append($.clone().attr("id","videoURL"))),fe.append(K.clone().append(Z.clone().text("Size").attr("for","size")).append(J.clone().attr("id","size").append(e("<option />",{value:"responsive",text:"Responsive"})).append(e("<option />",{value:"640x360",text:"640x360"})).append(e("<option />",{value:"560x315",text:"560x315"})).append(e("<option />",{value:"480x270",text:"480x270"})).append(e("<option />",{value:"320x180",text:"320x180"})))),fe.append(K.clone().append(ee.clone())),he.append(fe),X.append(V.clone().append(he.prepend(G.clone())));var ue=j.clone(),me=q.clone().attr("id","richText-Image").attr("data-editor",te);b.imageHTML&&(e(b.imageHTML).find("#imageURL").length>0||"imageURL"===e(b.imageHTML).attr("id"))?me.html(b.imageHTML):(me.append(K.clone().append(Z.clone().text("Image URL").attr("for","imageURL")).append($.clone().attr("id","imageURL"))),me.append(K.clone().append(Z.clone().text("Align").attr("for","align")).append(J.clone().attr("id","align").append(e("<option />",{value:"left",text:"Left"})).append(e("<option />",{value:"center",text:"Center"})).append(e("<option />",{value:"right",text:"Right"}))))),me.append(K.clone().append(ee.clone())),ue.append(me),W.append(V.clone().append(ue.prepend(G.clone())));var ge=j.clone(),ve=q.clone().attr("id","richText-File").attr("data-editor",te);b.fileHTML&&(e(b.fileHTML).find("#fileURL").length>0||"fileURL"===e(b.fileHTML).attr("id"))?ve.html(b.fileHTML):(ve.append(K.clone().append(Z.clone().text("File URL").attr("for","fileURL")).append($.clone().attr("id","fileURL"))),ve.append(K.clone().append(Z.clone().text("Link text").attr("for","fileText")).append($.clone().attr("id","fileText")))),ve.append(K.clone().append(ee.clone())),ge.append(ve),P.append(V.clone().append(ge.prepend(G.clone())));var xe=j.clone(),be=q.clone().attr("id","richText-Table").attr("data-editor",te);be.append(K.clone().append(Z.clone().text("Rows").attr("for","tableRows")).append($.clone().attr("id","tableRows").attr("type","number"))),be.append(K.clone().append(Z.clone().text("Columns").attr("for","tableColumns")).append($.clone().attr("id","tableColumns").attr("type","number"))),be.append(K.clone().append(ee.clone())),xe.append(be),Q.append(V.clone().append(xe.prepend(G.clone())));var Te=function(){var t,a,n="";"TEXTAREA"===T.prop("tagName")||(T.val()?(t=T.val(),a=T.prop("attributes"),e.each(a,function(){this.name&&(n+=" "+this.name+'="'+this.value+'"')}),T.replaceWith(e("<textarea"+n+' data-richtext="init">'+t+"</textarea>")),T=e('[data-richtext="init"]'),T.removeAttr("data-richtext")):T.html()?(t=T.html(),a=T.prop("attributes"),e.each(a,function(){this.name&&(n+=" "+this.name+'="'+this.value+'"')}),T.replaceWith(e("<textarea"+n+' data-richtext="init">'+t+"</textarea>")),T=e('[data-richtext="init"]'),T.removeAttr("data-richtext")):(a=T.prop("attributes"),e.each(a,function(){this.name&&(n+=" "+this.name+'="'+this.value+'"')}),T.replaceWith(e("<textarea"+n+' data-richtext="init"></textarea>')),T=e('[data-richtext="init"]'),T.removeAttr("data-richtext"))),w=e("<div />",{"class":"richText"});var i=e("<div />",{"class":"richText-toolbar"}),o=e("<div />",{"class":"richText-editor",id:te,contenteditable:!0});if(i.append(R),b.bold===!0&&R.append(S.clone().append(L)),b.italic===!0&&R.append(S.clone().append(k)),b.underline===!0&&R.append(S.clone().append(U)),b.leftAlign===!0&&R.append(S.clone().append(D)),b.centerAlign===!0&&R.append(S.clone().append(A)),b.rightAlign===!0&&R.append(S.clone().append(F)),b.ol===!0&&R.append(S.clone().append(H)),b.ul===!0&&R.append(S.clone().append(E)),b.fonts===!0&&b.fontList.length>0&&R.append(S.clone().append(I)),b.heading===!0&&R.append(S.clone().append(B)),b.fontColor===!0&&R.append(S.clone().append(M)),b.imageUpload===!0&&R.append(S.clone().append(W)),b.fileUpload===!0&&R.append(S.clone().append(P)),b.videoEmbed===!0&&R.append(S.clone().append(X)),b.urls===!0&&R.append(S.clone().append(Y)),b.table===!0&&R.append(S.clone().append(Q)),b.removeStyles===!0&&R.append(S.clone().append(z)),b.code===!0&&R.append(S.clone().append(_)),o.html(T.val()),w.append(i),w.append(o),w.append(T.clone().hide()),T.replaceWith(w),w.append(e("<div />",{"class":"richText-toolbar"}).append(e("<a />",{"class":"richText-undo is-disabled",html:'<span class="fa fa-undo"></span>'})).append(e("<a />",{"class":"richText-redo is-disabled",html:'<span class="fa fa-repeat"></span>'})).append(e("<a />",{"class":"richText-help",html:'<span class="fa fa-question-circle"></span>'}))),b.height&&b.height>0)w.children(".richText-editor, .richText-initial").css({"min-height":b.height+"px",height:b.height+"px"});else if(b.heightPercentage&&b.heightPercentage>0){var r=w.parent().innerHeight(),l=b.heightPercentage/100*r;l-=2*i.outerHeight(),l-=parseInt(w.css("margin-top")),l-=parseInt(w.css("margin-bottom")),l-=parseInt(w.find(".richText-editor").css("padding-top")),l-=parseInt(w.find(".richText-editor").css("padding-bottom")),w.children(".richText-editor, .richText-initial").css({"min-height":l+"px",height:l+"px"})}b["class"]&&w.addClass(b["class"]),b.id&&w.attr("id",b.id),ne.push(w.find("textarea").val())};return Te(),w.find(".richText-help").on("click",function(){var t=e(this).parents(".richText");if(t){var a=e("<div />",{"class":"richText-help-popup",style:"position:absolute;top:0;right:0;bottom:0;left:0;background-color: rgba(0,0,0,0.3);"}),n=e("<div />",{style:"position:relative;margin:60px auto;padding:20px;background-color:#FAFAFA;width:70%;font-family:Calibri,Verdana,Helvetica,sans-serif;font-size:small;"}),i=e("<div />",{html:'<span id="closeHelp" style="display:block;position:absolute;top:0;right:0;padding:10px;cursor:pointer;" class="fa fa-times" title="Close"></span>'});i.append("<h3>RichText</h3>"),i.append('<hr>Powered by <a href="https://github.com/webfashionist/RichText" target="_blank">webfashionist/RichText</a> (Github) <br>License: <a href="https://github.com/webfashionist/RichText/blob/master/LICENSE" target="_blank">AGPL-3.0</a>'),a.append(n.append(i)),t.append(a),a.on("click","#closeHelp",function(){e(this).parents(".richText-help-popup").remove()})}}),e(document).on("click",".richText-undo, .richText-redo",function(t){var a=e(this);a.hasClass("richText-undo")&&!a.hasClass("is-disabled")?c():a.hasClass("richText-redo")&&!a.hasClass("is-disabled")&&p()}),e(document).on("input change blur keydown",".richText-editor",function(e){return 9!==e.keyCode&&"9"!==e.keyCode||"keydown"!==e.type?(n(),void l()):(e.preventDefault(),o(window,e),!1)}),e(document).on("input change blur",".richText-initial",function(){b.useSingleQuotes===!0&&e(this).val(u(e(this).val())),i(),l()}),e(document).on("dblclick mouseup",".richText-editor",function(){l()}),e(document).on("click","#richText-Video button.btn",function(t){t.preventDefault();var a=e(this),i=a.parent(".richText-form-item").parent(".richText-form");if(i.attr("data-editor")===te){var o=i.find("input#videoURL").val(),r=i.find("select#size").val();if(o){var l="";l=v(o,r),l?(b.useSingleQuotes===!0,C(),f(l),n(),i.find("input#videoURL").val(""),e(".richText-toolbar li.is-selected").removeClass("is-selected")):(i.prepend(e("<div />",{style:"color:red;display:none;","class":"form-item is-error",text:"Video URL not supported"})),i.children(".form-item.is-error").slideDown(),setTimeout(function(){i.children(".form-item.is-error").slideUp(function(){e(this).remove()})},5e3))}else i.prepend(e("<div />",{style:"color:red;display:none;","class":"form-item is-error",text:"Please enter an URL"})),i.children(".form-item.is-error").slideDown(),setTimeout(function(){i.children(".form-item.is-error").slideUp(function(){e(this).remove()})},5e3)}}),e(document).on("mousedown",function(t){var a=e(t.target);if("IMG"===a.prop("tagName")&&a.parents("#"+te)){startX=t.pageX,startY=t.pageY,startW=a.innerWidth(),startH=a.innerHeight();var n=(a.offset().left,a.offset().left+a.innerWidth()),i=a.offset().top+a.innerHeight(),o=(a.offset().top,!1);a.css({cursor:"default"}),startY<=i&&startY>=i-20&&startX>=n-20&&startX<=n&&(ae=a,ae.css({cursor:"nwse-resize"}),o=!0),o!==!0&&!ae||ae.data("width")?o===!0||ae?t.preventDefault():ae=null:(ae.data("width",a.parents("#"+te).innerWidth()),ae.data("height",3*a.parents("#"+te).innerHeight()),t.preventDefault())}}),e(document).mouseup(function(){ae&&ae.css({cursor:"default"}),ae=null}).mousemove(function(e){if(null!==ae){var t=ae.data("width"),a=ae.width(),i=ae.data("height"),o=ae.height();startW+e.pageX-startX<=t&&startH+e.pageY-startY<=i?(ae.innerWidth(startW+e.pageX-startX),n()):startW+e.pageX-startX<=a&&startH+e.pageY-startY<=o&&(ae.innerWidth(startW+e.pageX-startX),n())}}),e(document).on("click","#richText-URL button.btn",function(t){t.preventDefault();var a=e(this),n=a.parent(".richText-form-item").parent(".richText-form");if(n.attr("data-editor")===te){var i=n.find("input#url").val(),o=n.find("input#urlText").val(),r=n.find("#openIn").val();if(r||(r="_self"),o||(o=i),i){var l="";l=b.useSingleQuotes===!0?"<a href='"+i+"' target='"+r+"'>"+o+"</a>":'<a href="'+i+'" target="'+r+'">'+o+"</a>",C(),f(l),n.find("input#url").val(""),n.find("input#urlText").val(""),e(".richText-toolbar li.is-selected").removeClass("is-selected")}else n.prepend(e("<div />",{style:"color:red;display:none;","class":"form-item is-error",text:"Please enter an URL"})),n.children(".form-item.is-error").slideDown(),setTimeout(function(){n.children(".form-item.is-error").slideUp(function(){e(this).remove()})},5e3)}}),e(document).on("click","#richText-Image button.btn",function(t){t.preventDefault();var a=e(this),n=a.parent(".richText-form-item").parent(".richText-form");if(n.attr("data-editor")===te){var i=n.find("#imageURL").val(),o=n.find("select#align").val();if(o||(o="center"),i){var r="";r=b.useSingleQuotes===!0?"center"===o?"<div style='text-align:center;'><img src='"+i+"'></div>":"<img src='"+i+"' align='"+o+"'>":"center"===o?'<div style="text-align:center;"><img src="'+i+'"></div>':'<img src="'+i+'" align="'+o+'">',C(),f(r),n.find("input#imageURL").val(""),e(".richText-toolbar li.is-selected").removeClass("is-selected")}else n.prepend(e("<div />",{style:"color:red;display:none;","class":"form-item is-error",text:"Please select an image."})),n.children(".form-item.is-error").slideDown(),setTimeout(function(){n.children(".form-item.is-error").slideUp(function(){e(this).remove()})},5e3)}}),e(document).on("click","#richText-File button.btn",function(t){t.preventDefault();var a=e(this),n=a.parent(".richText-form-item").parent(".richText-form");if(n.attr("data-editor")===te){var i=n.find("#fileURL").val(),o=n.find("#fileText").val();if(o||(o=i),i){var r="";r=b.useSingleQuotes===!0?"<a href='"+i+"' target='_blank'>"+o+"</a>":'<a href="'+i+'" target="_blank">'+o+"</a>",C(),f(r),n.find("input#fileURL").val(""),n.find("input#fileText").val(""),e(".richText-toolbar li.is-selected").removeClass("is-selected")}else n.prepend(e("<div />",{style:"color:red;display:none;","class":"form-item is-error",text:"Please select a file."})),n.children(".form-item.is-error").slideDown(),setTimeout(function(){n.children(".form-item.is-error").slideUp(function(){e(this).remove()})},5e3)}}),e(document).on("click","#richText-Table button.btn",function(t){t.preventDefault();var a=e(this),n=a.parent(".richText-form-item").parent(".richText-form");if(n.attr("data-editor")===te){var i=n.find("input#tableRows").val(),o=n.find("input#tableColumns").val();(!i||0>=i)&&(i=2),(!o||0>=o)&&(o=2);var r="";r=b.useSingleQuotes===!0?"<table class='table-1'><tbody>":'<table class="table-1"><tbody>';for(var l=1;i>=l;l++){r+="<tr>";for(var d=1;o>=d;d++)r+="<td> </td>";r+="</tr>"}r+="</tbod></table>",C(),f(r),n.find("input#tableColumns").val(""),n.find("input#tableRows").val(""),e(".richText-toolbar li.is-selected").removeClass("is-selected")}}),e(document).on("click",function(t){var a=e(t.target);if(0===a.parents(".richText-toolbar").length);else if(a.hasClass("richText-dropdown-outer"))a.parent("a").parent("li").removeClass("is-selected");else if(a.find(".richText").length>0)e(".richText-toolbar li").removeClass("is-selected");else if(a.parent().hasClass("richText-dropdown-close"))e(".richText-toolbar li").removeClass("is-selected");else if(a.hasClass("richText-btn")&&e(t.target).children(".richText-dropdown-outer").length>0)if(a.parent("li").addClass("is-selected"),a.hasClass("fa-link")){C();var n=r();a.find("input#urlText").val(""),a.find("input#url").val(""),n&&a.find("input#urlText").val(n)}else a.hasClass("fa-image")}),e(document).on("click",".richText-toolbar a[data-command]",function(t){var n=e(this),i=n.closest(".richText-toolbar");if(i.siblings("#"+te).length>0&&(!n.parent("li").attr("data-disable")||"false"===n.parent("li").attr("data-disable"))){t.preventDefault();var o=e(this).data("command");if("toggleCode"===o)g();else{var r=null;e(this).data("option")&&(r=e(this).data("option"),r.match(/^h[1-6]$/)&&(o="heading")),a(o,r),"removeFormat"===o&&a("formatBlock","div")}}n.parents("li.is-selected").removeClass("is-selected")}),window.getSelection&&document.createRange?(y=function(){var e=document.getElementById(te),t=window.getSelection&&window.getSelection();if(t&&t.rangeCount>0){var a=window.getSelection().getRangeAt(0),n=a.cloneRange();n.selectNodeContents(e),n.setEnd(a.startContainer,a.startOffset);var i=n.toString().length;return{start:i,end:i+a.toString().length}}return N?N:{start:0,end:0}},C=function(){var e=document.getElementById(te),t=N,a=0,n=document.createRange();n.setStart(e,0),n.collapse(!0);for(var i,o=[e],r=!1,l=!1;!l&&(i=o.pop());)if(3===i.nodeType){var d=a+i.length;!r&&t.start>=a&&t.start<=d&&(n.setStart(i,t.start-a),r=!0),r&&t.end>=a&&t.end<=d&&(n.setEnd(i,t.end-a),l=!0),a=d}else for(var s=i.childNodes.length;s--;)o.push(i.childNodes[s]);var c=window.getSelection();c.removeAllRanges(),c.addRange(n)}):document.selection&&document.body.createTextRange&&(y=function(){var e=document.getElementById(te),t=document.selection.createRange(),a=document.body.createTextRange();a.moveToElementText(e),a.setEndPoint("EndToStart",t);var n=a.text.length;return{start:n,end:n+t.text.length}},C=function(){var e=document.getElementById(te),t=N,a=document.body.createTextRange();a.moveToElementText(e),a.collapse(!0),a.moveEnd("character",t.end),a.moveStart("character",t.start),a.select()}),e(this)}}(jQuery);
|
# -*- coding: utf-8 -*-
"""
Created on Friday 2 Feb 2020
@author: Chris.Cui
Email: Chris.Cui@aurecongroup.com
"""
#%% load all the pkgs
from __future__ import print_function
import keras
from keras.datasets import mnist
from keras.models import Sequential, load_model
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras import backend as K
from keras.callbacks import ModelCheckpoint, EarlyStopping
import os
import numpy as np
from matplotlib import pyplot as plt
from datetime import datetime
import pickle
#%% Load the data
# the data, split between train and test sets
(x_train, y_train), (x_test, y_test) = mnist.load_data()
nb_train_sample = len(y_train)
nb_validation_sample = len(y_test)
#%% Preporcessing the data
# input image dimensions
img_rows, img_cols = 28, 28
if K.image_data_format() == 'channels_first':
x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)
x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)
input_shape = (1, img_rows, img_cols)
else:
x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)
x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)
input_shape = (img_rows, img_cols, 1)
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255
print('x_train shape:', x_train.shape)
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')
# convert class vectors to binary class matrices
num_classes = 10
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)
#%% design the structure of the model
model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3),
activation='relu',
input_shape=input_shape))
model.add(Conv2D(16, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(256, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(num_classes, activation='softmax'))
#%% model training merics
model.compile(loss=keras.losses.categorical_crossentropy,
optimizer=keras.optimizers.Adadelta(),
metrics=['accuracy'])
print(model.summary())
#%% Train the model
# checkpoint
# now = datetime.now()
# best_model_filepath="mnist.weights.best."+str( now.strftime("%Y.%m.%d_%H.%M.%S"))+".h5"
best_model_filepath = "./models/mnist.weights.best.h5"
checkpoint = ModelCheckpoint(best_model_filepath,
monitor='val_acc',
verbose=1, save_best_only=True, mode='Max')
stoppoint = EarlyStopping(monitor='val_acc', min_delta=0.001,
verbose=1, mode='Max', patience=5)
callbacks_list = [checkpoint, stoppoint]
# Fit the model
batch_size = 1024
epochs = 30
print('*'*80)
print('Start the training process at:', datetime.now())
print('*'*80)
history = model.fit(x_train, y_train,
batch_size=batch_size,
epochs=epochs,
verbose=1,
validation_data=(x_test, y_test),
callbacks=callbacks_list)
print('*'*80)
print('End the training process at:', datetime.now())
print('*'*80)
# save the training records
pickle_out = open("./models/history.pickle","wb")
pickle.dump(history, pickle_out)
# *** output on my desktop
# ...
# Epoch 00020: val_acc did not improve from 0.99210
# Epoch 00020: early stopping
# ***
# End the training process at: 2020-02-04 10:33:54.029526
# ***
#%%
score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
#%% save the training resutls
# Plot training & validation accuracy values
plt.figure(figsize=(8, 6))
plt.plot(history.history['acc'])
plt.plot(history.history['val_acc'])
plt.title('Model accuracy')
plt.ylabel('Accuracy')
plt.xlabel('Epoch')
plt.legend(['Train', 'Test'], loc='upper left')
# plt.show()
plt.savefig('./images/training_validation_accuracy_values.png', dpi= 300 )
# Plot training & validation loss values
plt.figure(figsize=(8, 6))
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('Model loss')
plt.ylabel('Loss')
plt.xlabel('Epoch')
plt.legend(['Train', 'Test'], loc='upper left')
# plt.show()
plt.savefig('./images/training_validation_loss_values.png', dpi= 300 )
#%% save and reload the model with a timestamp / in case overight the original one
# now=datetime.now()
# save_model_dir = './models/'
# final_model_name = str(now.strftime("%Y.%m.%d_%H.%M.%S")) +'.MnistModel.h5'
# save_final_model_path = os.path.join(save_model_dir, final_model_name)
# model.save(save_final_model_path)
# Final_model = load_model(save_final_model_path) # maybe overfitting.
# Final_model.summary()
#%% add more ...
|
function cargarAutores(){
let iframe= document.getElementById("frameAct");
iframe.setAttribute("src","fichasHTML/autor.html");
}
function cargarEditoriales(){
let iframe= document.getElementById("frameAct");
iframe.setAttribute("src","fichasHTML/editorial.html");
}
function cargarLibros(){
let iframe= document.getElementById("frameAct");
iframe.setAttribute("src","fichasHTML/libro.html");
}
function cargarIlustradores(){
let iframe= document.getElementById("frameAct");
iframe.setAttribute("src","fichasHTML/ilustrador.html");
}
|
###############################################################################
# WaterTAP Copyright (c) 2021, The Regents of the University of California,
# through Lawrence Berkeley National Laboratory, Oak Ridge National
# Laboratory, National Renewable Energy Laboratory, and National Energy
# Technology Laboratory (subject to receipt of any required approvals from
# the U.S. Dept. of Energy). All rights reserved.
#
# Please see the files COPYRIGHT.md and LICENSE.md for full copyright and license
# information, respectively. These files are also available online at the URL
# "https://github.com/watertap-org/watertap/"
#
###############################################################################
"""
Tests for zero-order electrodialysis reversal model
"""
import pytest
from io import StringIO
from pyomo.environ import (
Block,
check_optimal_termination,
ConcreteModel,
Constraint,
value,
Var,
)
from pyomo.util.check_units import assert_units_consistent
from idaes.core import FlowsheetBlock
from idaes.core.util import get_solver
from idaes.core.util.model_statistics import degrees_of_freedom
from idaes.core.util.testing import initialization_tester
from idaes.generic_models.costing import UnitModelCostingBlock
from watertap.unit_models.zero_order import ElectrodialysisReversalZO
from watertap.core.wt_database import Database
from watertap.core.zero_order_properties import WaterParameterBlock
from watertap.core.zero_order_costing import ZeroOrderCosting
solver = get_solver()
class TestElectrodialysisReversalZO_w_default_removal:
@pytest.fixture(scope="class")
def model(self):
m = ConcreteModel()
m.db = Database()
m.fs = FlowsheetBlock(default={"dynamic": False})
m.fs.params = WaterParameterBlock(default={"solute_list": ["tds", "foo"]})
m.fs.unit = ElectrodialysisReversalZO(
default={"property_package": m.fs.params, "database": m.db}
)
m.fs.unit.inlet.flow_mass_comp[0, "H2O"].fix(10000)
m.fs.unit.inlet.flow_mass_comp[0, "tds"].fix(250)
m.fs.unit.inlet.flow_mass_comp[0, "foo"].fix(1)
return m
@pytest.mark.unit
def test_build(self, model):
assert model.fs.unit.config.database is model.db
assert isinstance(model.fs.unit.electricity_constraint, Constraint)
assert isinstance(model.fs.unit.electricity, Var)
assert isinstance(model.fs.unit.elec_coeff_1, Var)
assert isinstance(model.fs.unit.elec_coeff_2, Var)
@pytest.mark.component
def test_load_parameters(self, model):
data = model.db.get_unit_operation_parameters("electrodialysis_reversal")
model.fs.unit.load_parameters_from_database(use_default_removal=True)
assert model.fs.unit.recovery_frac_mass_H2O[0].fixed
assert (
model.fs.unit.recovery_frac_mass_H2O[0].value
== data["recovery_frac_mass_H2O"]["value"]
)
for (t, j), v in model.fs.unit.removal_frac_mass_solute.items():
assert v.fixed
if j == "foo":
assert v.value == data["default_removal_frac_mass_solute"]["value"]
else:
assert v.value == data["removal_frac_mass_solute"][j]["value"]
assert model.fs.unit.elec_coeff_1.fixed
assert model.fs.unit.elec_coeff_1.value == data["elec_coeff_1"]["value"]
assert model.fs.unit.elec_coeff_2.fixed
assert model.fs.unit.elec_coeff_2.value == data["elec_coeff_2"]["value"]
@pytest.mark.component
def test_degrees_of_freedom(self, model):
assert degrees_of_freedom(model.fs.unit) == 0
@pytest.mark.component
def test_unit_consistency(self, model):
assert_units_consistent(model.fs.unit)
@pytest.mark.component
def test_initialize(self, model):
initialization_tester(model)
@pytest.mark.solver
@pytest.mark.skipif(solver is None, reason="Solver not available")
@pytest.mark.component
def test_solve(self, model):
results = solver.solve(model)
# Check for optimal solution
assert check_optimal_termination(results)
@pytest.mark.solver
@pytest.mark.skipif(solver is None, reason="Solver not available")
@pytest.mark.component
def test_solution(self, model):
assert pytest.approx(9.2628, rel=1e-5) == value(
model.fs.unit.properties_treated[0].flow_vol
)
assert pytest.approx(5.1632, rel=1e-5) == value(
model.fs.unit.properties_treated[0].conc_mass_comp["tds"]
)
assert pytest.approx(0.1079584, rel=1e-5) == value(
model.fs.unit.properties_treated[0].conc_mass_comp["foo"]
)
assert pytest.approx(204.5935, rel=1e-5) == value(
model.fs.unit.properties_byproduct[0].conc_mass_comp["tds"]
)
assert pytest.approx(1.01197e-08, rel=1e-5) == value(
model.fs.unit.properties_byproduct[0].conc_mass_comp["foo"]
)
assert pytest.approx(472761.372, rel=1e-5) == value(
model.fs.unit.electricity[0]
)
assert pytest.approx(12.8107, rel=1e-5) == value(
model.fs.unit.electricity_intensity[0]
)
@pytest.mark.solver
@pytest.mark.skipif(solver is None, reason="Solver not available")
@pytest.mark.component
def test_conservation(self, model):
for j in model.fs.params.component_list:
assert 1e-6 >= abs(
value(
model.fs.unit.inlet.flow_mass_comp[0, j]
- model.fs.unit.treated.flow_mass_comp[0, j]
- model.fs.unit.byproduct.flow_mass_comp[0, j]
)
)
@pytest.mark.component
def test_report(self, model):
stream = StringIO()
model.fs.unit.report(ostream=stream)
output = """
====================================================================================
Unit : fs.unit Time: 0.0
------------------------------------------------------------------------------------
Unit Performance
Variables:
Key : Value : Fixed : Bounds
Electricity intensity per Inlet Flowrate (kWh/m3) : 12.811 : False : (None, None)
Power Consumption (kW) : 4.7276e+05 : False : (0, None)
Solute Removal [foo] : 0.0000 : True : (0, None)
Solute Removal [tds] : 0.80870 : True : (0, None)
Water Recovery : 0.92140 : True : (1e-08, 1.0000001)
------------------------------------------------------------------------------------
Stream Table
Inlet Treated Byproduct
Volumetric Flowrate 10.251 9.2628 0.98817
Mass Concentration H2O 975.51 994.73 795.41
Mass Concentration tds 24.388 5.1632 204.59
Mass Concentration foo 0.097551 0.10796 1.0120e-08
====================================================================================
"""
assert output in stream.getvalue()
def test_costing():
m = ConcreteModel()
m.db = Database()
m.fs = FlowsheetBlock(default={"dynamic": False})
m.fs.params = WaterParameterBlock(default={"solute_list": ["tds", "toc", "tss"]})
m.fs.costing = ZeroOrderCosting()
m.fs.unit1 = ElectrodialysisReversalZO(
default={"property_package": m.fs.params, "database": m.db}
)
m.fs.unit1.inlet.flow_mass_comp[0, "H2O"].fix(10000)
m.fs.unit1.inlet.flow_mass_comp[0, "tds"].fix(1)
m.fs.unit1.inlet.flow_mass_comp[0, "toc"].fix(2)
m.fs.unit1.inlet.flow_mass_comp[0, "tss"].fix(3)
m.fs.unit1.load_parameters_from_database(use_default_removal=True)
assert degrees_of_freedom(m.fs.unit1) == 0
m.fs.unit1.costing = UnitModelCostingBlock(
default={"flowsheet_costing_block": m.fs.costing}
)
assert isinstance(m.fs.costing.electrodialysis_reversal, Block)
assert isinstance(m.fs.costing.electrodialysis_reversal.capital_a_parameter, Var)
assert isinstance(m.fs.costing.electrodialysis_reversal.capital_b_parameter, Var)
assert isinstance(m.fs.costing.electrodialysis_reversal.reference_state, Var)
assert isinstance(m.fs.unit1.costing.capital_cost, Var)
assert isinstance(m.fs.unit1.costing.capital_cost_constraint, Constraint)
assert_units_consistent(m.fs)
assert degrees_of_freedom(m.fs.unit1) == 0
assert m.fs.unit1.electricity[0] in m.fs.costing._registered_flows["electricity"]
db = Database()
params = db._get_technology("electrodialysis_reversal")
@pytest.mark.unit
def test_no_tds_in_solute_list_error():
m = ConcreteModel()
m.fs = FlowsheetBlock(default={"dynamic": False})
m.fs.params = WaterParameterBlock(default={"solute_list": ["foo"]})
with pytest.raises(
KeyError,
match="TDS must be included in the solute list for determining"
" electricity intensity and power consumption of the electrodialysis "
"reversal unit.",
):
m.fs.unit = ElectrodialysisReversalZO(
default={"property_package": m.fs.params, "database": db}
)
|
import React from "react";
import styled from "styled-components";
import LinkLabels from "../files/LinkLabels";
const NavList = styled.nav`
background: #282828;
height: 51px;
`
const NavItems = styled.div`
display: flex;
justify-content: space-around;
align-items: center;
// neets to be fixed for certain screen sizes
max-width: 200px;
height: 100%;
margin: 0 auto;
`
const NavAnchor = styled.a`
color: white;
text-decoration: none;
font-weight: bold;
font-family: arial;
// to match the original portfolio html template
font-size: 0.95rem;
// top and bottom, left and right
padding: 10px 20px;
&:hover {
cursor: pointer;
border-radius: 8px;
background-color: #383838;
transition: background-color .2s ease-in-out;
}
`
class Header extends React.Component {
constructor() {
super()
this.state = {}
}
render() {
return (
// returning a styled nav
<NavList>
<NavItems>
{LinkLabels.map((LinkLabel, i) => (
<NavAnchor key={i} href="#">{LinkLabel}</NavAnchor>
))}
</NavItems>
</NavList>
)
}
}
export default Header;
|
import React, { Component, PropTypes } from 'react';
import ReactDOM from 'react-dom';
export class AsyncImage extends Component {
componentDidMount() {
let imgLoader = ReactDOM.findDOMNode(this.refs.imgLoader);
let imgDest = ReactDOM.findDOMNode(this.refs.imgDest);
imgLoader.onload = null;
imgLoader.onerror = null;
imgDest.style.backgroundImage = "";
let imgSrc = imgLoader.getAttribute('src');
imgLoader.onload = () => { this.onImageLoad(); };
imgLoader.onerror = () => { this.onImageError(); };
imgLoader.src = imgSrc;
}
shouldComponentUpdate() {
return false;
}
componentWillUpdate() {
// Here we can catch props that are changing when component doesn't actually unmount
let imgDest = ReactDOM.findDOMNode(this.refs.imgDest);
imgDest.style.backgroundImage = "";
}
componentWillUnmount() {
this.destroyLoader();
}
onImageLoad() {
let imgLoader = ReactDOM.findDOMNode(this.refs.imgLoader);
let imgSrc = imgLoader.getAttribute('src');
let imgDest = ReactDOM.findDOMNode(this.refs.imgDest);
imgDest.style.backgroundImage = "url(" + imgSrc + ")";
imgDest.style.opacity = "1";
this.props.onImageLoad(this.props.src, this.props.id);
}
onImageError() {
let imgDest = ReactDOM.findDOMNode(this.refs.imgDest);
imgDest.classList.add(this.props.errorClassName);
imgDest.style.opacity = "1";
}
destroyLoader() {
let imgLoader = ReactDOM.findDOMNode(this.refs.imgLoader);
let imgDest = ReactDOM.findDOMNode(this.refs.imgDest);
imgLoader.onload = null;
imgLoader.onerror = null;
imgLoader.src = "";
imgDest.style.backgroundImage = "";
}
render() {
return (
<div className="async-image-container">
<img id={this.props.id} style={{"display":"none"}} src={this.props.src} ref="imgLoader" />
<span style={{"transition":"opacity 0.3s"}} className={this.props.className} ref="imgDest" />
</div>
);
}
}
AsyncImage.propTypes = {
src: PropTypes.string.isRequired,
id: PropTypes.string.isRequired,
className: PropTypes.string.isRequired,
errorClassName: PropTypes.string.isRequired,
onImageLoad: PropTypes.func.isRequired
};
export default AsyncImage;
|
import test from 'ava'
import isolate from 'helper/isolate'
const [logic, { block, declares, flow, variableSpace }] = isolate(
test,
'render/logic',
{
block: 'render/block',
declares: 'render/declares',
flow: 'render/flow',
variableSpace: 'render/variableSpace',
}
)
test.serial('empty', (t) => {
block.returns('{}')
const result = logic({})
t.is(result, 'export default function main() {}')
t.true(declares.calledOnce)
t.true(variableSpace.calledOnce)
t.true(flow.calledOnce)
t.true(block.calledOnce)
t.deepEqual(block.firstCall.args[0], [
`// Automatically added sleep\nsleep(1);`,
])
})
test.serial('nonempty', (t) => {
flow.returns(`// Flow`)
block.returns(
'' +
`{
// Flow
}`
)
const result = logic({})
t.is(
result,
'' +
`export default function main() {
// Flow
}`
)
t.true(declares.calledOnce)
t.true(variableSpace.calledOnce)
t.true(flow.calledOnce)
t.true(block.calledOnce)
t.deepEqual(block.firstCall.args[0], [
`// Flow`,
`// Automatically added sleep\nsleep(1);`,
])
})
|
# Copyright (c) 2018-present, Royal Bank of Canada.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import torch
import torch.nn as nn
import torch.nn.functional as F
def torch_allclose(x, y, rtol=1.e-5, atol=1.e-8):
"""
Wrap on numpy's allclose. Input x and y are both tensors of equal shape
Original numpy documentation:
https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.allclose.html
Notes:
If the following equation is element-wise True, then allclose returns
True.
absolute(`a` - `b`) <= (`atol` + `rtol` * absolute(`b`))
:param x: (torch tensor)
:param y: (torch tensor)
:param rtol: (float) the relative tolerance parameter
:param atol: (float) the absolute tolerance parameter
:return: (bool) if x and y are all close
"""
import numpy as np
return np.allclose(x.detach().cpu().numpy(), y.detach().cpu().numpy(),
rtol=rtol, atol=atol)
def replicate_input(x):
return x.detach().clone()
def replicate_input_withgrad(x):
return x.detach().clone().requires_grad_()
def calc_l2distsq(x, y):
d = (x - y)**2
return d.view(d.shape[0], -1).sum(dim=1)
def tanh_rescale(x, x_min=-1., x_max=1.):
return (torch.tanh(x)) * 0.5 * (x_max - x_min) + (x_max + x_min) * 0.5
def torch_arctanh(x, eps=1e-6):
return (torch.log((1 + x) / (1 - x))) * 0.5
def clamp(input, min=None, max=None):
if min is not None and max is not None:
return torch.clamp(input, min=min, max=max)
elif min is None and max is None:
return input
elif min is None and max is not None:
return torch.clamp(input, max=max)
elif min is not None and max is None:
return torch.clamp(input, min=min)
else:
raise ValueError("This is impossible")
def to_one_hot(y, num_classes=10):
"""
Take a batch of label y with n dims and convert it to
1-hot representation with n+1 dims.
Link: https://discuss.pytorch.org/t/convert-int-into-one-hot-format/507/24
"""
y = replicate_input(y).view(-1, 1)
y_one_hot = y.new_zeros((y.size()[0], num_classes)).scatter_(1, y, 1)
return y_one_hot
class CarliniWagnerLoss(nn.Module):
"""
Carlini-Wagner Loss: objective function #6.
Paper: https://arxiv.org/pdf/1608.04644.pdf
"""
def __init__(self):
super(CarliniWagnerLoss, self).__init__()
def forward(self, input, target):
"""
:param input: pre-softmax/logits.
:param target: true labels.
:return: CW loss value.
"""
num_classes = input.size(1)
label_mask = to_one_hot(target, num_classes=num_classes).float()
correct_logit = torch.sum(label_mask * input, dim=1)
wrong_logit = torch.max((1. - label_mask) * input, dim=1)[0]
loss = -F.relu(correct_logit - wrong_logit + 50.).sum()
return loss
def _batch_multiply_tensor_by_vector(vector, batch_tensor):
"""Equivalent to the following
for ii in range(len(vector)):
batch_tensor.data[ii] *= vector[ii]
return batch_tensor
"""
return (
batch_tensor.transpose(0, -1) * vector).transpose(0, -1).contiguous()
def _batch_clamp_tensor_by_vector(vector, batch_tensor):
"""Equivalent to the following
for ii in range(len(vector)):
batch_tensor[ii] = clamp(
batch_tensor[ii], -vector[ii], vector[ii])
"""
return torch.min(
torch.max(batch_tensor.transpose(0, -1), -vector), vector
).transpose(0, -1).contiguous()
def batch_multiply(float_or_vector, tensor):
if isinstance(float_or_vector, torch.Tensor):
assert len(float_or_vector) == len(tensor)
tensor = _batch_multiply_tensor_by_vector(float_or_vector, tensor)
elif isinstance(float_or_vector, float):
tensor *= float_or_vector
else:
raise TypeError("Value has to be float or torch.Tensor")
return tensor
def batch_clamp(float_or_vector, tensor):
if isinstance(float_or_vector, torch.Tensor):
assert len(float_or_vector) == len(tensor)
tensor = _batch_clamp_tensor_by_vector(float_or_vector, tensor)
return tensor
elif isinstance(float_or_vector, float):
tensor = clamp(tensor, -float_or_vector, float_or_vector)
else:
raise TypeError("Value has to be float or torch.Tensor")
return tensor
def _get_norm_batch(x, p):
batch_size = x.size(0)
return x.abs().pow(p).view(batch_size, -1).sum(dim=1).pow(1. / p)
def clamp_by_pnorm(x, p, r):
assert isinstance(p, float) or isinstance(p, int)
norm = _get_norm_batch(x, p)
if isinstance(r, torch.Tensor):
assert norm.size() == r.size()
else:
assert isinstance(r, float)
factor = torch.min(r / norm, torch.ones_like(norm))
return batch_multiply(factor, x)
def is_float_or_torch_tensor(x):
return isinstance(x, torch.Tensor) or isinstance(x, float)
def normalize_by_pnorm(x, p=2, small_constant=1e-6):
"""
Normalize gradients for gradient (not gradient sign) attacks.
# TODO: move this function to utils
:param x: tensor containing the gradients on the input.
:param p: (optional) order of the norm for the normalization (1 or 2).
:param small_constant: (optional float) to avoid dividing by zero.
:return: normalized gradients.
"""
# loss is averaged over the batch so need to multiply the batch
# size to find the actual gradient of each input sample
assert isinstance(p, float) or isinstance(p, int)
norm = _get_norm_batch(x, p)
norm = torch.max(norm, torch.ones_like(norm) * small_constant)
return batch_multiply(1. / norm, x)
def jacobian(model, x, output_class):
"""
Compute the output_class'th row of a Jacobian matrix. In other words,
compute the gradient wrt to the output_class.
:param model: forward pass function.
:param x: input tensor.
:param output_class: the output_fz class we want to compute the gradients.
:return: output_class'th row of the Jacobian matrix wrt x.
"""
xvar = replicate_input_withgrad(x)
scores = model(xvar)
# compute gradients for the class output_class wrt the input x
# using backpropagation
torch.sum(scores[:, output_class]).backward()
return xvar.grad.detach().clone()
MNIST_MEAN = (0.1307,)
MNIST_STD = (0.3081,)
CIFAR10_MEAN = (0.4914, 0.4822, 0.4465)
CIFAR10_STD = (0.2023, 0.1994, 0.2010)
class NormalizeByChannelMeanStd(nn.Module):
def __init__(self, mean, std):
super(NormalizeByChannelMeanStd, self).__init__()
if not isinstance(mean, torch.Tensor):
mean = torch.tensor(mean)
if not isinstance(std, torch.Tensor):
std = torch.tensor(std)
self.register_buffer("mean", mean)
self.register_buffer("std", std)
def forward(self, tensor):
return normalize_fn(tensor, self.mean, self.std)
def extra_repr(self):
return 'mean={}, std={}'.format(self.mean, self.std)
def normalize_fn(tensor, mean, std):
"""Differentiable version of torchvision.functional.normalize"""
# here we assume the color channel is in at dim=1
mean = mean[None, :, None, None]
std = std[None, :, None, None]
return tensor.sub(mean).div(std)
def batch_per_image_standardization(imgs):
# replicate tf.image.per_image_standardization, but in batch
assert imgs.ndimension() == 4
mean = imgs.view(imgs.shape[0], -1).mean(dim=1).view(
imgs.shape[0], 1, 1, 1)
return (imgs - mean) / batch_adjusted_stddev(imgs)
def batch_adjusted_stddev(imgs):
# for batch_per_image_standardization
std = imgs.view(imgs.shape[0], -1).std(dim=1).view(imgs.shape[0], 1, 1, 1)
std_min = 1. / imgs.new_tensor(imgs.shape[1:]).prod().float().sqrt()
return torch.max(std, std_min)
class PerImageStandardize(nn.Module):
def __init__(self):
super(PerImageStandardize, self).__init__()
def forward(self, tensor):
return batch_per_image_standardization(tensor)
def predict_from_logits(logits, dim=1):
return logits.max(dim=dim, keepdim=False)[1]
|
import torch
import torch.nn as nn
from torch.autograd import Variable
class ShakeDropFunction(torch.autograd.Function):
@staticmethod
def forward(ctx, x, training=True, p_drop=0.5, alpha_range=None):
if alpha_range is None:
alpha_range = [-1, 1]
if training:
gate = torch.cuda.FloatTensor([0]).bernoulli_(1 - p_drop)
ctx.save_for_backward(gate)
if gate.item() == 0:
alpha = torch.cuda.FloatTensor(x.size(0)).uniform_(*alpha_range)
alpha = alpha.view(alpha.size(0), 1, 1, 1).expand_as(x)
return alpha * x
else:
return x
else:
return (1 - p_drop) * x
@staticmethod
def backward(ctx, grad_output):
gate = ctx.saved_tensors[0]
if gate.item() == 0:
beta = torch.cuda.FloatTensor(grad_output.size(0)).uniform_(0, 1)
beta = beta.view(beta.size(0), 1, 1, 1).expand_as(grad_output)
beta = Variable(beta)
return beta * grad_output, None, None, None
else:
return grad_output, None, None, None
class ShakeDrop(nn.Module):
def __init__(self, p_drop=0.5, alpha_range=None):
super(ShakeDrop, self).__init__()
if alpha_range is None:
alpha_range = [-1, 1]
self.p_drop = p_drop
self.alpha_range = alpha_range
def forward(self, x):
return ShakeDropFunction.apply(x, self.training, self.p_drop, self.alpha_range)
|
import PenPal from "meteor/penpal";
import {
DEFAULT_PENPAL_SETTINGS,
SETTINGS_STORE,
PLUGIN_NAME
} from "../../constants.js";
import queries from "./configuration.queries.js";
export default {
async setBurpsuiteProConfiguration(
root,
{ configuration: jsonConfiguration },
context
) {
const configuration = JSON.parse(jsonConfiguration);
const {
penpal_settings: { rest_url = "", rest_timeout = 2000 } = {}
} = configuration;
let current_config = PenPal.DataStore.fetch(
PLUGIN_NAME,
SETTINGS_STORE,
{}
);
if (current_config.length > 0) {
PenPal.DataStore.update(
PLUGIN_NAME,
SETTINGS_STORE,
{ _id: current_config[0]._id },
{ $set: { rest_url, rest_timeout } }
);
} else {
PenPal.DataStore.insert(PLUGIN_NAME, SETTINGS_STORE, {
rest_url,
rest_timeout
});
}
return await queries.getBurpsuiteProConfiguration();
}
};
|
/* global describe, it, before, after, beforeEach */
'use strict';
import chai from 'chai';
chai.should();
import request from 'request';
import { app } from '../example/server';
import { Breaker } from '../lib';
describe('request', () => {
let server, breaker;
before(() => {
server = app.listen(3000);
});
beforeEach(() => {
breaker = Breaker.create(request, 'test:request');
});
after(() => {
server.close();
});
it('should wrap request and leave the callback API intact', (done) => {
breaker.get('http://127.0.0.1:3000/will/succeed', (error, response, body) => {
if (!error && response.statusCode === 200) {
body.should.equal('Success');
done();
}
});
});
it.skip('should wrap request and record failures for error response', (done) => {
breaker.get('http://127.0.0.1:3000/will/fail', (error, response, body) => {
if (!error && response.statusCode === 500) {
body.should.equal('Failure');
breaker.state.failure_count.should.equal(1);
done();
}
});
});
it.skip('should wrap request and leave the event API intact', (done) => {
breaker.get('http://127.0.0.1:3000/will/succeed')
.on('response', (response) => {
response.statusCode.should.equal(200);
});
});
});
|
import React, { useContext, useEffect, useRef, useState } from 'react';
import { StatusBar, View, StyleSheet, Alert } from 'react-native';
import { DrawerContentScrollView } from '@react-navigation/drawer';
import ReactNativeHapticFeedback from 'react-native-haptic-feedback';
import PropTypes from 'prop-types';
import { useIsFocused, useTheme } from '@react-navigation/native';
import { BlueHeaderDefaultMain, BlueSpacing20 } from '../../BlueComponents';
import WalletsCarousel from '../../components/WalletsCarousel';
import { PlaceholderWallet } from '../../class';
import WalletImport from '../../class/wallet-import';
import loc from '../../loc';
import { BlueStorageContext } from '../../blue_modules/storage-context';
import { BlurView } from '@react-native-community/blur';
const DrawerList = props => {
console.log('drawerList rendering...');
const walletsCarousel = useRef();
const { wallets, selectedWallet, pendingWallets, isDrawerListBlurred } = useContext(BlueStorageContext);
const [carouselData, setCarouselData] = useState([]);
const { colors } = useTheme();
const walletsCount = useRef(wallets.length);
const isFocused = useIsFocused();
const stylesHook = StyleSheet.create({
root: {
backgroundColor: colors.brandingColor,
},
});
useEffect(() => {
const allWallets = wallets.concat(pendingWallets);
setCarouselData(allWallets.concat(false));
const newCarouselData = allWallets.concat(false);
setCarouselData(newCarouselData);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [wallets, pendingWallets]);
useEffect(() => {
if (walletsCount.current < wallets.length) {
walletsCarousel.current?.scrollToItem({ item: wallets[walletsCount.current] });
}
walletsCount.current = wallets.length;
}, [wallets]);
useEffect(() => {
if (pendingWallets.length > 0) {
walletsCarousel.current?.scrollToItem(carouselData.length - pendingWallets.length);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [pendingWallets]);
const handleClick = index => {
console.log('click', index);
const wallet = carouselData[index];
if (wallet) {
if (wallet.type === PlaceholderWallet.type) {
Alert.alert(
loc.wallets.add_details,
loc.wallets.list_import_problem,
[
{
text: loc.wallets.details_delete,
onPress: () => {
WalletImport.removePlaceholderWallet();
},
style: 'destructive',
},
{
text: loc.wallets.list_tryagain,
onPress: () => {
props.navigation.navigate('AddWalletRoot', { screen: 'ImportWallet', params: { label: wallet.getSecret() } });
WalletImport.removePlaceholderWallet();
},
style: 'default',
},
],
{ cancelable: false },
);
} else {
props.navigation.navigate('WalletTransactions', {
walletID: wallet.getID(),
walletType: wallet.type,
key: `WalletTransactions-${wallet.getID()}`,
});
}
} else {
// if its out of index - this must be last card with incentive to create wallet
if (!carouselData.some(wallet => wallet.type === PlaceholderWallet.type)) {
props.navigation.navigate('Navigation', { screen: 'AddWalletRoot' });
}
}
};
const handleLongPress = () => {
if (carouselData.length > 1 && !carouselData.some(wallet => wallet.type === PlaceholderWallet.type)) {
props.navigation.navigate('ReorderWallets');
} else {
ReactNativeHapticFeedback.trigger('notificationError', { ignoreAndroidSystemSettings: false });
}
};
const onNewWalletPress = () => {
return !carouselData.some(wallet => wallet.type === PlaceholderWallet.type) ? props.navigation.navigate('AddWalletRoot') : null;
};
const ListHeaderComponent = () => {
return (
<>
<BlueHeaderDefaultMain leftText={loc.wallets.list_title} onNewWalletPress={onNewWalletPress} isDrawerList />
<BlueSpacing20 />
</>
);
};
const renderWalletsCarousel = (
<WalletsCarousel
data={carouselData}
extraData={carouselData}
onPress={handleClick}
handleLongPress={handleLongPress}
ref={walletsCarousel}
testID="WalletsList"
vertical
selectedWallet={selectedWallet}
ListHeaderComponent={ListHeaderComponent}
scrollEnabled={isFocused}
/>
);
return (
<DrawerContentScrollView {...props}>
<View styles={[styles.root, stylesHook.root]}>
<StatusBar barStyle="default" />
{renderWalletsCarousel}
</View>
{isDrawerListBlurred && (
<BlurView style={styles.absolute} blurType="light" blurAmount={10} reducedTransparencyFallbackColor="white" />
)}
</DrawerContentScrollView>
);
};
export default DrawerList;
const styles = StyleSheet.create({
root: {
flex: 1,
},
absolute: {
position: 'absolute',
top: 0,
left: 0,
bottom: 0,
right: 0,
},
});
DrawerList.propTypes = {
navigation: PropTypes.shape({
navigate: PropTypes.func,
addListener: PropTypes.func,
}),
route: PropTypes.shape({
name: PropTypes.string,
params: PropTypes.object,
}),
};
|
{
var __result1 = 1 * null !== 0;
var __expect1 = false;
}
{
var __result2 = null * 1 !== 0;
var __expect2 = false;
}
{
var __result3 = new Number(1) * null !== 0;
var __expect3 = false;
}
{
var __result4 = null * new Number(1) !== 0;
var __expect4 = false;
}
|
const XLSX = require('xlsx')
module.exports = function () {
const content = XLSX.readFile(this.resourcePath)
return `module.exports = ${JSON.stringify(content)}`
}
|
const userDetailsPage = require('../pages/userDetails')
const recallsListPage = require('../pages/recallsList')
context('User details', () => {
beforeEach(() => {
cy.task('reset')
cy.task('stubLogin')
cy.task('stubAuthUser')
cy.task('expectListRecalls', {
expectedResults: [],
})
cy.task('expectAddUserDetails')
cy.login()
})
it('user adds their details', () => {
cy.task('expectGetCurrentUserDetails', {
status: 404,
})
cy.task('expectAddUserDetails')
const userDetails = userDetailsPage.verifyOnPage()
userDetails.enterTextInInput({ name: 'firstName', text: 'Barry' })
userDetails.enterTextInInput({ name: 'lastName', text: 'Badger' })
userDetails.enterTextInInput({ name: 'email', text: 'barry@badger.com' })
userDetails.enterTextInInput({ name: 'phoneNumber', text: '0739378378' })
userDetails.checkRadio({ fieldName: 'caseworkerBand', value: 'FOUR_PLUS' })
userDetails.uploadFile({ fieldName: 'signature', fileName: 'signature.jpg', mimeType: 'image/jpeg' })
userDetails.clickButton({ qaAttr: 'saveButton' })
userDetails.assertApiRequestBody({
url: '/users',
method: 'POST',
bodyValues: {
firstName: 'Barry',
lastName: 'Badger',
email: 'barry@badger.com',
phoneNumber: '0739378378',
caseworkerBand: 'FOUR_PLUS',
},
})
})
it('user views their details', () => {
cy.task('expectGetCurrentUserDetails', {
status: 200,
expectedResult: {
firstName: 'Barry',
lastName: 'Badger',
email: 'barry@badger.com',
phoneNumber: '0739378378',
caseworkerBand: 'FOUR_PLUS',
signature: 'def',
userId: '123',
},
})
const userDetails = userDetailsPage.verifyOnPage()
userDetails.assertInputValue({ fieldName: 'firstName', value: 'Barry' })
userDetails.assertInputValue({ fieldName: 'lastName', value: 'Badger' })
userDetails.assertInputValue({ fieldName: 'email', value: 'barry@badger.com' })
userDetails.assertInputValue({ fieldName: 'phoneNumber', value: '0739378378' })
userDetails.assertRadioChecked({ fieldName: 'caseworkerBand', value: 'FOUR_PLUS' })
userDetails.assertElementPresent({ qaAttr: 'signature-image' })
})
it('user clicks on their name in the header to go to user details page', () => {
cy.task('expectGetCurrentUserDetails', {
status: 200,
expectedResult: {
firstName: 'Barry',
lastName: 'Badger',
email: 'barry@badger.com',
phoneNumber: '0739378378',
caseworkerBand: 'FOUR_PLUS',
signature: 'def',
userId: '123',
},
})
const recallsList = recallsListPage.verifyOnPage()
recallsList.clickLink({ qaAttr: 'header-user-name' })
userDetailsPage.verifyOnPage()
})
})
|
const fetch = require('node-fetch');
const genSVG = require('../lib/svg.js');
const KindModel = require('../models/kind.js');
const KindController = require('../controllers/kind.js');
module.exports = async (req, res) => {
try {
const { username, kind, type, ext, begin, end, direction } = req.query;
const [_kind, _type, _ext] = KindController.intercept(kind, type, ext);
fetch(`https://bangumi-mosaic-tile.herokuapp.com/users/${username}/${_kind}s/${_type}.json`).catch(() => {});
const entity = await KindModel.get(username, _kind, _type);
if (!entity) throw new Error(404);
res.setHeader('Cache-Control', 'max-age=86400');
res.setHeader('Access-Control-Allow-Origin', '*');
if (_ext === 'svg') {
res.setHeader('Content-Type', 'image/svg+xml');
res.send(genSVG(entity.data, { begin, end, direction }));
} else {
res.json(entity.data);
}
} catch (err) {
res.status(404);
res.json({ error: { code: 404, message: 'Not Found' } });
}
};
|
const cheerio = require('cheerio')
const fetch = require('node-fetch')
const { omitBy, isNil } = require('lodash')
const GITHUB_URL = 'https://github.com';
function getMatchString(value, pattern) {
const match = value.match(pattern);
if (match && match[1]) {
return match[1];
} else {
return null;
}
}
function filterLanguages(languages) {
return languages.filter(lang => lang.urlParam && lang.urlParam !== 'unknown');
}
function omitNil(object) {
return omitBy(object, isNil);
}
function removeDefaultAvatarSize(src) {
/* istanbul ignore if */
if (!src) {
return src;
}
return src.replace(/\?s=.*$/, '');
}
async function fetchAllLanguages() {
const data = await fetch(`${GITHUB_URL}/trending/`);
const $ = cheerio.load(await data.text());
const getLang = href => getMatchString(href, /\/trending\/([^?/]+)/i);
const popularLanguages = $('.col-md-3 .filter-item')
.get()
.map(a => {
const $a = $(a);
return {
urlParam: getLang($a.attr('href')),
name: $a.text(),
};
});
const allLanguages = $('.col-md-3 .select-menu-item')
.get()
.map(a => {
const $a = $(a);
return {
urlParam: getLang($a.attr('href')),
name: $a.children('[data-menu-button-text]').text(),
};
});
return {
popular: filterLanguages(popularLanguages),
all: filterLanguages(allLanguages),
};
}
async function fetchRepositories({
language = '',
since = 'daily',
} = {}) {
const url = `${GITHUB_URL}/trending/${language}?since=${since}`;
const data = await fetch(url);
const $ = cheerio.load(await data.text());
return (
$('.Box article.Box-row')
.get()
// eslint-disable-next-line complexity
.map((repo) => {
const $repo = $(repo);
const title = $repo
.find('.h3')
.text()
.trim();
const relativeUrl = $repo
.find('.h3')
.find('a')
.attr('href');
const currentPeriodStarsString =
$repo
.find('.float-sm-right')
.text()
.trim() || /* istanbul ignore next */ '';
const builtBy = $repo
.find('span:contains("Built by")')
.find('[data-hovercard-type="user"]')
.map((i, user) => {
const altString = $(user)
.children('img')
.attr('alt');
const avatarUrl = $(user)
.children('img')
.attr('src');
return {
username: altString
? altString.slice(1)
: /* istanbul ignore next */ null,
href: `${GITHUB_URL}${user.attribs.href}`,
avatar: removeDefaultAvatarSize(avatarUrl),
};
})
.get();
const colorNode = $repo.find('.repo-language-color');
const langColor = colorNode.length
? colorNode.css('background-color')
: null;
const langNode = $repo.find('[itemprop=programmingLanguage]');
const lang = langNode.length
? langNode.text().trim()
: /* istanbul ignore next */ null;
return omitNil({
author: title.split(' / ')[0],
name: title.split(' / ')[1],
url: `${GITHUB_URL}${relativeUrl}`,
description:
$repo
.find('p.my-1')
.text()
.trim() || /* istanbul ignore next */ '',
language: lang,
languageColor: langColor,
stars: parseInt(
$repo
.find(`[href="${relativeUrl}/stargazers"]`)
.text()
.replace(',', '') || /* istanbul ignore next */ '0',
10
),
forks: parseInt(
$repo
.find(`[href="${relativeUrl}/network/members"]`)
.text()
.replace(',', '') || /* istanbul ignore next */ '0',
10
),
currentPeriodStars: parseInt(
currentPeriodStarsString.split(' ')[0].replace(',', '') ||
/* istanbul ignore next */ '0',
10
),
builtBy,
});
})
);
}
async function fetchDevelopers({ language = '', since = 'daily' } = {}) {
const data = await fetch(
`${GITHUB_URL}/trending/developers/${language}?since=${since}`
);
const $ = cheerio.load(await data.text());
return $('.Box article.Box-row')
.get()
.map((dev) => {
const $dev = $(dev);
const relativeUrl = $dev.find('.h3 a').attr('href');
const name = getMatchString(
$dev
.find('.h3 a')
.text()
.trim(),
/^\((.+)\)$/i
);
const username = relativeUrl.slice(1);
const type = $dev
.find('img')
.parent()
.attr('data-hovercard-type');
const $repo = $dev.find('.mb-2');
$repo.find('svg').remove();
return omitNil({
username,
name,
type,
url: `${GITHUB_URL}${relativeUrl}`,
avatar: removeDefaultAvatarSize($dev.find('img').attr('src')),
repo: {
name: $repo
.find('a')
.text()
.trim(),
description:
$repo
.find('.f6')
.text()
.trim() || /* istanbul ignore next */ '',
url: `${GITHUB_URL}${$repo.find('a').attr('href')}`,
},
});
});
}
exports.fetchAllLanguages = fetchAllLanguages
exports.fetchRepositories = fetchRepositories
exports.fetchDevelopers = fetchDevelopers
|
from a10sdk.common.A10BaseClass import A10BaseClass
class Esp(A10BaseClass):
"""Class Description::
NAT64 ESP ALG (default: disabled).
Class esp supports CRUD Operations and inherits from `common/A10BaseClass`.
This class is the `"PARENT"` class for this module.`
:param uuid: {"description": "uuid of the object", "format": "string", "minLength": 1, "modify-not-allowed": 1, "optional": true, "maxLength": 64, "type": "string"}
:param esp_enable: {"optional": true, "enum": ["enable"], "type": "string", "description": "'enable': Enable NAT64 ESP ALG; ", "format": "enum"}
:param DeviceProxy: The device proxy for REST operations and session handling. Refer to `common/device_proxy.py`
URL for this object::
`https://<Hostname|Ip address>//axapi/v3/cgnv6/nat64/alg/esp`.
"""
def __init__(self, **kwargs):
self.ERROR_MSG = ""
self.required=[]
self.b_key = "esp"
self.a10_url="/axapi/v3/cgnv6/nat64/alg/esp"
self.DeviceProxy = ""
self.uuid = ""
self.esp_enable = ""
for keys, value in kwargs.items():
setattr(self,keys, value)
|
import torch
import torch.nn as nn
import torch.nn.functional as F
from models.sync_batchnorm.batchnorm import SynchronizedBatchNorm2d
from models.aspp import build_aspp
from models.decoder import build_decoder
from models.cam_decoder import build_attention_decoder
from models.backbone import build_backbone
import pdb
class DeepLab(nn.Module):
def __init__(self, backbone='resnet101', output_stride=16, num_classes=21,
bn='bn', freeze_bn=False, modal_num=3):
super(DeepLab, self).__init__()
if backbone == 'drn':
output_stride = 8
self.best_iou = 0
if bn == 'sync_bn':
BatchNorm = SynchronizedBatchNorm2d
elif bn == 'bn':
BatchNorm = nn.BatchNorm2d
elif bn == 'gn':
BatchNorm = nn.GroupNorm
else:
raise NotImplementedError('batch norm choice {} is not implemented'.format(bn))
self.backbone = build_backbone(backbone, output_stride, BatchNorm)
# aspp/decoder-branches
self.modal_num = modal_num
self.aspps = []
self.decoders = []
for item in range(modal_num):
self.aspps.append(build_aspp(backbone, output_stride, BatchNorm))
self.decoders.append(build_decoder(num_classes, backbone, BatchNorm))
self.aspps = nn.ModuleList(self.aspps)
self.decoders = nn.ModuleList(self.decoders)
# attention-branch
self.attention_decoder = build_attention_decoder(num_classes, modal_num, backbone, BatchNorm)
if freeze_bn:
self.freeze_bn()
def _load_pretrained_model(self):
if hasattr(self.backbone, '_load_pretrained_model'):
self.backbone._load_pretrained_model()
def forward(self, input):
x, low_level_feat = self.backbone(input)
cls_feats = []
outs = []
for _aspp, _decoder in zip(self.aspps, self.decoders):
_x = _aspp(x)
_cls_feat, _out = _decoder(_x, low_level_feat)
cls_feats.append(_cls_feat)
outs.append(_out)
# attention decoder
att_mask, _att_feat, _att_out = self.attention_decoder(cls_feats, low_level_feat)
cls_feats.append(_att_feat)
outs.append(_att_out)
#assert len(cls_feats) == 4, "cls_feats num:{}".format(len(cls_feats))
return x, low_level_feat, att_mask, cls_feats, outs
def freeze_bn(self):
for m in self.modules():
if isinstance(m, SynchronizedBatchNorm2d):
m.eval()
elif isinstance(m, nn.BatchNorm2d):
m.eval()
elif isinstance(m, nn.GroupNorm):
m.eval()
elif m.__class__.__name__.find('BatchNorm')!= -1:
m.eval()
def get_1x_lr_params(self):
modules = [self.backbone]
#modules = []
for i in range(len(modules)):
for m in modules[i].named_modules():
if isinstance(m[1], nn.Conv2d) or isinstance(m[1], SynchronizedBatchNorm2d) \
or isinstance(m[1], nn.BatchNorm2d):
for p in m[1].parameters():
if p.requires_grad:
yield p
def get_10x_lr_params(self):
modules = [self.aspps, self.decoders, self.attention_decoder]
for i in range(len(modules)):
for m in modules[i].named_modules():
if isinstance(m[1], nn.Conv2d) or isinstance(m[1], SynchronizedBatchNorm2d) \
or isinstance(m[1], nn.BatchNorm2d):
for p in m[1].parameters():
if p.requires_grad:
yield p
def optim_parameters(self, learning_rate):
return [{'params': self.get_1x_lr_params(), 'lr': learning_rate},
{'params': self.get_10x_lr_params(), 'lr': 10 * learning_rate}]
if __name__ == "__main__":
model = DeepLab(backbone='mobilenet', output_stride=16)
model.eval()
input = torch.rand(1, 3, 513, 513)
output = model(input)
print(output.size())
|
const memoize = require('lodash.memoize');
const sqrt2 = Math.sqrt(2);
function canStartOn( node ){
const { options, previewEles, ghostEles, handleNode } = this;
const isPreview = el => previewEles.anySame(el);
const isGhost = el => ghostEles.anySame(el);
const userFilter = el => el.filter( options.handleNodes ).length > 0;
const isHandle = el => handleNode.same(el);
const isTemp = el => isPreview(el) || isHandle(el) || isGhost(el);
const { enabled, active, grabbingNode } = this;
return (
enabled && !active && !grabbingNode
&& ( node == null || (!isTemp(node) && userFilter(node)) )
);
}
function canStartDrawModeOn( node ){
return this.canStartOn( node ) && this.drawMode;
}
function canStartNonDrawModeOn( node ){
return this.canStartOn( node ) && !this.drawMode;
}
function show( node ){
let { options, drawMode } = this;
if( !this.canStartOn(node) || ( drawMode && !options.handleInDrawMode ) ){ return; }
this.sourceNode = node;
this.setHandleFor( node );
this.emit( 'show', this.hp(), this.sourceNode );
return this;
}
function hide(){
this.removeHandle();
this.emit( 'hide', this.hp(), this.sourceNode );
return this;
}
function start( node ){
if( !this.canStartOn(node) ){ return; }
this.active = true;
this.sourceNode = node;
this.sourceNode.addClass('eh-source');
this.disableGestures();
this.disableEdgeEvents();
this.emit( 'start', this.hp(), node );
}
function update( pos ){
if( !this.active ){ return; }
let p = pos;
this.mx = p.x;
this.my = p.y;
this.updateEdge();
this.throttledSnap();
return this;
}
function snap(){
if( !this.active || !this.options.snap ){ return false; }
let cy = this.cy;
let tgt = this.targetNode;
let threshold = this.options.snapThreshold;
let mousePos = this.mp();
let { handleNode, previewEles, ghostNode } = this;
let radius = n => sqrt2 * Math.max(n.outerWidth(), n.outerHeight())/2; // worst-case enclosure of bb by circle
let sqDist = (x1, y1, x2, y2) => { let dx = x2 - x1; let dy = y2 - y1; return dx*dx + dy*dy; };
let sqDistByPt = (p1, p2) => sqDist(p1.x, p1.y, p2.x, p2.y);
let nodeSqDist = n => sqDistByPt(n.position(), mousePos);
let sqThreshold = n => { let r = radius(n); let t = r + threshold; return t * t; };
let isWithinThreshold = n => nodeSqDist(n) <= sqThreshold(n);
let bbSqDist = n => {
let p = n.position();
let halfW = n.outerWidth() / 2;
let halfH = n.outerHeight() / 2;
// node and mouse positions, line is formed from node to mouse
let nx = p.x;
let ny = p.y;
let mx = mousePos.x;
let my = mousePos.y;
// bounding box
let x1 = nx - halfW;
let x2 = nx + halfW;
let y1 = ny - halfH;
let y2 = ny + halfH;
let insideXBounds = x1 <= mx && mx <= x2;
let insideYBounds = y1 <= my && my <= y2;
if( insideXBounds && insideYBounds ){ // inside box
return 0;
} else if( insideXBounds ){ // perpendicular distance to box, top or bottom
let dy1 = my - y1;
let dy2 = my - y2;
return Math.min(dy1 * dy1, dy2 * dy2);
} else if( insideYBounds ){ // perpendicular distance to box, left or right
let dx1 = mx - x1;
let dx2 = mx - x2;
return Math.min(dx1 * dx1, dx2 * dx2);
} else if( mx < x1 && my < y1 ){ // top-left corner distance
return sqDist(mx, my, x1, y1);
} else if( mx > x2 && my < y1 ){ // top-right corner distance
return sqDist(mx, my, x2, y1);
} else if( mx < x1 && my > y2 ){ // bottom-left corner distance
return sqDist(mx, my, x1, y2);
} else { // bottom-right corner distance
return sqDist(mx, my, x2, y2);
}
};
let cmpBbSqDist = (n1, n2) => bbSqDist(n1) - bbSqDist(n2);
let cmp = cmpBbSqDist;
let allowHoverDelay = false;
let mouseIsInside = n => {
let mp = mousePos;
let w = n.outerWidth();
let halfW = w/2;
let h = n.outerHeight();
let halfH = h/2;
let p = n.position();
let x1 = p.x - halfW;
let x2 = p.x + halfW;
let y1 = p.y - halfH;
let y2 = p.y + halfH;
return (
x1 <= mp.x && mp.x <= x2
&& y1 <= mp.y && mp.y <= y2
);
};
let isEhEle = n => n.same(handleNode) || n.same(previewEles) || n.same(ghostNode);
let nodesByDist = cy.nodes(n => !isEhEle(n) && isWithinThreshold(n)).sort(cmp);
let snapped = false;
if( tgt.nonempty() && !isWithinThreshold(tgt) ){
this.unpreview(tgt);
}
for(let i = 0; i < nodesByDist.length; i++){
let n = nodesByDist[i];
// skip a parent node when the mouse is inside it
if( n.isParent() && mouseIsInside(n) ){ continue; }
// skip a child node when the mouse is not inside the parent
if( n.isChild() && !mouseIsInside(n.parent()) ){ continue; }
if( n.same(tgt) || this.preview(n, allowHoverDelay) ){
snapped = true;
break;
}
}
return snapped;
}
function preview( target, allowHoverDelay = true ){
let { options, sourceNode, ghostNode, ghostEles, presumptiveTargets, previewEles, active } = this;
let source = sourceNode;
let isLoop = target.same( source );
let loopAllowed = options.loopAllowed( target );
let isGhost = target.same( ghostNode );
let noEdge = !options.edgeType( source, target );
let isHandle = target.same( this.handleNode );
let isExistingTgt = target.same( this.targetNode );
if (!active || isHandle || isGhost || noEdge || isExistingTgt || (isLoop && !loopAllowed) || (!options.canConnect(source, target))){
return false;
}
if( this.targetNode.nonempty() ){
this.unpreview( this.targetNode );
}
clearTimeout( this.previewTimeout );
let applyPreview = () => {
this.targetNode = target;
presumptiveTargets.merge( target );
target.addClass('eh-presumptive-target');
target.addClass('eh-target');
this.emit( 'hoverover', this.mp(), source, target );
if( options.preview ){
target.addClass('eh-preview');
ghostEles.addClass('eh-preview-active');
sourceNode.addClass('eh-preview-active');
target.addClass('eh-preview-active');
this.makePreview();
this.emit( 'previewon', this.mp(), source, target, previewEles );
}
};
if( allowHoverDelay && options.hoverDelay > 0 ){
this.previewTimeout = setTimeout( applyPreview, options.hoverDelay );
} else {
applyPreview();
}
return true;
}
function unpreview( target ) {
if( !this.active || target.same( this.handleNode ) ){ return; }
let { previewTimeout, sourceNode, previewEles, ghostEles, cy } = this;
clearTimeout( previewTimeout );
this.previewTimeout = null;
let source = sourceNode;
target.removeClass('eh-preview eh-target eh-presumptive-target eh-preview-active');
ghostEles.removeClass('eh-preview-active');
sourceNode.removeClass('eh-preview-active');
this.targetNode = cy.collection();
this.removePreview( source, target );
this.emit( 'hoverout', this.mp(), source, target );
this.emit( 'previewoff', this.mp(), source, target, previewEles );
return this;
}
function stop(){
if( !this.active ){ return; }
let { sourceNode, targetNode, ghostEles, presumptiveTargets } = this;
clearTimeout( this.previewTimeout );
sourceNode.removeClass('eh-source eh-preview-active');
targetNode.removeClass('eh-target eh-preview eh-hover eh-preview-active');
presumptiveTargets.removeClass('eh-presumptive-target');
this.makeEdges();
this.removeHandle();
ghostEles.remove();
this.clearCollections();
this.resetGestures();
this.enableEdgeEvents();
this.active = false;
this.emit( 'stop', this.mp(), sourceNode );
return this;
}
module.exports = {
show, hide, start, update, preview, unpreview, stop, snap,
canStartOn, canStartDrawModeOn, canStartNonDrawModeOn
};
|
import logging
from ailment import Expr, Stmt
from ....engines.light import SimEngineLightAILMixin
from ....engines.light import SimEngineLight
_l = logging.getLogger(name=__name__)
class SimplifierAILState:
def __init__(self, arch, variables=None):
self.arch = arch
self._variables = {} if variables is None else variables
def __repr__(self):
return "<SimplifierAILState>"
def copy(self):
rd = SimplifierAILState(
self.arch,
variables=self._variables.copy(),
)
return rd
def merge(self, *others):
raise NotImplementedError()
def store_variable(self, old, new):
if new is not None:
self._variables[old] = new
def get_variable(self, old):
return self._variables.get(old, None)
def remove_variable(self, old):
self._variables.pop(old, None)
def filter_variables(self, atom):
keys_to_remove = set()
for k, v in self._variables.items():
if isinstance(v, Expr.Expression) and (v == atom or v.has_atom(atom)):
keys_to_remove.add(k)
for k in keys_to_remove:
self._variables.pop(k)
class SimplifierAILEngine(
SimEngineLightAILMixin,
SimEngineLight,
):
def __init__(self): #pylint: disable=useless-super-delegation
super().__init__()
def process(self, state, *args, **kwargs):
# override SimEngineLight.process() so that we can return the processed block
super().process(state, *args, **kwargs)
return self.block
def _process_Stmt(self, whitelist=None):
if whitelist is not None:
whitelist = set(whitelist)
for stmt_idx, stmt in enumerate(self.block.statements):
if whitelist is not None and stmt_idx not in whitelist:
continue
new_stmt = self._ail_handle_Stmt(stmt)
if new_stmt and new_stmt != stmt:
self.block.statements[stmt_idx] = new_stmt
# handle stmt
def _ail_handle_Stmt(self, stmt):
handler = "_ail_handle_%s" % type(stmt).__name__
if hasattr(self, handler):
return getattr(self, handler)(stmt)
else:
_l.warning('Unsupported statement type %s.', type(stmt).__name__)
return stmt
def _ail_handle_Assignment(self, stmt):
src = self._expr(stmt.src)
dst = self._expr(stmt.dst)
if isinstance(dst, Expr.Register) and not src.has_atom(dst):
self.state.filter_variables(dst)
self.state.store_variable(dst, src)
if (src, dst) != (stmt.src, stmt.dst):
return Stmt.Assignment(stmt.idx, dst, src, **stmt.tags)
return stmt
def _ail_handle_Store(self, stmt):
addr = self._expr(stmt.addr)
data = self._expr(stmt.data)
# replace
if(addr, data) != (stmt.addr, stmt.data):
return Stmt.Store(stmt.idx, addr, data, stmt.size,
stmt.endness, variable=stmt.variable, **stmt.tags)
return stmt
def _ail_handle_Jump(self, stmt):
target = self._expr(stmt.target)
return Stmt.Jump(stmt.idx, target, **stmt.tags)
def _ail_handle_ConditionalJump(self, stmt): #pylint: disable=no-self-use
return stmt
def _ail_handle_Call(self, stmt):
target = self._expr(stmt.target)
new_args = None
if stmt.args:
new_args = [ ]
for arg in stmt.args:
new_arg = self._expr(arg)
new_args.append(new_arg)
return Stmt.Call(stmt.idx, target, calling_convention=stmt.calling_convention,
prototype=stmt.prototype, args=new_args, ret_expr=stmt.ret_expr,
**stmt.tags)
def _ail_handle_Load(self, expr):
addr = self._expr(expr.addr)
if addr != expr.addr:
return Expr.Load(expr.idx, addr, expr.size, expr.endness, **expr.tags)
return expr
# handle expr
def _expr(self, expr):
handler = "_ail_handle_%s" % type(expr).__name__
if hasattr(self, handler):
v = getattr(self, handler)(expr)
if v is None:
return expr
return v
_l.warning('Unsupported expression type %s.', type(expr).__name__)
return expr
def _ail_handle_StackBaseOffset(self, expr): # pylint:disable=no-self-use
return expr
def _ail_handle_Register(self, expr):
new_expr = self.state.get_variable(expr)
# TODO if got new expr here, former assignment can be killed
return expr if new_expr is None else new_expr
def _ail_handle_Mul(self, expr):
operand_0 = self._expr(expr.operands[0])
operand_1 = self._expr(expr.operands[1])
if (operand_0, operand_1) != (expr.operands[0], expr.operands[1]):
return Expr.BinaryOp(expr.idx, 'Mul', [operand_0, operand_1], **expr.tags)
return expr
def _ail_handle_Const(self, expr):
return expr
def _ail_handle_Convert(self, expr):
operand_expr = self._expr(expr.operand)
# import ipdb; ipdb.set_trace()
if type(operand_expr) is Expr.Convert:
if expr.from_bits == operand_expr.to_bits and expr.to_bits == operand_expr.from_bits:
# eliminate the redundant Convert
return operand_expr.operand
else:
return Expr.Convert(expr.idx, operand_expr.from_bits, expr.to_bits, expr.is_signed,
operand_expr.operand, **expr.tags)
elif type(operand_expr) is Expr.Const:
# do the conversion right away
value = operand_expr.value
mask = (2 ** expr.to_bits) - 1
value &= mask
return Expr.Const(expr.idx, operand_expr.variable, value, expr.to_bits, **expr.tags)
elif type(operand_expr) is Expr.BinaryOp \
and operand_expr.op in {'Mul', 'Shl', 'Div', 'DivMod', 'Add', 'Sub'}:
if isinstance(operand_expr.operands[1], Expr.Const):
if isinstance(operand_expr.operands[0], Expr.Register) and \
expr.from_bits == operand_expr.operands[0].bits:
converted = Expr.Convert(expr.idx, expr.from_bits, expr.to_bits, expr.is_signed,
operand_expr.operands[0])
return Expr.BinaryOp(operand_expr.idx, operand_expr.op,
[converted, operand_expr.operands[1]], **expr.tags)
elif isinstance(operand_expr.operands[0], Expr.Convert) and \
expr.from_bits == operand_expr.operands[0].to_bits and \
expr.to_bits == operand_expr.operands[0].from_bits:
return Expr.BinaryOp(operand_expr.idx, operand_expr.op,
[operand_expr.operands[0].operand, operand_expr.operands[1]], **operand_expr.tags)
elif isinstance(operand_expr.operands[0], Expr.Convert) \
and isinstance(operand_expr.operands[1], Expr.Convert) \
and operand_expr.operands[0].from_bits == operand_expr.operands[1].from_bits:
if operand_expr.operands[0].to_bits == operand_expr.operands[1].to_bits \
and expr.from_bits == operand_expr.operands[0].to_bits \
and expr.to_bits == operand_expr.operands[1].from_bits:
return Expr.BinaryOp(operand_expr.idx, operand_expr.op,
[operand_expr.operands[0].operand, operand_expr.operands[1].operand],
**operand_expr.tags)
converted = Expr.Convert(expr.idx, expr.from_bits, expr.to_bits, expr.is_signed,
operand_expr, **expr.tags)
return converted
|
import pathlib
from setuptools import setup
# The directory containing this file
HERE = pathlib.Path(__file__).parent
# The text of the README file
README = (HERE / "README.md").read_text()
# This call to setup() does all the work
setup(
name="mongodump-s3",
version="1.1.2",
description="Backup utility for MongoDB. "
"Compatible with Azure, Amazon Web Services and Google Cloud Platform.",
long_description=README,
long_description_content_type="text/markdown",
url="https://github.com/exesse/mongodump-s3",
author="Vladislav I. Kulbatski ",
author_email="hi@exesse.org",
license="MIT",
classifiers=[
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.8",
],
packages=["mongodump_s3"],
include_package_data=False,
install_requires=[
"requests>=2.26.0",
"hurry.filesize==0.9",
"python-dotenv>=0.18.0",
"azure-storage-blob>=12.8.1",
"boto3>=1.17.111",
"google-cloud-storage>=1.41.0"
],
entry_points={
"console_scripts": [
"mongodump-s3=mongodump_s3.__main__:main",
]
},
)
|
const moment = require('moment-timezone')
const Supporter = require('../../../structs/db/Supporter.js')
const Schedule = require('../../../structs/db/Schedule.js')
const FailRecord = require('../../../structs/db/FailRecord.js')
const { MenuEmbed, MenuVisual, MessageVisual } = require('discord.js-prompts')
const ThemedEmbed = require('../common/utils/ThemedEmbed.js')
const LocalizedPrompt = require('../common/utils/LocalizedPrompt.js')
const Translator = require('../../../structs/Translator.js')
const handlePaginationError = require('../common/utils/handlePaginationError.js')
const ArticleRateLimiter = require('../../../structs/ArticleMessageRateLimiter.js')
const getConfig = require('../../../config.js').get
/**
* @typedef {Object} Data
* @property {import('../../../structs/db/Profile.js')} [profile]
* @property {import('../../../structs/db/Feed.js')[]} feeds
* @property {import('discord.js').TextChannel} [channel]
* @property {string} [searchQuery]
* @property {string} guildID
*/
/**
* @param {import('../../../structs/db/Feed.js')[]} feeds
* @param {string} query
*/
function queryFeeds (feeds, query) {
if (!query) {
return feeds
}
return feeds.filter(feed => {
for (const key in feed) {
const value = feed[key]
if (typeof value === 'string' && value.toLowerCase().includes(query.toLowerCase())) {
return true
}
}
})
}
/**
* Returns the set of channels within an array of feeds
* that is at their limit
*
* @param {import('../../../structs/db/Feed.js')[]} feeds
*/
async function getChannelsAtLimit (feeds) {
// Get all channel ids with no dupes
const channels = feeds.map(f => f.channel).filter((channel, index, array) => array.indexOf(channel) === index)
// Check if each one is at its limit
const promises = channels.map(channelId => ArticleRateLimiter.getLimiter(channelId).isAtDailyLimit())
const limitResolves = await Promise.all(promises)
const channelsAtLimit = new Set()
// Only insert the channels at limit
limitResolves.forEach((atLimit, index) => {
const channelId = channels[index]
if (atLimit) {
channelsAtLimit.add(channelId)
}
})
return channelsAtLimit
}
/**
* @param {Data} data
*/
async function listFeedVisual (data) {
const { feeds, profile, guildID, channel, searchQuery } = data
const [supporter, schedules, supporterGuilds] = await Promise.all([
Supporter.getValidSupporterOfGuild(guildID),
Schedule.getAll(),
Supporter.getValidFastGuilds()
])
const unqueriedFeeds = channel ? feeds.filter(f => f.channel === channel.id) : feeds
const targetFeeds = queryFeeds(unqueriedFeeds, searchQuery)
const translate = Translator.createProfileTranslator(profile)
const channelsAtLimit = await getChannelsAtLimit(feeds)
if (feeds.length === 0) {
return new MessageVisual(translate('commands.list.noFeeds'))
} else if (targetFeeds.length === 0) {
return new MessageVisual(translate('commands.list.noFeedsChannel', {
channel: `<#${channel.id}>${channelsAtLimit.has(channel.id) ? ` (${translate('commands.list.channelLimitReached')})` : ''}`
}))
}
const config = getConfig()
const failRecordsMap = {}
const maxFeedsAllowed = supporter ? await supporter.getMaxFeeds() : config.feeds.max
// Generate the info for each feed as an array, and push into another array
const failRecords = await Promise.all(targetFeeds.map(feed => FailRecord.get(feed.url)))
const fetchedSchedules = await Promise.all(targetFeeds.map(feed => feed.determineSchedule(schedules, supporterGuilds)))
for (const record of failRecords) {
if (record) {
failRecordsMap[record._id] = record
}
}
let vipDetails = ''
if (supporter) {
vipDetails += '**Patron Until:** '
if (supporter.expireAt) {
const expireAt = moment(supporter.expireAt)
const daysLeft = Math.round(moment.duration(expireAt.diff(moment())).asDays())
vipDetails += `${expireAt.format('D MMMM YYYY')} (${daysLeft} days)\n`
} else {
vipDetails += 'Ongoing\n'
}
} else {
vipDetails = '\n'
}
const desc = maxFeedsAllowed === 0
? `${vipDetails}\u200b\n`
: `${vipDetails}**${translate('commands.list.serverLimit')}:** ${targetFeeds.length}/${maxFeedsAllowed} [+](https://www.patreon.com/monitorss)\n\n\u200b`
const list = new ThemedEmbed()
.setDescription(desc)
const countString = targetFeeds.length === feeds.length ? targetFeeds.length : `${targetFeeds.length}/${feeds.length} total`
if (!channel) {
list.setAuthor(translate('commands.list.feedList') + ` (${countString})`)
} else {
list.setAuthor(translate('commands.list.feedListChannel', {
channel: channel.name
}) + ` (${countString})`)
}
if (supporter) {
list.setFooter(`Patronage backed by ${supporter._id}`)
}
const menu = new MenuEmbed(list)
.enablePagination(handlePaginationError)
let someFailed = false
targetFeeds.forEach((feed, index) => {
// URL
const url = feed.url.length > 500 ? translate('commands.list.exceeds500Characters') : feed.url
// Title
const title = feed.title
// Channel
const atLimit = channelsAtLimit.has(feed.channel)
const channel = `<#${feed.channel}>${atLimit ? ` (${translate('commands.list.channelLimitReached')})` : ''}`
// Status
const failRecord = failRecordsMap[feed.url]
let status = ''
if (feed.disabled) {
status = translate('commands.list.statusDisabled', { reason: feed.disabled })
} else if (failRecord && failRecord.hasFailed()) {
status = translate('commands.list.statusFailed')
someFailed = true
} else if (failRecord && !failRecord.hasFailed()) {
// Determine hours between config spec and now, then calculate health
const hours = (new Date().getTime() - new Date(failRecord.failedAt).getTime()) / 36e5
const health = FailRecord.cutoff === 0 ? '(100% health)' : `(${100 - Math.ceil(hours / FailRecord.cutoff * 100)}% health)`
status = translate('commands.list.statusOk', { failCount: health })
} else {
status = translate('commands.list.statusOk', { failCount: '(100% health)' })
}
// Title checks
const titleChecks = feed.checkTitles === true
? translate('commands.list.titleChecksEnabled')
: ''
// Webhook
const webhook = feed.webhook
? `${translate('commands.list.webhook')}: ${feed.webhook.id}\n`
: ''
// Refresh rate
const schedule = fetchedSchedules[index]
let refreshRate = failRecord && failRecord.hasFailed()
? 'N/A'
: schedule.refreshRateMinutes < 1
? `${schedule.refreshRateMinutes * 60} ${translate('commands.list.seconds')}`
: `${schedule.refreshRateMinutes} ${translate('commands.list.minutes')}`
// : translate('commands.list.unknown')
// Patreon link
if (Supporter.enabled && !supporter) {
refreshRate += ' [-](https://www.patreon.com/monitorss)'
}
const name = `${title.length > 200 ? title.slice(0, 200) + '[...]' : title}`
const value = `${titleChecks}${status}${translate('commands.list.refreshRate')}: ${refreshRate}\n${translate('generics.channelUpper')}: ${channel}\n${webhook}${translate('commands.list.link')}: ${url}`
const number = feeds.indexOf(feed) + 1
menu.addOption(name, value, number)
})
if (someFailed) {
const failAlert = translate('commands.list.failAlert', {
prefix: profile && profile.prefix ? profile.prefix : config.bot.prefix
})
menu.embed.setDescription(`${menu.embed.description}${failAlert}\n\u200b`)
}
return new MenuVisual(menu)
}
const prompt = new LocalizedPrompt(listFeedVisual)
exports.visual = listFeedVisual
exports.prompt = prompt
|
module.exports={D:{"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0,"13":0,"14":0,"15":0,"16":0,"17":0,"18":0,"19":0,"20":0,"21":0,"22":0,"23":0,"24":0,"25":0,"26":0,"27":0,"28":0,"29":0,"30":0,"31":0,"32":0,"33":0,"34":0,"35":0,"36":0,"37":0,"38":0,"39":0.005236,"40":0.005236,"41":0,"42":0,"43":0.005236,"44":0,"45":0.005236,"46":0.020944,"47":0,"48":0,"49":0.188496,"50":0.005236,"51":0,"52":0.005236,"53":0,"54":0.005236,"55":0.005236,"56":0.005236,"57":0.015708,"58":0.02618,"59":0.005236,"60":0.010472,"61":0.005236,"62":0.010472,"63":0.151844,"64":0,"65":0.089012,"66":0.02618,"67":0.07854,"68":0.120428,"69":0.057596,"70":0.225148,"71":12.686828,"72":0.094248,"73":0.036652,"74":0,"75":0},C:{"2":0,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0,"13":0,"14":0,"15":0,"16":0,"17":0,"18":0,"19":0,"20":0,"21":0,"22":0,"23":0,"24":0,"25":0,"26":0,"27":0,"28":0,"29":0,"30":0,"31":0,"32":0,"33":0,"34":0,"35":0,"36":0,"37":0,"38":0.031416,"39":0,"40":0.005236,"41":0,"42":0,"43":0,"44":0,"45":0,"46":0,"47":0,"48":0,"49":0,"50":0.047124,"51":0.015708,"52":0.02618,"53":0.015708,"54":0,"55":0,"56":0.010472,"57":0,"58":0,"59":0,"60":0,"61":0.005236,"62":0.068068,"63":0.015708,"64":1.46608,"65":0.020944,"66":0,"67":0,"3.5":0,"3.6":0},F:{"9":0,"11":0,"12":0,"15":0,"16":0,"17":0.005236,"18":0,"19":0,"20":0,"21":0,"22":0,"23":0,"24":0,"25":0,"26":0,"27":0.02618,"28":0,"29":0,"30":0,"31":0,"32":0,"33":0,"34":0,"35":0,"36":0,"37":0,"38":0,"39":0,"40":0,"41":0,"42":0,"43":0,"44":0,"45":0,"46":0,"47":0,"48":0,"49":0.010472,"50":0,"51":0,"52":0,"53":0,"54":0,"55":0,"56":0.020944,"57":0.36652,"9.5-9.6":0,"10.0-10.1":0,"10.5":0,"10.6":0,"11.1":0,"11.5":0,"11.6":0,"12.1":0.005236},E:{"4":0,"5":0,"6":0,"7":0,"8":0,"9":0.005236,"10":0.031416,"11":0.047124,"12":0.60214,_:"0","3.1":0,"3.2":0,"5.1":0.005236,"6.1":0,"7.1":0,"9.1":0.015708,"10.1":0.068068,"11.1":0.089012},G:{"8":0.36150848653519,"3.2":0.0096586236860547,"4.0-4.1":0.0055192135348884,"4.2-4.3":0.0027596067674442,"5.0-5.1":0.015177837220943,"6.0-6.1":0.0096586236860547,"7.0-7.1":0.030355674441886,"8.1-8.4":0.066230562418661,"9.0-9.2":0.066230562418661,"9.3":0.30217694103514,"10.0-10.2":0.19869168725598,"10.3":0.41256121173291,"11.0-11.2":0.55330115687256,"11.3-11.4":1.3660053498849,"12.0-12.1":10.383020462509},I:{"3":0.0018796345776031,"4":0.25187103339882,_:"67","2.1":0.013157442043222,"2.2":0.041351960707269,"2.3":0.020675980353635,"4.1":0.18796345776031,"4.2-4.3":0.48682535559921,"4.4":0,"4.4.3-4.4.4":0.90974313555992},K:{_:"0 10 11 12 11.1 11.5 12.1"},A:{"6":0,"7":0,"8":0,"9":0.020944,"10":0.005236,"11":1.837836,"5.5":0},B:{"12":0.005236,"13":0.015708,"14":0.031416,"15":0.099484,"16":0.109956,"17":2.06822,_:"18"},P:{"4":0.30694127748691,"5.0-5.4":0.032886565445026,"6.2-6.4":0.098659696335079,_:"7.2-7.4 8.2"},N:{"10":0,"11":0.104808},J:{"7":0.0152448,"10":0.0609792},R:{_:"0"},M:{"0":0.109572},O:{"0":0.16674},Q:{_:"1.2"},H:{"0":0.35630954639175},L:{"0":55.350508}};
|
#!/usr/bin/env python
# -*- coding:utf8 -*-
# Copyright 2017, Schuberg Philis BV
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# Romero Galiza Jr. - rgaliza@schubergphilis.com
__all__ = ['billing', 'bppolicy', 'group', 'monitor', 'qos', 'ratingplan',
'system', 'tiering', 'usage', 'user', 'whitelist']
|
#input variables to Zapier Code Transfer Step 17: Update Smart Campaign Descriptions
input={
'token': 'Token', #from Step 4: Get Marketo Access Token
'parent id': 'fid', #from Step 5: Get Parent ID or Create Parent Folder
}
import re
import urllib.parse
import ast
mapping = ast.literal_eval(input['dict'])
search_string= '"id":(\d*),"name":'
smart_campaigns = re.findall(search_string,input['raw'] )
#print(smart_campaigns)
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Bearer' + input['token']
}
response =""
description = mapping['UTM']
for sc_id in smart_campaigns:
url = 'https://028-jjw-728.mktorest.com/rest/asset/v1/smartCampaign/'+sc_id+'.json'
payload = 'description=' + urllib.parse.quote(description)
response = response + requests.request("POST", url, headers=headers, data = payload).text
return {'id': 1234, 'rawHTML': response}
|
// Import the ORM to create functions that will interact with the database.
var orm = require("../config/orm.js");
var burger = {
// model to call the orm.selectAll to query all from table
all: function(cb){
orm.selectAll(function(res){
cb(res);
})
},
// model to call the orm.insertOne to insert a new burger
create: function(burger_name,cb){
orm.insertOne(burger_name,cb)
},
// model to call the orm.updateOne to update a burger and move to devoured
update: function(devoured, id, cb) {
orm.updateOne(devoured, id, function(res) {
cb(res);
});
},
};
// Export the database functions for the controller
module.exports = burger;
|
# coding: utf-8
import re
import six
from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization
class UpdateDomainApiAclPolicyRequestBody:
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
sensitive_list = []
openapi_types = {
'api_acl_policy': 'AclPolicyOption'
}
attribute_map = {
'api_acl_policy': 'api_acl_policy'
}
def __init__(self, api_acl_policy=None):
"""UpdateDomainApiAclPolicyRequestBody - a model defined in huaweicloud sdk"""
self._api_acl_policy = None
self.discriminator = None
self.api_acl_policy = api_acl_policy
@property
def api_acl_policy(self):
"""Gets the api_acl_policy of this UpdateDomainApiAclPolicyRequestBody.
:return: The api_acl_policy of this UpdateDomainApiAclPolicyRequestBody.
:rtype: AclPolicyOption
"""
return self._api_acl_policy
@api_acl_policy.setter
def api_acl_policy(self, api_acl_policy):
"""Sets the api_acl_policy of this UpdateDomainApiAclPolicyRequestBody.
:param api_acl_policy: The api_acl_policy of this UpdateDomainApiAclPolicyRequestBody.
:type: AclPolicyOption
"""
self._api_acl_policy = api_acl_policy
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
if attr in self.sensitive_list:
result[attr] = "****"
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
import simplejson as json
if six.PY2:
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
return json.dumps(sanitize_for_serialization(self), ensure_ascii=False)
def __repr__(self):
"""For `print`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, UpdateDomainApiAclPolicyRequestBody):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
|
var searchData=
[
['real_1186',['Real',['../namespaceioh_1_1problem.html#a58542a542875ac11e6f3171393038ee4',1,'ioh::problem']]],
['referencetype_1187',['ReferenceType',['../structioh_1_1suite_1_1_suite_1_1_iterator.html#ab95d88e4d8ce452ee6769d5d23c36515',1,'ioh::suite::Suite::Iterator']]],
['reftype_1188',['RefType',['../classioh_1_1watch_1_1_pointer_reference.html#a5c29cb86a5786e7acfbdf7878d09fd18',1,'ioh::watch::PointerReference']]],
['run_1189',['Run',['../classioh_1_1logger_1_1_store.html#aa7e63e4ca2b07673a67500761987e102',1,'ioh::logger::Store']]],
['runs_1190',['Runs',['../classioh_1_1logger_1_1_store.html#a42ffc5a584ec41bf60be4ab1708b6e95',1,'ioh::logger::Store']]]
];
|
/*
@功能:购物车页面js
@作者:diamondwang
@时间:2013年11月14日
*/
$(function(){
//减少
$(".reduce_num").click(function(){
var amount = $(this).parent().find(".amount");
if (parseInt($(amount).val()) <= 1){
alert("商品数量最少为1");
} else{
$(amount).val(parseInt($(amount).val()) - 1);
}
//小计
var subtotal = parseFloat($(this).parent().parent().find(".col3 span").text()) * parseInt($(amount).val());
$(this).parent().parent().find(".col5 span").text(subtotal.toFixed(2));
//总计金额
var total = 0;
$(".col5 span").each(function(){
total += parseFloat($(this).text());
});
$("#total").text(total.toFixed(2));
changeAmount($(this).closest('tr').attr('data_id'),$(amount).val());
});
//增加
$(".add_num").click(function(){
var amount = $(this).parent().find(".amount");
$(amount).val(parseInt($(amount).val()) + 1);
//小计
var subtotal = parseFloat($(this).parent().parent().find(".col3 span").text()) * parseInt($(amount).val());
$(this).parent().parent().find(".col5 span").text(subtotal.toFixed(2));
//总计金额
var total = 0;
$(".col5 span").each(function(){
total += parseFloat($(this).text());
});
$("#total").text(total.toFixed(2));
changeAmount($(this).closest('tr').attr('data_id'),$(amount).val());
});
//直接输入
$(".amount").blur(function(){
var amount = $(this).parent().find(".amount");
if (parseInt($(this).val()) < 1){
alert("商品数量最少为1");
$(this).val(1);
}
//小计
var subtotal = parseFloat($(this).parent().parent().find(".col3 span").text()) * parseInt($(this).val());
$(this).parent().parent().find(".col5 span").text(subtotal.toFixed(2));
//总计金额
var total = 0;
$(".col5 span").each(function(){
total += parseFloat($(this).text());
});
$("#total").text(total.toFixed(2));
changeAmount($(this).closest('tr').attr('data_id'),$(amount).val());
});
//删除
$('#del').click(function () {
if(confirm('你确定删除吗?')){
changeAmount($(this).closest('tr').attr('data_id'),0);
$(this).closest('tr').remove();
}
});
var total = 0;
$(".col5 span").each(function(){
total += parseFloat($(this).text());
});
$("#total").text(total.toFixed(2));
});
function changeAmount(goods_id,amount) {
$.get("/cart/ajax-cart.html",{goods_id:goods_id,amount:amount})
}
|
//------------------------------------------------------------------------------
// Author: Lukasz Janyst <lukasz@jany.st>
// Date: 30.01.2018
//
// Licensed under the 3-Clause BSD License, see the LICENSE file for details.
//------------------------------------------------------------------------------
import { makeId } from './helpers';
//------------------------------------------------------------------------------
// Backend
//------------------------------------------------------------------------------
export class Backend {
//----------------------------------------------------------------------------
// Constants
//----------------------------------------------------------------------------
static CONNECTING = 0;
static OPENED = 1;
static CLOSED = 2;
static MSG_RECEIVED = 3;
static COUNTDOWN = 4;
static REMOVE_LISTENER = 0;
//----------------------------------------------------------------------------
// Constructor
//----------------------------------------------------------------------------
constructor() {
const loc = window.location;
const wsProtocol = loc.protocol === 'https:' ? 'wss:' : 'ws:';
this.wsUrl =
process.env.NODE_ENV === 'production'
? `${wsProtocol}//${loc.host}/ws`
: 'ws://localhost:7654/ws';
this.ws = null;
this.countdownTimer = null;
this.countdown = 0;
this.nextTry = 2;
this.eventListeners = new Set();
this.connect();
}
//----------------------------------------------------------------------------
// Connect
//----------------------------------------------------------------------------
connect = () => {
//--------------------------------------------------------------------------
// Check and clear the existing state
//--------------------------------------------------------------------------
if(this.ws)
throw Error('Socket not closed');
if(this.countdownTimer)
clearInterval(this.countdownTimer);
//--------------------------------------------------------------------------
// Attempt the connection
//--------------------------------------------------------------------------
this.dispatchEvent(Backend.CONNECTING, null);
this.ws = new WebSocket(this.wsUrl);
//--------------------------------------------------------------------------
// On open
//--------------------------------------------------------------------------
this.ws.onopen = () => {
this.dispatchEvent(Backend.OPENED, null);
this.nextTry = 2;
};
//--------------------------------------------------------------------------
// On Message
//--------------------------------------------------------------------------
this.ws.onmessage = (evt) => {
const message = JSON.parse(evt.data);
this.dispatchEvent(Backend.MSG_RECEIVED, message);
};
//--------------------------------------------------------------------------
// On Close
//--------------------------------------------------------------------------
this.ws.onclose = () => {
this.dispatchEvent(Backend.CLOSED, null);
this.ws = null;
this.nextTry *= 2;
if(this.nextTry > 256)
this.nextTry = 256;
this.countdown = this.nextTry - 1;
this.dispatchEvent(Backend.COUNTDOWN, this.countdown + 1);
const tick = () => {
this.dispatchEvent(Backend.COUNTDOWN, this.countdown);
if(this.countdown === 0) {
this.connect();
return;
}
this.countdown -= 1;
};
this.countdownTimer = setInterval(tick, 1000);
};
};
//----------------------------------------------------------------------------
// Add event listener
//----------------------------------------------------------------------------
addEventListener = (listener) => {
this.eventListeners.add(listener);
}
//----------------------------------------------------------------------------
// Remove an event listener
//----------------------------------------------------------------------------
removeEventListener = (listener) => {
this.eventListeners.delete(listener);
}
//----------------------------------------------------------------------------
// Dispatch event
//----------------------------------------------------------------------------
dispatchEvent = (event, data) => {
let toRemove = [];
for(const listener of this.eventListeners) {
let ret = listener(event, data);
if(ret === Backend.REMOVE_LISTENER)
toRemove.push(listener);
}
for(const listener of toRemove)
this.removeEventListener(listener);
}
//----------------------------------------------------------------------------
// Send message
//----------------------------------------------------------------------------
sendMessage = (message) => {
//--------------------------------------------------------------------------
// Only send messages if we're connected
//--------------------------------------------------------------------------
if(!this.ws || this.ws.readyState !== WebSocket.OPEN)
return Promise.reject(new Error('Backend not connected.'));
//--------------------------------------------------------------------------
// Wrap the message
//--------------------------------------------------------------------------
const id = makeId(32);
const newMessage = Object.assign(message, {
type: 'ACTION',
id
});
return new Promise((resolve, reject) => {
//------------------------------------------------------------------------
// Listener handling the answer
//------------------------------------------------------------------------
const listener = (event, data) => {
//----------------------------------------------------------------------
// Disconnected, the answer will never arrive
//----------------------------------------------------------------------
if(event === Backend.CLOSED) {
reject(new Error('Backend disconnected'));
return Backend.REMOVE_LISTENER;
}
//----------------------------------------------------------------------
// We got the response
//----------------------------------------------------------------------
if(event === Backend.MSG_RECEIVED && data.type === 'ACTION_EXECUTED'
&& data.id === id) {
if(data.status === 'OK') {
let cleanData = Object.assign(data);
delete cleanData.type;
delete cleanData.id;
delete cleanData.status;
resolve(cleanData);
}
else
reject(new Error(data.message));
return Backend.REMOVE_LISTENER;
}
return null;
};
//------------------------------------------------------------------------
// Register the resposne listener and send the message
//------------------------------------------------------------------------
this.addEventListener(listener);
this.ws.send(JSON.stringify(newMessage));
});
}
};
//------------------------------------------------------------------------------
// The backend
//------------------------------------------------------------------------------
export let backend = new Backend();
|
"""home URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include('fbapp.urls')),
]
|
import os
from ROOT import *
values = open("RA7table.txt").readlines()
print "Creating RA7 OnZ and OffZ signal regions plots..."
gStyle.SetOptStat(0)
OnZstack = THStack("OnZstack", "RA7 table: OnZ signal regions")
hOnZ = TH1F("hOnZ", "RA7 table: OnZ signal regions", 15, 0, 15)
hOnZ.SetFillColor(38)
hOnZerror = TH1F("hOnZerror", "RA7 table: OnZ signal regions", 15, 0, 15)
hOnZerror.SetFillColor(1)
hOnZerror.SetMarkerColor(1)
hOnZerror.SetFillStyle(3018);
hOnZdata = TH1F("hOnZdata", "RA7 table: OnZ signal regions", 15, 0, 15)
hOnZdata.SetMarkerStyle(33)
hOnZdata.SetMarkerColor(kRed)
for i in range(0, 15):
rate = values[i].split()
for x in range(0, len(rate)):
hOnZ.GetXaxis().SetBinLabel(i+1, "SR"+str(i+1))
hOnZ.SetBinContent(i+1, float(rate[2]))
hOnZerror.GetXaxis().SetBinLabel(i+1, "SR"+str(i+1))
hOnZerror.SetBinContent(i+1, float(rate[2]))
hOnZerror.SetBinError(i+1, float(rate[4])+float(rate[6]))
hOnZdata.GetXaxis().SetBinLabel(i+1, "SR"+str(i+1))
hOnZdata.SetBinContent(i+1, float(rate[0]))
OnZstack.Add(hOnZ, "B")
OnZstack.Add(hOnZerror, "E2")
OnZstack.Add(hOnZdata, "P0")
OnZstack.Draw("nostack")
OnZstack.GetYaxis().SetTitle("Rate")
c1.SaveAs("RA7_OnZ_SR.pdf")
OffZstack = THStack("OffZstack", "RA7 table: OffZ signal regions")
hOffZ = TH1F("hOffZ", "RA7 table: OffZ signal regions", 15, 0, 15)
hOffZ.SetFillColor(38)
hOffZerror = TH1F("hOffZerror", "RA7 table: OffZ signal regions", 15, 0, 15)
hOffZerror.SetFillColor(1)
hOffZerror.SetMarkerColor(1)
hOffZerror.SetFillStyle(3018);
hOffZdata = TH1F("hOffZdata", "RA7 table: OffZ signal regions", 15, 0, 15)
hOffZdata.SetMarkerStyle(33)
hOffZdata.SetMarkerColor(kRed)
for j in range(15, 30):
rate = values[j].split()
for y in range(0, len(rate)):
hOffZ.GetXaxis().SetBinLabel(j-14, "SR"+str(j-14))
hOffZ.SetBinContent(j-14, float(rate[2]))
hOffZerror.GetXaxis().SetBinLabel(j-14, "SR"+str(j-14))
hOffZerror.SetBinContent(j-14, float(rate[2]))
hOffZerror.SetBinError(j-14, float(rate[4])+float(rate[6]))
hOffZdata.GetXaxis().SetBinLabel(j-14, "SR"+str(j-14))
hOffZdata.SetBinContent(j-14, float(rate[0]))
OffZstack.Add(hOffZ, "B")
OffZstack.Add(hOffZerror, "E2")
OffZstack.Add(hOffZdata, "P0")
OffZstack.Draw("nostack")
OffZstack.GetYaxis().SetTitle("Rate")
c1.SaveAs("RA7_OffZ_SR.pdf")
with open('RA7table.tex', 'wb') as texfile:
texfile.write("\\documentclass[a4paper,11pt,landscape]{article}\n")
texfile.write("\\usepackage[landscape]{geometry}\n")
texfile.write("\\usepackage{fixltx2e}\n")
texfile.write("\\usepackage{hyperref}\n")
texfile.write("\\usepackage{multirow}\n")
texfile.write("\\usepackage{graphicx}\n")
texfile.write("\\begin{document}\n")
texfile.write("\\renewcommand{\\arraystretch}{2}\n")
texfile.write("\\begin{center}\n")
texfile.write("\\large{Baseline selection: 3 tight leptons with $p_T > 20 / 15 / 10$ GeV, min. 2 jets, $E^{miss}_T > 50$ GeV and $M_{ll} \geq 12$ GeV}\\normalsize \\\\ \\vspace{2cm}\n")
texfile.write("\\begin{tabular}{|c|c|c|c|c|}\n")
texfile.write("\\hline \n")
texfile.write("b-tags & $E^{miss}_T$ & $60 < H_T \leq 400$ & $400 \leq H_T < 600$ & $H_T \geq 600$\\\\ \n")
texfile.write("\\hline \n")
texfile.write("\\multirow{2}{*}{0 b-tags} & $50 \leq E^{miss}_T < 150$ & SR1 & SR3 & \multirow{7}{*}{SR14}\\\\ \n")
texfile.write("\\cline{2-4} \n")
texfile.write("& $150 \leq E^{miss}_T < 300$ & SR2 & SR4 &\\\\ \n")
texfile.write("\\cline{1-4}\n")
texfile.write("\\multirow{2}{*}{1 b-tag} & $50 \leq E^{miss}_T < 150$ & SR5 & SR7 &\\\\ \n")
texfile.write("\\cline{2-4}\n")
texfile.write("& $150 \leq E^{miss}_T < 300$ & SR6 & SR8 &\\\\ \n")
texfile.write("\\cline{1-4}\n")
texfile.write("\\multirow{2}{*}{2 b-tags} & $50 \leq E^{miss}_T < 150$ & SR9 & SR11 &\\\\ \n")
texfile.write("\\cline{2-4}\n")
texfile.write("& $150 \leq E^{miss}_T < 300$ & SR10 & SR12 &\\\\ \n")
texfile.write("\\cline{1-4}\n")
texfile.write("$ \geq 3$ b-tags & $50 \leq E^{miss}_T < 300$ & \multicolumn{2}{|c|}{SR13} &\\\\ \n")
texfile.write("\\hline \n")
texfile.write("inclusive & $E^{miss}_T \geq 300$ & \multicolumn{3}{|c|}{SR15} \\\\ \n")
texfile.write("\\hline \n")
texfile.write("\\end{tabular} \\\\ \\vspace{0.2cm} \n")
texfile.write("\\newpage \n")
texfile.write("\\large{Baseline selection: 3 tight leptons with $p_T > 20 / 15 / 10$ GeV, min. 2 jets, $E^{miss}_T > 50$ GeV and $M_{ll} \geq 12$ GeV}\\normalsize \\\\ \\vspace{1cm}\n")
texfile.write("OnZ signal regions: OSSF-pair with $76 < M_{ll} < 106$ GeV \\ \\vspace{0.5cm} \\\\ \n")
texfile.write("\\begin{tabular}{|c|c|c|c|c|}\n")
texfile.write("\\hline \n")
texfile.write("b-tags & $E^{miss}_T$ & $60 < H_T \leq 400$ & $400 \leq H_T < 600$ & $H_T \geq 600$\\\\ \n")
texfile.write("\\hline \n")
texfile.write("\\multirow{2}{*}{0 b-tags} & $50 \leq E^{miss}_T < 150$ & ")
texfile.write(values[0])
texfile.write(" & ")
texfile.write(values[2])
texfile.write(" & \multirow{7}{*}{")
texfile.write(values[13])
texfile.write("}\\\\ \n")
texfile.write("\\cline{2-4} \n")
texfile.write("& $150 \leq E^{miss}_T < 300$ & ")
texfile.write(values[1])
texfile.write(" & ")
texfile.write(values[3])
texfile.write(" &\\\\ \n")
texfile.write("\\cline{1-4}\n")
texfile.write("\\multirow{2}{*}{1 b-tag} & $50 \leq E^{miss}_T < 150$ & ")
texfile.write(values[4])
texfile.write(" & ")
texfile.write(values[6])
texfile.write(" &\\\\ \n")
texfile.write("\\cline{2-4}\n")
texfile.write("& $150 \leq E^{miss}_T < 300$ & ")
texfile.write(values[5])
texfile.write(" & ")
texfile.write(values[7])
texfile.write(" &\\\\ \n")
texfile.write("\\cline{1-4}\n")
texfile.write("\\multirow{2}{*}{2 b-tags} & $50 \leq E^{miss}_T < 150$ & ")
texfile.write(values[8])
texfile.write(" & ")
texfile.write(values[10])
texfile.write(" &\\\\ \n")
texfile.write("\\cline{2-4}\n")
texfile.write("& $150 \leq E^{miss}_T < 300$ & ")
texfile.write(values[9])
texfile.write(" & ")
texfile.write(values[11])
texfile.write(" &\\\\ \n")
texfile.write("\\cline{1-4}\n")
texfile.write("$ \geq 3$ b-tags & $50 \leq E^{miss}_T < 300$ & \multicolumn{2}{|c|}{")
texfile.write(values[12])
texfile.write("} &\\\\ \n")
texfile.write("\\hline \n")
texfile.write("inclusive & $E^{miss}_T \geq 300$ & \multicolumn{3}{|c|}{")
texfile.write(values[14])
texfile.write("}\\\\ \n")
texfile.write("\\hline \n")
texfile.write("\\end{tabular} \\\\ \\vspace{0.2cm} \n")
texfile.write("Explanation of rates: \\quad $\\textrm{observed : expected } \\pm \\textrm{ stat } \\pm \\textrm{ syst}$")
texfile.write("\\newpage \n")
texfile.write("\\large{Baseline selection: 3 tight leptons with $p_T > 20 / 15 / 10$ GeV, min. 2 jets, $E^{miss}_T > 50$ GeV and $M_{ll} \geq 12$ GeV}\\normalsize \\\\ \\vspace{1cm}\n")
texfile.write("OffZ signal regions: OSSF-pair with $M_{ll} < 76$ GeV or $M_{ll} > 106$ GeV \\\\ \\vspace{0.5cm}\n")
texfile.write("\\begin{tabular}{|c|c|c|c|c|}\n")
texfile.write("\\hline \n")
texfile.write("b-tags & $E^{miss}_T$ & $60 < H_T \leq 400$ & $400 \leq H_T < 600$ & $H_T \geq 600$\\\\ \n")
texfile.write("\\hline \n")
texfile.write("\\multirow{2}{*}{0 b-tags} & $50 \leq E^{miss}_T < 150$ & ")
texfile.write(values[15])
texfile.write(" & ")
texfile.write(values[17])
texfile.write(" & \multirow{7}{*}{")
texfile.write(values[28])
texfile.write("}\\\\ \n")
texfile.write("\\cline{2-4} \n")
texfile.write("& $150 \leq E^{miss}_T < 300$ & ")
texfile.write(values[16])
texfile.write(" & ")
texfile.write(values[18])
texfile.write(" &\\\\ \n")
texfile.write("\\cline{1-4}\n")
texfile.write("\\multirow{2}{*}{1 b-tag} & $50 \leq E^{miss}_T < 150$ & ")
texfile.write(values[19])
texfile.write(" & ")
texfile.write(values[21])
texfile.write(" &\\\\ \n")
texfile.write("\\cline{2-4}\n")
texfile.write("& $150 \leq E^{miss}_T < 300$ & ")
texfile.write(values[20])
texfile.write(" & ")
texfile.write(values[22])
texfile.write(" &\\\\ \n")
texfile.write("\\cline{1-4}\n")
texfile.write("\\multirow{2}{*}{2 b-tags} & $50 \leq E^{miss}_T < 150$ & ")
texfile.write(values[23])
texfile.write(" & ")
texfile.write(values[25])
texfile.write(" &\\\\ \n")
texfile.write("\\cline{2-4}\n")
texfile.write("& $150 \leq E^{miss}_T < 300$ & ")
texfile.write(values[24])
texfile.write(" & ")
texfile.write(values[26])
texfile.write(" &\\\\ \n")
texfile.write("\\cline{1-4}\n")
texfile.write("$ \geq 3$ b-tags & $50 \leq E^{miss}_T < 300$ & \multicolumn{2}{|c|}{")
texfile.write(values[27])
texfile.write("} &\\\\ \n")
texfile.write("\\hline \n")
texfile.write("inclusive & $E^{miss}_T \geq 300$ & \multicolumn{3}{|c|}{")
texfile.write(values[29])
texfile.write("}\\\\ \n")
texfile.write("\\hline \n")
texfile.write("\\end{tabular} \\\\ \\vspace{0.2cm} \n")
texfile.write("Explanation of rates: \\quad $\\textrm{observed : expected } \\pm \\textrm{ stat } \\pm \\textrm{ syst}$")
texfile.write("\\newpage \n")
texfile.write("\\begin{figure}[htbp] \n")
texfile.write("\\includegraphics{RA7_OnZ_SR.pdf} \n")
texfile.write("\\end{figure} \n")
texfile.write("\\newpage \n")
texfile.write("\\begin{figure}[htbp] \n")
texfile.write("\\includegraphics{RA7_OffZ_SR.pdf} \n")
texfile.write("\\end{figure} \n")
texfile.write("\\end{center}\n")
texfile.write("\\renewcommand{\\arraystretch}{1}\n")
texfile.write("\\end{document}\n")
texfile.close()
os.system("pdflatex RA7table.tex")
os.remove("RA7table.tex")
os.remove("RA7table.log")
os.remove("RA7table.aux")
os.remove("RA7table.out")
os.remove("RA7_OnZ_SR.pdf")
os.remove("RA7_OffZ_SR.pdf")
|
var m, m1;
!function(m) {
var x, m2;
m2 || (m2 = {}), "string" == typeof x || ("boolean" == typeof x, x.toString());
}(m || (m = {})), (function(m1) {
var x, m2, m21;
(m21 = m2 || (m2 = {})).m3 || (m21.m3 = {}), "string" == typeof x || ("boolean" == typeof x, x.toString());
})(m1 || (m1 = {}));
|
from django.contrib import admin
from django.urls import re_path
from dashboard import views
urlpatterns = [
re_path(r'^$', views.dashboardCurrentTime),
re_path(r'^t=(\d{2}):(\d{2}):(\d{2})$', views.dashboardRequestTime),
]
|
import BombSweeper from 'bombsweeper.js';
const default_replaces = {
"N": "🟩",
"*": "💣",
"0": "⬜",
"e0": "0️⃣",
"1": "1️⃣",
"2": "2️⃣",
"3": "3️⃣",
"4": "4️⃣",
"5": "5️⃣",
"6": "6️⃣",
"7": "7️⃣",
"8": "8️⃣",
"F": "🚩"
};
export default class extends BombSweeper {
constructor(width = 9, height = 9, onWin = () => { }, onLoss = () => { }, replaces = default_replaces) {
super(width, height, onWin, onLoss);
this.replaces = replaces;
this.flags = [];
}
setFlag(x, y) {
this.checkValue(x, y);
if (this.flags.find(a => a[0] == x && a[1] == y)) throw new Error("The chosen position is already flagged.");
if (this.mask[y][x]) throw new Error("You cannot flag an already revealed box.")
this.flags.push([x, y]);
return this;
}
removeFlag(x, y) {
this.checkValue(x, y);
const found = this.flags.find(a => a[0] == x && a[1] == y);
if (found) {
const new_arr = this.flags.filter(a => !(a[0] == x && a[1] == y));
this.flags = new_arr;
return this;
} else throw new Error("The chosen position isn't flagged.");
}
CheckCell(x, y) {
this.checkValue(x, y);
if (this.flags.find(a => a[0] == x && a[1] == y)) throw new Error("The chosen position is flagged. You cannot reveal it.");
super.CheckCell(x, y);
return this;
}
showToUser() {
let str = "";
for (const i in this.board) {
for (const o in this.board[i]) {
if (o == 0) str += "`" + this.replaces[i == 0 ? "e0" : i] + "`";
if (this.mask[i][o]) str += this.replaces[this.board[i][o]];
else {
if (this.flags.find(a => a[0] == o && a[1] == i)) str += this.replaces["F"];
else str += this.replaces["N"];
}
}
str += "\n";
}
str += `\`🟥`;
for (let i = 0; i < this.width; i++) {
str += `${this.replaces[i == 0 ? "e0" : i]}${(i % 2) ? "" : " "}${(this.width - 1) == i ? "`" : ""}`;
}
return str;
}
checkValue(x, y) {
if (typeof x !== 'number') throw new Error("'x' must be an integer");
if (typeof y !== 'number') throw new Error("'y' must be an integer");
if (x > (this.width - 1)) throw new Error("'x' must be less than the width");
if (y > (this.height - 1)) throw new Error("'y' must be less than the height");
if (x < 0) throw new Error("'x' must not be less than 0");
if (y < 0) throw new Error("'x' must not be less than 0");
return true;
}
}
|
import os
from conan.tools.files import load_toolchain_args
from conan.tools.gnu.make import make_jobs_cmd_line_arg
from conan.tools.microsoft import unix_path
from conans.client.build import join_arguments
class Autotools(object):
def __init__(self, conanfile):
self._conanfile = conanfile
toolchain_file_content = load_toolchain_args(self._conanfile.generators_folder)
self._configure_args = toolchain_file_content.get("configure_args")
self._make_args = toolchain_file_content.get("make_args")
def configure(self, build_script_folder=None):
"""
http://jingfenghanmax.blogspot.com.es/2010/09/configure-with-host-target-and-build.html
https://gcc.gnu.org/onlinedocs/gccint/Configure-Terms.html
"""
# FIXME: Conan 2.0 Are we keeping the "should_XXX" properties???
if not self._conanfile.should_configure:
return
source = self._conanfile.source_folder
if build_script_folder:
source = os.path.join(self._conanfile.source_folder, build_script_folder)
configure_cmd = "{}/configure".format(source)
configure_cmd = unix_path(self._conanfile, configure_cmd)
cmd = "{} {}".format(configure_cmd, self._configure_args)
self._conanfile.output.info("Calling:\n > %s" % cmd)
self._conanfile.run(cmd)
def make(self, target=None):
make_program = self._conanfile.conf["tools.gnu:make_program"]
if make_program is None:
make_program = "mingw32-make" if self._use_win_mingw() else "make"
str_args = self._make_args
jobs = ""
if "-j" not in str_args and "nmake" not in make_program.lower():
jobs = make_jobs_cmd_line_arg(self._conanfile) or ""
command = join_arguments([make_program, target, str_args, jobs])
self._conanfile.run(command)
def install(self):
if not self._conanfile.should_install:
return
self.make(target="install")
def _use_win_mingw(self):
if hasattr(self._conanfile, 'settings_build'):
os_build = self._conanfile.settings_build.get_safe('os')
else:
os_build = self._conanfile.settings.get_safe("os")
if os_build == "Windows":
compiler = self._conanfile.settings.get_safe("compiler")
sub = self._conanfile.settings.get_safe("os.subsystem")
if sub in ("cygwin", "msys2", "msys") or compiler == "qcc":
return False
else:
if self._conanfile.win_bash:
return False
return True
return False
|
import numpy as np
import matplotlib.pyplot as plt
import scipy.stats as ss
from matplotlib.animation import FuncAnimation
class UpdateDist(object):
def __init__(self, ax, prob=0.5):
self.success = 0
self.prob = prob
self.line, = ax.plot([], [], 'k-')
self.x = np.linspace(0, 1, 200)
self.ax = ax
# Set up plot parameters
self.ax.set_xlim(0, 1)
self.ax.set_ylim(0, 15)
self.ax.grid(True)
# This vertical line represents the theoretical value, to
# which the plotted distribution should converge.
self.ax.axvline(prob, linestyle='--', color='black')
def init(self):
self.success = 0
self.line.set_data([], [])
return self.line,
def __call__(self, i):
# This way the plot can continuously run and we just keep
# watching new realizations of the process
if i == 0:
return self.init()
# Choose success based on exceed a threshold with a uniform pick
if np.random.rand(1,) < self.prob:
self.success += 1
y = ss.beta.pdf(self.x, self.success + 1, (i - self.success) + 1)
self.line.set_data(self.x, y)
return self.line,
fig, ax = plt.subplots()
ud = UpdateDist(ax, prob=0.7)
anim = FuncAnimation(fig, ud, frames=np.arange(100), init_func=ud.init,
interval=100, blit=True)
plt.show()
|
/**
* tng.js - png reader
* Copyright (c) 2015, Christopher Jeffrey (MIT License).
* https://github.com/chjj/tng
*/
var fs = require('fs')
, util = require('util')
, path = require('path')
, zlib = require('zlib')
, assert = require('assert')
, cp = require('child_process')
, exec = cp.execFileSync;
/**
* PNG
*/
function PNG(file, options) {
var buf
, chunks
, idat
, pixels;
if (!(this instanceof PNG)) {
return new PNG(file, options);
}
if (!file) throw new Error('no file');
this.options = options || {};
this.colors = options.colors || require('blessed/lib/colors');
this.optimization = this.options.optimization || 'mem';
this.speed = this.options.speed || 1;
if (Buffer.isBuffer(file)) {
this.file = this.options.filename || null;
buf = file;
} else {
this.options.filename = file;
this.file = path.resolve(process.cwd(), file);
buf = fs.readFileSync(this.file);
}
this.format = buf.readUInt32BE(0) === 0x89504e47 ? 'png'
: buf.slice(0, 3).toString('ascii') === 'GIF' ? 'gif'
: buf.readUInt16BE(0) === 0xffd8 ? 'jpg'
: path.extname(this.file).slice(1).toLowerCase() || 'png';
if (this.format !== 'png') {
try {
return this.toPNG(buf);
} catch (e) {
throw e;
}
}
chunks = this.parseRaw(buf);
idat = this.parseChunks(chunks);
pixels = this.parseLines(idat);
this.bmp = this.createBitmap(pixels);
this.cellmap = this.createCellmap(this.bmp);
this.frames = this.compileFrames(this.frames);
}
PNG.prototype.parseRaw = function(buf) {
var chunks = []
, index = 0
, i = 0
, buf
, len
, type
, name
, data
, crc
, check
, critical
, public_
, conforming
, copysafe
, pos;
this._debug(this.file);
if (buf.readUInt32BE(0) !== 0x89504e47
|| buf.readUInt32BE(4) !== 0x0d0a1a0a) {
throw new Error('bad header');
}
i += 8;
while (i < buf.length) {
try {
len = buf.readUInt32BE(i);
i += 4;
pos = i;
type = buf.slice(i, i + 4);
name = type.toString('ascii');
i += 4;
data = buf.slice(i, i + len);
i += len;
check = this.crc32(buf.slice(pos, i));
crc = buf.readInt32BE(i);
i += 4;
critical = !!(~type[0] & 32);
public_ = !!(~type[1] & 32);
conforming = !!(~type[2] & 32);
copysafe = !!(~type[3] & 32);
if (crc !== check) {
throw new Error(name + ': bad crc');
}
} catch (e) {
if (this.options.debug) throw e;
break;
}
chunks.push({
index: index++,
id: name.toLowerCase(),
len: len,
pos: pos,
end: i,
type: type,
name: name,
data: data,
crc: crc,
check: check,
raw: buf.slice(pos, i),
flags: {
critical: critical,
public_: public_,
conforming: conforming,
copysafe: copysafe
}
});
}
return chunks;
};
PNG.prototype.parseChunks = function(chunks) {
var i
, chunk
, name
, data
, p
, idat
, info;
for (i = 0; i < chunks.length; i++) {
chunk = chunks[i];
name = chunk.id;
data = chunk.data;
info = {};
switch (name) {
case 'ihdr': {
this.width = info.width = data.readUInt32BE(0);
this.height = info.height = data.readUInt32BE(4);
this.bitDepth = info.bitDepth = data.readUInt8(8);
this.colorType = info.colorType = data.readUInt8(9);
this.compression = info.compression = data.readUInt8(10);
this.filter = info.filter = data.readUInt8(11);
this.interlace = info.interlace = data.readUInt8(12);
switch (this.bitDepth) {
case 1: case 2: case 4: case 8: case 16: case 24: case 32: break;
default: throw new Error('bad bit depth: ' + this.bitDepth);
}
switch (this.colorType) {
case 0: case 2: case 3: case 4: case 6: break;
default: throw new Error('bad color: ' + this.colorType);
}
switch (this.compression) {
case 0: break;
default: throw new Error('bad compression: ' + this.compression);
}
switch (this.filter) {
case 0: case 1: case 2: case 3: case 4: break;
default: throw new Error('bad filter: ' + this.filter);
}
switch (this.interlace) {
case 0: case 1: break;
default: throw new Error('bad interlace: ' + this.interlace);
}
break;
}
case 'plte': {
this.palette = info.palette = [];
for (p = 0; p < data.length; p += 3) {
this.palette.push({
r: data[p + 0],
g: data[p + 1],
b: data[p + 2],
a: 255
});
}
break;
}
case 'idat': {
this.size = this.size || 0;
this.size += data.length;
this.idat = this.idat || [];
this.idat.push(data);
info.size = data.length;
break;
}
case 'iend': {
this.end = true;
break;
}
case 'trns': {
this.alpha = info.alpha = Array.prototype.slice.call(data);
if (this.palette) {
for (p = 0; p < data.length; p++) {
if (!this.palette[p]) break;
this.palette[p].a = data[p];
}
}
break;
}
// https://wiki.mozilla.org/APNG_Specification
case 'actl': {
this.actl = info = {};
this.frames = [];
this.actl.numFrames = data.readUInt32BE(0);
this.actl.numPlays = data.readUInt32BE(4);
break;
}
case 'fctl': {
// IDAT is the first frame depending on the order:
// IDAT is a frame: acTL->fcTL->IDAT->[fcTL]->fdAT
// IDAT is not a frame: acTL->IDAT->[fcTL]->fdAT
if (!this.idat) {
this.idat = [];
this.frames.push({
idat: true,
fctl: info,
fdat: this.idat
});
} else {
this.frames.push({
fctl: info,
fdat: []
});
}
info.sequenceNumber = data.readUInt32BE(0);
info.width = data.readUInt32BE(4);
info.height = data.readUInt32BE(8);
info.xOffset = data.readUInt32BE(12);
info.yOffset = data.readUInt32BE(16);
info.delayNum = data.readUInt16BE(20);
info.delayDen = data.readUInt16BE(22);
info.disposeOp = data.readUInt8(24);
info.blendOp = data.readUInt8(25);
break;
}
case 'fdat': {
info.sequenceNumber = data.readUInt32BE(0);
info.data = data.slice(4);
this.frames[this.frames.length - 1].fdat.push(info.data);
break;
}
}
chunk.info = info;
}
this._debug(chunks);
if (this.frames) {
this.frames = this.frames.map(function(frame, i) {
frame.fdat = this.decompress(frame.fdat);
if (!frame.fdat.length) throw new Error('no data');
return frame;
}, this);
}
idat = this.decompress(this.idat);
if (!idat.length) throw new Error('no data');
return idat;
};
PNG.prototype.parseLines = function(data) {
var pixels = []
, x
, p
, prior
, line
, filter
, samples
, pendingSamples
, ch
, shiftStart
, i
, toShift
, sample;
this.sampleDepth =
this.colorType === 0 ? 1
: this.colorType === 2 ? 3
: this.colorType === 3 ? 1
: this.colorType === 4 ? 2
: this.colorType === 6 ? 4
: 1;
this.bitsPerPixel = this.bitDepth * this.sampleDepth;
this.bytesPerPixel = Math.ceil(this.bitsPerPixel / 8);
this.wastedBits = ((this.width * this.bitsPerPixel) / 8) - ((this.width * this.bitsPerPixel / 8) | 0);
this.byteWidth = Math.ceil(this.width * (this.bitsPerPixel / 8));
this.shiftStart = ((this.bitDepth + (8 / this.bitDepth - this.bitDepth)) - 1) | 0;
this.shiftMult = this.bitDepth >= 8 ? 0 : this.bitDepth;
this.mask = this.bitDepth === 32 ? 0xffffffff : (1 << this.bitDepth) - 1;
if (this.interlace === 1) {
samples = this.sampleInterlacedLines(data);
for (i = 0; i < samples.length; i += this.sampleDepth) {
pixels.push(samples.slice(i, i + this.sampleDepth));
}
return pixels;
}
for (p = 0; p < data.length; p += this.byteWidth) {
prior = line || [];
filter = data[p++];
line = data.slice(p, p + this.byteWidth);
line = this.unfilterLine(filter, line, prior);
samples = this.sampleLine(line);
for (i = 0; i < samples.length; i += this.sampleDepth) {
pixels.push(samples.slice(i, i + this.sampleDepth));
}
}
return pixels;
};
PNG.prototype.unfilterLine = function(filter, line, prior) {
for (var x = 0; x < line.length; x++) {
if (filter === 0) {
break;
} else if (filter === 1) {
line[x] = this.filters.sub(x, line, prior, this.bytesPerPixel);
} else if (filter === 2) {
line[x] = this.filters.up(x, line, prior, this.bytesPerPixel);
} else if (filter === 3) {
line[x] = this.filters.average(x, line, prior, this.bytesPerPixel);
} else if (filter === 4) {
line[x] = this.filters.paeth(x, line, prior, this.bytesPerPixel);
}
}
return line;
};
PNG.prototype.sampleLine = function(line, width) {
var samples = []
, x = 0
, pendingSamples
, ch
, i
, sample
, shiftStart
, toShift;
while (x < line.length) {
pendingSamples = this.sampleDepth;
while (pendingSamples--) {
ch = line[x];
if (this.bitDepth === 16) {
ch = (ch << 8) | line[++x];
} else if (this.bitDepth === 24) {
ch = (ch << 16) | (line[++x] << 8) | line[++x];
} else if (this.bitDepth === 32) {
ch = (ch << 24) | (line[++x] << 16) | (line[++x] << 8) | line[++x];
} else if (this.bitDepth > 32) {
throw new Error('bitDepth ' + this.bitDepth + ' unsupported.');
}
shiftStart = this.shiftStart;
toShift = shiftStart - (x === line.length - 1 ? this.wastedBits : 0);
for (i = 0; i <= toShift; i++) {
sample = (ch >> (this.shiftMult * shiftStart)) & this.mask;
if (this.colorType !== 3) {
if (this.bitDepth < 8) { // <= 8 would work too, doesn't matter
// sample = sample * (0xff / this.mask) | 0; // would work too
sample *= 0xff / this.mask;
sample |= 0;
} else if (this.bitDepth > 8) {
sample = (sample / this.mask) * 255 | 0;
}
}
samples.push(sample);
shiftStart--;
}
x++;
}
}
// Needed for deinterlacing?
if (width != null) {
samples = samples.slice(0, width * this.sampleDepth);
}
return samples;
};
// http://www.w3.org/TR/PNG-Filters.html
PNG.prototype.filters = {
sub: function Sub(x, line, prior, bpp) {
if (x < bpp) return line[x];
return (line[x] + line[x - bpp]) % 256;
},
up: function Up(x, line, prior, bpp) {
return (line[x] + (prior[x] || 0)) % 256;
},
average: function Average(x, line, prior, bpp) {
if (x < bpp) return Math.floor((prior[x] || 0) / 2);
// if (x < bpp) return (prior[x] || 0) >> 1;
return (line[x]
+ Math.floor((line[x - bpp] + prior[x]) / 2)
// + ((line[x - bpp] + prior[x]) >> 1)
) % 256;
},
paeth: function Paeth(x, line, prior, bpp) {
if (x < bpp) return prior[x] || 0;
return (line[x] + this._predictor(
line[x - bpp], prior[x] || 0, prior[x - bpp] || 0
)) % 256;
},
_predictor: function PaethPredictor(a, b, c) {
// a = left, b = above, c = upper left
var p = a + b - c
, pa = Math.abs(p - a)
, pb = Math.abs(p - b)
, pc = Math.abs(p - c);
if (pa <= pb && pa <= pc) return a;
if (pb <= pc) return b;
return c;
}
};
/**
* Adam7 deinterlacing ported to javascript from PyPNG:
* pypng - Pure Python library for PNG image encoding/decoding
* Copyright (c) 2009-2015, David Jones (MIT License).
* https://github.com/drj11/pypng
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation files
* (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
PNG.prototype.sampleInterlacedLines = function(raw) {
var psize
, vpr
, samples
, source_offset
, i
, pass
, xstart
, ystart
, xstep
, ystep
, recon
, ppr
, row_size
, y
, filter_type
, scanline
, flat
, offset
, k
, end_offset
, skip
, j
, k
, f;
var adam7 = [
[0, 0, 8, 8],
[4, 0, 8, 8],
[0, 4, 4, 8],
[2, 0, 4, 4],
[0, 2, 2, 4],
[1, 0, 2, 2],
[0, 1, 1, 2]
];
// Fractional bytes per pixel
psize = (this.bitDepth / 8) * this.sampleDepth;
// Values per row (of the target image)
vpr = this.width * this.sampleDepth;
// Make a result array, and make it big enough. Interleaving
// writes to the output array randomly (well, not quite), so the
// entire output array must be in memory.
samples = new Buffer(vpr * this.height);
samples.fill(0);
source_offset = 0;
for (i = 0; i < adam7.length; i++) {
pass = adam7[i];
xstart = pass[0];
ystart = pass[1];
xstep = pass[2];
ystep = pass[3];
if (xstart >= this.width) continue;
// The previous (reconstructed) scanline. Empty array at the
// beginning of a pass to indicate that there is no previous
// line.
recon = [];
// Pixels per row (reduced pass image)
ppr = Math.ceil((this.width - xstart) / xstep);
// Row size in bytes for this pass.
row_size = Math.ceil(psize * ppr);
for (y = ystart; y < this.height; y += ystep) {
filter_type = raw[source_offset];
source_offset += 1;
scanline = raw.slice(source_offset, source_offset + row_size);
source_offset += row_size;
recon = this.unfilterLine(filter_type, scanline, recon);
// Convert so that there is one element per pixel value
flat = this.sampleLine(recon, ppr);
if (xstep === 1) {
assert.equal(xstart, 0);
offset = y * vpr;
for (k = offset, f = 0; k < offset + vpr; k++, f++) {
samples[k] = flat[f];
}
} else {
offset = y * vpr + xstart * this.sampleDepth;
end_offset = (y + 1) * vpr;
skip = this.sampleDepth * xstep;
for (j = 0; j < this.sampleDepth; j++) {
for (k = offset + j, f = j; k < end_offset; k += skip, f += this.sampleDepth) {
samples[k] = flat[f];
}
}
}
}
}
return samples;
};
PNG.prototype.createBitmap = function(pixels) {
var bmp = []
, i;
if (this.colorType === 0) {
pixels = pixels.map(function(sample) {
return { r: sample[0], g: sample[0], b: sample[0], a: 255 };
});
} else if (this.colorType === 2) {
pixels = pixels.map(function(sample) {
return { r: sample[0], g: sample[1], b: sample[2], a: 255 };
});
} else if (this.colorType === 3) {
pixels = pixels.map(function(sample) {
if (!this.palette[sample[0]]) throw new Error('bad palette index');
return this.palette[sample[0]];
}, this);
} else if (this.colorType === 4) {
pixels = pixels.map(function(sample) {
return { r: sample[0], g: sample[0], b: sample[0], a: sample[1] };
});
} else if (this.colorType === 6) {
pixels = pixels.map(function(sample) {
return { r: sample[0], g: sample[1], b: sample[2], a: sample[3] };
});
}
for (i = 0; i < pixels.length; i += this.width) {
bmp.push(pixels.slice(i, i + this.width));
}
return bmp;
};
PNG.prototype.createCellmap = function(bmp, options) {
var bmp = bmp || this.bmp
, options = options || this.options
, cellmap = []
, scale = options.scale || 0.20
, height = bmp.length
, width = bmp[0].length
, cmwidth = options.width
, cmheight = options.height
, line
, x
, y
, xx
, yy
, scale
, xs
, ys;
if (cmwidth) {
scale = cmwidth / width;
} else if (cmheight) {
scale = cmheight / height;
}
if (!cmheight) {
cmheight = Math.round(height * scale);
}
if (!cmwidth) {
cmwidth = Math.round(width * scale);
}
ys = height / cmheight;
xs = width / cmwidth;
for (y = 0; y < bmp.length; y += ys) {
line = [];
yy = Math.round(y);
if (!bmp[yy]) break;
for (x = 0; x < bmp[yy].length; x += xs) {
xx = Math.round(x);
if (!bmp[yy][xx]) break;
line.push(bmp[yy][xx]);
}
cellmap.push(line);
}
return cellmap;
};
PNG.prototype.renderANSI = function(bmp) {
var self = this
, out = '';
bmp.forEach(function(line, y) {
line.forEach(function(pixel, x) {
var outch = self.getOutch(x, y, line, pixel);
out += self.pixelToSGR(pixel, outch);
});
out += '\n';
});
return out;
};
PNG.prototype.renderContent = function(bmp, el) {
var self = this
, out = '';
bmp.forEach(function(line, y) {
line.forEach(function(pixel, x) {
var outch = self.getOutch(x, y, line, pixel);
out += self.pixelToTags(pixel, outch);
});
out += '\n';
});
el.setContent(out);
return out;
};
PNG.prototype.renderScreen = function(bmp, screen, xi, xl, yi, yl) {
var self = this
, lines = screen.lines
, cellLines
, y
, yy
, x
, xx
, alpha
, attr
, ch;
cellLines = bmp.reduce(function(cellLines, line, y) {
var cellLine = [];
line.forEach(function(pixel, x) {
var outch = self.getOutch(x, y, line, pixel)
, cell = self.pixelToCell(pixel, outch);
cellLine.push(cell);
});
cellLines.push(cellLine);
return cellLines;
}, []);
for (y = yi; y < yl; y++) {
yy = y - yi;
for (x = xi; x < xl; x++) {
xx = x - xi;
if (lines[y] && lines[y][x] && cellLines[yy] && cellLines[yy][xx]) {
alpha = cellLines[yy][xx].pop();
// completely transparent
if (alpha === 0.0) {
continue;
}
// translucency / blending
if (alpha < 1.0) {
attr = cellLines[yy][xx][0];
ch = cellLines[yy][xx][1];
lines[y][x][0] = this.colors.blend(lines[y][x][0], attr, alpha);
if (ch !== ' ') lines[y][x][1] = ch;
lines[y].dirty = true;
continue;
}
// completely opaque
lines[y][x] = cellLines[yy][xx];
lines[y].dirty = true;
}
}
}
};
PNG.prototype.renderElement = function(bmp, el) {
var xi = el.aleft + el.ileft
, xl = el.aleft + el.width - el.iright
, yi = el.atop + el.itop
, yl = el.atop + el.height - el.ibottom;
return this.renderScreen(bmp, el.screen, xi, xl, yi, yl);
};
PNG.prototype.pixelToSGR = function(pixel, ch) {
var bga = 1.0
, fga = 0.5
, a = pixel.a / 255
, bg
, fg;
bg = this.colors.match(
pixel.r * a * bga | 0,
pixel.g * a * bga | 0,
pixel.b * a * bga | 0);
if (ch && this.options.ascii) {
fg = this.colors.match(
pixel.r * a * fga | 0,
pixel.g * a * fga | 0,
pixel.b * a * fga | 0);
if (a === 0) {
return '\x1b[38;5;' + fg + 'm' + ch + '\x1b[m';
}
return '\x1b[38;5;' + fg + 'm\x1b[48;5;' + bg + 'm' + ch + '\x1b[m';
}
if (a === 0) return ' ';
return '\x1b[48;5;' + bg + 'm \x1b[m';
};
PNG.prototype.pixelToTags = function(pixel, ch) {
var bga = 1.0
, fga = 0.5
, a = pixel.a / 255
, bg
, fg;
bg = this.colors.RGBtoHex(
pixel.r * a * bga | 0,
pixel.g * a * bga | 0,
pixel.b * a * bga | 0);
if (ch && this.options.ascii) {
fg = this.colors.RGBtoHex(
pixel.r * a * fga | 0,
pixel.g * a * fga | 0,
pixel.b * a * fga | 0);
if (a === 0) {
return '{' + fg + '-fg}' + ch + '{/}';
}
return '{' + fg + '-fg}{' + bg + '-bg}' + ch + '{/}';
}
if (a === 0) return ' ';
return '{' + bg + '-bg} {/' + bg + '-bg}';
};
PNG.prototype.pixelToCell = function(pixel, ch) {
var bga = 1.0
, fga = 0.5
, a = pixel.a / 255
, bg
, fg;
bg = this.colors.match(
pixel.r * bga | 0,
pixel.g * bga | 0,
pixel.b * bga | 0);
if (ch && this.options.ascii) {
fg = this.colors.match(
pixel.r * fga | 0,
pixel.g * fga | 0,
pixel.b * fga | 0);
} else {
fg = 0x1ff;
ch = null;
}
// if (a === 0) bg = 0x1ff;
return [(0 << 18) | (fg << 9) | (bg << 0), ch || ' ', a];
};
// Taken from libcaca:
PNG.prototype.getOutch = (function() {
var dchars = '????8@8@#8@8##8#MKXWwz$&%x><\\/xo;+=|^-:i\'.`, `. ';
var luminance = function(pixel) {
var a = pixel.a / 255
, r = pixel.r * a
, g = pixel.g * a
, b = pixel.b * a
, l = 0.2126 * r + 0.7152 * g + 0.0722 * b;
return l / 255;
};
return function(x, y, line, pixel) {
var lumi = luminance(pixel)
, outch = dchars[lumi * (dchars.length - 1) | 0];
return outch;
};
})();
PNG.prototype.compileFrames = function(frames) {
return this.optimization === 'mem'
? this.compileFrames_lomem(frames)
: this.compileFrames_locpu(frames);
};
PNG.prototype.compileFrames_lomem = function(frames) {
if (!this.actl) return;
return frames.map(function(frame, i) {
this.width = frame.fctl.width;
this.height = frame.fctl.height;
var pixels = frame._pixels || this.parseLines(frame.fdat)
, bmp = frame._bmp || this.createBitmap(pixels)
, fc = frame.fctl;
return {
actl: this.actl,
fctl: frame.fctl,
delay: (fc.delayNum / (fc.delayDen || 100)) * 1000 | 0,
bmp: bmp
};
}, this);
};
PNG.prototype.compileFrames_locpu = function(frames) {
if (!this.actl) return;
this._curBmp = null;
this._lastBmp = null;
return frames.map(function(frame, i) {
this.width = frame.fctl.width;
this.height = frame.fctl.height;
var pixels = frame._pixels || this.parseLines(frame.fdat)
, bmp = frame._bmp || this.createBitmap(pixels)
, renderBmp = this.renderFrame(bmp, frame, i)
, cellmap = this.createCellmap(renderBmp)
, fc = frame.fctl;
return {
actl: this.actl,
fctl: frame.fctl,
delay: (fc.delayNum / (fc.delayDen || 100)) * 1000 | 0,
bmp: renderBmp,
cellmap: cellmap
};
}, this);
};
PNG.prototype.renderFrame = function(bmp, frame, i) {
var first = this.frames[0]
, last = this.frames[i - 1]
, fc = frame.fctl
, xo = fc.xOffset
, yo = fc.yOffset
, lxo
, lyo
, x
, y
, line
, p;
if (!this._curBmp) {
this._curBmp = [];
for (y = 0; y < first.fctl.height; y++) {
line = [];
for (x = 0; x < first.fctl.width; x++) {
p = bmp[y][x];
line.push({ r: p.r, g: p.g, b: p.b, a: p.a });
}
this._curBmp.push(line);
}
}
if (last && last.fctl.disposeOp !== 0) {
lxo = last.fctl.xOffset;
lyo = last.fctl.yOffset;
for (y = 0; y < last.fctl.height; y++) {
for (x = 0; x < last.fctl.width; x++) {
if (last.fctl.disposeOp === 0) {
// none / keep
} else if (last.fctl.disposeOp === 1) {
// background / clear
this._curBmp[lyo + y][lxo + x] = { r: 0, g: 0, b: 0, a: 0 };
} else if (last.fctl.disposeOp === 2) {
// previous / restore
p = this._lastBmp[y][x];
this._curBmp[lyo + y][lxo + x] = { r: p.r, g: p.g, b: p.b, a: p.a };
}
}
}
}
if (frame.fctl.disposeOp === 2) {
this._lastBmp = [];
for (y = 0; y < frame.fctl.height; y++) {
line = [];
for (x = 0; x < frame.fctl.width; x++) {
p = this._curBmp[yo + y][xo + x];
line.push({ r: p.r, g: p.g, b: p.b, a: p.a });
}
this._lastBmp.push(line);
}
} else {
this._lastBmp = null;
}
for (y = 0; y < frame.fctl.height; y++) {
for (x = 0; x < frame.fctl.width; x++) {
p = bmp[y][x];
if (fc.blendOp === 0) {
// source
this._curBmp[yo + y][xo + x] = { r: p.r, g: p.g, b: p.b, a: p.a };
} else if (fc.blendOp === 1) {
// over
if (p.a !== 0) {
this._curBmp[yo + y][xo + x] = { r: p.r, g: p.g, b: p.b, a: p.a };
}
}
}
}
return this._curBmp;
};
PNG.prototype._animate = function(callback) {
if (!this.frames) {
return callback(this.bmp, this.cellmap);
}
var self = this
, numPlays = this.actl.numPlays || Infinity
, running = 0
, i = -1;
this._curBmp = null;
this._lastBmp = null;
var next_lomem = function() {
if (!running) return;
var frame = self.frames[++i];
if (!frame) {
if (!--numPlays) return callback();
i = -1;
// XXX may be able to optimize by only setting the self._curBmp once???
self._curBmp = null;
self._lastBmp = null;
return setImmediate(next);
}
var bmp = frame.bmp
, renderBmp = self.renderFrame(bmp, frame, i)
, cellmap = self.createCellmap(renderBmp);
callback(renderBmp, cellmap);
return setTimeout(next, frame.delay / self.speed | 0);
};
var next_locpu = function() {
if (!running) return;
var frame = self.frames[++i];
if (!frame) {
if (!--numPlays) return callback();
i = -1;
return setImmediate(next);
}
callback(frame.bmp, frame.cellmap);
return setTimeout(next, frame.delay / self.speed | 0);
};
var next = this.optimization === 'mem'
? next_lomem
: next_locpu;
this._control = function(state) {
if (state === -1) {
i = -1;
self._curBmp = null;
self._lastBmp = null;
running = 0;
callback(self.frames[0].bmp,
self.frames[0].cellmap || self.createCellmap(self.frames[0].bmp));
return;
}
if (state === running) return;
running = state;
return next();
};
this._control(1);
};
PNG.prototype.play = function(callback) {
if (!this._control || callback) {
this.stop();
return this._animate(callback);
}
this._control(1);
};
PNG.prototype.pause = function() {
if (!this._control) return;
this._control(0);
};
PNG.prototype.stop = function() {
if (!this._control) return;
this._control(-1);
};
PNG.prototype.toPNG = function(input) {
var options = this.options
, file = this.file
, format = this.format
, buf
, img
, gif
, i
, control
, disposeOp;
if (format !== 'gif') {
buf = exec('convert', [format + ':-', 'png:-'],
{ stdio: ['pipe', 'pipe', 'ignore'], input: input });
img = PNG(buf, options);
img.file = file;
return img;
}
gif = GIF(input, options);
this.width = gif.width;
this.height = gif.height;
this.frames = [];
for (i = 0; i < gif.images.length; i++) {
img = gif.images[i];
// Convert from gif disposal to png disposal. See:
// http://www.w3.org/Graphics/GIF/spec-gif89a.txt
control = img.control || gif;
disposeOp = Math.max(0, (control.disposeMethod || 0) - 1);
if (disposeOp > 2) disposeOp = 0;
this.frames.push({
fctl: {
sequenceNumber: i,
width: img.width,
height: img.height,
xOffset: img.left,
yOffset: img.top,
delayNum: control.delay,
delayDen: 100,
disposeOp: disposeOp,
blendOp: 1
},
fdat: [],
_pixels: [],
_bmp: img.bmp
});
}
this.bmp = this.frames[0]._bmp;
this.cellmap = this.createCellmap(this.bmp);
if (this.frames.length > 1) {
this.actl = { numFrames: gif.images.length, numPlays: gif.numPlays || 0 };
this.frames = this.compileFrames(this.frames);
} else {
this.frames = undefined;
}
return this;
};
// Convert a gif to an apng using imagemagick. Unfortunately imagemagick
// doesn't support apngs, so we coalesce the gif frames into one image and then
// slice them into frames.
PNG.prototype.gifMagick = function(input) {
var options = this.options
, file = this.file
, format = this.format
, buf
, fmt
, img
, frames
, frame
, width
, height
, iwidth
, twidth
, i
, lines
, line
, x
, y;
buf = exec('convert',
[format + ':-', '-coalesce', '+append', 'png:-'],
{ stdio: ['pipe', 'pipe', 'ignore'], input: input });
fmt = '{"W":%W,"H":%H,"w":%w,"h":%h,"d":%T,"x":"%X","y":"%Y"},'
frames = exec('identify', ['-format', fmt, format + ':-'],
{ encoding: 'utf8', stdio: ['pipe', 'pipe', 'ignore'], input: input });
frames = JSON.parse('[' + frames.trim().slice(0, -1) + ']');
img = PNG(buf, options);
img.file = file;
Object.keys(img).forEach(function(key) {
this[key] = img[key];
}, this);
width = frames[0].W;
height = frames[0].H;
iwidth = 0;
twidth = 0;
this.width = width;
this.height = height;
this.frames = [];
for (i = 0; i < frames.length; i++) {
frame = frames[i];
frame.x = +frame.x;
frame.y = +frame.y;
iwidth = twidth;
twidth += width;
lines = [];
for (y = frame.y; y < height; y++) {
line = [];
for (x = iwidth + frame.x; x < twidth; x++) {
line.push(img.bmp[y][x]);
}
lines.push(line);
}
this.frames.push({
fctl: {
sequenceNumber: i,
width: frame.w,
height: frame.h,
xOffset: frame.x,
yOffset: frame.y,
delayNum: frame.d,
delayDen: 100,
disposeOp: 0,
blendOp: 0
},
fdat: [],
_pixels: [],
_bmp: lines
});
}
this.bmp = this.frames[0]._bmp;
this.cellmap = this.createCellmap(this.bmp);
if (this.frames.length > 1) {
this.actl = { numFrames: frames.length, numPlays: 0 };
this.frames = this.compileFrames(this.frames);
} else {
this.frames = undefined;
}
return this;
};
PNG.prototype.decompress = function(buffers) {
return zlib.inflateSync(new Buffer(buffers.reduce(function(out, data) {
return out.concat(Array.prototype.slice.call(data));
}, [])));
};
/**
* node-crc
* https://github.com/alexgorbatchev/node-crc
* https://github.com/alexgorbatchev/node-crc/blob/master/LICENSE
*
* The MIT License (MIT)
*
* Copyright 2014 Alex Gorbatchev
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
PNG.prototype.crc32 = (function() {
var crcTable = [
0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f,
0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988,
0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2,
0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7,
0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9,
0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172,
0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c,
0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59,
0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423,
0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,
0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106,
0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433,
0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d,
0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e,
0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950,
0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65,
0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7,
0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0,
0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa,
0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81,
0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a,
0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84,
0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1,
0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb,
0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc,
0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e,
0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b,
0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55,
0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,
0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28,
0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d,
0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f,
0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38,
0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242,
0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777,
0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69,
0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2,
0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc,
0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693,
0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94,
0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d
];
return function crc32(buf) {
//var crc = previous === 0 ? 0 : ~~previous ^ -1;
var crc = -1;
for (var i = 0, len = buf.length; i < len; i++) {
crc = crcTable[(crc ^ buf[i]) & 0xff] ^ (crc >>> 8);
}
return crc ^ -1;
};
})();
PNG.prototype._debug = function(obj) {
if (!this.options.log) return;
return this.options.log(util.inspect(obj, {
depth: 20
}));
};
/**
* GIF
*/
function GIF(file, options) {
var self = this;
if (!(this instanceof GIF)) {
return new GIF(file, options);
}
var info = {}
, p = 0
, buf
, i
, total
, sig
, desc
, img
, ext
, label
, size;
if (!file) throw new Error('no file');
options = options || {};
this.options = options;
// XXX If the gif is not optimized enough
// it may OOM the process with too many frames.
// TODO: Implement in PNG reader.
this.pixelLimit = this.options.pixelLimit || 7622550;
this.totalPixels = 0;
if (Buffer.isBuffer(file)) {
buf = file;
file = null;
} else {
file = path.resolve(process.cwd(), file);
buf = fs.readFileSync(file);
}
sig = buf.slice(0, 6).toString('ascii');
if (sig !== 'GIF87a' && sig !== 'GIF89a') {
throw new Error('bad header: ' + sig);
}
this.width = buf.readUInt16LE(6);
this.height = buf.readUInt16LE(8);
this.flags = buf.readUInt8(10);
this.gct = !!(this.flags & 0x80);
this.gctsize = (this.flags & 0x07) + 1;
this.bgIndex = buf.readUInt8(11);
this.aspect = buf.readUInt8(12);
p += 13;
if (this.gct) {
this.colors = [];
total = 1 << this.gctsize;
for (i = 0; i < total; i++, p += 3) {
this.colors.push([buf[p], buf[p + 1], buf[p + 2], 255]);
}
}
this.images = [];
this.extensions = [];
try {
while (p < buf.length) {
desc = buf.readUInt8(p);
p += 1;
if (desc === 0x2c) {
img = {};
img.left = buf.readUInt16LE(p);
p += 2;
img.top = buf.readUInt16LE(p);
p += 2;
img.width = buf.readUInt16LE(p);
p += 2;
img.height = buf.readUInt16LE(p);
p += 2;
img.flags = buf.readUInt8(p);
p += 1;
img.lct = !!(img.flags & 0x80);
img.ilace = !!(img.flags & 0x40);
img.lctsize = (img.flags & 0x07) + 1;
if (img.lct) {
img.lcolors = [];
total = 1 << img.lctsize;
for (i = 0; i < total; i++, p += 3) {
img.lcolors.push([buf[p], buf[p + 1], buf[p + 2], 255]);
}
}
img.codeSize = buf.readUInt8(p);
p += 1;
img.size = buf.readUInt8(p);
p += 1;
img.lzw = [buf.slice(p, p + img.size)];
p += img.size;
while (buf[p] !== 0x00) {
// Some gifs screw up their size.
// XXX Same for all subblocks?
if (buf[p] === 0x3b && p === buf.length - 1) {
p--;
break;
}
size = buf.readUInt8(p);
p += 1;
img.lzw.push(buf.slice(p, p + size));
p += size;
}
assert.equal(buf.readUInt8(p), 0x00);
p += 1;
if (ext && ext.label === 0xf9) {
img.control = ext;
}
this.totalPixels += img.width * img.height;
this.images.push(img);
if (this.totalPixels >= this.pixelLimit) {
break;
}
} else if (desc === 0x21) {
// Extensions:
// http://www.w3.org/Graphics/GIF/spec-gif89a.txt
ext = {};
label = buf.readUInt8(p);
p += 1;
ext.label = label;
if (label === 0xf9) {
size = buf.readUInt8(p);
assert.equal(size, 0x04);
p += 1;
ext.fields = buf.readUInt8(p);
ext.disposeMethod = (ext.fields >> 2) & 0x07;
ext.useTransparent = !!(ext.fields & 0x01);
p += 1;
ext.delay = buf.readUInt16LE(p);
p += 2;
ext.transparentColor = buf.readUInt8(p);
p += 1;
while (buf[p] !== 0x00) {
size = buf.readUInt8(p);
p += 1;
p += size;
}
assert.equal(buf.readUInt8(p), 0x00);
p += 1;
this.delay = ext.delay;
this.transparentColor = ext.transparentColor;
this.disposeMethod = ext.disposeMethod;
this.useTransparent = ext.useTransparent;
} else if (label === 0xff) {
// https://wiki.whatwg.org/wiki/GIF#Specifications
size = buf.readUInt8(p);
p += 1;
ext.id = buf.slice(p, p + 8).toString('ascii');
p += 8;
ext.auth = buf.slice(p, p + 3).toString('ascii');
p += 3;
ext.data = [];
while (buf[p] !== 0x00) {
size = buf.readUInt8(p);
p += 1;
ext.data.push(buf.slice(p, p + size));
p += size;
}
ext.data = new Buffer(ext.data.reduce(function(out, data) {
return out.concat(Array.prototype.slice.call(data));
}, []));
// AnimExts looping extension (identical to netscape)
if (ext.id === 'ANIMEXTS' && ext.auth === '1.0') {
ext.id = 'NETSCAPE';
ext.auth = '2.0';
ext.animexts = true;
}
// Netscape extensions
if (ext.id === 'NETSCAPE' && ext.auth === '2.0') {
if (ext.data.readUInt8(0) === 0x01) {
// Netscape looping extension
// http://graphcomp.com/info/specs/ani_gif.html
ext.numPlays = ext.data.readUInt16LE(1);
this.numPlays = ext.numPlays;
} else if (ext.data.readUInt8(0) === 0x02) {
// Netscape buffering extension
this.minBuffer = ext.data;
}
}
// Adobe XMP extension
if (ext.id === 'XMP Data' && ext.auth === 'XMP') {
ext.xmp = ext.data.toString('utf8');
this.xmp = ext.xmp;
}
// ICC extension
if (ext.id === 'ICCRGBG1' && ext.auth === '012') {
// NOTE: Says size is 4 bytes, not 1? Maybe just buffer size?
this.icc = ext.data;
}
// fractint extension
if (ext.id === 'fractint' && /^00[1-7]$/.test(ext.auth)) {
// NOTE: Says size is 4 bytes, not 1? Maybe just buffer size?
// Size: '!\377\013' == [0x00, 0x15, 0xff, 0x0b]
this.fractint = ext.data;
}
assert.equal(buf.readUInt8(p), 0x00);
p += 1;
} else {
ext.data = [];
while (buf[p] !== 0x00) {
size = buf.readUInt8(p);
p += 1;
ext.data.push(buf.slice(p, p + size));
p += size;
}
assert.equal(buf.readUInt8(p), 0x00);
p += 1;
}
this.extensions.push(ext);
} else if (desc === 0x3b) {
break;
} else if (p === buf.length - 1) {
// } else if (desc === 0x00 && p === buf.length - 1) {
break;
} else {
throw new Error('unknown block');
}
}
} catch (e) {
if (options.debug) {
throw e;
}
}
this.images = this.images.map(function(img, imageIndex) {
var control = img.control || this;
img.lzw = new Buffer(img.lzw.reduce(function(out, data) {
return out.concat(Array.prototype.slice.call(data));
}, []));
try {
img.data = this.decompress(img.lzw, img.codeSize);
} catch (e) {
if (options.debug) throw e;
return;
}
var interlacing = [
[ 0, 8 ],
[ 4, 8 ],
[ 2, 4 ],
[ 1, 2 ],
[ 0, 0 ]
];
var table = img.lcolors || this.colors
, row = 0
, col = 0
, ilp = 0
, p = 0
, b
, idx
, i
, y
, x
, line
, pixel;
img.samples = [];
// Rewritten version of:
// https://github.com/lbv/ka-cs-programs/blob/master/lib/gif-reader.js
for (;;) {
b = img.data[p++];
if (b == null) break;
idx = (row * img.width + col) * 4;
if (!table[b]) {
if (options.debug) throw new Error('bad samples');
table[b] = [0, 0, 0, 0];
}
img.samples[idx] = table[b][0];
img.samples[idx + 1] = table[b][1];
img.samples[idx + 2] = table[b][2];
img.samples[idx + 3] = table[b][3];
if (control.useTransparent && b === control.transparentColor) {
img.samples[idx + 3] = 0;
}
if (++col >= img.width) {
col = 0;
if (img.ilace) {
row += interlacing[ilp][1];
if (row >= img.height) {
row = interlacing[++ilp][0];
}
} else {
row++;
}
}
}
img.pixels = [];
for (i = 0; i < img.samples.length; i += 4) {
img.pixels.push(img.samples.slice(i, i + 4));
}
img.bmp = [];
for (y = 0, p = 0; y < img.height; y++) {
line = [];
for (x = 0; x < img.width; x++) {
pixel = img.pixels[p++];
if (!pixel) {
if (options.debug) throw new Error('no pixel');
line.push({ r: 0, g: 0, b: 0, a: 0 });
continue;
}
line.push({ r: pixel[0], g: pixel[1], b: pixel[2], a: pixel[3] });
}
img.bmp.push(line);
}
return img;
}, this).filter(Boolean);
if (!this.images.length) {
throw new Error('no image data or bad decompress');
}
}
// Rewritten version of:
// https://github.com/lbv/ka-cs-programs/blob/master/lib/gif-reader.js
GIF.prototype.decompress = function(input, codeSize) {
var bitDepth = codeSize + 1
, CC = 1 << codeSize
, EOI = CC + 1
, stack = []
, table = []
, ntable = 0
, oldCode = null
, buffer = 0
, nbuffer = 0
, p = 0
, buf = []
, bits
, read
, ans
, n
, code
, i
, K
, b
, maxElem;
for (;;) {
if (stack.length === 0) {
bits = bitDepth;
read = 0;
ans = 0;
while (read < bits) {
if (nbuffer === 0) {
if (p >= input.length) return buf;
buffer = input[p++];
nbuffer = 8;
}
n = Math.min(bits - read, nbuffer);
ans |= (buffer & ((1 << n) - 1)) << read;
read += n;
nbuffer -= n;
buffer >>= n;
}
code = ans;
if (code === EOI) {
break;
}
if (code === CC) {
table = [];
for (i = 0; i < CC; ++i) {
table[i] = [i, -1, i];
}
bitDepth = codeSize + 1;
maxElem = 1 << bitDepth;
ntable = CC + 2;
oldCode = null;
continue;
}
if (oldCode === null) {
oldCode = code;
buf.push(table[code][0]);
continue;
}
if (code < ntable) {
for (i = code; i >= 0; i = table[i][1]) {
stack.push(table[i][0]);
}
table[ntable++] = [
table[code][2],
oldCode,
table[oldCode][2]
];
} else {
K = table[oldCode][2];
table[ntable++] = [K, oldCode, K];
for (i = code; i >= 0; i = table[i][1]) {
stack.push(table[i][0]);
}
}
oldCode = code;
if (ntable === maxElem) {
maxElem = 1 << (++bitDepth);
if (bitDepth > 12) bitDepth = 12;
}
}
b = stack.pop();
if (b == null) break;
buf.push(b);
}
return buf;
};
/**
* Expose
*/
exports = PNG;
exports.png = PNG;
exports.gif = GIF;
module.exports = exports;
|
module.exports = {
loader: 'style-loader',
options: {}
};
|
//! moment.js locale configuration
//! locale : Italian (Switzerland) [it-ch]
//! author : xfh : https://github.com/xfh
;(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined'
&& typeof require === 'function' ? factory(require('../moment')) :
typeof define === 'function' && define.amd ? define(['../moment'], factory) :
factory(global.moment)
}(this, (function (moment) { 'use strict';
//! moment.js locale configuration
var itCh = moment.defineLocale('it-ch', {
months: 'gennaio_febbraio_marzo_aprile_maggio_giugno_luglio_agosto_settembre_ottobre_novembre_dicembre'.split(
'_'
),
monthsShort: 'gen_feb_mar_apr_mag_giu_lug_ago_set_ott_nov_dic'.split('_'),
weekdays: 'domenica_lunedì_martedì_mercoledì_giovedì_venerdì_sabato'.split(
'_'
),
weekdaysShort: 'dom_lun_mar_mer_gio_ven_sab'.split('_'),
weekdaysMin: 'do_lu_ma_me_gi_ve_sa'.split('_'),
longDateFormat: {
LT: 'HH:mm',
LTS: 'HH:mm:ss',
L: 'DD.MM.YYYY',
LL: 'D MMMM YYYY',
LLL: 'D MMMM YYYY HH:mm',
LLLL: 'dddd D MMMM YYYY HH:mm',
},
calendar: {
sameDay: '[Oggi alle] LT',
nextDay: '[Domani alle] LT',
nextWeek: 'dddd [alle] LT',
lastDay: '[Ieri alle] LT',
lastWeek: function () {
switch (this.day()) {
case 0:
return '[la scorsa] dddd [alle] LT';
default:
return '[lo scorso] dddd [alle] LT';
}
},
sameElse: 'L',
},
relativeTime: {
future: function (s) {
return (/^[0-9].+$/.test(s) ? 'tra' : 'in') + ' ' + s;
},
past: '%s fa',
s: 'alcuni secondi',
ss: '%d secondi',
m: 'un minuto',
mm: '%d minuti',
h: "un'ora",
hh: '%d ore',
d: 'un giorno',
dd: '%d giorni',
M: 'un mese',
MM: '%d mesi',
y: 'un anno',
yy: '%d anni',
},
dayOfMonthOrdinalParse: /\d{1,2}º/,
ordinal: '%dº',
week: {
dow: 1, // Monday is the first day of the week.
doy: 4, // The week that contains Jan 4th is the first week of the year.
},
});
return itCh;
})));
|
'use strict';
function joinUriSegments(prefix, uri) {
return prefix === '' ? uri : [prefix, uri].join('/');
}
module.exports = joinUriSegments;
|
import axios from "../utils/axios";
class AuthService {
signIn = (email, password) => {
return new Promise((resolve, reject) => {
axios.post("/api/home/login", { email, password })
.then(response => {
if (response.data.user) {
this.setToken("JWT")
resolve(response.data.user)
} else {
reject(response.data.user)
}
})
.catch(error => {
reject(error)
})
});
}
signInWithToken = () => {
return new Promise((resolve, reject) => {
axios.post("/api/home/me")
.then(response => {
if (response.data.user) {
resolve(response.data.user)
} else {
reject(response.data.user)
}
})
.catch(error => {
reject(error)
})
});
}
signOut = () => {
this.removeToken();
}
setToken = (token) => {
localStorage.setItem("accessToken", token);
}
getToken = () => localStorage.getItem("accessToken")
removeToken = () => localStorage.removeItem("accessToken")
isAuthenticated = () => !!this.getToken();
}
const authService = new AuthService();
export default authService;
|
import {featureService} from '../../../src/leaflet/services/FeatureService';
import {EditFeaturesParameters} from '../../../src/common/iServer/EditFeaturesParameters';
import {GetFeaturesByIDsParameters} from '../../../src/common/iServer/GetFeaturesByIDsParameters';
var editServiceURL = GlobeParameter.editServiceURL_leaflet;
var id1, id2;
var originFeature = null;
describe('leaflet_FeatureService_editFeatures_Region', () => {
var originalTimeout;
beforeEach(() => {
originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
jasmine.DEFAULT_TIMEOUT_INTERVAL = 50000;
});
afterEach(() => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout;
});
// 增加REGION要素,returnContent为true
it('successEvent:add_REGION', (done) => {
var addFeatureResult_REGION = null;
var polygon = L.polygon([[38.837029131724, 118.05408801141], [38.606951847395, 117.80757663534], [38.530259419285, 118.43207212138], [38.837029131724, 118.05408801141]]);
var addFeaturesParams = new EditFeaturesParameters({
dataSourceName: "Jingjin",
dataSetName: "Landuse_R",
features: polygon,
editType: "add",
returnContent: true,
isUseBatch: false
});
var addFeaturesService = featureService(editServiceURL);
addFeaturesService.editFeatures(addFeaturesParams, (result) => {
addFeatureResult_REGION = result
});
setTimeout(() => {
try {
expect(addFeaturesService).not.toBeNull();
expect(addFeatureResult_REGION.type).toBe("processCompleted");
expect(addFeatureResult_REGION.object.isInTheSameDomain).toBeFalsy();
expect(addFeatureResult_REGION.object.options.method).toBe("POST");
expect(addFeatureResult_REGION.object.options.data).toContain("'parts':[4]");
expect(addFeatureResult_REGION.object.options.data).toContain('"REGION"');
expect(addFeatureResult_REGION.result).not.toBeNull();
expect(addFeatureResult_REGION.result.succeed).toBeTruthy();
expect(addFeatureResult_REGION.result.length).toEqual(1);
id1 = addFeatureResult_REGION.result[0];
addFeaturesService.destroy();
done();
} catch (exception) {
console.log("'successEvent:addFeature_REGION'案例失败:" + exception.name + ":" + exception.message);
addFeaturesService.destroy();
expect(false).toBeTruthy();
done();
}
}, 2000)
});
// 增加REGION要素,returnContent为false
it('successEvent:add_returnContent=false', (done) => {
var addFeatureResult = null;
var polygon = L.polygon([[37.837029131724, 117.05408801141], [37.606951847395, 116.80757663534], [37.530259419285, 117.43207212138], [37.837029131724, 117.05408801141]]);
var addFeaturesParams = new EditFeaturesParameters({
dataSourceName: "Jingjin",
dataSetName: "Landuse_R",
features: polygon,
editType: "add",
returnContent: false,
isUseBatch: false
});
var addFeaturesService = featureService(editServiceURL);
addFeaturesService.editFeatures(addFeaturesParams, (result) => {
addFeatureResult = result
});
setTimeout(() => {
try {
expect(addFeaturesService).not.toBeNull();
expect(addFeatureResult.type).toBe("processCompleted");
expect(addFeatureResult.object.isInTheSameDomain).toBeFalsy();
expect(addFeatureResult.object.options.method).toBe("POST");
expect(addFeatureResult.object.options.data).toContain("'parts':[4]");
expect(addFeatureResult.object.options.data).toContain('"REGION"');
expect(addFeatureResult.result).not.toBeNull();
expect(addFeatureResult.result.succeed).toBeTruthy();
expect(addFeatureResult.result.newResourceID.length).toBeGreaterThan(0);
expect(addFeatureResult.result.newResourceLocation.length).toBeGreaterThan(0);
expect(addFeatureResult.result.postResultType).toBe("CreateChild");
id2 = id1 + 1;
addFeaturesService.destroy();
done();
} catch (exception) {
console.log("'successEvent:addFeature_REGION'案例失败:" + exception.name + ":" + exception.message);
addFeaturesService.destroy();
expect(false).toBeTruthy();
done();
}
}, 2000)
});
// 批量删除要素
it('successEvent:delete', (done) => {
var deleteFeatureResult = null;
var deleteFeaturesParams = new EditFeaturesParameters({
dataSourceName: "Jingjin",
dataSetName: "Landuse_R",
IDs: [id1, id2],
editType: "delete"
});
var deleteFeaturesService = featureService(editServiceURL);
deleteFeaturesService.editFeatures(deleteFeaturesParams, (result) => {
deleteFeatureResult = result
});
setTimeout(() => {
try {
expect(deleteFeaturesService).not.toBeNull();
expect(deleteFeatureResult).not.toBeNull();
expect(deleteFeatureResult.type).toBe("processCompleted");
var id = "[" + id1 + "," + id2 + "]";
expect(deleteFeatureResult.object.options.data).toBe(id);
expect(deleteFeatureResult.object.options.method).toBe("DELETE");
expect(deleteFeatureResult.result.succeed).toBeTruthy();
deleteFeaturesService.destroy();
done();
} catch (exception) {
expect(false).toBeTruthy();
console.log("'successEvent:deleteFeatures'案例失败" + exception.name + ":" + exception.message);
deleteFeaturesService.destroy();
done();
}
}, 2000);
});
// 更新要素
// 首先确认从服务器上获取一个有效要素
it('getFeatureForUpdate', (done) => {
var getFeatureResult = null;
var getFeaturesByIDsParams = new GetFeaturesByIDsParameters({
returnContent: true,
datasetNames: ["Jingjin:Landuse_R"],
IDs: [1]
});
var getFeaturesByIDsService = featureService(editServiceURL);
getFeaturesByIDsService.getFeaturesByIDs(getFeaturesByIDsParams, (result) => {
getFeatureResult = result
});
setTimeout(() => {
if (getFeatureResult != null) {
expect(getFeaturesByIDsService).not.toBeNull();
expect(getFeatureResult.type).toBe("processCompleted");
expect(getFeatureResult.result).not.toBeNull();
expect(getFeatureResult.result.succeed).toBeTruthy();
originFeature = getFeatureResult.result.features.features[0];
getFeaturesByIDsService.destroy();
done();
} else {
originFeature = null;
console.log("未获取到数据");
getFeaturesByIDsService.destroy();
done();
}
}, 4000)
});
// 将上面获取的要素update
it('successEvent:update', (done) => {
var updateFeatureResult = null;
if (originFeature != null) {
var random = parseInt(Math.random() * 10000000);
originFeature.properties.LANDTYPE = "用材林" + random;
var updateFeaturesParams = new EditFeaturesParameters({
dataSourceName: "Jingjin",
dataSetName: "Landuse_R",
features: originFeature,
editType: "update"
});
var updateFeaturesService = featureService(editServiceURL);
updateFeaturesService.editFeatures(updateFeaturesParams, (result) => {
updateFeatureResult = result
});
setTimeout(() => {
if (updateFeatureResult != null) {
try {
console.log(updateFeatureResult);
expect(updateFeaturesService).not.toBeNull();
expect(updateFeatureResult).not.toBeNull();
expect(updateFeatureResult.type).toBe("processCompleted");
expect(updateFeatureResult.result.succeed).toBeTruthy();
updateFeaturesService.destroy();
done();
} catch (exception) {
expect(false).toBeTruthy();
console.log("'successEvent:updateFeature'案例失败" + exception.name + ":" + exception.message);
updateFeaturesService.destroy();
done();
}
}
else {
console.log("'updateFeature'在设置的延时时间内未完成要素更新");
done();
}
}, 5000);
}
else {
console.log("'updateFeature'未获取到数据");
done();
}
});
});
|
'use strict';
// Define the `carouselMain` module
var carouselMain = angular.module('carouselMain', []);
// Register `carouselMain` component, along with its associated controller and template
carouselMain.
component('carouselMain', {
templateUrl: 'components/ui/carousel-main/carousel-main.template.html',
controller:
function CarouselMainController() {
this.image = [
'img/poster/poster1.jpg',
'img/poster/poster2.jpg',
'img/poster/poster3.jpg',
'img/poster/poster4.jpg'
];
}
});
|
const colors = require('../graphics/colors');
module.exports = class Ctx {
constructor(message, commandName, args) {
this.message = message;
this.channel = message.channel;
this.guild = message.guild;
this.user = message.author;
this.member = message.member;
this.commandName = commandName;
this.args = args;
}
async react(reaction) {
await this.message.react(reaction);
}
async sendText(text, options = {}) {
await this.channel.send(text, options);
}
async sendEmbed(embed, options = {}) {
await this.channel.send(embed, options);
}
async sendTextAndEmbed(text, embed, options = {}) {
options.embed = embed;
await this.channel.send(text, options);
}
get hexColor() {
return this.guild ? this.guild.me.displayHexColor : colors.primary;
}
get guildID() {
return this.guild ? this.guild.id : null;
}
get userID() {
return this.user.id;
}
get channelID() {
return this.channel.id;
}
};
|
// FR lang variables
// Modified by Motte, last updated 2006-03-23
tinyMCE.addToLang('',{
paste_text_desc : 'Coller comme du texte',
paste_text_title : 'Faites CTRL+V pour coller le texte dans la fenêtre.',
paste_text_linebreaks : 'Conserver les retours à la ligne',
paste_word_desc : 'Coller depuis Word',
paste_word_title : 'Faites CTRL+V pour coller le texte dans la fenêtre.',
selectall_desc : 'Sélectionner tout'
});
|
import argparse
import logging
import os
import torch
import torch.utils.data
from model.config import cfg
from model.engine.inference import do_evaluation
from model.modeling.detector import build_detection_model
from model.utils import dist_util
from model.utils.checkpoint import CheckPointer
from model.utils.dist_util import synchronize
from model.utils.logger import setup_logger
def evaluation(cfg, ckpt, distributed):
logger = logging.getLogger("SSD.inference")
model = build_detection_model(cfg)
checkpointer = CheckPointer(model, save_dir=cfg.OUTPUT_DIR, logger=logger)
device = torch.device(cfg.MODEL.DEVICE)
model.to(device)
checkpointer.load(ckpt, use_latest=ckpt is None)
do_evaluation(cfg, model, distributed)
def main():
parser = argparse.ArgumentParser(description='SSD Evaluation on VOC and COCO dataset.')
parser.add_argument(
"--config-file",
default="",
metavar="FILE",
help="path to config file",
type=str,
)
parser.add_argument("--local_rank", type=int, default=0)
parser.add_argument(
"--ckpt",
help="The path to the checkpoint for test, default is the latest checkpoint.",
default=None,
type=str,
)
parser.add_argument("--output_dir", default="eval_results", type=str, help="The directory to store evaluation results.")
parser.add_argument(
"opts",
help="Modify config options using the command-line",
default=None,
nargs=argparse.REMAINDER,
)
args = parser.parse_args()
num_gpus = int(os.environ["WORLD_SIZE"]) if "WORLD_SIZE" in os.environ else 1
distributed = num_gpus > 1
if torch.cuda.is_available():
# This flag allows you to enable the inbuilt cudnn auto-tuner to
# find the best algorithm to use for your hardware.
torch.backends.cudnn.benchmark = True
if distributed:
torch.cuda.set_device(args.local_rank)
torch.distributed.init_process_group(backend="nccl", init_method="env://")
synchronize()
cfg.merge_from_file(args.config_file)
cfg.merge_from_list(args.opts)
cfg.freeze()
# evaluation(cfg, ckpt=args.ckpt, distributed=distributed)
logger = setup_logger("SSD", dist_util.get_rank(), cfg.OUTPUT_DIR)
logger.info("Using {} GPUs".format(num_gpus))
logger.info(args)
logger.info("Loaded configuration file {}".format(args.config_file))
with open(args.config_file, "r") as cf:
config_str = "\n" + cf.read()
logger.info(config_str)
logger.info("Running with config:\n{}".format(cfg))
evaluation(cfg, ckpt=args.ckpt, distributed=distributed)
if __name__ == '__main__':
main()
|
(function($){
$.fn.validationEngineLanguage = function(){
};
$.validationEngineLanguage = {
newLang: function(){
$.validationEngineLanguage.allRules = {
"required": { // Add your regex rules here, you can take telephone as an example
"regex": "none",
"alertText": "* 此欄位不可空白",
"alertTextCheckboxMultiple": "* 請選擇一個項目",
"alertTextCheckboxe": "* 您必需勾選此欄位",
"alertTextDateRange": "* 日期範圍欄位都不可空白"
},
"dateRange": {
"regex": "none",
"alertText": "* 無效的 ",
"alertText2": " 日期範圍"
},
"dateTimeRange": {
"regex": "none",
"alertText": "* 無效的 ",
"alertText2": " 時間範圍"
},
"minSize": {
"regex": "none",
"alertText": "* 最少 ",
"alertText2": " 個字元"
},
"maxSize": {
"regex": "none",
"alertText": "* 最多 ",
"alertText2": " 個字元"
},
"groupRequired": {
"regex": "none",
"alertText": "* 你必需選填其中一個欄位"
},
"min": {
"regex": "none",
"alertText": "* 最小值為 "
},
"max": {
"regex": "none",
"alertText": "* 最大值為 "
},
"past": {
"regex": "none",
"alertText": "* 日期必需早於 "
},
"future": {
"regex": "none",
"alertText": "* 日期必需晚於 "
},
"maxCheckbox": {
"regex": "none",
"alertText": "* 最多選取 ",
"alertText2": " 個項目"
},
"minCheckbox": {
"regex": "none",
"alertText": "* 請選取 ",
"alertText2": " 個項目"
},
"equals": {
"regex": "none",
"alertText": "* 欄位內容不相符"
},
"phone": {
// credit: jquery.h5validate.js / orefalo
"regex": /^([\+][0-9]{1,3}[ \.\-])?([\(]{1}[0-9]{2,6}[\)])?([0-9 \.\-\/]{3,20})((x|ext|extension)[ ]?[0-9]{1,4})?$/,
"alertText": "* 無效的電話號碼"
},
"email": {
// Shamelessly lifted from Scott Gonzalez via the Bassistance Validation plugin http://projects.scottsplayground.com/email_address_validation/
"regex": /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i,
"alertText": "* Invalid email address"
},
"integer": {
"regex": /^[\-\+]?\d+$/,
"alertText": "* 不是有效的整數"
},
"number": {
// Number, including positive, negative, and floating decimal. credit: orefalo
"regex": /^[\-\+]?(([0-9]+)([\.,]([0-9]+))?|([\.,]([0-9]+))?)$/,
"alertText": "* 無效的數字"
},
"date": {
"regex": /^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])$/,
"alertText": "* 無效的日期,格式必需為 YYYY-MM-DD"
},
"ipv4": {
"regex": /^((([01]?[0-9]{1,2})|(2[0-4][0-9])|(25[0-5]))[.]){3}(([0-1]?[0-9]{1,2})|(2[0-4][0-9])|(25[0-5]))$/,
"alertText": "* 無效的 IP 位址"
},
"url": {
"regex": /^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i,
"alertText": "* Invalid URL"
},
"onlyNumberSp": {
"regex": /^[0-9\ ]+$/,
"alertText": "* 只能填數字"
},
"onlyLetterSp": {
"regex": /^[a-zA-Z\ \']+$/,
"alertText": "* 只接受英文字母大小寫"
},
"onlyLetterNumber": {
"regex": /^[0-9a-zA-Z]+$/,
"alertText": "* 不接受特殊字元"
},
// --- CUSTOM RULES -- Those are specific to the demos, they can be removed or changed to your likings
"ajaxUserCall": {
"url": "ajaxValidateFieldUser",
// you may want to pass extra data on the ajax call
"extraData": "name=eric",
"alertText": "* 此名稱已經被其他人使用",
"alertTextLoad": "* 正在確認名稱是否有其他人使用,請稍等。"
},
"ajaxUserCallPhp": {
"url": "phpajax/ajaxValidateFieldUser.php",
// you may want to pass extra data on the ajax call
"extraData": "name=eric",
// if you provide an "alertTextOk", it will show as a green prompt when the field validates
"alertTextOk": "* 此帳號名稱可以使用",
"alertText": "* 此帳號名稱已經被其他人使用",
"alertTextLoad": "* 正在確認帳號名稱是否有其他人使用,請稍等。"
},
"ajaxNameCall": {
// remote json service location
"url": "ajaxValidateFieldName",
// error
"alertText": "* 此名稱可以使用",
// if you provide an "alertTextOk", it will show as a green prompt when the field validates
"alertTextOk": "* 此名稱已經被其他人使用",
// speaks by itself
"alertTextLoad": "* 正在確認名稱是否有其他人使用,請稍等。"
},
"ajaxNameCallPhp": {
// remote json service location
"url": "phpajax/ajaxValidateFieldName.php",
// error
"alertText": "* 此名稱已經被其他人使用",
// speaks by itself
"alertTextLoad": "* 正在確認名稱是否有其他人使用,請稍等。"
},
"validate2fields": {
"alertText": "* 請輸入 HELLO"
},
//tls warning:homegrown not fielded
"dateFormat":{
"regex": /^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])$|^(?:(?:(?:0?[13578]|1[02])(\/|-)31)|(?:(?:0?[1,3-9]|1[0-2])(\/|-)(?:29|30)))(\/|-)(?:[1-9]\d\d\d|\d[1-9]\d\d|\d\d[1-9]\d|\d\d\d[1-9])$|^(?:(?:0?[1-9]|1[0-2])(\/|-)(?:0?[1-9]|1\d|2[0-8]))(\/|-)(?:[1-9]\d\d\d|\d[1-9]\d\d|\d\d[1-9]\d|\d\d\d[1-9])$|^(0?2(\/|-)29)(\/|-)(?:(?:0[48]00|[13579][26]00|[2468][048]00)|(?:\d\d)?(?:0[48]|[2468][048]|[13579][26]))$/,
"alertText": "* 無效的日期格式"
},
//tls warning:homegrown not fielded
"dateTimeFormat": {
"regex": /^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])\s+(1[012]|0?[1-9]){1}:(0?[1-5]|[0-6][0-9]){1}:(0?[0-6]|[0-6][0-9]){1}\s+(am|pm|AM|PM){1}$|^(?:(?:(?:0?[13578]|1[02])(\/|-)31)|(?:(?:0?[1,3-9]|1[0-2])(\/|-)(?:29|30)))(\/|-)(?:[1-9]\d\d\d|\d[1-9]\d\d|\d\d[1-9]\d|\d\d\d[1-9])$|^((1[012]|0?[1-9]){1}\/(0?[1-9]|[12][0-9]|3[01]){1}\/\d{2,4}\s+(1[012]|0?[1-9]){1}:(0?[1-5]|[0-6][0-9]){1}:(0?[0-6]|[0-6][0-9]){1}\s+(am|pm|AM|PM){1})$/,
"alertText": "* 無效的日期或時間格式",
"alertText2": "可接受的格式: ",
"alertText3": "mm/dd/yyyy hh:mm:ss AM|PM 或 ",
"alertText4": "yyyy-mm-dd hh:mm:ss AM|PM"
}
};
}
};
$.validationEngineLanguage.newLang();
})(jQuery);
|
const options = {
loop: true,
nav: true,
dots: false,
autoplayHoverPause: true,
autoplay: true,
navText: ["<i class='fas fa-chevron-left'></i>", "<i class='fas fa-chevron-right'></i>"],
responsive: {
0: {
items: 1,
},
576: {
items: 2,
},
768: {
items: 2,
},
1024: {
items: 3,
},
1200: {
items: 4,
},
},
};
export default options;
|
# Copyright 2020 Adam Liddell
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Minimal Python S2 Geometry cell ID, token and lat/lon conversion library."""
import math
import re
from typing import Optional, Tuple
#
# s2cell exceptions
#
class InvalidCellID(Exception):
"""Exception type for invalid cell IDs."""
class InvalidToken(Exception):
"""Exception type for invalid tokens."""
#
# S2 base constants needed for cell mapping
#
# The maximum level supported within an S2 cell ID. Each level is represented by two bits in the
# final cell ID
_S2_MAX_LEVEL = 30
# The maximum value within the I and J bits of an S2 cell ID
_S2_MAX_SIZE = 1 << _S2_MAX_LEVEL
# The number of bits in a S2 cell ID used for specifying the base face
_S2_FACE_BITS = 3
# The number of bits in a S2 cell ID used for specifying the position along the Hilbert curve
_S2_POS_BITS = 2 * _S2_MAX_LEVEL + 1
# The maximum value of the Si/Ti integers used when mapping from IJ to ST. This is twice the max
# value of I and J, since Si/Ti allow referencing both the center and edge of a leaf cell
_S2_MAX_SI_TI = 1 << (_S2_MAX_LEVEL + 1)
# Mask that specifies the swap orientation bit for the Hilbert curve
_S2_SWAP_MASK = 1
# Mask that specifies the invert orientation bit for the Hilbert curve
_S2_INVERT_MASK = 2
# The number of bits per I and J in the lookup tables
_S2_LOOKUP_BITS = 4
# Lookup table for mapping 10 bits of IJ + orientation to 10 bits of Hilbert curve position +
# orientation. Populated later by _s2_init_lookups
_S2_LOOKUP_POS = None
# Lookup table for mapping 10 bits of Hilbert curve position + orientation to 10 bits of IJ +
# orientation. Populated later by _s2_init_lookups
_S2_LOOKUP_IJ = None
# Lookup table of two bits of IJ from two bits of curve position, based also on the current curve
# orientation from the swap and invert bits
_S2_POS_TO_IJ = [
[0, 1, 3, 2], # 0: Normal order, no swap or invert
[0, 2, 3, 1], # 1: Swap bit set, swap I and J bits
[3, 2, 0, 1], # 2: Invert bit set, invert bits
[3, 1, 0, 2], # 3: Swap and invert bits set
]
# Lookup for the orientation update mask of one of the four sub-cells within a higher level cell.
# This mask is XOR'ed with the current orientation to get the sub-cell orientation.
_S2_POS_TO_ORIENTATION_MASK = [_S2_SWAP_MASK, 0, 0, _S2_SWAP_MASK | _S2_INVERT_MASK]
#
# S2 helper functions
#
def _s2_uv_to_st(component: float) -> float:
"""
Convert S2 UV to ST.
This is done using the quadratic projection that is used by default for S2. The C++ and Java S2
libraries use a different definition of the ST cell-space, but the end result in IJ is the same.
The below uses the C++ ST definition.
See s2geometry/blob/c59d0ca01ae3976db7f8abdc83fcc871a3a95186/src/s2/s2coords.h#L317-L320
"""
if component >= 0.0:
return 0.5 * math.sqrt(1.0 + 3.0 * component)
return 1.0 - 0.5 * math.sqrt(1.0 - 3.0 * component)
def _s2_st_to_uv(component: float) -> float:
"""
Convert S2 ST to UV.
This is done using the quadratic projection that is used by default for S2. The C++ and Java S2
libraries use a different definition of the ST cell-space, but the end result in IJ is the same.
The below uses the C++ ST definition.
See s2geometry/blob/c59d0ca01ae3976db7f8abdc83fcc871a3a95186/src/s2/s2coords.h#L312-L315
"""
if component >= 0.5:
return (1.0 / 3.0) * (4.0 * component ** 2 - 1.0)
return (1.0 / 3.0) * (1.0 - 4.0 * (1.0 - component) ** 2)
def _s2_st_to_ij(component: float) -> int:
"""
Convert S2 ST to IJ.
The mapping here differs between C++ and Java versions, but the combination of
_st_to_ij(_uv_to_st(val)) is the same for both. The below uses the C++ ST definition.
See s2geometry/blob/2c02e21040e0b82aa5719e96033d02b8ce7c0eff/src/s2/s2coords.h#L333-L336
"""
# The reference implementation does round(_S2_MAX_SIZE * component - 0.5), which is equivalent
# to math.floor(_S2_MAX_SIZE * component)
return int(max(0, min(_S2_MAX_SIZE - 1, math.floor(_S2_MAX_SIZE * component))))
def _s2_si_ti_to_st(component: int) -> float:
"""
Convert S2 Si/Ti to ST.
This converts an integer in range 0 to _S2_MAX_SI_TI into a float in range 0.0 to 1.0.
See s2geometry/blob/c59d0ca01ae3976db7f8abdc83fcc871a3a95186/src/s2/s2coords.h#L338-L341
"""
return (1.0 / _S2_MAX_SI_TI) * component
def _s2_face_uv_to_xyz( # pylint: disable=invalid-name
face: int, uv: Tuple[float, float]
) -> Tuple[float, float, float]:
"""
Convert face + UV to S2Point XYZ.
See s2geometry/blob/c59d0ca01ae3976db7f8abdc83fcc871a3a95186/src/s2/s2coords.h#L348-L357
Args:
face: The S2 face for the input point.
uv: The S2 face UV coordinates.
Returns:
The unnormalised S2Point XYZ.
Raises:
ValueError: If the face is not valid in range 0-5.
"""
# Face -> XYZ components -> indices with negation:
# 0 -> ( 1, u, v) -> ( /, 0, 1)
# 1 -> (-u, 1, v) -> (-0, /, 1)
# 2 -> (-u, -v, 1) -> (-0, -1, /)
# 3 -> (-1, -v, -u) -> (-/, -1, -0) <- -1 here means -1 times the value in index 1,
# 4 -> ( v, -1, -u) -> ( 1, -/, -0) not index -1
# 5 -> ( v, u, -1) -> ( 1, 0, -/)
if face == 0:
s2_point = (1, uv[0], uv[1])
elif face == 1:
s2_point = (-uv[0], 1, uv[1])
elif face == 2:
s2_point = (-uv[0], -uv[1], 1)
elif face == 3:
s2_point = (-1, -uv[1], -uv[0])
elif face == 4:
s2_point = (uv[1], -1, -uv[0])
elif face == 5:
s2_point = (uv[1], uv[0], -1)
else:
raise ValueError('Cannot convert UV to XYZ with invalid face: {}'.format(face))
return s2_point
def _s2_init_lookups() -> None:
"""
Initialise the S2 lookups in global vars _S2_LOOKUP_POS and _S2_LOOKUP_IJ.
This generates 4 variations of a 4 level deep Hilbert curve, one for each swap/invert bit
combination. This allows mapping between 8 bits (+2 orientation) of Hilbert curve position and 8
bits (+2 orientation) of I and J, and vice versa. The new orientation bits read from the mapping
tell us the base orientation of the curve segments within the next deeper level of sub-cells.
This implementation differs in structure from the reference implementation, since it is
iterative rather than recursive. The end result is the same lookup table.
See s2geometry/blob/c59d0ca01ae3976db7f8abdc83fcc871a3a95186/src/s2/s2cell_id.cc#L75-L109
"""
global _S2_LOOKUP_POS, _S2_LOOKUP_IJ # pylint: disable=global-statement
if _S2_LOOKUP_POS is None or _S2_LOOKUP_IJ is None: # pragma: no branch
# Initialise empty lookup tables
lookup_length = 1 << int(2 * _S2_LOOKUP_BITS + 2) # = 1024
_S2_LOOKUP_POS = [0] * lookup_length
_S2_LOOKUP_IJ = [0] * lookup_length
# Generate lookups for each of the base orientations given by the swap and invert bits
for base_orientation in [
0, _S2_SWAP_MASK, _S2_INVERT_MASK, _S2_SWAP_MASK | _S2_INVERT_MASK # 0-3 effectively
]:
# Walk the 256 possible positions within a level 4 curve. This implementation is not
# the fastest since it does not reuse the common ancestor of neighbouring positions, but
# is simpler to read
for pos in range(4 ** 4): # 4 levels of sub-divisions
ij = 0 # Has pattern iiiijjjj, not ijijijij # pylint: disable=invalid-name
orientation = base_orientation
# Walk the pairs of bits of pos, from most significant to least, getting IJ and
# orientation as we go
for bit_pair_offset in range(4):
# Bit pair is effectively the sub-cell index
bit_pair = (pos >> ((3 - bit_pair_offset) * 2)) & 0b11
# Get the I and J for the sub-cell index. These need to be spread into iiiijjjj
# by inserting as bit positions 4 and 0
ij_bits = _S2_POS_TO_IJ[orientation][bit_pair]
ij = ( # pylint: disable=invalid-name
(ij << 1) # Free up position 4 and 0 from old IJ
| ((ij_bits & 2) << 3) # I bit in position 4
| (ij_bits & 1) # J bit in position 0
)
# Update the orientation with the new sub-cell orientation
orientation = orientation ^ _S2_POS_TO_ORIENTATION_MASK[bit_pair]
# Shift IJ and position to allow orientation bits in LSBs of lookup
ij <<= 2 # pylint: disable=invalid-name
pos <<= 2
# Write lookups
_S2_LOOKUP_POS[ij | base_orientation] = pos | orientation
_S2_LOOKUP_IJ[pos | base_orientation] = ij | orientation
#
# Cell ID <-> Token translation functions
#
def cell_id_to_token(cell_id: int) -> str:
"""
Convert S2 cell ID to a S2 token.
Converts the S2 cell ID to hex and strips any trailing zeros. The 0 cell ID token is represented
as 'X' to prevent it being an empty string.
See s2geometry/blob/c59d0ca01ae3976db7f8abdc83fcc871a3a95186/src/s2/s2cell_id.cc#L204-L220
Args:
cell_id: The S2 cell ID integer.
Returns:
The S2 token string for the S2 cell ID.
Raises:
TypeError: If the cell_id is not int.
"""
# Check type
if not isinstance(cell_id, int):
raise TypeError('Cannot convert S2 cell ID from type: {}'.format(type(cell_id)))
# The zero token is encoded as 'X' rather than as a zero-length string
if cell_id == 0:
return 'X'
# Convert cell ID to 16 character hex string and strip any implicit trailing zeros
return '{:016x}'.format(cell_id).rstrip('0')
def token_to_cell_id(token: str) -> int:
"""
Convert S2 token to S2 cell ID.
Restores the stripped 0 characters from the token and converts the hex string to integer.
See s2geometry/blob/c59d0ca01ae3976db7f8abdc83fcc871a3a95186/src/s2/s2cell_id.cc#L222-L239
Args:
token: The S2 token string. Can be upper or lower case hex string.
Returns:
The S2 cell ID for the S2 token.
Raises:
TypeError: If the token is not str.
InvalidToken: If the token length is over 16.
"""
# Check input
if not isinstance(token, str):
raise TypeError('Cannot convert S2 token from type: {}'.format(type(token)))
if len(token) > 16:
raise InvalidToken('Cannot convert S2 token with length > 16 characters')
# Check for the zero cell ID represented by the character 'x' or 'X' rather than as the empty
# string
if token in ('x', 'X'):
return 0
# Add stripped implicit zeros to create the full 16 character hex string
token = token + ('0' * (16 - len(token)))
# Convert to cell ID by converting hex to int
return int(token, 16)
#
# Encode functions
#
def lat_lon_to_cell_id( # pylint: disable=too-many-locals
lat: float, lon: float, level: int = 30
) -> int:
"""
Convert lat/lon to a S2 cell ID.
It is expected that the lat/lon provided are normalised, with latitude in the range -90 to 90.
Args:
lat: The latitude to convert, in degrees.
lon: The longitude to convert, in degrees.
level: The level of the cell ID to generate, from 0 up to 30.
Returns:
The S2 cell ID for the lat/lon location.
Raises:
ValueError: When level is not an integer, is < 0 or is > 30.
"""
if not isinstance(level, int) or level < 0 or level > _S2_MAX_LEVEL:
raise ValueError('S2 level must be integer >= 0 and <= 30')
# Populate _S2_LOOKUP_POS on first run.
# See s2geometry/blob/c59d0ca01ae3976db7f8abdc83fcc871a3a95186/src/s2/s2cell_id.cc#L75-L109
#
# This table takes 10 bits of I and J and orientation and returns 10 bits of curve position and
# new orientation
if _S2_LOOKUP_POS is None: # pragma: no cover
_s2_init_lookups()
# Reuse constant expressions
lat_rad = math.radians(lat)
lon_rad = math.radians(lon)
sin_lat_rad = math.sin(lat_rad)
cos_lat_rad = math.cos(lat_rad)
sin_lon_rad = math.sin(lon_rad)
cos_lon_rad = math.cos(lon_rad)
# Convert to S2Point
# This is effectively the unit non-geodetic ECEF vector
s2_point = (
cos_lat_rad * cos_lon_rad, # X
cos_lat_rad * sin_lon_rad, # Y
sin_lat_rad # Z
)
# Get cube face
# See s2geometry/blob/2c02e21040e0b82aa5719e96033d02b8ce7c0eff/src/s2/s2coords.h#L380-L384
#
# The face is determined by the largest XYZ component of the S2Point vector. When the component
# is negative, the second set of three faces is used.
# Largest component -> face:
# +x -> 0
# +y -> 1
# +z -> 2
# -x -> 3
# -y -> 4
# -z -> 5
face = max(enumerate(s2_point), key=lambda p: abs(p[1]))[0] # Largest absolute component
if s2_point[face] < 0.0:
face += 3
# Convert face + XYZ to cube-space face + UV
# See s2geometry/blob/2c02e21040e0b82aa5719e96033d02b8ce7c0eff/src/s2/s2coords.h#L366-L372
#
# The faces are oriented to ensure continuity of curve.
# Face -> UV components -> indices with negation (without divisor, which is always the remaining
# component (index: face % 3)):
# 0 -> ( y, z) -> ( 1, 2)
# 1 -> (-x, z) -> (-0, 2)
# 2 -> (-x, -y) -> (-0, -1) <- -1 here means -1 times the value in index 1, not index -1
# 3 -> ( z, y) -> ( 2, 1)
# 4 -> ( z, -x) -> ( 2, -0)
# 5 -> (-y, -x) -> (-1, -0)
#
# For a compiled language, a switch statement on face is preferable as it will be more easily
# optimised as a jump table etc; but in Python the indexing method is more concise.
#
# The index selection can be reduced to some bit magic:
# U: 1 - ((face + 1) >> 1)
# V: 2 - (face >> 1)
#
# The negation of the the two components is then selected:
# U: (face in [1, 2, 5]) ? -1: 1
# V: (face in [2, 4, 5])) ? -1: 1
uv = ( # pylint: disable=invalid-name
s2_point[1 - ((face + 1) >> 1)] / s2_point[face % 3], # U
s2_point[2 - (face >> 1)] / s2_point[face % 3] # V
)
if face in (1, 2, 5):
uv = (-uv[0], uv[1]) # Negate U # pylint: disable=invalid-name
if face in (2, 4, 5):
uv = (uv[0], -uv[1]) # Negate V # pylint: disable=invalid-name
# Project cube-space UV to cell-space ST
# See s2geometry/blob/2c02e21040e0b82aa5719e96033d02b8ce7c0eff/src/s2/s2coords.h#L317-L320
st = (_s2_uv_to_st(uv[0]), _s2_uv_to_st(uv[1])) # pylint: disable=invalid-name
# Convert ST to IJ integers
# See s2geometry/blob/2c02e21040e0b82aa5719e96033d02b8ce7c0eff/src/s2/s2coords.h#L333-L336
ij = (_s2_st_to_ij(st[0]), _s2_st_to_ij(st[1])) # pylint: disable=invalid-name
# Convert face + IJ to cell ID
# See s2geometry/blob/c59d0ca01ae3976db7f8abdc83fcc871a3a95186/src/s2/s2cell_id.cc#L256-L298
#
# This is done by looking up 8 bits of I and J (4 each) at a time in the lookup table, along
# with two bits of orientation (swap (1) and invert (2)). This gives back 8 bits of position
# along the curve and two new orientation bits for the curve within the sub-cells in the next
# step.
#
# The swap bit swaps I and J with each other
# The invert bit inverts the bits of I and J, which means axes are negated
#
# Compared to the standard versions, we check the required number of steps we need to do for the
# requested level and don't perform steps that will be completely overwritten in the truncation
# below, rather than always doing every step. Each step does 4 bits each of I and J, which is 4
# levels, so the required number of steps is ceil((level + 2) / 4), when level is > 0. The
# additional 2 levels added are required to account for the top 3 bits (4 before right shift)
# that are occupied by the face bits.
bits = face & _S2_SWAP_MASK # iiiijjjjoo. Initially set by by face
cell_id = face << (_S2_POS_BITS - 1) # Insert face at second most signficant bits
lookup_mask = (1 << int(_S2_LOOKUP_BITS)) - 1 # Mask of 4 one bits: 0b1111
required_steps = math.ceil((level + 2) / 4) if level > 0 else 0
for k in range(7, 7 - required_steps, -1):
# Grab 4 bits of each of I and J
offset = k * _S2_LOOKUP_BITS
bits += ((ij[0] >> offset) & lookup_mask) << (_S2_LOOKUP_BITS + 2)
bits += ((ij[1] >> offset) & lookup_mask) << 2
# Map bits from iiiijjjjoo to ppppppppoo using lookup table
bits = _S2_LOOKUP_POS[bits]
# Insert position bits into cell ID
cell_id |= (bits >> 2) << (k * 2 * _S2_LOOKUP_BITS)
# Remove position bits, leaving just new swap and invert bits for the next round
bits &= _S2_SWAP_MASK | _S2_INVERT_MASK # Mask: 0b11
# Left shift and add trailing bit
# The trailing bit addition is disabled, as we are overwriting this below in the truncation
# anyway. This line is kept as an example of the full method for S2 cell ID creation as is done
# in the standard library versions.
cell_id = cell_id << 1 # + 1
# Truncate to desired level
# This is done by finding the mask of the trailing 1 bit for the specified level, then zeroing
# out all bits less significant than this, then finally setting the trailing 1 bit. This is
# still necessary to do even after a reduced number of steps `required_steps` above, since each
# step contains multiple levels that may need partial overwrite. Additionally, we need to add
# the trailing 1 bit, which is not yet set above.
least_significant_bit_mask = 1 << (2 * (_S2_MAX_LEVEL - level))
cell_id = (cell_id & -least_significant_bit_mask) | least_significant_bit_mask
return cell_id
def lat_lon_to_token(lat: float, lon: float, level: int = 30) -> str:
"""
Convert lat/lon to a S2 token.
Converts the S2 cell ID to hex and strips any trailing zeros. The 0 cell ID token is represented
as 'X' to prevent it being an empty string.
It is expected that the lat/lon provided are normalised, with latitude in the range -90 to 90.
See s2geometry/blob/c59d0ca01ae3976db7f8abdc83fcc871a3a95186/src/s2/s2cell_id.cc#L204-L220
Args:
lat: The latitude to convert, in degrees.
lon: The longitude to convert, in degrees.
level: The level of the cell ID to generate, from 0 up to 30.
Returns:
The S2 token string for the lat/lon location.
Raises:
ValueError: When level is not an integer, is < 0 or is > 30.
"""
# Generate cell ID and convert to token
return cell_id_to_token(lat_lon_to_cell_id(lat=lat, lon=lon, level=level))
#
# Decode functions
#
def cell_id_to_lat_lon( # pylint: disable=too-many-locals
cell_id: int
) -> Tuple[float, float]:
"""
Convert S2 cell ID to lat/lon.
Args:
cell_id: The S2 cell ID integer.
Returns:
The lat/lon (in degrees) tuple generated from the S2 cell ID.
Raises:
TypeError: If the cell_id is not int.
InvalidCellID: If the cell_id is invalid.
"""
# Check input
if not cell_id_is_valid(cell_id):
raise InvalidCellID('Cannot decode invalid S2 cell ID: {}'.format(cell_id))
# Populate _S2_LOOKUP_IJ on first run.
# See s2geometry/blob/c59d0ca01ae3976db7f8abdc83fcc871a3a95186/src/s2/s2cell_id.cc#L75-L109
# This table takes 10 bits of curve position and orientation and returns 10 bits of I and J and
# new orientation
if _S2_LOOKUP_IJ is None: # pragma: no cover
_s2_init_lookups()
# Extract face + IJ from cell ID
# See s2geometry/blob/c59d0ca01ae3976db7f8abdc83fcc871a3a95186/src/s2/s2cell_id.cc#L312-L367
#
# This is done by looking up 8 bits of curve position at a time in the lookup table, along with
# two bits of orientation (swap (1) and invert (2)). This gives back 8 bits of I and J (4 each)
# and two new orientation bits for the curve within the sub-cells in the next step.
#
# The swap bit swaps I and J with each other
# The invert bit inverts the bits of I and J, which means axes are negated
#
# In the first loop (most significant bits), the 3 bits occupied by the face need to be masked
# out, since these are not set in the IJ to cell ID during encoding.
#
# The I and J returned here are of one of the two leaf (level 30) cells that are located
# diagonally closest to the cell center. This happens because repeated ..00.. will select the
# 'lower left' (for nominally oriented Hilbert curve segments) of the sub-cells. The ..10..
# arising from the trailing bit, prior to the repeated ..00.. bits, ensures we first pick the
# 'upper right' of the cell, then iterate in to lower left until we hit the leaf cell. This
# means we pick the leaf cell to the north east of the parent cell center (again for nominal
# orientation).
# However, in the case of the swapped and inverted curve segment (4th sub-curve segment), the
# ..10.. will select the 'lower left' and then iterate to the 'upper right' with each ..00..
# following. In that case, we will be offset left and down by one leaf cell in each of I and J,
# which needs to be fixed to have a consistent mapping. This is detectable by seeing that the
# final bit of I or J is 1 (i.e we have picked an odd row/column, which will happen concurrently
# in both I and J, so we only need to check one), except in case of level 29 where the logic is
# inverted and the correction needs to be applied when we pick an even row/column (i.e I/J ends
# in 0), since there are no trailing ..00.. available after the ``..10..`` when we are at level
# 29+.
#
# This behaviour can be captured in the expression:
# apply_correction = not leaf and (i ^ (is level 29)) & 1
# apply_correction = not leaf and (i ^ (cell_id >> 2)) & 1
#
# We check for level 29 by looking for the trailing 1 in the third LSB, when we already know
# that we are not a leaf cell (which could give false positive) by the initial check in the
# expression.
# See s2geometry/blob/c59d0ca01ae3976db7f8abdc83fcc871a3a95186/src/s2/s2cell_id.h#L503-L529
#
face = cell_id >> _S2_POS_BITS
bits = face & _S2_SWAP_MASK # ppppppppoo. Initially set by by face
lookup_mask = (1 << _S2_LOOKUP_BITS) - 1 # Mask of 4 one bits: 0b1111
i = 0
j = 0
for k in range(7, -1, -1):
# Pull out 8 bits of cell ID, except in first loop where we pull out only 4
n_bits = (_S2_MAX_LEVEL - 7 * _S2_LOOKUP_BITS) if k == 7 else _S2_LOOKUP_BITS
extract_mask = (1 << (2 * n_bits)) - 1 # 8 (or 4) one bits
bits += (
(cell_id >> (k * 2 * _S2_LOOKUP_BITS + 1)) & extract_mask
) << 2
# Map bits from ppppppppoo to iiiijjjjoo using lookup table
bits = _S2_LOOKUP_IJ[bits]
# Extract I and J bits
offset = k * _S2_LOOKUP_BITS
i += (bits >> (_S2_LOOKUP_BITS + 2)) << offset # Don't need lookup mask here
j += ((bits >> 2) & lookup_mask) << offset
# Remove I and J bits, leaving just new swap and invert bits for the next round
bits &= _S2_SWAP_MASK | _S2_INVERT_MASK # Mask: 0b11
# Resolve the center of the cell. For leaf cells, we add half the leaf cell size. For non-leaf
# cells, we currently have one of either two cells diagonally around the cell center and want
# to pick the leaf-cell edges that represent the parent cell center, as described above. The
# center_correction_delta is 2x the offset, as we left shift I and J first.
# This gives us the values Si and Ti, which are discrete representation of S and T in range 0 to
# _S2_MAX_SI_TI. The extra power of 2 over IJ allows for identifying both the center and edge of
# cells, whilst IJ is just the leaf cells.
# See s2geometry/blob/c59d0ca01ae3976db7f8abdc83fcc871a3a95186/src/s2/s2coords.h#L57-L65
is_leaf = bool(cell_id & 1) # Cell is leaf cell when trailing one bit is in LSB
apply_correction = not is_leaf and ((i ^ (cell_id >> 2)) & 1)
correction_delta = 1 if is_leaf else (2 if apply_correction else 0)
si = (i << 1) + correction_delta # pylint: disable=invalid-name
ti = (j << 1) + correction_delta # pylint: disable=invalid-name
# Convert integer si/ti to double ST
# See s2geometry/blob/c59d0ca01ae3976db7f8abdc83fcc871a3a95186/src/s2/s2coords.h#L338-L341
st = (_s2_si_ti_to_st(si), _s2_si_ti_to_st(ti)) # pylint: disable=invalid-name
# Project cell-space ST to cube-space UV
# See s2geometry/blob/c59d0ca01ae3976db7f8abdc83fcc871a3a95186/src/s2/s2coords.h#L312-L315
uv = (_s2_st_to_uv(st[0]), _s2_st_to_uv(st[1])) # pylint: disable=invalid-name
# Convert face + UV to S2Point XYZ
# See s2geometry/blob/c59d0ca01ae3976db7f8abdc83fcc871a3a95186/src/s2/s2coords.h#L348-L357
s2_point = _s2_face_uv_to_xyz(face, uv)
# Normalise XYZ S2Point vector
# This section is part of the reference implementation but is not necessary when mapping
# straight into lat/lon, since the normalised and unnormalised triangles used to calculate the
# angles are geometrically similar. If anything, the normalisation process loses precision when
# tested against the reference implementation, albeit not at a level that is important either
# way. The code below is left for demonstration of the normalisation process.
# norm = math.sqrt(s2_point[0] ** 2 + s2_point[1] ** 2 + s2_point[2] ** 2)
# s2_point = (s2_point[0] / norm, s2_point[1] / norm, s2_point[2] / norm)
# Map into lat/lon
# See s2geometry/blob/c59d0ca01ae3976db7f8abdc83fcc871a3a95186/src/s2/s2latlng.h#L196-L205
lat_rad = math.atan2(s2_point[2], math.sqrt(s2_point[0] ** 2 + s2_point[1] ** 2))
lon_rad = math.atan2(s2_point[1], s2_point[0])
return (math.degrees(lat_rad), math.degrees(lon_rad))
def token_to_lat_lon(token: str) -> Tuple[float, float]:
"""
Convert S2 token to lat/lon.
See s2geometry/blob/c59d0ca01ae3976db7f8abdc83fcc871a3a95186/src/s2/s2cell_id.cc#L222-L239
Args:
token: The S2 token string. Can be upper or lower case hex string.
Returns:
The lat/lon (in degrees) tuple generated from the S2 token.
Raises:
TypeError: If the token is not str.
InvalidToken: If the token length is over 16.
InvalidToken: If the token is invalid.
InvalidCellID: If the contained cell_id is invalid.
"""
# Check input
if not token_is_valid(token):
raise InvalidToken('Cannot decode invalid S2 token: {}'.format(token))
# Convert to cell ID and decode to lat/lon
return cell_id_to_lat_lon(token_to_cell_id(token))
#
# Token canonicalisation
#
def token_to_canonical_token(token: str) -> str:
"""
Convert S2 token to a canonicalised S2 token.
This produces a token that matches the form generated by the reference C++ implementation:
- Lower case (except 'X' below)
- No whitespace
- Trailing '0' characters stripped
- Zero cell ID represented as 'X', not 'x' or ''
Args:
token: The S2 token string to canonicalise.
Returns:
The canonicalised S2 token.
"""
# Convert token to lower case.
# Note that 'X' below will be returned upper case
token = token.lower()
# Strip any surrounding whitespace
token = token.strip()
# Strip any trailing zeros
token = token.rstrip('0')
# If empty string or 'x', return 'X' token
if token in ('', 'x'):
token = 'X'
return token
#
# Validation
#
def cell_id_is_valid(cell_id: int) -> bool:
"""
Check that a S2 cell ID is valid.
Looks for valid face bits and a trailing 1 bit in one of the correct locations.
Args:
cell_id: The S2 cell integer to validate.
Returns:
True if the cell ID is valid, False otherwise.
Raises:
TypeError: If the cell_id is not int.
"""
# Check input
if not isinstance(cell_id, int):
raise TypeError('Cannot decode S2 cell ID from type: {}'.format(type(cell_id)))
# Check for zero ID
# This avoids overflow warnings below when 1 gets added to max uint64
if cell_id == 0:
return False
# Check face bits
if (cell_id >> _S2_POS_BITS) > 5:
return False
# Check trailing 1 bit is in one of the even bit positions allowed for the 30 levels, using the
# mask: 0b0001010101010101010101010101010101010101010101010101010101010101 = 0x1555555555555555
lowest_set_bit = cell_id & (~cell_id + 1) # pylint: disable=invalid-unary-operand-type
if not lowest_set_bit & 0x1555555555555555:
return False
return True # Checks have passed, cell ID must be valid
def token_is_valid(token: str) -> bool:
"""
Check that a S2 token is valid.
Looks for valid characters, then checks that the contained S2 cell ID is also valid. Note that
the '', 'x' and 'X' tokens are considered invalid, since the cell IDs they represent are
invalid.
Args:
token: The S2 token string to validate.
Returns:
True if the token is valid, False otherwise.
Raises:
TypeError: If the token is not str.
"""
# Check input
if not isinstance(token, str):
raise TypeError('Cannot check S2 token with type: {}'.format(type(token)))
# First check string with regex
if not re.match(r'^[0-9a-fA-f]{1,16}$', token):
return False
# Check the contained cell ID is valid
return cell_id_is_valid(token_to_cell_id(token))
#
# Level extraction functions
#
def cell_id_to_level(cell_id: int) -> int:
"""
Get the level for a S2 cell ID.
See s2geometry/blob/c59d0ca01ae3976db7f8abdc83fcc871a3a95186/src/s2/s2cell_id.h#L543-L551
Args:
cell_id: The S2 cell ID integer.
Returns:
The level of the S2 cell ID.
Raises:
TypeError: If the cell_id is not int.
InvalidCellID: If the cell_id is invalid.
"""
# Check input
if not cell_id_is_valid(cell_id):
raise InvalidCellID('Cannot decode invalid S2 cell ID: {}'.format(cell_id))
# Find the position of the lowest set one bit, which will be the trailing one bit. The level is
# given by the max level (30) minus the floored division by two of the position of the lowest
# set bit.
#
# The position of the lowest set bit is found using 'count trailing zeros', which would be
# equivalent to the C++20 function std::countr_zero() or the ctz instruction.
lsb_pos = 0
while cell_id != 0: # pragma: no branch
if cell_id & 1:
break
lsb_pos += 1
cell_id >>= 1
return int(_S2_MAX_LEVEL - (lsb_pos >> 1))
def token_to_level(token: str) -> int:
"""
Get the level for a S2 token.
See s2geometry/blob/c59d0ca01ae3976db7f8abdc83fcc871a3a95186/src/s2/s2cell_id.h#L543-L551
Args:
token: The S2 token string. Can be upper or lower case hex string.
Returns:
The level of the S2 token.
Raises:
TypeError: If the token is not str.
InvalidToken: If the token length is over 16.
InvalidToken: If the token is invalid.
InvalidCellID: If the contained cell_id is invalid.
"""
# Check input
if not token_is_valid(token):
raise InvalidToken('Cannot decode invalid S2 token: {}'.format(token))
# Convert to cell ID and get the level for that
return cell_id_to_level(token_to_cell_id(token))
#
# Parent functions
#
def cell_id_to_parent_cell_id(
cell_id: int, level: Optional[int] = None
) -> int:
"""
Get the parent cell ID of a S2 cell ID.
Args:
cell_id: The S2 cell ID integer.
level: The parent level to get the cell ID for. Must be less than or equal to the current
level of the provided cell ID. If unspecified, or None, the direct parent cell ID will
be returned.
Returns:
The parent cell ID at the specified level.
Raises:
TypeError: If the cell_id is not int.
InvalidCellID: If the cell_id is invalid.
ValueError: If cell ID is already level 0 and level is None.
ValueError: When level is not an integer, is < 0 or is > 30.
ValueError: If level is greater than the provided cell ID level.
"""
# Check input
if not cell_id_is_valid(cell_id):
raise InvalidCellID('Cannot decode invalid S2 cell ID: {}'.format(cell_id))
# Get current level of the cell ID and check it is suitable with the requested level
current_level = cell_id_to_level(cell_id)
if level is None and current_level == 0:
raise ValueError('Cannot get parent cell ID of a level 0 cell ID')
if level is None:
level = current_level - 1
if not isinstance(level, int) or level < 0 or level > _S2_MAX_LEVEL:
raise ValueError('S2 level must be integer >= 0 and <= 30')
if level > current_level:
raise ValueError('Cannot get level {} parent cell ID of cell ID with level {}'.format(
level, current_level
))
if level == current_level:
# Requested parent level is current level, return cell ID itself
return cell_id
# Truncate to desired level
# This is done by finding the mask of the trailing 1 bit for the specified level, then zeroing
# out all bits less significant than this, then finally setting the trailing 1 bit. This is
# still necessary to do even after a reduced number of steps `required_steps` above, since each
# step contains multiple levels that may need partial overwrite. Additionally, we need to add
# the trailing 1 bit, which is not yet set above.
least_significant_bit_mask = 1 << (2 * (_S2_MAX_LEVEL - level))
cell_id = (cell_id & -least_significant_bit_mask) | least_significant_bit_mask
return cell_id
def token_to_parent_token(token: str, level: Optional[int] = None) -> str:
"""
Get the parent token of a S2 token.
Args:
token: The S2 token string. Can be upper or lower case hex string.
level: The parent level to get the token for. Must be less than or equal to the current
level of the provided toke. If unspecified, or None, the direct parent token will be
returned.
Returns:
The parent token at the specified level.
Raises:
TypeError: If the token is not str.
InvalidToken: If the token length is over 16.
InvalidToken: If the token is invalid.
InvalidCellID: If the contained cell_id is invalid.
ValueError: If token is already level 0 and level is None.
ValueError: When level is not an integer, is < 0 or is > 30.
ValueError: If level is greater than the provided token level.
"""
# Check input
if not token_is_valid(token):
raise InvalidToken('Cannot decode invalid S2 token: {}'.format(token))
# Convert to cell ID and get parent and convert back to token
return cell_id_to_token(cell_id_to_parent_cell_id(token_to_cell_id(token), level))
|
goog.require('os.histo.Bin');
goog.require('os.histo.FilterComponent');
goog.require('os.histo.UniqueBinMethod');
describe('os.histo.UniqueBinMethod', function() {
var method = new os.histo.UniqueBinMethod();
method.setField('field');
it('should get the correct string key', function() {
var item = {field: 'Tada!'};
var value = method.getValue(item);
var key = method.getBinKey(value);
expect(key).toBe(value);
expect(key).toBe('Tada!');
});
it('should get the correct numeric key', function() {
var item = {field: 10};
var value = method.getValue(item);
var key = method.getBinKey(value);
expect(key).toBe(value);
expect(key).toBe('10');
});
it('should get the correct null/undefined key and label', function() {
var value = method.getValue({});
var key = method.getBinKey(value);
var label = method.getBinLabel(value);
expect(key).toBe(value);
expect(key).toBe(label);
expect(key).toBe('No field');
var value = method.getValue({field: null});
var key = method.getBinKey(value);
var label = method.getBinLabel(value);
expect(key).toBe(value);
expect(key).toBe(label);
expect(key).toBe('No field');
});
it('should filter dimensions correctly', function() {
var data = [
{field: 1},
{field: 10},
{field: 100}
];
var xf = crossfilter(data);
var dim = xf.dimension(function(d) {
return d.field;
});
var item = data[1];
method.filterDimension(dim, item);
var list = dim.top(Infinity);
expect(list.length).toBe(1);
expect(list[0]).toBe(item);
});
it('should export to filter correctly', function() {
var orHeader = '<Or>';
var orFooter = '</Or>';
var emptyFilter = os.histo.FilterComponent.IS_EMPTY_HEAD + 'field' + os.histo.FilterComponent.IS_EMPTY_TAIL;
// no bins to export
expect(method.exportAsFilter([])).toBe('');
// invalid bin isn't exported
var invalidBin = new os.histo.Bin();
invalidBin.setKey(os.histo.UniqueBinMethod.INVALID_VALUE);
expect(method.exportAsFilter([invalidBin])).toBe('');
// empty filter created correctly. single filter does not wrap in an Or block.
var emptyBin = new os.histo.Bin();
emptyBin.setKey('No field');
expect(method.exportAsFilter([emptyBin])).toBe(emptyFilter);
// bin with a value is exported. single filter does not wrap in an Or block.
var valueBin = new os.histo.Bin();
var theValue = 'TEST VALUE';
valueBin.setKey(theValue);
valueBin.setLabel(theValue);
var equalFilter = os.histo.FilterComponent.IS_EQUAL_HEAD + 'field' + os.histo.FilterComponent.IS_EQUAL_MID +
theValue + os.histo.FilterComponent.IS_EQUAL_TAIL;
expect(method.exportAsFilter([valueBin])).toBe(equalFilter);
// exports multiple bins, wrapped in an Or block
expect(method.exportAsFilter([emptyBin, valueBin]))
.toBe(orHeader + emptyFilter + equalFilter + orFooter);
// ignores invalid bins but still exports valid bins
expect(method.exportAsFilter([invalidBin, emptyBin, valueBin]))
.toBe(orHeader + emptyFilter + equalFilter + orFooter);
});
it('should clone correctly', function() {
var fn = function(value) {
return 'hi';
};
method.setValueFunction(fn);
var clone = method.clone();
expect(clone.getField()).toBe('field');
expect(clone.valueFunction).toBe(fn);
});
it('should restore correctly', function() {
var method = new os.histo.UniqueBinMethod();
method.setField('field');
// if the field isn't set, don't change it
method.restore({});
expect(method.getField()).toBe('field');
method.restore({
field: null
});
expect(method.getField()).toBe('field');
// sets the field if the value is a string
method.restore({
field: ''
});
expect(method.getField()).toBe('');
method.restore({
field: 'otherField'
});
expect(method.getField()).toBe('otherField');
});
});
|
from abc import abstractmethod
import abc
from strategery.exceptions import TaskError
class StrategeryFeature(metaclass=abc.ABCMeta):
@classmethod
def strategery_key(cls):
return cls
@staticmethod
@abstractmethod
def compute(*args, **kwargs):
raise NotImplementedError('StrategeryFeature must implement @staticmethod `compute`!')
|
import { ThemeProvider } from 'styled-components'
import Router from 'routes'
import theme, { GlobalCSS } from 'theme'
const App = () => (
<ThemeProvider theme={theme}>
<GlobalCSS />
<Router />
</ThemeProvider>
)
export default App
|
zipdata({"9502141":[15,"新潟市西区","内野潟端"],"9508623":[15,"新潟市中央区","美咲町","1丁目2番1号新潟美咲合同庁舎2号館"],"9502097":[15,"新潟市西区","寺尾東","3丁目14番41号"],"9508585":[15,"新潟市中央区","八千代","1丁目4-16"],"9500328":[15,"新潟市江南区","舞潟"],"9503341":[15,"新潟市北区","川西"],"9501464":[15,"新潟市南区","下道潟"],"9501144":[15,"新潟市中央区","祖父興野"],"9501196":[15,"新潟市西区","大野","2843-1"],"9500135":[15,"新潟市江南区","所島"],"9501213":[15,"新潟市南区","能登"],"9500106":[15,"新潟市東区","西野"],"9502022":[15,"新潟市西区","小針"],"9508612":[15,"新潟市中央区","弁天","3丁目2-3ニッセイ新潟駅前ビル1階"],"9500912":[15,"新潟市中央区","南笹口"],"9502255":[15,"新潟市西区","神山"],"9500326":[15,"新潟市江南区","上和田"],"9500152":[15,"新潟市江南区","亀田緑町"],"9502152":[15,"新潟市西区","五十嵐下崎山"],"9501443":[15,"新潟市南区","菱潟"],"9502101":[15,"新潟市西区","五十嵐一の町"],"9500972":[15,"新潟市中央区","新和"],"9503345":[15,"新潟市北区","長戸"],"9503114":[15,"新潟市北区","名目所"],"9500809":[15,"新潟市東区","柳ケ丘"],"9501466":[15,"新潟市南区","沖新保"],"9502043":[15,"新潟市西区","須賀"],"9501473":[15,"新潟市南区","下木山"],"9500195":[15,"新潟市江南区","泉町","3丁目4-5"],"9508668":[15,"新潟市中央区","弁天橋通","3丁目1番15号"],"9501115":[15,"新潟市西区","鳥原"],"9502161":[15,"新潟市西区","五十嵐西"],"9502025":[15,"新潟市西区","小針南"],"9500004":[15,"新潟市東区","新川町"],"9500111":[15,"新潟市江南区","直り山"],"9501114":[15,"新潟市西区","小平方"],"9501246":[15,"新潟市南区","下山崎"],"9508546":[15,"新潟市中央区","万代","3丁目1番1号メディアシップ14階"],"9500057":[15,"新潟市東区","山の下町"],"9501102":[15,"新潟市西区","善久"],"9500971":[15,"新潟市中央区","近江"],"9500991":[15,"新潟市中央区","下所島"],"9500922":[15,"新潟市中央区","山二ツ"],"9502028":[15,"新潟市西区","小新南"],"9501426":[15,"新潟市南区","新生町"],"9502026":[15,"新潟市西区","小針南台"],"9500982":[15,"新潟市中央区","堀之内南"],"9500943":[15,"新潟市中央区","女池神明"],"9500164":[15,"新潟市江南区","亀田本町"],"9501188":[15,"新潟市西区","善久","823"],"9501204":[15,"新潟市南区","大通西"],"9500073":[15,"新潟市中央区","日の出"],"9502254":[15,"新潟市西区","東山"],"9502062":[15,"新潟市西区","寺尾中央公園"],"9500804":[15,"新潟市東区","本所"],"9501111":[15,"新潟市西区","大野町"],"9503127":[15,"新潟市北区","松浜みなと"],"9500105":[15,"新潟市江南区","大淵"],"9501127":[15,"新潟市西区","大潟"],"9500121":[15,"新潟市江南区","亀田向陽"],"9502093":[15,"新潟市西区","寺尾朝日通","17番9号"],"9502011":[15,"新潟市西区","小針上山"],"9508794":[15,"新潟市中央区","万代","2丁目3-16リバービューSDビル3F"],"9501203":[15,"新潟市南区","大通黄金"],"9508611":[15,"新潟市中央区","弁天","3丁目2-3ニッセイ新潟駅前ビル2階"],"9500981":[15,"新潟市中央区","堀之内"],"9502092":[15,"新潟市西区","流通センター","4丁目6-2"],"9508666":[15,"新潟市中央区","沼垂東","6丁目8-1"],"9501295":[15,"新潟市南区","北田中","780-6"],"9501304":[15,"新潟市南区","月潟"],"9500141":[15,"新潟市江南区","亀田工業団地"],"9502006":[15,"新潟市西区","青山新町"],"9503363":[15,"新潟市北区","大久保"],"9501344":[15,"新潟市南区","福島"],"9500909":[15,"新潟市中央区","八千代"],"9502036":[15,"新潟市西区","新通西"],"9500023":[15,"新潟市東区","松園"],"9508507":[15,"新潟市中央区","東大通","1丁目2-30住友生命新潟ビル2階"],"9501254":[15,"新潟市南区","七穂"],"9502136":[15,"新潟市西区","勘助郷屋"],"9502143":[15,"新潟市西区","内野早角"],"9500323":[15,"新潟市江南区","嘉瀬"],"9501241":[15,"新潟市南区","下塩俵"],"9500946":[15,"新潟市中央区","女池西"],"9500102":[15,"新潟市北区","細山"],"9501148":[15,"新潟市中央区","上沼"],"9501348":[15,"新潟市西蒲区","打越"],"9501457":[15,"新潟市南区","清水"],"9503102":[15,"新潟市北区","島見町"],"9500137":[15,"新潟市江南区","城山"],"9500832":[15,"新潟市東区","下場新町"],"9502262":[15,"新潟市西区","藤蔵新田"],"9501227":[15,"新潟市南区","鰺潟"],"9508533":[15,"新潟市中央区","万代","1丁目3-30"],"9503368":[15,"新潟市北区","森下"],"9500156":[15,"新潟市江南区","早苗"],"9501134":[15,"新潟市江南区","天野"],"9500115":[15,"新潟市江南区","丸山"],"9508749":[15,"新潟市中央区","堀之内南","3丁目1-20"],"9500865":[15,"新潟市中央区","本馬越"],"9501181":[15,"新潟市西区","緒立流通","1丁目2-1"],"9501495":[15,"新潟市南区","和泉","651"],"9501256":[15,"新潟市南区","山王新田"],"9508504":[15,"新潟市中央区","東大通","2丁目4-10日本生命ビル"],"9500028":[15,"新潟市東区","小金台"],"9503369":[15,"新潟市北区","三ツ森川原"],"9503195":[15,"新潟市北区","新崎","2丁目6番1号"],"9500107":[15,"新潟市江南区","三百地"],"9508610":[15,"新潟市中央区","女池北","1丁目1-1"],"9501125":[15,"新潟市西区","流通"],"9501424":[15,"新潟市南区","下八枚"],"9500808":[15,"新潟市東区","海老ケ瀬新町"],"9508548":[15,"新潟市中央区","万代","3丁目1番1号メディアシップ13階"],"9502156":[15,"新潟市西区","内野関場"],"9502055":[15,"新潟市西区","寺尾上"],"9508539":[15,"新潟市中央区","万代","4丁目4-20"],"9500126":[15,"新潟市江南区","東本町"],"9500961":[15,"新潟市中央区","東出来島"],"9508503":[15,"新潟市中央区","東大通","2丁目1-18"],"9503356":[15,"新潟市北区","山飯野"],"9500127":[15,"新潟市江南区","諏訪"],"9503338":[15,"新潟市北区","長場"],"9508686":[15,"新潟市中央区","東幸町","11-11"],"9508522":[15,"新潟市中央区","東大通","1丁目2-30"],"9500202":[15,"新潟市江南区","藤山"],"9503305":[15,"新潟市北区","浦ノ入"],"9501406":[15,"新潟市南区","東笠巻新田"],"9503371":[15,"新潟市北区","下早通"],"9500122":[15,"新潟市江南区","稲葉"],"9503132":[15,"新潟市北区","松潟"],"9502074":[15,"新潟市西区","真砂"],"9501345":[15,"新潟市西蒲区","羽黒"],"9502076":[15,"新潟市西区","上新栄町"],"9500903":[15,"新潟市中央区","春日町"],"9500913":[15,"新潟市中央区","鐙"],"9503358":[15,"新潟市北区","灰塚"],"9503353":[15,"新潟市北区","長戸呂"],"9508736":[15,"新潟市中央区","小張木","15"],"9501233":[15,"新潟市南区","保坂"],"9500813":[15,"新潟市東区","大形本町"],"9501346":[15,"新潟市西蒲区","真木"],"9502023":[15,"新潟市西区","小新"],"9501349":[15,"新潟市西蒲区","牧ケ島"],"9500112":[15,"新潟市江南区","松山"],"9500134":[15,"新潟市江南区","曙町"],"9501123":[15,"新潟市西区","黒鳥"],"9502061":[15,"新潟市西区","寺尾北"],"9501452":[15,"新潟市南区","古川新田"],"9501492":[15,"新潟市南区","清水","4501-1"],"9500884":[15,"新潟市東区","榎"],"9503112":[15,"新潟市北区","太夫浜"],"9500812":[15,"新潟市東区","豊"],"9502138":[15,"新潟市西区","藤野木"],"9501121":[15,"新潟市西区","板井"],"9501221":[15,"新潟市南区","神屋"],"9500831":[15,"新潟市東区","下場"],"9508655":[15,"新潟市中央区","鐙西","2丁目29-12"],"9503326":[15,"新潟市北区","柳原"],"9502033":[15,"新潟市西区","亀貝"],"9500892":[15,"新潟市東区","寺山"],"9503306":[15,"新潟市北区","内島見"],"9501136":[15,"新潟市中央区","曽川"],"9500948":[15,"新潟市中央区","女池南"],"9502042":[15,"新潟市西区","坂井"],"9508558":[15,"新潟市中央区","新光町","6-2勤労福祉会館内"],"9508543":[15,"新潟市中央区","美咲町","1丁目2番1号新潟美咲合同庁舎2号館"],"9501242":[15,"新潟市南区","中塩俵"],"9501132":[15,"新潟市中央区","丸潟新田"],"9502146":[15,"新潟市西区","金巻新田"],"9500081":[15,"新潟市中央区","三和町"],"9502111":[15,"新潟市西区","大学南"],"9500983":[15,"新潟市中央区","神道寺"],"9500136":[15,"新潟市江南区","城所"],"9503376":[15,"新潟市北区","早通北"],"9503126":[15,"新潟市北区","松浜"],"9501222":[15,"新潟市南区","白根東町"],"9502004":[15,"新潟市西区","平島"],"9501407":[15,"新潟市南区","鷲ノ木新田"],"9500945":[15,"新潟市中央区","女池上山"],"9502171":[15,"新潟市西区","五十嵐三の町"],"9501261":[15,"新潟市南区","味方"],"9501186":[15,"新潟市西区","流通","1丁目5-13"],"9500963":[15,"新潟市中央区","南出来島"],"9503365":[15,"新潟市北区","太子堂"],"9501411":[15,"新潟市南区","赤渋"],"9501432":[15,"新潟市南区","十二道島"],"9508727":[15,"新潟市中央区","南長潟","12-10"],"9500138":[15,"新潟市江南区","日水"],"9502201":[15,"新潟市西区","四ツ郷屋"],"9508709":[15,"新潟市東区","下木戸","1丁目4番1号"],"9500027":[15,"新潟市東区","松和町"],"9508640":[15,"新潟市東区","小金町","3丁目1番1号"],"9502089":[15,"新潟市西区","流通センター","3丁目3-2"],"9502085":[15,"新潟市西区","真砂","1丁目14-1"],"9500013":[15,"新潟市東区","白銀"],"9500952":[15,"新潟市中央区","親松"],"9508720":[15,"新潟市東区","山木戸","8丁目8-1"],"9502075":[15,"新潟市西区","松海が丘"],"9508528":[15,"新潟市中央区","東大通","2丁目3-28"],"9508505":[15,"新潟市中央区","東大通","1丁目2-30"],"9500921":[15,"新潟市中央区","京王"],"9501182":[15,"新潟市西区","山田","2307"],"9500086":[15,"新潟市中央区","花園"],"9500292":[15,"新潟市江南区","横越中央","1丁目1-1"],"9501294":[15,"新潟市南区","味方","1544"],"9508708":[15,"新潟市東区","竹尾","638"],"9508553":[15,"新潟市中央区","新光町","4-1"],"9500022":[15,"新潟市東区","幸栄"],"9501324":[15,"新潟市西蒲区","高野宮"],"9508737":[15,"新潟市中央区","弁天橋通","3丁目4-10"],"9500082":[15,"新潟市中央区","東万代町"],"9508798":[15,"新潟市中央区","八千代","2丁目2-8"],"9500915":[15,"新潟市中央区","鐙西"],"9508613":[15,"新潟市中央区","弁天","3丁目2-3ニッセイ新潟駅前ビル"],"9502113":[15,"新潟市西区","内野山手"],"9502086":[15,"新潟市西区","真砂","3丁目16番10号"],"9500014":[15,"新潟市東区","松崎"],"9500012":[15,"新潟市東区","有楽"],"9503303":[15,"新潟市北区","横土居"],"9500992":[15,"新潟市中央区","上所上"],"9500033":[15,"新潟市東区","河渡新町"],"9501145":[15,"新潟市中央区","久蔵興野"],"9503334":[15,"新潟市北区","大月"],"9500324":[15,"新潟市江南区","酒屋町"],"9500217":[15,"新潟市江南区","阿賀野"],"9501247":[15,"新潟市南区","山崎興野"],"9508537":[15,"新潟市中央区","美咲町","1丁目2番1号新潟美咲合同庁舎2号館"],"9503362":[15,"新潟市北区","高森新田"],"9500841":[15,"新潟市東区","中野山"],"9501201":[15,"新潟市南区","大通"],"9508510":[15,"新潟市中央区","東大通","2丁目4-1"],"9501436":[15,"新潟市南区","田尾"],"9500322":[15,"新潟市江南区","両川"],"9508654":[15,"新潟市中央区","天神","1丁目12番8LEXNB7階"],"9500053":[15,"新潟市東区","宝町"],"9503354":[15,"新潟市北区","十二"],"9501428":[15,"新潟市南区","上浦"],"9501474":[15,"新潟市南区","上木山"],"9500148":[15,"新潟市江南区","東早通"],"9508681":[15,"新潟市中央区","女池南","3丁目2-32"],"9501194":[15,"新潟市西区","山田","2309番地7"],"9502041":[15,"新潟市西区","坂井東"],"9501332":[15,"新潟市西蒲区","長場"],"9503131":[15,"新潟市北区","濁川"],"9502126":[15,"新潟市西区","大友"],"9500155":[15,"新潟市江南区","泉町"],"9503359":[15,"新潟市北区","十二前"],"9500806":[15,"新潟市東区","海老ケ瀬"],"9501441":[15,"新潟市南区","蜘手興野"],"9501414":[15,"新潟市南区","小蔵子"],"9508721":[15,"新潟市江南区","山二ツ","381-4"],"9500855":[15,"新潟市東区","江南"],"9501314":[15,"新潟市南区","東長嶋"],"9500024":[15,"新潟市東区","河渡"],"9502035":[15,"新潟市西区","新通"],"9500203":[15,"新潟市江南区","小杉"],"9501147":[15,"新潟市中央区","高美町"],"9508583":[15,"新潟市中央区","上所","3丁目10-1"],"9500905":[15,"新潟市中央区","天神尾"],"9500994":[15,"新潟市中央区","上所"],"9500003":[15,"新潟市東区","下山"],"9508680":[15,"新潟市東区","海老ケ瀬","471"],"9501112":[15,"新潟市西区","金巻"],"9502145":[15,"新潟市西区","田島"],"9508559":[15,"新潟市中央区","新光町","1番地10"],"9501143":[15,"新潟市中央区","俵柳"],"9508603":[15,"新潟市中央区","女池","4丁目17-26"],"9508605":[15,"新潟市中央区","女池南","1丁目2-13"],"9501434":[15,"新潟市南区","櫛笥"],"9500803":[15,"新潟市東区","中興野"],"9508745":[15,"新潟市東区","榎町","75"],"9501301":[15,"新潟市南区","下曲通"],"9501326":[15,"新潟市西蒲区","東船越"],"9503311":[15,"新潟市北区","横井"],"9508715":[15,"新潟市東区","松島","1丁目2-8"],"9508629":[15,"新潟市中央区","美咲町","1丁目23-51"],"9508551":[15,"新潟市中央区","新光町","4-1"],"9503350":[15,"新潟市北区","横越"],"9500025":[15,"新潟市東区","藤見町"],"9502123":[15,"新潟市西区","笠木"],"9502264":[15,"新潟市西区","みずき野"],"9508580":[15,"新潟市中央区","上所中","3丁目14-8"],"9502044":[15,"新潟市西区","坂井砂山"],"9500169":[15,"新潟市江南区","亀田長潟"],"9500125":[15,"新潟市江南区","亀田新明町"],"9500985":[15,"新潟市中央区","和合町"],"9501445":[15,"新潟市南区","菱潟新田"],"9500062":[15,"新潟市東区","錦町"],"9508633":[15,"新潟市東区","小金町","1丁目7-20"],"9503103":[15,"新潟市北区","白勢町"],"9501258":[15,"新潟市南区","吉江"],"9508738":[15,"新潟市中央区","幸西","1丁目4-21"],"9503373":[15,"新潟市北区","須戸"],"9508622":[15,"新潟市中央区","美咲町","1丁目23-2"],"9501425":[15,"新潟市南区","戸石"],"9508724":[15,"新潟市中央区","和合町","2丁目4-18"],"9508524":[15,"新潟市中央区","東大通","2丁目4-10"],"9500129":[15,"新潟市江南区","三條岡"],"9501211":[15,"新潟市南区","白根古川"],"9501465":[15,"新潟市南区","上道潟"],"9502112":[15,"新潟市西区","内野町"],"9502172":[15,"新潟市西区","内野上新町"],"9503322":[15,"新潟市北区","嘉山"],"9508556":[15,"新潟市中央区","新光町","1-18"],"9502071":[15,"新潟市西区","西有明町"],"9501498":[15,"新潟市南区","次郎右エ門興野","字沼697番地"],"9500864":[15,"新潟市東区","紫竹"],"9502175":[15,"新潟市西区","五十嵐三の町南"],"9500104":[15,"新潟市江南区","笹山"],"9502084":[15,"新潟市西区","流通センター","4丁目5-2"],"9500842":[15,"新潟市東区","もえぎ野"],"9501471":[15,"新潟市南区","和泉"],"9502052":[15,"新潟市西区","寺尾"],"9503351":[15,"新潟市北区","大瀬柳"],"9502063":[15,"新潟市西区","寺尾台"],"9508677":[15,"新潟市東区","海老ケ瀬","994"],"9501417":[15,"新潟市南区","西笠巻新田"],"9501325":[15,"新潟市西蒲区","小吉"],"9501322":[15,"新潟市西蒲区","六分"],"9500901":[15,"新潟市中央区","弁天"],"9500103":[15,"新潟市江南区","蔵岡"],"9502003":[15,"新潟市西区","東青山"],"9508717":[15,"新潟市中央区","幸西","2丁目6-19"],"9503343":[15,"新潟市北区","上土地亀"],"9508540":[15,"新潟市中央区","万代","5丁目11-30"],"9503360":[15,"新潟市北区","小杉"],"9500071":[15,"新潟市東区","末広町"],"9503372":[15,"新潟市北区","早通"],"9500861":[15,"新潟市東区","中山"],"9502054":[15,"新潟市西区","寺尾東"],"9501215":[15,"新潟市南区","助次右エ門組"],"9508579":[15,"新潟市中央区","万代","2丁目1-1"],"9500953":[15,"新潟市中央区","大島"],"9500157":[15,"新潟市中央区","鵜ノ子"],"9500083":[15,"新潟市中央区","蒲原町"],"9501415":[15,"新潟市南区","引越"],"9502082":[15,"新潟市西区","流通センター","2丁目1-3"],"9508722":[15,"新潟市中央区","和合町","1丁目9-16"],"9500026":[15,"新潟市東区","小金町"],"9502038":[15,"新潟市西区","新通南"],"9500211":[15,"新潟市江南区","横越川根町"],"9500833":[15,"新潟市東区","下場本町"],"9501401":[15,"新潟市南区","獺ヶ通"],"9502095":[15,"新潟市西区","流通センター","2丁目2-3"],"9501423":[15,"新潟市南区","中小見"],"9500114":[15,"新潟市江南区","茗荷谷"],"9500821":[15,"新潟市東区","岡山"],"9500325":[15,"新潟市江南区","花ノ牧"],"9501234":[15,"新潟市南区","根岸"],"9501476":[15,"新潟市南区","平成町"],"9500015":[15,"新潟市東区","河渡庚"],"9502072":[15,"新潟市西区","松美台"],"9508501":[15,"新潟市中央区","東大通","1丁目2番25号北越第一ビルディング5F"],"9502256":[15,"新潟市西区","山崎"],"9500964":[15,"新潟市中央区","網川原"],"9500871":[15,"新潟市東区","山木戸"],"9508544":[15,"新潟市中央区","万代","1丁目6-1"],"9502027":[15,"新潟市西区","小新大通"],"9508602":[15,"新潟市中央区","女池","3丁目1-2"],"9503352":[15,"新潟市北区","長戸呂新田"],"9502147":[15,"新潟市西区","道河原"],"9508547":[15,"新潟市中央区","万代","3丁目1番1号メディアシップ3階"],"9502198":[15,"新潟市西区","流通センター","4丁目5-4"],"9502125":[15,"新潟市西区","中野小屋"],"9503331":[15,"新潟市北区","新鼻"],"9508661":[15,"新潟市中央区","万代","1丁目4-33"],"9501104":[15,"新潟市西区","寺地"],"9503355":[15,"新潟市北区","上堀田"],"9501334":[15,"新潟市西蒲区","上小吉"],"9500002":[15,"新潟市東区","根室新町"],"9500885":[15,"新潟市東区","下木戸"],"9508577":[15,"新潟市中央区","鳥屋野","331"],"9508732":[15,"新潟市中央区","上近江","2丁目19-14"],"9503133":[15,"新潟市北区","すみれ野"],"9500902":[15,"新潟市中央区","南万代町"],"9508678":[15,"新潟市東区","大形本町","3丁目1-2"],"9500167":[15,"新潟市江南区","五月町"],"9501245":[15,"新潟市南区","新山崎町"],"9500881":[15,"新潟市東区","榎町"],"9502188":[15,"新潟市西区","流通センター","2丁目2-1"],"9502021":[15,"新潟市西区","小針藤山"],"9501183":[15,"新潟市西区","金巻","字須上1657"],"9503327":[15,"新潟市北区","石動"],"9502155":[15,"新潟市西区","五十嵐上崎山"],"9502045":[15,"新潟市西区","五十嵐東"],"9501416":[15,"新潟市南区","西笠巻"],"9500087":[15,"新潟市中央区","東大通"],"9500883":[15,"新潟市東区","鴎島町"],"9500886":[15,"新潟市東区","中木戸"],"9501216":[15,"新潟市南区","白根ノ内七軒"],"9502261":[15,"新潟市西区","赤塚"],"9500045":[15,"新潟市東区","神明町"],"9500047":[15,"新潟市東区","臨海町"],"9501341":[15,"新潟市西蒲区","道上"],"9500088":[15,"新潟市中央区","万代"],"9501323":[15,"新潟市西蒲区","東小吉"],"9500116":[15,"新潟市東区","北山"],"9508619":[15,"新潟市中央区","弁天","1丁目2-4"],"9500893":[15,"新潟市東区","はなみずき"],"9503128":[15,"新潟市北区","松浜東町"],"9502121":[15,"新潟市西区","槇尾"],"9501232":[15,"新潟市南区","十五間"],"9500204":[15,"新潟市江南区","横越"],"9500064":[15,"新潟市東区","松島"],"9501135":[15,"新潟市江南区","曽野木"],"9502053":[15,"新潟市西区","寺尾前通"],"9500143":[15,"新潟市江南区","元町"],"9501185":[15,"新潟市西区","山田","2307"],"9500908":[15,"新潟市中央区","幸西"],"9508532":[15,"新潟市中央区","美咲町","1丁目2番1号新潟美咲合同庁舎2号館"],"9501447":[15,"新潟市南区","飯島"],"9500168":[15,"新潟市江南区","早通"],"9500917":[15,"新潟市中央区","天神"],"9500133":[15,"新潟市江南区","砂崩"],"9501195":[15,"新潟市西区","山田","2307-108"],"9500140":[15,"新潟市江南区","梅見台"],"9500067":[15,"新潟市東区","大山"],"9500835":[15,"新潟市東区","猿ケ馬場"],"9501311":[15,"新潟市南区","木滑"],"9508650":[15,"新潟市中央区","東大通","1丁目3-10"],"9508625":[15,"新潟市中央区","美咲町","1丁目2番1号新潟美咲合同庁舎2号館"],"9500973":[15,"新潟市中央区","上近江"],"9508588":[15,"新潟市中央区","八千代","1丁目7-20"],"9500132":[15,"新潟市江南区","砂岡"],"9501225":[15,"新潟市南区","七軒町"],"9500077":[15,"新潟市中央区","天明町"],"9502251":[15,"新潟市西区","中権寺"],"9502031":[15,"新潟市西区","流通センター"],"9501202":[15,"新潟市南区","大通南"],"9508557":[15,"新潟市中央区","新光町","1-10"],"9503304":[15,"新潟市北区","木崎"],"9503105":[15,"新潟市北区","新富町"],"9503364":[15,"新潟市北区","大迎"],"9502013":[15,"新潟市西区","小針が丘"],"9501342":[15,"新潟市西蒲区","河間"],"9501151":[15,"新潟市中央区","湖南"],"9508552":[15,"新潟市中央区","新光町","1-16"],"9508589":[15,"新潟市中央区","八千代","1丁目6-1"],"9501461":[15,"新潟市南区","平潟"],"9508550":[15,"新潟市中央区","万代","1丁目3-4"],"9508711":[15,"新潟市中央区","万代島","5-1万代島ビル7F"],"9508572":[15,"新潟市中央区","八千代","2丁目3番1号"],"9502292":[15,"新潟市西区","みずき野","3丁目1番1号"],"9501331":[15,"新潟市西蒲区","東中"],"9500149":[15,"新潟市江南区","下早通"],"9502154":[15,"新潟市西区","内野潟向"],"9502133":[15,"新潟市西区","前野外新田"],"9501244":[15,"新潟市南区","上塩俵"],"9501321":[15,"新潟市西蒲区","針ケ曽根"],"9508639":[15,"新潟市東区","小金町","2丁目6-1"],"9500933":[15,"新潟市中央区","清五郎"],"9501477":[15,"新潟市南区","田中"],"9500055":[15,"新潟市東区","北葉町"],"9501437":[15,"新潟市南区","鍋潟"],"9501412":[15,"新潟市南区","臼井"],"9502034":[15,"新潟市西区","新田"],"9503323":[15,"新潟市北区","東栄町"],"9508630":[15,"新潟市中央区","美咲町","2丁目2-28"],"9501433":[15,"新潟市南区","次郎右エ門興野"],"9501101":[15,"新潟市西区","山田"],"9500209":[15,"新潟市江南区","横越東町"],"9501105":[15,"新潟市西区","ときめき東"],"9508565":[15,"新潟市中央区","新光町","6-1"],"9500916":[15,"新潟市中央区","米山"],"9501462":[15,"新潟市南区","蔵主"],"9501475":[15,"新潟市南区","戸頭"],"9508581":[15,"新潟市中央区","幸西","4丁目3-5"],"9502253":[15,"新潟市西区","木山"],"9501224":[15,"新潟市南区","白根水道町"],"9501192":[15,"新潟市西区","流通","1丁目5-3"],"9500329":[15,"新潟市江南区","平賀"],"9500021":[15,"新潟市東区","物見山"],"9503123":[15,"新潟市北区","新元島町"],"9500145":[15,"新潟市中央区","亀田早通"],"9500144":[15,"新潟市江南区","茅野山"],"9500923":[15,"新潟市中央区","姥ケ山"],"9500044":[15,"新潟市東区","古湊町"],"9500101":[15,"新潟市東区","江口"],"9503115":[15,"新潟市北区","松浜新町"],"9501305":[15,"新潟市南区","大別當"],"9502064":[15,"新潟市西区","寺尾西"],"9500801":[15,"新潟市東区","津島屋"],"9503344":[15,"新潟市北区","浦木"],"9500834":[15,"新潟市東区","石山団地"],"9501226":[15,"新潟市南区","白根四ツ興野"],"9503375":[15,"新潟市北区","早通南"],"9500954":[15,"新潟市中央区","美咲町"],"9503314":[15,"新潟市北区","村新田"],"9501133":[15,"新潟市中央区","嘉木"],"9501252":[15,"新潟市南区","大倉"],"9502073":[15,"新潟市西区","有明町"],"9500046":[15,"新潟市東区","浜町"],"9500063":[15,"新潟市東区","上王瀬町"],"9500836":[15,"新潟市東区","東中野山"],"9502014":[15,"新潟市西区","小針西"],"9503309":[15,"新潟市北区","北陽"],"9508560":[15,"新潟市中央区","新光町","7-1新潟県自治会館別館"],"9508531":[15,"新潟市中央区","万代","5丁目11-20"],"9501327":[15,"新潟市西蒲区","中之口"],"9501187":[15,"新潟市西区","北場","1185-3"],"9508730":[15,"新潟市東区","宝町","13-5"],"9501113":[15,"新潟市西区","鳥原新田"],"9500327":[15,"新潟市江南区","和田"],"9501455":[15,"新潟市南区","新飯田"],"9508710":[15,"新潟市中央区","万代島","6-1"],"9508626":[15,"新潟市中央区","鳥屋野","301-1"],"9501421":[15,"新潟市南区","中山"],"9503393":[15,"新潟市北区","葛塚","3197"],"9508741":[15,"新潟市中央区","愛宕","3丁目1-1"],"9508735":[15,"新潟市東区","津島屋","7丁目77"],"9501214":[15,"新潟市南区","上下諏訪木"],"9503328":[15,"新潟市北区","前新田沖"],"9508801":[15,"新潟市中央区","美咲町","1丁目1-1"],"9501313":[15,"新潟市南区","釣寄"],"9501124":[15,"新潟市西区","緒立流通"],"9500823":[15,"新潟市東区","東中島"],"9502137":[15,"新潟市西区","小見郷屋"],"9501253":[15,"新潟市南区","大倉新田"],"9508621":[15,"新潟市中央区","美咲町","1丁目23-26"],"9500914":[15,"新潟市東区","紫竹山"],"9503324":[15,"新潟市北区","前新田"],"9500084":[15,"新潟市中央区","明石"],"9500085":[15,"新潟市中央区","長嶺町"],"9502181":[15,"新潟市西区","五十嵐2の町","8050"],"9500944":[15,"新潟市中央区","愛宕"],"9508759":[15,"新潟市中央区","東大通","2丁目2番18号"],"9500904":[15,"新潟市中央区","水島町"],"9500192":[15,"新潟市江南区","元町","2丁目3-56"],"9500207":[15,"新潟市江南区","二本木"],"9508566":[15,"新潟市中央区","新光町","6-6"],"9508746":[15,"新潟市中央区","東堀前通7番町","1071-1"],"9501298":[15,"新潟市南区","七軒","字前211-1"],"9500891":[15,"新潟市東区","上木戸"],"9501403":[15,"新潟市南区","犬帰新田"],"9508567":[15,"新潟市中央区","新光町","11-2"],"9508545":[15,"新潟市中央区","万代","2丁目3-6"],"9502001":[15,"新潟市西区","浦山"],"9508518":[15,"新潟市中央区","東大通","2丁目4-10"],"9500151":[15,"新潟市江南区","亀田四ツ興野"],"9508520":[15,"新潟市中央区","東大通","1丁目3-1"],"9501236":[15,"新潟市南区","高井東"],"9500941":[15,"新潟市中央区","女池"],"9503302":[15,"新潟市北区","浜浦"],"9503381":[15,"新潟市北区","内沼沖"],"9500113":[15,"新潟市江南区","西山"],"9502088":[15,"新潟市西区","流通センター","3丁目1-1"],"9500942":[15,"新潟市中央区","小張木"],"9500947":[15,"新潟市中央区","女池北"],"9501243":[15,"新潟市南区","松橋"],"9508660":[15,"新潟市中央区","鐙","2丁目14-13"],"9500042":[15,"新潟市東区","東臨港町"],"9503325":[15,"新潟市北区","白新町"],"9508748":[15,"新潟市中央区","東大通","1丁目2-23"],"9501405":[15,"新潟市南区","東笠巻"],"9500166":[15,"新潟市江南区","旭"],"9500162":[15,"新潟市江南区","亀田大月"],"9500056":[15,"新潟市東区","古川町"],"9503111":[15,"新潟市北区","太夫浜新町"],"9502163":[15,"新潟市西区","新中浜"],"9501442":[15,"新潟市南区","鋳物師興野"],"9503377":[15,"新潟市北区","彩野"],"9500072":[15,"新潟市中央区","竜が島"],"9500043":[15,"新潟市東区","臨港"],"9501146":[15,"新潟市中央区","太右エ門新田"],"9500822":[15,"新潟市東区","新岡山"],"9501296":[15,"新潟市南区","北田中","780-12"],"9500146":[15,"新潟市江南区","丸潟"],"9500032":[15,"新潟市東区","河渡甲"],"9508747":[15,"新潟市中央区","鐙","1丁目1-17"],"9501231":[15,"新潟市南区","小坂"],"9500034":[15,"新潟市東区","浜谷町"],"9500872":[15,"新潟市東区","牡丹山"],"9508571":[15,"新潟市中央区","上所","3丁目10-1"],"9501431":[15,"新潟市南区","上八枚"],"9508555":[15,"新潟市中央区","新光町","1-11"],"9508742":[15,"新潟市中央区","米山","5丁目10-20"],"9502005":[15,"新潟市西区","青山水道"],"9500931":[15,"新潟市中央区","南長潟"],"9501402":[15,"新潟市南区","西酒屋"],"9503301":[15,"新潟市北区","笹山"],"9500807":[15,"新潟市東区","木工新町"],"9500066":[15,"新潟市東区","長者町"],"9500001":[15,"新潟市東区","松浜町"],"9500041":[15,"新潟市東区","臨港町"],"9503374":[15,"新潟市北区","仏伝"],"9500123":[15,"新潟市江南区","亀田水道町"],"9503342":[15,"新潟市北区","美里"],"9500949":[15,"新潟市中央区","桜木町"],"9501453":[15,"新潟市南区","兎新田"],"9501467":[15,"新潟市南区","東萱場"],"9500932":[15,"新潟市中央区","長潟"],"9500814":[15,"新潟市東区","逢谷内"],"9508718":[15,"新潟市中央区","長潟","138番地"],"9500825":[15,"新潟市東区","児池"],"9502102":[15,"新潟市西区","五十嵐二の町"],"9500805":[15,"新潟市東区","石動"],"9500206":[15,"新潟市江南区","木津"],"9503124":[15,"新潟市北区","三軒屋町"],"9503315":[15,"新潟市北区","朝日町"],"9508541":[15,"新潟市中央区","万代","4丁目4-27"],"9503313":[15,"新潟市北区","太田"],"9508535":[15,"新潟市中央区","万代","3丁目1番1号"],"9500031":[15,"新潟市東区","船江町"],"9500161":[15,"新潟市東区","亀田中島"],"9500016":[15,"新潟市東区","河渡本町"],"9500925":[15,"新潟市中央区","弁天橋通"],"9508530":[15,"新潟市中央区","東大通","1丁目2-23北陸ビル9階"],"9503333":[15,"新潟市北区","内沼"],"9500005":[15,"新潟市東区","太平"],"9501126":[15,"新潟市西区","北場"],"9501404":[15,"新潟市南区","大郷"],"9501422":[15,"新潟市南区","堀掛"],"9500907":[15,"新潟市中央区","幸町"],"9502087":[15,"新潟市西区","西有明町","1-27"],"9501463":[15,"新潟市南区","平潟新田"],"9500075":[15,"新潟市中央区","沼垂東"],"9508740":[15,"新潟市中央区","笹口","3丁目7-15"],"9500993":[15,"新潟市中央区","上所中"],"9508723":[15,"新潟市東区","臨港町","3丁目4914番479"],"9500052":[15,"新潟市東区","秋葉通"],"9501293":[15,"新潟市南区","上下諏訪木","770-1"],"9501217":[15,"新潟市南区","白根"],"9501347":[15,"新潟市西蒲区","姥島"],"9508575":[15,"新潟市中央区","上所","2丁目2-2新潟ユニゾンプラザ3階"],"9503335":[15,"新潟市北区","上大月"],"9500076":[15,"新潟市中央区","沼垂西"],"9502174":[15,"新潟市西区","五十嵐三の町西"],"9502177":[15,"新潟市西区","五十嵐三の町中"],"9500036":[15,"新潟市東区","空港西"],"9502015":[15,"新潟市西区","西小針台"],"9502153":[15,"新潟市西区","内野崎山"],"9500130":[15,"新潟市江南区","砂山"],"9500824":[15,"新潟市東区","中島"],"9500061":[15,"新潟市東区","月見町"],"9500853":[15,"新潟市東区","東明"],"9508586":[15,"新潟市中央区","万代","4丁目5番15号"],"9503134":[15,"新潟市北区","新崎"],"9508514":[15,"新潟市中央区","東大通","1丁目4-2"],"9500196":[15,"新潟市江南区","下早通柳田","2丁目2番12号"],"9500911":[15,"新潟市中央区","笹口"],"9500924":[15,"新潟市中央区","美の里"],"9501200":[15,"新潟市南区",""],"9501456":[15,"新潟市南区","茨曽根"],"9501122":[15,"新潟市西区","木場"],"9500074":[15,"新潟市中央区","鏡が岡"],"9500210":[15,"新潟市江南区","横越上町"],"9500854":[15,"新潟市東区","南紫竹"],"9501413":[15,"新潟市南区","朝捲"],"9501343":[15,"新潟市西蒲区","三ツ門"],"9503135":[15,"新潟市北区","つくし野"],"9503367":[15,"新潟市北区","高森"],"9501235":[15,"新潟市南区","高井興野"],"9503361":[15,"新潟市北区","新井郷"],"9508582":[15,"新潟市中央区","八千代","1丁目4-34"],"9501297":[15,"新潟市南区","北田中","780-13"],"9501302":[15,"新潟市南区","上曲通"],"9502135":[15,"新潟市西区","明田"],"9508641":[15,"新潟市中央区","花園","1丁目1-1"],"9501209":[15,"新潟市南区","親和町"],"9502263":[15,"新潟市西区","坂田"],"9500017":[15,"新潟市東区","新松崎"],"9503121":[15,"新潟市北区","松浜町"],"9500124":[15,"新潟市江南区","亀田東町"],"9500212":[15,"新潟市江南区","茜ケ丘"],"9500139":[15,"新潟市江南区","手代山"],"9501446":[15,"新潟市南区","庄瀬"],"9508733":[15,"新潟市中央区","堀之内","55-1"],"9501303":[15,"新潟市南区","西萱場"],"9503101":[15,"新潟市北区","太郎代"],"9500198":[15,"新潟市江南区","亀田工業団地","3丁目1-1"],"9500208":[15,"新潟市江南区","横越中央"],"9502012":[15,"新潟市西区","小針台"],"9502195":[15,"新潟市西区","流通センター","2丁目2-6"],"9500078":[15,"新潟市中央区","万代島"],"9500214":[15,"新潟市江南区","うぐいす"],"9508511":[15,"新潟市中央区","東大通","2-2-18タチバナビル"],"9502002":[15,"新潟市西区","青山"],"9500867":[15,"新潟市東区","竹尾卸新町"],"9503357":[15,"新潟市北区","平林"],"9500811":[15,"新潟市東区","材木町"],"9501189":[15,"新潟市西区","山田","2310-39"],"9500863":[15,"新潟市東区","卸新町"],"9503116":[15,"新潟市北区","神谷内"],"9500205":[15,"新潟市江南区","沢海"],"9500851":[15,"新潟市東区","新石山"],"9503337":[15,"新潟市北区","里飯野"],"9501451":[15,"新潟市南区","真木"],"9503104":[15,"新潟市北区","東栄町"],"9502144":[15,"新潟市西区","曽和"],"9502142":[15,"新潟市西区","内野戸中才"],"9508502":[15,"新潟市中央区","東大通","2丁目2-18"],"9508624":[15,"新潟市中央区","美咲町","1丁目2番1号新潟美咲合同庁舎2号館"],"9500802":[15,"新潟市東区","一日市"],"9502124":[15,"新潟市西区","田潟"],"9503317":[15,"新潟市北区","かぶとやま"],"9508608":[15,"新潟市中央区","女池","6丁目18-11"],"9500213":[15,"新潟市江南区","木津工業団地"],"9508651":[15,"新潟市中央区","鐙西","2丁目35-30"],"9508570":[15,"新潟市中央区","新光町","4-1"],"9501193":[15,"新潟市西区","山田","2310-15"],"9508753":[15,"新潟市中央区","沼垂東","2丁目11-21"],"9502164":[15,"新潟市西区","内野中浜"],"9502037":[15,"新潟市西区","大野"],"9502252":[15,"新潟市西区","谷内"],"9500000":[15,"新潟市北区",""],"9501444":[15,"新潟市南区","牛崎"],"9502173":[15,"新潟市西区","五十嵐三の町東"],"9500906":[15,"新潟市中央区","東幸町"],"9500142":[15,"新潟市江南区","泥潟"],"9508751":[15,"新潟市中央区","弁天","3丁目2-3"],"9502132":[15,"新潟市西区","小瀬"],"9502134":[15,"新潟市西区","保古野木"],"9500163":[15,"新潟市江南区","東船場"],"9500011":[15,"新潟市東区","向陽"],"9500150":[15,"新潟市江南区","下早通柳田"],"9503316":[15,"新潟市北区","鳥屋"],"9501262":[15,"新潟市南区","西白根"],"9500321":[15,"新潟市江南区","割野"],"9502192":[15,"新潟市西区","流通センター","4丁目4-6"],"9502131":[15,"新潟市西区","早潟"],"9501333":[15,"新潟市西蒲区","潟浦新"],"9503198":[15,"新潟市北区","島見町","1398番地"],"9500984":[15,"新潟市中央区","女池東"],"9501197":[15,"新潟市中央区","鐘木","463番地7"],"9503336":[15,"新潟市北区","岡新田"],"9501106":[15,"新潟市西区","ときめき西"],"9500862":[15,"新潟市東区","竹尾"],"9500065":[15,"新潟市東区","東新町"],"9500051":[15,"新潟市東区","桃山町"],"9503125":[15,"新潟市北区","松浜本町"],"9501103":[15,"新潟市西区","立仏"],"9508523":[15,"新潟市中央区","東大通","1丁目2-23"],"9503366":[15,"新潟市北区","三ツ屋"],"9503308":[15,"新潟市北区","下大谷内"],"9501328":[15,"新潟市西蒲区","門田"],"9501237":[15,"新潟市南区","北田中"],"9501255":[15,"新潟市南区","山王"],"9500215":[15,"新潟市江南区","平山"],"9500218":[15,"新潟市江南区","いぶき野"],"9500153":[15,"新潟市江南区","船戸山"],"9503321":[15,"新潟市北区","葛塚"],"9502162":[15,"新潟市西区","五十嵐中島"],"9500165":[15,"新潟市江南区","西町"],"9500951":[15,"新潟市中央区","鳥屋野"],"9501218":[15,"新潟市南区","白根魚町"],"9503346":[15,"新潟市北区","下土地亀"],"9502176":[15,"新潟市西区","五十嵐三の町北"],"9508606":[15,"新潟市中央区","女池","6丁目1-21"],"9500131":[15,"新潟市江南区","袋津"],"9501142":[15,"新潟市江南区","楚川"],"9503113":[15,"新潟市北区","松栄町"],"9500193":[15,"新潟市江南区","下早通柳田","2丁目2番15号"],"9503307":[15,"新潟市北区","樋ノ入"],"9501454":[15,"新潟市南区","上新田"],"9502151":[15,"新潟市西区","内野西"],"9502032":[15,"新潟市西区","的場流通"],"9508512":[15,"新潟市中央区","東大通","1丁目3番1号"],"9508601":[15,"新潟市中央区","女池神明","1丁目7-1"],"9501312":[15,"新潟市南区","釣寄新"],"9501212":[15,"新潟市南区","七軒"],"9503339":[15,"新潟市北区","新鼻乙"],"9508620":[15,"新潟市中央区","南笹口","1丁目1-54"],"9502024":[15,"新潟市西区","小新西"],"9500852":[15,"新潟市東区","石山"],"9500882":[15,"新潟市東区","王瀬新町"],"9500965":[15,"新潟市中央区","新光町"],"9500962":[15,"新潟市中央区","出来島"],"9500054":[15,"新潟市東区","秋葉"],"9500926":[15,"新潟市中央区","高志"],"9508707":[15,"新潟市東区","竹尾卸新町","752-10"],"9501131":[15,"新潟市中央区","鍋潟新田"],"9508755":[15,"新潟市中央区","万代","4丁目4-8"],"9500147":[15,"新潟市江南区","長潟"],"9503122":[15,"新潟市北区","西名目所"],"9501141":[15,"新潟市中央区","鐘木"],"9501257":[15,"新潟市南区","吉田新田"],"9502096":[15,"新潟市西区","流通センター","1丁目1-2"],"9502051":[15,"新潟市西区","寺尾朝日通"],"9500868":[15,"新潟市東区","紫竹卸新町"],"9501472":[15,"新潟市南区","浦梨"],"9503312":[15,"新潟市北区","笠柳"],"9501223":[15,"新潟市南区","白根日の出町"],"9503332":[15,"新潟市北区","新鼻甲"],"9501435":[15,"新潟市南区","万年"],"9500154":[15,"新潟市江南区","荻曽根"],"9500201":[15,"新潟市江南区","駒込"],"9508750":[15,"新潟市中央区","東大通","1丁目3-8"],"9501208":[15,"新潟市南区","杉菜"],"9501292":[15,"新潟市南区","白根","1235"],"9500843":[15,"新潟市東区","粟山"],"9500986":[15,"新潟市中央区","神道寺南"],"9500837":[15,"新潟市東区","若葉町"],"9500866":[15,"新潟市中央区","西馬越"],"9501251":[15,"新潟市南区","居宿"],"9500035":[15,"新潟市東区","平和町"],"9508744":[15,"新潟市東区","桃山町","2丁目200"],"9502122":[15,"新潟市西区","高山"],"9508576":[15,"新潟市中央区","八千代","1丁目3-9"]}
);
|
const MPVController = require('./src/mpv.js');
const readline = require('readline');
let options = undefined;
if(process.argv.length > 2){
options = {
optionsPath: process.argv[2]
}
}
let mpv = new MPVController(options);
console.log(mpv);
mpv.start();
mpv.on('data', (data) => {
console.log(data);
});
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
function getInput(){
rl.question('Enter a command:\n', (answer) => {
try {
let json = JSON.parse(answer);
mpv.ipc(json);
} catch (e) {
console.log("That wasn't valid JSON");
console.log(answer);
}
getInput();
});
}
getInput();
|
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'simpleencryptor.ui'
#
# Created: Wed Nov 15 00:20:41 2017
# by: pyside-uic 0.2.15 running on PySide 1.2.4
#
# WARNING! All changes made in this file will be lost!
import sys
from PySide import QtCore, QtGui
from modules.util import Util
class Ui_MainWindow(object):
def __init__(self, app):
self.app = app
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.setFixedSize(939, 494)
MainWindow.setAcceptDrops(False)
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.decrypt = QtGui.QPushButton(self.centralwidget)
self.decrypt.setGeometry(QtCore.QRect(260, 300, 85, 27))
self.decrypt.setObjectName("decrypt")
self.decrypt.clicked.connect(lambda: self.decryptClicked())
self.encrypt = QtGui.QPushButton(self.centralwidget)
self.encrypt.setGeometry(QtCore.QRect(130, 300, 85, 27))
self.encrypt.setObjectName("encrypt")
self.encrypt.clicked.connect(lambda: self.encryptClicked())
self.textInput = QtGui.QTextEdit(self.centralwidget)
self.textInput.setGeometry(QtCore.QRect(30, 200, 421, 75))
self.textInput.setObjectName("textInput")
self.textOutput = QtGui.QTextEdit(self.centralwidget)
self.textOutput.setGeometry(QtCore.QRect(30, 360, 421, 75))
self.textOutput.setObjectName("textOutput")
self.titleWidget = QtGui.QLabel(self.centralwidget)
self.titleWidget.setGeometry(QtCore.QRect(300, 20, 321, 41))
font = QtGui.QFont()
font.setFamily("Verdana")
font.setPointSize(16)
font.setWeight(75)
font.setItalic(True)
font.setStrikeOut(False)
font.setBold(True)
self.titleWidget.setFont(font)
self.titleWidget.setAlignment(QtCore.Qt.AlignCenter)
self.titleWidget.setIndent(0)
self.titleWidget.setObjectName("titleWidget")
self.buttonGroupInput = QtGui.QGroupBox(self.centralwidget)
self.buttonGroupInput.setGeometry(QtCore.QRect(30, 140, 411, 51))
self.buttonGroupInput.setObjectName("buttonGroupInput")
self.radioButtonText = QtGui.QRadioButton(self.buttonGroupInput)
self.radioButtonText.setGeometry(QtCore.QRect(260, 30, 100, 22))
self.radioButtonText.setObjectName("radioButtonText")
self.radioButtonText.toggled.connect(self.buttonTextChecked)
self.radioButtonBinary = QtGui.QRadioButton(self.buttonGroupInput)
self.radioButtonBinary.setGeometry(QtCore.QRect(30, 30, 121, 22))
self.radioButtonBinary.setChecked(True)
self.radioButtonBinary.setObjectName("radioButtonBinary")
self.radioButtonBinary.toggled.connect(self.buttonBinaryChecked)
self.binary = True
self.automatons = QtGui.QLabel(self.centralwidget)
self.automatons.setGeometry(QtCore.QRect(30, 90, 131, 21))
self.automatons.setObjectName("automatons")
self.numberAutomatons = QtGui.QLabel(self.centralwidget)
self.numberAutomatons.setGeometry(QtCore.QRect(180, 90, 91, 21))
self.numberAutomatons.setObjectName("numberAutomatons")
self.changedNumberAutomatons(self.app.automatons)
self.textOutputPublicKey = QtGui.QTextEdit(self.centralwidget)
self.textOutputPublicKey.setGeometry(QtCore.QRect(490, 310, 421, 131))
self.textOutputPublicKey.setObjectName("textOutputPrivateKey")
self.privateKey = QtGui.QLabel(self.centralwidget)
self.privateKey.setGeometry(QtCore.QRect(490, 110, 131, 21))
self.privateKey.setObjectName("privateKey")
self.publicKey = QtGui.QLabel(self.centralwidget)
self.publicKey.setGeometry(QtCore.QRect(490, 280, 131, 21))
self.publicKey.setObjectName("publicKey")
self.textOutputPrivateKey = QtGui.QTextEdit(self.centralwidget)
self.textOutputPrivateKey.setGeometry(QtCore.QRect(490, 140, 421, 131))
self.textOutputPrivateKey.setObjectName("textOutputPublicKey")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtGui.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 939, 25))
self.menubar.setObjectName("menubar")
self.menuOptions = QtGui.QMenu(self.menubar)
self.menuOptions.setObjectName("menuOptions")
self.menuProtocolConfig = QtGui.QMenu(self.menuOptions)
self.menuProtocolConfig.setObjectName("menuProtocolConfig")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtGui.QStatusBar(MainWindow)
self.statusbar.setSizeGripEnabled(True)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.actionExit = QtGui.QAction(MainWindow)
self.actionExit.setObjectName("actionExit")
self.actionUseGuan = QtGui.QAction(MainWindow)
self.actionUseGuan.setCheckable(True)
self.actionUseGuan.setObjectName("actionUseGuan")
self.actionSetNumberAutomatons = QtGui.QAction(MainWindow)
self.actionSetNumberAutomatons.setObjectName("actionSetNumberAutomatons")
self.menuProtocolConfig.addAction(self.actionUseGuan)
self.menuProtocolConfig.addAction(self.actionSetNumberAutomatons)
self.menuOptions.addAction(self.menuProtocolConfig.menuAction())
self.menuOptions.addAction(self.actionExit)
self.menubar.addAction(self.menuOptions.menuAction())
self.menubar.triggered[QtGui.QAction].connect(self.processtrigger)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def processtrigger(self, q):
if(q == self.actionUseGuan and self.actionUseGuan.isChecked()):
self.app.setRule('guan')
if (q == self.actionSetNumberAutomatons):
i, okPressed = QtGui.QInputDialog.getInt(self.centralwidget,
"Numero de automatas",
'Seleccione la cantidad de automatas para la encripcion: ',
self.app.automatons, 0, 100, 1)
if okPressed:
self.app.setAutomatons(int(i))
if(q == self.actionExit):
self.app.close()
def changedNumberAutomatons(self, i):
self.numberAutomatons.setText(str(i))
def buttonBinaryChecked(self, enabled):
if enabled:
self.binary = True
def buttonTextChecked(self, enabled):
if(enabled):
self.binary = False
def encryptGuanClicked(self):
plain = self.textInput.toPlainText()
enc = self.app.encrypt(plain, len(plain), 2, 'guan')
self.textOutput.setPlainText(enc)
def encryptClicked(self):
plain = self.textInput.toPlainText()
if(self.binary == False):
plain = Util.stringToBits(plain)
else:
plain = Util.binaryStrToBits(plain)
enc = self.app.encrypt(plain, len(plain))
if(self.binary == False):
enc = Util.bitsToString(enc)
else:
enc = Util.bitsToBinaryStr(enc)
self.textOutput.setPlainText(enc)
self.textOutputPrivateKey.setPlainText(self.app.getPrivateKey())
self.textOutputPublicKey.setPlainText(self.app.getPublicKey())
def decryptClicked(self):
plain = self.textInput.toPlainText()
if(self.binary == False):
plain = Util.stringToBits(plain)
else:
plain = Util.binaryStrToBits(plain)
dec = self.app.decrypt(plain)
if(self.binary == False):
dec = Util.bitsToString(dec)
else:
dec = Util.bitsToBinaryStr(dec)
self.textOutput.setPlainText(dec)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(QtGui.QApplication.translate("MainWindow", "Encriptor/Decriptor", None, QtGui.QApplication.UnicodeUTF8))
self.decrypt.setText(QtGui.QApplication.translate("MainWindow", "Decriptar", None, QtGui.QApplication.UnicodeUTF8))
self.encrypt.setText(QtGui.QApplication.translate("MainWindow", "Encriptar", None, QtGui.QApplication.UnicodeUTF8))
self.titleWidget.setText(QtGui.QApplication.translate("MainWindow", "Encriptor/Decriptor", None, QtGui.QApplication.UnicodeUTF8))
self.buttonGroupInput.setTitle(QtGui.QApplication.translate("MainWindow", "Entrada", None, QtGui.QApplication.UnicodeUTF8))
self.radioButtonText.setText(QtGui.QApplication.translate("MainWindow", "Texto", None, QtGui.QApplication.UnicodeUTF8))
self.radioButtonBinary.setText(QtGui.QApplication.translate("MainWindow", "Cadena binaria", None, QtGui.QApplication.UnicodeUTF8))
self.automatons.setText(QtGui.QApplication.translate("MainWindow", "Número de autómatas:", None, QtGui.QApplication.UnicodeUTF8))
#self.numberAutomatons.setText(QtGui.QApplication.translate("MainWindow", "2", None, QtGui.QApplication.UnicodeUTF8))
self.privateKey.setText(QtGui.QApplication.translate("MainWindow", "Llave Privada:", None, QtGui.QApplication.UnicodeUTF8))
self.publicKey.setText(QtGui.QApplication.translate("MainWindow", "Llave Pública:", None, QtGui.QApplication.UnicodeUTF8))
self.menuOptions.setTitle(QtGui.QApplication.translate("MainWindow", "Opciones", None, QtGui.QApplication.UnicodeUTF8))
self.menuProtocolConfig.setTitle(QtGui.QApplication.translate("MainWindow", "Configurar protocolo", None, QtGui.QApplication.UnicodeUTF8))
self.actionExit.setText(QtGui.QApplication.translate("MainWindow", "Salir", None, QtGui.QApplication.UnicodeUTF8))
self.actionUseGuan.setText(QtGui.QApplication.translate("MainWindow", "Regla de Guan", None, QtGui.QApplication.UnicodeUTF8))
self.actionSetNumberAutomatons.setText(QtGui.QApplication.translate("MainWindow", "Cantidad autómatas", None, QtGui.QApplication.UnicodeUTF8))
if __name__ == '__main__' and __package__ is None:
from os import sys, path
sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))
|
declareUpdate();
const entityCollection = "jobInfoTestEntity";
const olderUri = "/" + entityCollection + "/older.json";
const newerUri = "/" + entityCollection + "/newer.json";
xdmp.documentInsert(olderUri, {"test": olderUri}, {
permissions: [xdmp.permission("data-hub-common", "read"), xdmp.permission("data-hub-common", "update")],
collections: entityCollection,
metadata: {"datahubCreatedOn": xs.dateTime("2019-09-19T00:00:00")}
});
xdmp.documentInsert(newerUri, {"test": newerUri}, {
permissions: [xdmp.permission("data-hub-common", "read"), xdmp.permission("data-hub-common", "update")],
collections: entityCollection,
metadata: {
"datahubCreatedOn": xs.dateTime("2019-09-20T00:00:00"),
"datahubCreatedByJob": "job1 job2 job3"
}
});
|
/**********************************************************************
* Copyright (c) 2021 Hilscher Gesellschaft fuer Systemautomation mbH
* See LICENSE file
**********************************************************************/
"use strict";
var querystring = require("querystring");
var client = require("../../../../client");
var validate = require("../../../../utils/validate");
var checkers = require("../../../../utils/checkers");
/**
* Get a list of all containers in a deployment job
* @param {string} jobId
* @param {number} page
* @param {number} limit
* @param {string} sortBy
* @param {string} sortOrder
* @param {function} callback optional
*/
module.exports = function (jobId, page, limit, sortBy, sortOrder, callback) {
if (checkers.isFunction(page)) {
callback = page;
page = null;
}
if (checkers.isFunction(limit)) {
callback = limit;
limit = null;
}
if (checkers.isFunction(sortBy)) {
callback = sortBy;
sortBy = null;
}
if (checkers.isFunction(sortOrder)) {
callback = sortOrder;
sortOrder = null;
}
try {
const query = {};
if (page !== undefined && page !== null) {
query.page = page;
validate.validateNumber(page);
}
if (limit !== undefined && limit !== null) {
query.limit = limit;
validate.validateNumber(limit);
}
if (sortBy) {
query.sortBy = sortBy;
validate.validateString(sortBy);
}
if (sortOrder) {
query.sortOrder = sortOrder;
validate.validateString(sortOrder);
}
validate.validateString(jobId);
var path = `/deployments/jobs/${jobId}/containers?${querystring.stringify(query)}`;
return client.get("auth", path, callback);
} catch (e) {
if (callback) {
return callback(e, null);
}
return Promise.reject(e);
}
};
|
import React from "react";
import "./DrawerToggleButton.css";
const drawerToggleButton = props => (
<button className="toggle-button" onClick={props.click}>
<div className="toggle-button-line" />
<div className="toggle-button-line" />
<div className="toggle-button-line" />
</button>
);
export default drawerToggleButton;
|
/**
* @author zhixin wen <wenzhixin2010@gmail.com>
* @version 1.2.1
*
* http://wenzhixin.net.cn/p/multiple-select/
*/
(function ($) {
'use strict';
// it only does '%s', and return '' when arguments are undefined
var sprintf = function (str) {
var args = arguments,
flag = true,
i = 1;
str = str.replace(/%s/g, function () {
var arg = args[i++];
if (typeof arg === 'undefined') {
flag = false;
return '';
}
return arg;
});
return flag ? str : '';
};
var removeDiacritics = function (str) {
var defaultDiacriticsRemovalMap = [
{'base':'A', 'letters':/[\u0041\u24B6\uFF21\u00C0\u00C1\u00C2\u1EA6\u1EA4\u1EAA\u1EA8\u00C3\u0100\u0102\u1EB0\u1EAE\u1EB4\u1EB2\u0226\u01E0\u00C4\u01DE\u1EA2\u00C5\u01FA\u01CD\u0200\u0202\u1EA0\u1EAC\u1EB6\u1E00\u0104\u023A\u2C6F]/g},
{'base':'AA','letters':/[\uA732]/g},
{'base':'AE','letters':/[\u00C6\u01FC\u01E2]/g},
{'base':'AO','letters':/[\uA734]/g},
{'base':'AU','letters':/[\uA736]/g},
{'base':'AV','letters':/[\uA738\uA73A]/g},
{'base':'AY','letters':/[\uA73C]/g},
{'base':'B', 'letters':/[\u0042\u24B7\uFF22\u1E02\u1E04\u1E06\u0243\u0182\u0181]/g},
{'base':'C', 'letters':/[\u0043\u24B8\uFF23\u0106\u0108\u010A\u010C\u00C7\u1E08\u0187\u023B\uA73E]/g},
{'base':'D', 'letters':/[\u0044\u24B9\uFF24\u1E0A\u010E\u1E0C\u1E10\u1E12\u1E0E\u0110\u018B\u018A\u0189\uA779]/g},
{'base':'DZ','letters':/[\u01F1\u01C4]/g},
{'base':'Dz','letters':/[\u01F2\u01C5]/g},
{'base':'E', 'letters':/[\u0045\u24BA\uFF25\u00C8\u00C9\u00CA\u1EC0\u1EBE\u1EC4\u1EC2\u1EBC\u0112\u1E14\u1E16\u0114\u0116\u00CB\u1EBA\u011A\u0204\u0206\u1EB8\u1EC6\u0228\u1E1C\u0118\u1E18\u1E1A\u0190\u018E]/g},
{'base':'F', 'letters':/[\u0046\u24BB\uFF26\u1E1E\u0191\uA77B]/g},
{'base':'G', 'letters':/[\u0047\u24BC\uFF27\u01F4\u011C\u1E20\u011E\u0120\u01E6\u0122\u01E4\u0193\uA7A0\uA77D\uA77E]/g},
{'base':'H', 'letters':/[\u0048\u24BD\uFF28\u0124\u1E22\u1E26\u021E\u1E24\u1E28\u1E2A\u0126\u2C67\u2C75\uA78D]/g},
{'base':'I', 'letters':/[\u0049\u24BE\uFF29\u00CC\u00CD\u00CE\u0128\u012A\u012C\u0130\u00CF\u1E2E\u1EC8\u01CF\u0208\u020A\u1ECA\u012E\u1E2C\u0197]/g},
{'base':'J', 'letters':/[\u004A\u24BF\uFF2A\u0134\u0248]/g},
{'base':'K', 'letters':/[\u004B\u24C0\uFF2B\u1E30\u01E8\u1E32\u0136\u1E34\u0198\u2C69\uA740\uA742\uA744\uA7A2]/g},
{'base':'L', 'letters':/[\u004C\u24C1\uFF2C\u013F\u0139\u013D\u1E36\u1E38\u013B\u1E3C\u1E3A\u0141\u023D\u2C62\u2C60\uA748\uA746\uA780]/g},
{'base':'LJ','letters':/[\u01C7]/g},
{'base':'Lj','letters':/[\u01C8]/g},
{'base':'M', 'letters':/[\u004D\u24C2\uFF2D\u1E3E\u1E40\u1E42\u2C6E\u019C]/g},
{'base':'N', 'letters':/[\u004E\u24C3\uFF2E\u01F8\u0143\u00D1\u1E44\u0147\u1E46\u0145\u1E4A\u1E48\u0220\u019D\uA790\uA7A4]/g},
{'base':'NJ','letters':/[\u01CA]/g},
{'base':'Nj','letters':/[\u01CB]/g},
{'base':'O', 'letters':/[\u004F\u24C4\uFF2F\u00D2\u00D3\u00D4\u1ED2\u1ED0\u1ED6\u1ED4\u00D5\u1E4C\u022C\u1E4E\u014C\u1E50\u1E52\u014E\u022E\u0230\u00D6\u022A\u1ECE\u0150\u01D1\u020C\u020E\u01A0\u1EDC\u1EDA\u1EE0\u1EDE\u1EE2\u1ECC\u1ED8\u01EA\u01EC\u00D8\u01FE\u0186\u019F\uA74A\uA74C]/g},
{'base':'OI','letters':/[\u01A2]/g},
{'base':'OO','letters':/[\uA74E]/g},
{'base':'OU','letters':/[\u0222]/g},
{'base':'P', 'letters':/[\u0050\u24C5\uFF30\u1E54\u1E56\u01A4\u2C63\uA750\uA752\uA754]/g},
{'base':'Q', 'letters':/[\u0051\u24C6\uFF31\uA756\uA758\u024A]/g},
{'base':'R', 'letters':/[\u0052\u24C7\uFF32\u0154\u1E58\u0158\u0210\u0212\u1E5A\u1E5C\u0156\u1E5E\u024C\u2C64\uA75A\uA7A6\uA782]/g},
{'base':'S', 'letters':/[\u0053\u24C8\uFF33\u1E9E\u015A\u1E64\u015C\u1E60\u0160\u1E66\u1E62\u1E68\u0218\u015E\u2C7E\uA7A8\uA784]/g},
{'base':'T', 'letters':/[\u0054\u24C9\uFF34\u1E6A\u0164\u1E6C\u021A\u0162\u1E70\u1E6E\u0166\u01AC\u01AE\u023E\uA786]/g},
{'base':'TZ','letters':/[\uA728]/g},
{'base':'U', 'letters':/[\u0055\u24CA\uFF35\u00D9\u00DA\u00DB\u0168\u1E78\u016A\u1E7A\u016C\u00DC\u01DB\u01D7\u01D5\u01D9\u1EE6\u016E\u0170\u01D3\u0214\u0216\u01AF\u1EEA\u1EE8\u1EEE\u1EEC\u1EF0\u1EE4\u1E72\u0172\u1E76\u1E74\u0244]/g},
{'base':'V', 'letters':/[\u0056\u24CB\uFF36\u1E7C\u1E7E\u01B2\uA75E\u0245]/g},
{'base':'VY','letters':/[\uA760]/g},
{'base':'W', 'letters':/[\u0057\u24CC\uFF37\u1E80\u1E82\u0174\u1E86\u1E84\u1E88\u2C72]/g},
{'base':'X', 'letters':/[\u0058\u24CD\uFF38\u1E8A\u1E8C]/g},
{'base':'Y', 'letters':/[\u0059\u24CE\uFF39\u1EF2\u00DD\u0176\u1EF8\u0232\u1E8E\u0178\u1EF6\u1EF4\u01B3\u024E\u1EFE]/g},
{'base':'Z', 'letters':/[\u005A\u24CF\uFF3A\u0179\u1E90\u017B\u017D\u1E92\u1E94\u01B5\u0224\u2C7F\u2C6B\uA762]/g},
{'base':'a', 'letters':/[\u0061\u24D0\uFF41\u1E9A\u00E0\u00E1\u00E2\u1EA7\u1EA5\u1EAB\u1EA9\u00E3\u0101\u0103\u1EB1\u1EAF\u1EB5\u1EB3\u0227\u01E1\u00E4\u01DF\u1EA3\u00E5\u01FB\u01CE\u0201\u0203\u1EA1\u1EAD\u1EB7\u1E01\u0105\u2C65\u0250]/g},
{'base':'aa','letters':/[\uA733]/g},
{'base':'ae','letters':/[\u00E6\u01FD\u01E3]/g},
{'base':'ao','letters':/[\uA735]/g},
{'base':'au','letters':/[\uA737]/g},
{'base':'av','letters':/[\uA739\uA73B]/g},
{'base':'ay','letters':/[\uA73D]/g},
{'base':'b', 'letters':/[\u0062\u24D1\uFF42\u1E03\u1E05\u1E07\u0180\u0183\u0253]/g},
{'base':'c', 'letters':/[\u0063\u24D2\uFF43\u0107\u0109\u010B\u010D\u00E7\u1E09\u0188\u023C\uA73F\u2184]/g},
{'base':'d', 'letters':/[\u0064\u24D3\uFF44\u1E0B\u010F\u1E0D\u1E11\u1E13\u1E0F\u0111\u018C\u0256\u0257\uA77A]/g},
{'base':'dz','letters':/[\u01F3\u01C6]/g},
{'base':'e', 'letters':/[\u0065\u24D4\uFF45\u00E8\u00E9\u00EA\u1EC1\u1EBF\u1EC5\u1EC3\u1EBD\u0113\u1E15\u1E17\u0115\u0117\u00EB\u1EBB\u011B\u0205\u0207\u1EB9\u1EC7\u0229\u1E1D\u0119\u1E19\u1E1B\u0247\u025B\u01DD]/g},
{'base':'f', 'letters':/[\u0066\u24D5\uFF46\u1E1F\u0192\uA77C]/g},
{'base':'g', 'letters':/[\u0067\u24D6\uFF47\u01F5\u011D\u1E21\u011F\u0121\u01E7\u0123\u01E5\u0260\uA7A1\u1D79\uA77F]/g},
{'base':'h', 'letters':/[\u0068\u24D7\uFF48\u0125\u1E23\u1E27\u021F\u1E25\u1E29\u1E2B\u1E96\u0127\u2C68\u2C76\u0265]/g},
{'base':'hv','letters':/[\u0195]/g},
{'base':'i', 'letters':/[\u0069\u24D8\uFF49\u00EC\u00ED\u00EE\u0129\u012B\u012D\u00EF\u1E2F\u1EC9\u01D0\u0209\u020B\u1ECB\u012F\u1E2D\u0268\u0131]/g},
{'base':'j', 'letters':/[\u006A\u24D9\uFF4A\u0135\u01F0\u0249]/g},
{'base':'k', 'letters':/[\u006B\u24DA\uFF4B\u1E31\u01E9\u1E33\u0137\u1E35\u0199\u2C6A\uA741\uA743\uA745\uA7A3]/g},
{'base':'l', 'letters':/[\u006C\u24DB\uFF4C\u0140\u013A\u013E\u1E37\u1E39\u013C\u1E3D\u1E3B\u017F\u0142\u019A\u026B\u2C61\uA749\uA781\uA747]/g},
{'base':'lj','letters':/[\u01C9]/g},
{'base':'m', 'letters':/[\u006D\u24DC\uFF4D\u1E3F\u1E41\u1E43\u0271\u026F]/g},
{'base':'n', 'letters':/[\u006E\u24DD\uFF4E\u01F9\u0144\u00F1\u1E45\u0148\u1E47\u0146\u1E4B\u1E49\u019E\u0272\u0149\uA791\uA7A5]/g},
{'base':'nj','letters':/[\u01CC]/g},
{'base':'o', 'letters':/[\u006F\u24DE\uFF4F\u00F2\u00F3\u00F4\u1ED3\u1ED1\u1ED7\u1ED5\u00F5\u1E4D\u022D\u1E4F\u014D\u1E51\u1E53\u014F\u022F\u0231\u00F6\u022B\u1ECF\u0151\u01D2\u020D\u020F\u01A1\u1EDD\u1EDB\u1EE1\u1EDF\u1EE3\u1ECD\u1ED9\u01EB\u01ED\u00F8\u01FF\u0254\uA74B\uA74D\u0275]/g},
{'base':'oi','letters':/[\u01A3]/g},
{'base':'ou','letters':/[\u0223]/g},
{'base':'oo','letters':/[\uA74F]/g},
{'base':'p','letters':/[\u0070\u24DF\uFF50\u1E55\u1E57\u01A5\u1D7D\uA751\uA753\uA755]/g},
{'base':'q','letters':/[\u0071\u24E0\uFF51\u024B\uA757\uA759]/g},
{'base':'r','letters':/[\u0072\u24E1\uFF52\u0155\u1E59\u0159\u0211\u0213\u1E5B\u1E5D\u0157\u1E5F\u024D\u027D\uA75B\uA7A7\uA783]/g},
{'base':'s','letters':/[\u0073\u24E2\uFF53\u00DF\u015B\u1E65\u015D\u1E61\u0161\u1E67\u1E63\u1E69\u0219\u015F\u023F\uA7A9\uA785\u1E9B]/g},
{'base':'t','letters':/[\u0074\u24E3\uFF54\u1E6B\u1E97\u0165\u1E6D\u021B\u0163\u1E71\u1E6F\u0167\u01AD\u0288\u2C66\uA787]/g},
{'base':'tz','letters':/[\uA729]/g},
{'base':'u','letters':/[\u0075\u24E4\uFF55\u00F9\u00FA\u00FB\u0169\u1E79\u016B\u1E7B\u016D\u00FC\u01DC\u01D8\u01D6\u01DA\u1EE7\u016F\u0171\u01D4\u0215\u0217\u01B0\u1EEB\u1EE9\u1EEF\u1EED\u1EF1\u1EE5\u1E73\u0173\u1E77\u1E75\u0289]/g},
{'base':'v','letters':/[\u0076\u24E5\uFF56\u1E7D\u1E7F\u028B\uA75F\u028C]/g},
{'base':'vy','letters':/[\uA761]/g},
{'base':'w','letters':/[\u0077\u24E6\uFF57\u1E81\u1E83\u0175\u1E87\u1E85\u1E98\u1E89\u2C73]/g},
{'base':'x','letters':/[\u0078\u24E7\uFF58\u1E8B\u1E8D]/g},
{'base':'y','letters':/[\u0079\u24E8\uFF59\u1EF3\u00FD\u0177\u1EF9\u0233\u1E8F\u00FF\u1EF7\u1E99\u1EF5\u01B4\u024F\u1EFF]/g},
{'base':'z','letters':/[\u007A\u24E9\uFF5A\u017A\u1E91\u017C\u017E\u1E93\u1E95\u01B6\u0225\u0240\u2C6C\uA763]/g}
];
for (var i = 0; i < defaultDiacriticsRemovalMap.length; i++) {
str = str.replace(defaultDiacriticsRemovalMap[i].letters, defaultDiacriticsRemovalMap[i].base);
}
return str;
};
function MultipleSelect($el, options) {
var that = this,
name = $el.attr('name') || options.name || '';
this.options = options;
// hide select element
this.$el = $el.hide();
// label element
this.$label = this.$el.closest('label');
if (this.$label.length === 0 && this.$el.attr('id')) {
this.$label = $(sprintf('label[for="%s"]', this.$el.attr('id').replace(/:/g, '\\:')));
}
// restore class and title from select element
this.$parent = $(sprintf(
'<div class="ms-parent %s" %s/>',
$el.attr('class') || '',
sprintf('title="%s"', $el.attr('title'))));
// add placeholder to choice button
this.$choice = $(sprintf([
'<button type="button" class="ms-choice">',
'<span class="placeholder">%s</span>',
'<div></div>',
'</button>'
].join(''),
this.options.placeholder));
// default position is bottom
this.$drop = $(sprintf('<div class="ms-drop %s"%s></div>',
this.options.position,
sprintf(' style="width: %s"', this.options.dropWidth)));
this.$el.after(this.$parent);
this.$parent.append(this.$choice);
this.$parent.append(this.$drop);
if (this.$el.prop('disabled')) {
this.$choice.addClass('disabled');
}
this.$parent.css('width',
this.options.width ||
this.$el.css('width') ||
this.$el.outerWidth() + 20);
this.selectAllName = 'data-name="selectAll' + name + '"';
this.selectGroupName = 'data-name="selectGroup' + name + '"';
this.selectItemName = 'data-name="selectItem' + name + '"';
if (!this.options.keepOpen) {
$(document).click(function (e) {
if ($(e.target)[0] === that.$choice[0] ||
$(e.target).parents('.ms-choice')[0] === that.$choice[0]) {
return;
}
if (($(e.target)[0] === that.$drop[0] ||
$(e.target).parents('.ms-drop')[0] !== that.$drop[0] && e.target !== $el[0]) &&
that.options.isOpen) {
that.close();
}
});
}
}
MultipleSelect.prototype = {
constructor: MultipleSelect,
init: function () {
var that = this,
$ul = $('<ul></ul>');
this.$drop.html('');
if (this.options.filter) {
this.$drop.append([
'<div class="ms-search">',
'<input type="text" autocomplete="off" autocorrect="off" autocapitilize="off" spellcheck="false">',
'</div>'].join('')
);
}
if (this.options.selectAll && !this.options.single) {
$ul.append([
'<li class="ms-select-all">',
'<label>',
sprintf('<input type="checkbox" %s /> ', this.selectAllName),
this.options.selectAllDelimiter[0],
this.options.selectAllText,
this.options.selectAllDelimiter[1],
'</label>',
'</li>'
].join(''));
}
$.each(this.$el.children(), function (i, elm) {
$ul.append(that.optionToHtml(i, elm));
});
$ul.append(sprintf('<li class="ms-no-results">%s</li>', this.options.noMatchesFound));
this.$drop.append($ul);
this.$drop.find('ul').css('max-height', this.options.maxHeight + 'px');
this.$drop.find('.multiple').css('width', this.options.multipleWidth + 'px');
this.$searchInput = this.$drop.find('.ms-search input');
this.$selectAll = this.$drop.find('input[' + this.selectAllName + ']');
this.$selectGroups = this.$drop.find('input[' + this.selectGroupName + ']');
this.$selectItems = this.$drop.find('input[' + this.selectItemName + ']:enabled');
this.$disableItems = this.$drop.find('input[' + this.selectItemName + ']:disabled');
this.$noResults = this.$drop.find('.ms-no-results');
this.events();
this.updateSelectAll(true);
this.update(true);
if (this.options.isOpen) {
this.open();
}
},
optionToHtml: function (i, elm, group, groupDisabled) {
var that = this,
$elm = $(elm),
classes = $elm.attr('class') || '',
title = sprintf('title="%s"', $elm.attr('title')),
multiple = this.options.multiple ? 'multiple' : '',
disabled,
type = this.options.single ? 'radio' : 'checkbox';
if ($elm.is('option')) {
var value = $elm.val(),
text = that.options.textTemplate($elm),
selected = $elm.prop('selected'),
style = sprintf('style="%s"', this.options.styler(value)),
$el;
disabled = groupDisabled || $elm.prop('disabled');
$el = $([
sprintf('<li class="%s %s" %s %s>', multiple, classes, title, style),
sprintf('<label class="%s">', disabled ? 'disabled' : ''),
sprintf('<input type="%s" %s%s%s%s>',
type, this.selectItemName,
selected ? ' checked="checked"' : '',
disabled ? ' disabled="disabled"' : '',
sprintf(' data-group="%s"', group)),
sprintf('<span>%s</span>', text),
'</label>',
'</li>'
].join(''));
$el.find('input').val(value);
return $el;
}
if ($elm.is('optgroup')) {
var label = that.options.labelTemplate($elm),
$group = $('<div/>');
group = 'group_' + i;
disabled = $elm.prop('disabled');
$group.append([
'<li class="group">',
sprintf('<label class="optgroup %s" data-group="%s">', disabled ? 'disabled' : '', group),
this.options.hideOptgroupCheckboxes || this.options.single ? '' :
sprintf('<input type="checkbox" %s %s>',
this.selectGroupName, disabled ? 'disabled="disabled"' : ''),
label,
'</label>',
'</li>'
].join(''));
$.each($elm.children(), function (i, elm) {
$group.append(that.optionToHtml(i, elm, group, disabled));
});
return $group.html();
}
},
events: function () {
var that = this,
toggleOpen = function (e) {
e.preventDefault();
that[that.options.isOpen ? 'close' : 'open']();
};
if (this.$label) {
this.$label.off('click').on('click', function (e) {
if (e.target.nodeName.toLowerCase() !== 'label' || e.target !== this) {
return;
}
toggleOpen(e);
if (!that.options.filter || !that.options.isOpen) {
that.focus();
}
e.stopPropagation(); // Causes lost focus otherwise
});
}
this.$choice.off('click').on('click', toggleOpen)
.off('focus').on('focus', this.options.onFocus)
.off('blur').on('blur', this.options.onBlur);
this.$parent.off('keydown').on('keydown', function (e) {
switch (e.which) {
case 27: // esc key
that.close();
that.$choice.focus();
break;
}
});
this.$searchInput.off('keydown').on('keydown',function (e) {
// Ensure shift-tab causes lost focus from filter as with clicking away
if (e.keyCode === 9 && e.shiftKey) {
that.close();
}
}).off('keyup').on('keyup', function (e) {
// enter or space
// Avoid selecting/deselecting if no choices made
if (that.options.filterAcceptOnEnter && (e.which === 13 || e.which == 32) && that.$searchInput.val()) {
that.$selectAll.click();
that.close();
that.focus();
return;
}
that.filter();
});
this.$selectAll.off('click').on('click', function () {
var checked = $(this).prop('checked'),
$items = that.$selectItems.filter(':visible');
if ($items.length === that.$selectItems.length) {
that[checked ? 'checkAll' : 'uncheckAll']();
} else { // when the filter option is true
that.$selectGroups.prop('checked', checked);
$items.prop('checked', checked);
that.options[checked ? 'onCheckAll' : 'onUncheckAll']();
that.update();
}
});
this.$selectGroups.off('click').on('click', function () {
var group = $(this).parent().attr('data-group'),
$items = that.$selectItems.filter(':visible'),
$children = $items.filter(sprintf('[data-group="%s"]', group)),
checked = $children.length !== $children.filter(':checked').length;
$children.prop('checked', checked);
that.updateSelectAll();
that.update();
that.options.onOptgroupClick({
label: $(this).parent().text(),
checked: checked,
children: $children.get(),
instance: that
});
});
this.$selectItems.off('click').on('click', function () {
that.updateSelectAll();
that.update();
that.updateOptGroupSelect();
that.options.onClick({
label: $(this).parent().text(),
value: $(this).val(),
checked: $(this).prop('checked'),
instance: that
});
if (that.options.single && that.options.isOpen && !that.options.keepOpen) {
that.close();
}
if (that.options.single) {
var clickedVal = $(this).val();
that.$selectItems.filter(function() {
return $(this).val() !== clickedVal;
}).each(function() {
$(this).prop('checked', false);
});
that.update();
}
});
},
open: function () {
if (this.$choice.hasClass('disabled')) {
return;
}
this.options.isOpen = true;
this.$choice.find('>div').addClass('open');
this.$drop[this.animateMethod('show')]();
// fix filter bug: no results show
this.$selectAll.parent().show();
this.$noResults.hide();
// Fix #77: 'All selected' when no options
if (!this.$el.children().length) {
this.$selectAll.parent().hide();
this.$noResults.show();
}
if (this.options.container) {
var offset = this.$drop.offset();
this.$drop.appendTo($(this.options.container));
this.$drop.offset({
top: offset.top,
left: offset.left
});
}
if (this.options.filter) {
this.$searchInput.val('');
this.$searchInput.focus();
this.filter();
}
this.options.onOpen();
},
close: function () {
this.options.isOpen = false;
this.$choice.find('>div').removeClass('open');
this.$drop[this.animateMethod('hide')]();
if (this.options.container) {
this.$parent.append(this.$drop);
this.$drop.css({
'top': 'auto',
'left': 'auto'
});
}
this.options.onClose();
},
animateMethod: function (method) {
var methods = {
show: {
fade: 'fadeIn',
slide: 'slideDown'
},
hide: {
fade: 'fadeOut',
slide: 'slideUp'
}
};
return methods[method][this.options.animate] || method;
},
update: function (isInit) {
var selects = this.options.displayValues ? this.getSelects() : this.getSelects('text'),
$span = this.$choice.find('>span'),
sl = selects.length;
if (sl === 0) {
$span.addClass('placeholder').html(this.options.placeholder);
} else if (this.options.allSelected && sl === this.$selectItems.length + this.$disableItems.length) {
$span.removeClass('placeholder').html(this.options.allSelected);
} else if (this.options.ellipsis && sl > this.options.minimumCountSelected) {
$span.removeClass('placeholder').text(selects.slice(0, this.options.minimumCountSelected)
.join(this.options.delimiter) + '...');
} else if (this.options.countSelected && sl > this.options.minimumCountSelected) {
$span.removeClass('placeholder').html(this.options.countSelected
.replace('#', selects.length)
.replace('%', this.$selectItems.length + this.$disableItems.length));
} else {
$span.removeClass('placeholder').text(selects.join(this.options.delimiter));
}
if (this.options.addTitle) {
$span.prop('title', this.getSelects('text'));
}
// set selects to select
this.$el.val(this.getSelects()).trigger('change');
// add selected class to selected li
this.$drop.find('li').removeClass('selected');
this.$drop.find('input:checked').each(function () {
$(this).parents('li').first().addClass('selected');
});
// trigger <select> change event
if (!isInit) {
this.$el.trigger('change');
}
},
updateSelectAll: function (isInit) {
var $items = this.$selectItems;
if (!isInit) {
$items = $items.filter(':visible');
}
this.$selectAll.prop('checked', $items.length &&
$items.length === $items.filter(':checked').length);
if (!isInit && this.$selectAll.prop('checked')) {
this.options.onCheckAll();
}
},
updateOptGroupSelect: function () {
var $items = this.$selectItems.filter(':visible');
$.each(this.$selectGroups, function (i, val) {
var group = $(val).parent().attr('data-group'),
$children = $items.filter(sprintf('[data-group="%s"]', group));
$(val).prop('checked', $children.length &&
$children.length === $children.filter(':checked').length);
});
},
//value or text, default: 'value'
getSelects: function (type) {
var that = this,
texts = [],
values = [];
this.$drop.find(sprintf('input[%s]:checked', this.selectItemName)).each(function () {
texts.push($(this).parents('li').first().text());
values.push($(this).val());
});
if (type === 'text' && this.$selectGroups.length) {
texts = [];
this.$selectGroups.each(function () {
var html = [],
text = $.trim($(this).parent().text()),
group = $(this).parent().data('group'),
$children = that.$drop.find(sprintf('[%s][data-group="%s"]', that.selectItemName, group)),
$selected = $children.filter(':checked');
if (!$selected.length) {
return;
}
html.push('[');
html.push(text);
if ($children.length > $selected.length) {
var list = [];
$selected.each(function () {
list.push($(this).parent().text());
});
html.push(': ' + list.join(', '));
}
html.push(']');
texts.push(html.join(''));
});
}
return type === 'text' ? texts : values;
},
setSelects: function (values) {
var that = this;
this.$selectItems.prop('checked', false);
this.$disableItems.prop('checked', false);
$.each(values, function (i, value) {
that.$selectItems.filter(sprintf('[value="%s"]', value)).prop('checked', true);
that.$disableItems.filter(sprintf('[value="%s"]', value)).prop('checked', true);
});
this.$selectAll.prop('checked', this.$selectItems.length ===
this.$selectItems.filter(':checked').length + this.$disableItems.filter(':checked').length);
$.each(that.$selectGroups, function (i, val) {
var group = $(val).parent().attr('data-group'),
$children = that.$selectItems.filter('[data-group="' + group + '"]');
$(val).prop('checked', $children.length &&
$children.length === $children.filter(':checked').length);
});
this.update();
},
enable: function () {
this.$choice.removeClass('disabled');
},
disable: function () {
this.$choice.addClass('disabled');
},
checkAll: function () {
this.$selectItems.prop('checked', true);
this.$selectGroups.prop('checked', true);
this.$selectAll.prop('checked', true);
this.update();
this.options.onCheckAll();
},
uncheckAll: function () {
this.$selectItems.prop('checked', false);
this.$selectGroups.prop('checked', false);
this.$selectAll.prop('checked', false);
this.update();
this.options.onUncheckAll();
},
focus: function () {
this.$choice.focus();
this.options.onFocus();
},
blur: function () {
this.$choice.blur();
this.options.onBlur();
},
refresh: function () {
this.init();
},
filter: function () {
var that = this,
text = $.trim(this.$searchInput.val()).toLowerCase();
if (text.length === 0) {
this.$selectAll.parent().show();
this.$selectItems.parent().show();
this.$disableItems.parent().show();
this.$selectGroups.parent().show();
this.$noResults.hide();
} else {
this.$selectItems.each(function () {
var $parent = $(this).parent();
$parent[removeDiacritics($parent.text().toLowerCase()).indexOf(removeDiacritics(text)) < 0 ? 'hide' : 'show']();
});
this.$disableItems.parent().hide();
this.$selectGroups.each(function () {
var $parent = $(this).parent();
var group = $parent.attr('data-group'),
$items = that.$selectItems.filter(':visible');
$parent[$items.filter(sprintf('[data-group="%s"]', group)).length ? 'show' : 'hide']();
});
//Check if no matches found
if (this.$selectItems.parent().filter(':visible').length) {
this.$selectAll.parent().show();
this.$noResults.hide();
} else {
this.$selectAll.parent().hide();
this.$noResults.show();
}
}
this.updateOptGroupSelect();
this.updateSelectAll();
this.options.onFilter(text);
}
};
$.fn.multipleSelect = function () {
var option = arguments[0],
args = arguments,
value,
allowedMethods = [
'getSelects', 'setSelects',
'enable', 'disable',
'open', 'close',
'checkAll', 'uncheckAll',
'focus', 'blur',
'refresh', 'close'
];
this.each(function () {
var $this = $(this),
data = $this.data('multipleSelect'),
options = $.extend({}, $.fn.multipleSelect.defaults,
$this.data(), typeof option === 'object' && option);
if (!data) {
data = new MultipleSelect($this, options);
$this.data('multipleSelect', data);
}
if (typeof option === 'string') {
if ($.inArray(option, allowedMethods) < 0) {
throw 'Unknown method: ' + option;
}
value = data[option](args[1]);
} else {
data.init();
if (args[1]) {
value = data[args[1]].apply(data, [].slice.call(args, 2));
}
}
});
return typeof value !== 'undefined' ? value : this;
};
$.fn.multipleSelect.defaults = {
name: '',
isOpen: false,
placeholder: '',
selectAll: true,
selectAllDelimiter: ['[', ']'],
minimumCountSelected: 10,
ellipsis: false,
multiple: false,
multipleWidth: 80,
single: false,
filter: true,
width: undefined,
dropWidth: undefined,
maxHeight: 250,
container: null,
position: 'bottom',
keepOpen: false,
animate: 'none', // 'none', 'fade', 'slide'
displayValues: false,
delimiter: ', ',
addTitle: false,
filterAcceptOnEnter: false,
hideOptgroupCheckboxes: false,
selectAllText: '全选',
allSelected: '全部选中',
countSelected: '# 个选中(共 % 个)',
noMatchesFound: '未查询到匹配项',
styler: function () {
return false;
},
textTemplate: function ($elm) {
return $elm.html();
},
labelTemplate: function ($elm) {
return $elm.attr('label');
},
onOpen: function () {
return false;
},
onClose: function () {
return false;
},
onCheckAll: function () {
return false;
},
onUncheckAll: function () {
return false;
},
onFocus: function () {
return false;
},
onBlur: function () {
return false;
},
onOptgroupClick: function () {
return false;
},
onClick: function () {
return false;
},
onFilter: function () {
return false;
}
};
})(jQuery);
|
# Required for Python to search this directory for module files
# We only export public API here.
from webkitpy.common.net.bugzilla.bugzilla import Bugzilla
# Unclear if Bug and Attachment need to be public classes.
from webkitpy.common.net.bugzilla.bug import Bug
from webkitpy.common.net.bugzilla.attachment import Attachment
|
(window["webpackJsonp"]=window["webpackJsonp"]||[]).push([["chunk-4915323a"],{"133c":function(t,e,r){"use strict";var n=r("d785"),a=r.n(n);a.a},"3cbc":function(t,e,r){"use strict";r.r(e);var n=function(){var t=this,e=t.$createElement,r=t._self._c||e;return r("div",{staticClass:"pan-item",style:{zIndex:t.zIndex,height:t.height,width:t.width}},[r("div",{staticClass:"pan-info"},[r("div",{staticClass:"pan-info-roles-container"},[t._t("default")],2)]),t._v(" "),r("div",{staticClass:"pan-thumb",style:{backgroundImage:"url("+t.image+")"}})])},a=[],i=(r("c5f6"),{name:"PanThumb",props:{image:{type:String,required:!0},zIndex:{type:Number,default:1},width:{type:String,default:"150px"},height:{type:String,default:"150px"}}}),o=i,c=(r("133c"),r("2877")),f=Object(c["a"])(o,n,a,!1,null,"799537af",null);e["default"]=f.exports},"5dbc":function(t,e,r){var n=r("d3f4"),a=r("8b97").set;t.exports=function(t,e,r){var i,o=e.constructor;return o!==r&&"function"==typeof o&&(i=o.prototype)!==r.prototype&&n(i)&&a&&a(t,i),t}},"8b97":function(t,e,r){var n=r("d3f4"),a=r("cb7c"),i=function(t,e){if(a(t),!n(e)&&null!==e)throw TypeError(e+": can't set as prototype!")};t.exports={set:Object.setPrototypeOf||("__proto__"in{}?function(t,e,n){try{n=r("9b43")(Function.call,r("11e9").f(Object.prototype,"__proto__").set,2),n(t,[]),e=!(t instanceof Array)}catch(a){e=!0}return function(t,r){return i(t,r),e?t.__proto__=r:n(t,r),t}}({},!1):void 0),check:i}},aa77:function(t,e,r){var n=r("5ca1"),a=r("be13"),i=r("79e5"),o=r("fdef"),c="["+o+"]",f="
",s=RegExp("^"+c+c+"*"),u=RegExp(c+c+"*$"),p=function(t,e,r){var a={},c=i(function(){return!!o[t]()||f[t]()!=f}),s=a[t]=c?e(l):o[t];r&&(a[r]=s),n(n.P+n.F*c,"String",a)},l=p.trim=function(t,e){return t=String(a(t)),1&e&&(t=t.replace(s,"")),2&e&&(t=t.replace(u,"")),t};t.exports=p},c5f6:function(t,e,r){"use strict";var n=r("7726"),a=r("69a8"),i=r("2d95"),o=r("5dbc"),c=r("6a99"),f=r("79e5"),s=r("9093").f,u=r("11e9").f,p=r("86cc").f,l=r("aa77").trim,d="Number",h=n[d],_=h,b=h.prototype,g=i(r("2aeb")(b))==d,I="trim"in String.prototype,v=function(t){var e=c(t,!1);if("string"==typeof e&&e.length>2){e=I?e.trim():l(e,3);var r,n,a,i=e.charCodeAt(0);if(43===i||45===i){if(r=e.charCodeAt(2),88===r||120===r)return NaN}else if(48===i){switch(e.charCodeAt(1)){case 66:case 98:n=2,a=49;break;case 79:case 111:n=8,a=55;break;default:return+e}for(var o,f=e.slice(2),s=0,u=f.length;s<u;s++)if(o=f.charCodeAt(s),o<48||o>a)return NaN;return parseInt(f,n)}}return+e};if(!h(" 0o1")||!h("0b1")||h("+0x1")){h=function(t){var e=arguments.length<1?0:t,r=this;return r instanceof h&&(g?f(function(){b.valueOf.call(r)}):i(r)!=d)?o(new _(v(e)),r,h):v(e)};for(var N,y=r("9e1e")?s(_):"MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,EPSILON,isFinite,isInteger,isNaN,isSafeInteger,MAX_SAFE_INTEGER,MIN_SAFE_INTEGER,parseFloat,parseInt,isInteger".split(","),E=0;y.length>E;E++)a(_,N=y[E])&&!a(h,N)&&p(h,N,u(_,N));h.prototype=b,b.constructor=h,r("2aba")(n,d,h)}},d785:function(t,e,r){},fdef:function(t,e){t.exports="\t\n\v\f\r \u2028\u2029\ufeff"}}]);
|
"""Python wrappers around TensorFlow ops.
This file is MACHINE GENERATED! Do not edit.
"""
import collections as _collections
import six as _six
from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow
from tensorflow.python.eager import context as _context
from tensorflow.python.eager import core as _core
from tensorflow.python.eager import execute as _execute
from tensorflow.python.framework import dtypes as _dtypes
from tensorflow.python.framework import errors as _errors
from tensorflow.python.framework import tensor_shape as _tensor_shape
from tensorflow.core.framework import op_def_pb2 as _op_def_pb2
# Needed to trigger the call to _set_call_cpp_shape_fn.
from tensorflow.python.framework import common_shapes as _common_shapes
from tensorflow.python.framework import op_def_registry as _op_def_registry
from tensorflow.python.framework import ops as _ops
from tensorflow.python.framework import op_def_library as _op_def_library
from tensorflow.python.util.deprecation import deprecated_endpoints
from tensorflow.python.util.tf_export import tf_export
_sparse_feature_cross_outputs = ["output_indices", "output_values",
"output_shape"]
_SparseFeatureCrossOutput = _collections.namedtuple(
"SparseFeatureCross", _sparse_feature_cross_outputs)
@tf_export('sparse_feature_cross')
def sparse_feature_cross(indices, values, shapes, dense, hashed_output, num_buckets, out_type, internal_type, name=None):
r"""Generates sparse cross form a list of sparse tensors.
The op takes two lists, one of 2D `SparseTensor` and one of 2D `Tensor`, each
representing features of one feature column. It outputs a 2D `SparseTensor` with
the batchwise crosses of these features.
For example, if the inputs are
inputs[0]: SparseTensor with shape = [2, 2]
[0, 0]: "a"
[1, 0]: "b"
[1, 1]: "c"
inputs[1]: SparseTensor with shape = [2, 1]
[0, 0]: "d"
[1, 0]: "e"
inputs[2]: Tensor [["f"], ["g"]]
then the output will be
shape = [2, 2]
[0, 0]: "a_X_d_X_f"
[1, 0]: "b_X_e_X_g"
[1, 1]: "c_X_e_X_g"
if hashed_output=true then the output will be
shape = [2, 2]
[0, 0]: HashCombine(
Fingerprint64("f"), HashCombine(
Fingerprint64("d"), Fingerprint64("a")))
[1, 0]: HashCombine(
Fingerprint64("g"), HashCombine(
Fingerprint64("e"), Fingerprint64("b")))
[1, 1]: HashCombine(
Fingerprint64("g"), HashCombine(
Fingerprint64("e"), Fingerprint64("c")))
Args:
indices: A list of `Tensor` objects with type `int64`.
2-D. Indices of each input `SparseTensor`.
values: A list of `Tensor` objects with types from: `int64`, `string`.
1-D. values of each `SparseTensor`.
shapes: A list with the same length as `indices` of `Tensor` objects with type `int64`.
1-D. Shapes of each `SparseTensor`.
dense: A list of `Tensor` objects with types from: `int64`, `string`.
2-D. Columns represented by dense `Tensor`.
hashed_output: A `bool`.
num_buckets: An `int` that is `>= 0`.
out_type: A `tf.DType` from: `tf.int64, tf.string`.
internal_type: A `tf.DType` from: `tf.int64, tf.string`.
name: A name for the operation (optional).
Returns:
A tuple of `Tensor` objects (output_indices, output_values, output_shape).
output_indices: A `Tensor` of type `int64`. 2-D. Indices of the concatenated `SparseTensor`.
output_values: A `Tensor` of type `out_type`. 1-D. Non-empty values of the concatenated or hashed
`SparseTensor`.
output_shape: A `Tensor` of type `int64`. 1-D. Shape of the concatenated `SparseTensor`.
"""
_ctx = _context._context
if _ctx is None or not _ctx._eager_context.is_eager:
if not isinstance(indices, (list, tuple)):
raise TypeError(
"Expected list for 'indices' argument to "
"'sparse_feature_cross' Op, not %r." % indices)
_attr_N = len(indices)
if not isinstance(shapes, (list, tuple)):
raise TypeError(
"Expected list for 'shapes' argument to "
"'sparse_feature_cross' Op, not %r." % shapes)
if len(shapes) != _attr_N:
raise ValueError(
"List argument 'shapes' to 'sparse_feature_cross' Op with length %d "
"must match length %d of argument 'indices'." %
(len(shapes), _attr_N))
hashed_output = _execute.make_bool(hashed_output, "hashed_output")
num_buckets = _execute.make_int(num_buckets, "num_buckets")
out_type = _execute.make_type(out_type, "out_type")
internal_type = _execute.make_type(internal_type, "internal_type")
_, _, _op = _op_def_lib._apply_op_helper(
"SparseFeatureCross", indices=indices, values=values, shapes=shapes,
dense=dense, hashed_output=hashed_output, num_buckets=num_buckets,
out_type=out_type, internal_type=internal_type, name=name)
_result = _op.outputs[:]
_inputs_flat = _op.inputs
_attrs = ("N", _op.get_attr("N"), "hashed_output",
_op.get_attr("hashed_output"), "num_buckets",
_op.get_attr("num_buckets"), "sparse_types",
_op.get_attr("sparse_types"), "dense_types",
_op.get_attr("dense_types"), "out_type",
_op.get_attr("out_type"), "internal_type",
_op.get_attr("internal_type"))
_execute.record_gradient(
"SparseFeatureCross", _inputs_flat, _attrs, _result, name)
_result = _SparseFeatureCrossOutput._make(_result)
return _result
else:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._eager_context.device_name,
"SparseFeatureCross", name, _ctx._post_execution_callbacks, indices,
values, shapes, dense, "hashed_output", hashed_output, "num_buckets",
num_buckets, "out_type", out_type, "internal_type", internal_type)
_result = _SparseFeatureCrossOutput._make(_result)
return _result
except _core._FallbackException:
return sparse_feature_cross_eager_fallback(
indices, values, shapes, dense, hashed_output=hashed_output,
num_buckets=num_buckets, out_type=out_type,
internal_type=internal_type, name=name, ctx=_ctx)
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
def sparse_feature_cross_eager_fallback(indices, values, shapes, dense, hashed_output, num_buckets, out_type, internal_type, name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function sparse_feature_cross
"""
_ctx = ctx if ctx else _context.context()
if not isinstance(indices, (list, tuple)):
raise TypeError(
"Expected list for 'indices' argument to "
"'sparse_feature_cross' Op, not %r." % indices)
_attr_N = len(indices)
if not isinstance(shapes, (list, tuple)):
raise TypeError(
"Expected list for 'shapes' argument to "
"'sparse_feature_cross' Op, not %r." % shapes)
if len(shapes) != _attr_N:
raise ValueError(
"List argument 'shapes' to 'sparse_feature_cross' Op with length %d "
"must match length %d of argument 'indices'." %
(len(shapes), _attr_N))
hashed_output = _execute.make_bool(hashed_output, "hashed_output")
num_buckets = _execute.make_int(num_buckets, "num_buckets")
out_type = _execute.make_type(out_type, "out_type")
internal_type = _execute.make_type(internal_type, "internal_type")
_attr_sparse_types, values = _execute.convert_to_mixed_eager_tensors(values, _ctx)
_attr_dense_types, dense = _execute.convert_to_mixed_eager_tensors(dense, _ctx)
indices = _ops.convert_n_to_tensor(indices, _dtypes.int64)
shapes = _ops.convert_n_to_tensor(shapes, _dtypes.int64)
_inputs_flat = list(indices) + list(values) + list(shapes) + list(dense)
_attrs = ("N", _attr_N, "hashed_output", hashed_output, "num_buckets",
num_buckets, "sparse_types", _attr_sparse_types, "dense_types",
_attr_dense_types, "out_type", out_type, "internal_type", internal_type)
_result = _execute.execute(b"SparseFeatureCross", 3, inputs=_inputs_flat,
attrs=_attrs, ctx=_ctx, name=name)
_execute.record_gradient(
"SparseFeatureCross", _inputs_flat, _attrs, _result, name)
_result = _SparseFeatureCrossOutput._make(_result)
return _result
_ops.RegisterShape("SparseFeatureCross")(None)
_sparse_feature_cross_v2_outputs = ["output_indices", "output_values",
"output_shape"]
_SparseFeatureCrossV2Output = _collections.namedtuple(
"SparseFeatureCrossV2", _sparse_feature_cross_v2_outputs)
@tf_export('sparse_feature_cross_v2')
def sparse_feature_cross_v2(indices, values, shapes, dense, hashed_output, num_buckets, hash_key, out_type, internal_type, name=None):
r"""Generates sparse cross form a list of sparse tensors.
The op takes two lists, one of 2D `SparseTensor` and one of 2D `Tensor`, each
representing features of one feature column. It outputs a 2D `SparseTensor` with
the batchwise crosses of these features.
For example, if the inputs are
inputs[0]: SparseTensor with shape = [2, 2]
[0, 0]: "a"
[1, 0]: "b"
[1, 1]: "c"
inputs[1]: SparseTensor with shape = [2, 1]
[0, 0]: "d"
[1, 0]: "e"
inputs[2]: Tensor [["f"], ["g"]]
then the output will be
shape = [2, 2]
[0, 0]: "a_X_d_X_f"
[1, 0]: "b_X_e_X_g"
[1, 1]: "c_X_e_X_g"
if hashed_output=true then the output will be
shape = [2, 2]
[0, 0]: FingerprintCat64(
Fingerprint64("f"), FingerprintCat64(
Fingerprint64("d"), Fingerprint64("a")))
[1, 0]: FingerprintCat64(
Fingerprint64("g"), FingerprintCat64(
Fingerprint64("e"), Fingerprint64("b")))
[1, 1]: FingerprintCat64(
Fingerprint64("g"), FingerprintCat64(
Fingerprint64("e"), Fingerprint64("c")))
Args:
indices: A list of `Tensor` objects with type `int64`.
2-D. Indices of each input `SparseTensor`.
values: A list of `Tensor` objects with types from: `int64`, `string`.
1-D. values of each `SparseTensor`.
shapes: A list with the same length as `indices` of `Tensor` objects with type `int64`.
1-D. Shapes of each `SparseTensor`.
dense: A list of `Tensor` objects with types from: `int64`, `string`.
2-D. Columns represented by dense `Tensor`.
hashed_output: A `bool`.
num_buckets: An `int` that is `>= 0`.
hash_key: An `int`.
out_type: A `tf.DType` from: `tf.int64, tf.string`.
internal_type: A `tf.DType` from: `tf.int64, tf.string`.
name: A name for the operation (optional).
Returns:
A tuple of `Tensor` objects (output_indices, output_values, output_shape).
output_indices: A `Tensor` of type `int64`. 2-D. Indices of the concatenated `SparseTensor`.
output_values: A `Tensor` of type `out_type`. 1-D. Non-empty values of the concatenated or hashed
`SparseTensor`.
output_shape: A `Tensor` of type `int64`. 1-D. Shape of the concatenated `SparseTensor`.
"""
_ctx = _context._context
if _ctx is None or not _ctx._eager_context.is_eager:
if not isinstance(indices, (list, tuple)):
raise TypeError(
"Expected list for 'indices' argument to "
"'sparse_feature_cross_v2' Op, not %r." % indices)
_attr_N = len(indices)
if not isinstance(shapes, (list, tuple)):
raise TypeError(
"Expected list for 'shapes' argument to "
"'sparse_feature_cross_v2' Op, not %r." % shapes)
if len(shapes) != _attr_N:
raise ValueError(
"List argument 'shapes' to 'sparse_feature_cross_v2' Op with length %d "
"must match length %d of argument 'indices'." %
(len(shapes), _attr_N))
hashed_output = _execute.make_bool(hashed_output, "hashed_output")
num_buckets = _execute.make_int(num_buckets, "num_buckets")
hash_key = _execute.make_int(hash_key, "hash_key")
out_type = _execute.make_type(out_type, "out_type")
internal_type = _execute.make_type(internal_type, "internal_type")
_, _, _op = _op_def_lib._apply_op_helper(
"SparseFeatureCrossV2", indices=indices, values=values, shapes=shapes,
dense=dense, hashed_output=hashed_output, num_buckets=num_buckets,
hash_key=hash_key, out_type=out_type, internal_type=internal_type,
name=name)
_result = _op.outputs[:]
_inputs_flat = _op.inputs
_attrs = ("N", _op.get_attr("N"), "hashed_output",
_op.get_attr("hashed_output"), "num_buckets",
_op.get_attr("num_buckets"), "hash_key",
_op.get_attr("hash_key"), "sparse_types",
_op.get_attr("sparse_types"), "dense_types",
_op.get_attr("dense_types"), "out_type",
_op.get_attr("out_type"), "internal_type",
_op.get_attr("internal_type"))
_execute.record_gradient(
"SparseFeatureCrossV2", _inputs_flat, _attrs, _result, name)
_result = _SparseFeatureCrossV2Output._make(_result)
return _result
else:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._eager_context.device_name,
"SparseFeatureCrossV2", name, _ctx._post_execution_callbacks, indices,
values, shapes, dense, "hashed_output", hashed_output, "num_buckets",
num_buckets, "hash_key", hash_key, "out_type", out_type,
"internal_type", internal_type)
_result = _SparseFeatureCrossV2Output._make(_result)
return _result
except _core._FallbackException:
return sparse_feature_cross_v2_eager_fallback(
indices, values, shapes, dense, hashed_output=hashed_output,
num_buckets=num_buckets, hash_key=hash_key, out_type=out_type,
internal_type=internal_type, name=name, ctx=_ctx)
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
def sparse_feature_cross_v2_eager_fallback(indices, values, shapes, dense, hashed_output, num_buckets, hash_key, out_type, internal_type, name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function sparse_feature_cross_v2
"""
_ctx = ctx if ctx else _context.context()
if not isinstance(indices, (list, tuple)):
raise TypeError(
"Expected list for 'indices' argument to "
"'sparse_feature_cross_v2' Op, not %r." % indices)
_attr_N = len(indices)
if not isinstance(shapes, (list, tuple)):
raise TypeError(
"Expected list for 'shapes' argument to "
"'sparse_feature_cross_v2' Op, not %r." % shapes)
if len(shapes) != _attr_N:
raise ValueError(
"List argument 'shapes' to 'sparse_feature_cross_v2' Op with length %d "
"must match length %d of argument 'indices'." %
(len(shapes), _attr_N))
hashed_output = _execute.make_bool(hashed_output, "hashed_output")
num_buckets = _execute.make_int(num_buckets, "num_buckets")
hash_key = _execute.make_int(hash_key, "hash_key")
out_type = _execute.make_type(out_type, "out_type")
internal_type = _execute.make_type(internal_type, "internal_type")
_attr_sparse_types, values = _execute.convert_to_mixed_eager_tensors(values, _ctx)
_attr_dense_types, dense = _execute.convert_to_mixed_eager_tensors(dense, _ctx)
indices = _ops.convert_n_to_tensor(indices, _dtypes.int64)
shapes = _ops.convert_n_to_tensor(shapes, _dtypes.int64)
_inputs_flat = list(indices) + list(values) + list(shapes) + list(dense)
_attrs = ("N", _attr_N, "hashed_output", hashed_output, "num_buckets",
num_buckets, "hash_key", hash_key, "sparse_types", _attr_sparse_types,
"dense_types", _attr_dense_types, "out_type", out_type, "internal_type",
internal_type)
_result = _execute.execute(b"SparseFeatureCrossV2", 3, inputs=_inputs_flat,
attrs=_attrs, ctx=_ctx, name=name)
_execute.record_gradient(
"SparseFeatureCrossV2", _inputs_flat, _attrs, _result, name)
_result = _SparseFeatureCrossV2Output._make(_result)
return _result
_ops.RegisterShape("SparseFeatureCrossV2")(None)
def _InitOpDefLibrary(op_list_proto_bytes):
op_list = _op_def_pb2.OpList()
op_list.ParseFromString(op_list_proto_bytes)
_op_def_registry.register_op_list(op_list)
op_def_lib = _op_def_library.OpDefLibrary()
op_def_lib.add_op_list(op_list)
return op_def_lib
# op {
# name: "SparseFeatureCross"
# input_arg {
# name: "indices"
# type: DT_INT64
# number_attr: "N"
# }
# input_arg {
# name: "values"
# type_list_attr: "sparse_types"
# }
# input_arg {
# name: "shapes"
# type: DT_INT64
# number_attr: "N"
# }
# input_arg {
# name: "dense"
# type_list_attr: "dense_types"
# }
# output_arg {
# name: "output_indices"
# type: DT_INT64
# }
# output_arg {
# name: "output_values"
# type_attr: "out_type"
# }
# output_arg {
# name: "output_shape"
# type: DT_INT64
# }
# attr {
# name: "N"
# type: "int"
# has_minimum: true
# }
# attr {
# name: "hashed_output"
# type: "bool"
# }
# attr {
# name: "num_buckets"
# type: "int"
# has_minimum: true
# }
# attr {
# name: "sparse_types"
# type: "list(type)"
# has_minimum: true
# allowed_values {
# list {
# type: DT_INT64
# type: DT_STRING
# }
# }
# }
# attr {
# name: "dense_types"
# type: "list(type)"
# has_minimum: true
# allowed_values {
# list {
# type: DT_INT64
# type: DT_STRING
# }
# }
# }
# attr {
# name: "out_type"
# type: "type"
# allowed_values {
# list {
# type: DT_INT64
# type: DT_STRING
# }
# }
# }
# attr {
# name: "internal_type"
# type: "type"
# allowed_values {
# list {
# type: DT_INT64
# type: DT_STRING
# }
# }
# }
# }
# op {
# name: "SparseFeatureCrossV2"
# input_arg {
# name: "indices"
# type: DT_INT64
# number_attr: "N"
# }
# input_arg {
# name: "values"
# type_list_attr: "sparse_types"
# }
# input_arg {
# name: "shapes"
# type: DT_INT64
# number_attr: "N"
# }
# input_arg {
# name: "dense"
# type_list_attr: "dense_types"
# }
# output_arg {
# name: "output_indices"
# type: DT_INT64
# }
# output_arg {
# name: "output_values"
# type_attr: "out_type"
# }
# output_arg {
# name: "output_shape"
# type: DT_INT64
# }
# attr {
# name: "N"
# type: "int"
# has_minimum: true
# }
# attr {
# name: "hashed_output"
# type: "bool"
# }
# attr {
# name: "num_buckets"
# type: "int"
# has_minimum: true
# }
# attr {
# name: "hash_key"
# type: "int"
# }
# attr {
# name: "sparse_types"
# type: "list(type)"
# has_minimum: true
# allowed_values {
# list {
# type: DT_INT64
# type: DT_STRING
# }
# }
# }
# attr {
# name: "dense_types"
# type: "list(type)"
# has_minimum: true
# allowed_values {
# list {
# type: DT_INT64
# type: DT_STRING
# }
# }
# }
# attr {
# name: "out_type"
# type: "type"
# allowed_values {
# list {
# type: DT_INT64
# type: DT_STRING
# }
# }
# }
# attr {
# name: "internal_type"
# type: "type"
# allowed_values {
# list {
# type: DT_INT64
# type: DT_STRING
# }
# }
# }
# }
_op_def_lib = _InitOpDefLibrary(b"\n\337\002\n\022SparseFeatureCross\022\016\n\007indices\030\t*\001N\022\026\n\006values2\014sparse_types\022\r\n\006shapes\030\t*\001N\022\024\n\005dense2\013dense_types\032\022\n\016output_indices\030\t\032\031\n\routput_values\"\010out_type\032\020\n\014output_shape\030\t\"\n\n\001N\022\003int(\001\"\025\n\rhashed_output\022\004bool\"\024\n\013num_buckets\022\003int(\001\"$\n\014sparse_types\022\nlist(type)(\001:\006\n\0042\002\t\007\"#\n\013dense_types\022\nlist(type)(\001:\006\n\0042\002\t\007\"\030\n\010out_type\022\004type:\006\n\0042\002\t\007\"\035\n\rinternal_type\022\004type:\006\n\0042\002\t\007\n\362\002\n\024SparseFeatureCrossV2\022\016\n\007indices\030\t*\001N\022\026\n\006values2\014sparse_types\022\r\n\006shapes\030\t*\001N\022\024\n\005dense2\013dense_types\032\022\n\016output_indices\030\t\032\031\n\routput_values\"\010out_type\032\020\n\014output_shape\030\t\"\n\n\001N\022\003int(\001\"\025\n\rhashed_output\022\004bool\"\024\n\013num_buckets\022\003int(\001\"\017\n\010hash_key\022\003int\"$\n\014sparse_types\022\nlist(type)(\001:\006\n\0042\002\t\007\"#\n\013dense_types\022\nlist(type)(\001:\006\n\0042\002\t\007\"\030\n\010out_type\022\004type:\006\n\0042\002\t\007\"\035\n\rinternal_type\022\004type:\006\n\0042\002\t\007")
|
const React=require("react");function StackOverflowColor(e){return React.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 32 32",width:32,height:32,strokeWidth:!0,stroke:!0},e),React.createElement("path",{fill:"#F48024",d:"M16 2C8.27812 2 2 8.27812 2 16c0 7.7219 6.27812 14 14 14 7.7219 0 14-6.2781 14-14 0-7.72188-6.2781-14-14-14Z"}),React.createElement("path",{fill:"#fff",d:"m19.5405 18.3626-7.4323-1.0743.2576-1.6278 7.2679 1.3976-.0932 1.3045Zm.1315-1.732-6.5772-3.0694.6029-1.3154 6.5772 3.0694-.6029 1.3154Zm.877-1.6443-5.5907-4.6589.9318-1.09618 5.5907 4.65888-.9318 1.0962ZM17.37 7.80615l1.151-.87695 4.33 5.8099-1.151.877-4.33-5.80995Zm2.1924 12.71595H11.889v-1.6443h7.6734v1.6443Z"}),React.createElement("path",{fill:"#fff",d:"M20.6586 17.2334v4.3848h-9.8659v-4.3848H9.14844v6.0291H22.3029v-6.0291h-1.6443Z"}))}module.exports=StackOverflowColor;
|
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
require('reflect-metadata');
var http = require('http');
var SetCookieParser = _interopDefault(require('set-cookie-parser'));
var url = require('url');
var http2 = require('http2');
var common = require('@glasswing/common');
var YAML = _interopDefault(require('yaml'));
var net = require('net');
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/* global Reflect, Promise */
var extendStatics = function(d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
function __extends(d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
function __awaiter(thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
function __generator(thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
}
function __spreadArrays() {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
}
var HttpRequest = /** @class */ (function (_super) {
__extends(HttpRequest, _super);
/**
* Constructor
* @param socket
* @param routeParams
*/
function HttpRequest(socket, routeParams) {
var _this = _super.call(this, socket) || this;
_this.cookieParams = _this.parseCookieParams();
_this.routeParams = routeParams;
_this.queryParams = _this.parseQueryParams();
return _this;
}
/**
*
* @param im
* @param routeParams
*/
HttpRequest.fromIncommingMessage = function (im, routeParams) {
var request = im;
request.cookieParams = request.parseCookieParams();
request.routeParams = routeParams;
request.queryParams = request.parseQueryParams();
return request;
};
/**
* Parse Cookie string
* @param cookies
*/
HttpRequest.prototype.parseCookieParams = function (cookies) {
var cookiesString = cookies ? cookies : (this.headers || {}).cookie || '';
return SetCookieParser.parse(cookiesString.split('; '), {
decodeValues: true,
map: true,
});
};
/**
* Parse url string
* @param url
*/
HttpRequest.prototype.parseQueryParams = function (url$1) {
var urlString = url$1 ? url$1 : this.url || '';
return url.parse(urlString, true).query;
};
/**
*
*/
HttpRequest.prototype.toHttpRequest = function () {
return this;
};
return HttpRequest;
}(http.IncomingMessage));
var Http2Request = /** @class */ (function (_super) {
__extends(Http2Request, _super);
/**
* Constructor
* @param stream
* @param headers
* @param options
* @param rawHeaders
* @param routeParams
*/
function Http2Request(stream, headers, options, rawHeaders, routeParams) {
var _this = _super.call(this, stream, headers, options, rawHeaders) || this;
_this.cookieParams = _this.parseCookieParams();
_this.routeParams = routeParams;
_this.queryParams = _this.parseQueryParams();
return _this;
}
/**
*
* @param im
* @param routeParams
*/
Http2Request.fromIncommingMessage = function (im, routeParams) {
var request = im;
request.cookieParams = request.parseCookieParams();
request.routeParams = routeParams;
request.queryParams = request.parseQueryParams();
return request;
};
/**
* Parse Cookie string
* @param cookies
*/
Http2Request.prototype.parseCookieParams = function (cookies) {
var cookiesString = cookies ? cookies : (this.headers || {}).cookie || '';
return SetCookieParser.parse(cookiesString.split('; '), {
decodeValues: true,
map: true,
});
};
/**
* Parse url string
* @param url
*/
Http2Request.prototype.parseQueryParams = function (url$1) {
var urlString = url$1 ? url$1 : this.url || '';
return url.parse(urlString, true).query;
};
/**
*
*/
Http2Request.prototype.toHttpRequest = function () {
return this;
};
return Http2Request;
}(http2.Http2ServerRequest));
(function (HttpRequestHeader) {
HttpRequestHeader["ACCEPT"] = "Accept";
HttpRequestHeader["ACCEPT_CH"] = "Accept-CH";
HttpRequestHeader["ACCEPT_CH_LIFETIME"] = "Accept-CH-Lifetime";
HttpRequestHeader["ACCEPT_CHARSET"] = "Accept-Charset";
HttpRequestHeader["ACCEPT_ENCODING"] = "Accept-Encoding";
HttpRequestHeader["ACCEPT_LANGUAGE"] = "Accept-Language";
HttpRequestHeader["ACCEPT_PATCH"] = "Accept-Patch";
HttpRequestHeader["ACCEPT_RANGES"] = "Accept-Ranges";
HttpRequestHeader["ACCESS_CONTROL_ALLOW_CREDENTIALS"] = "Access-Control-Allow-Credentials";
HttpRequestHeader["ACCESS_CONTROL_ALLOW_HEADERS"] = "Access-Control-Allow-Headers";
HttpRequestHeader["ACCESS_CONTROL_ALLOW_METHODS"] = "Access-Control-Allow-Methods";
HttpRequestHeader["ACCESS_CONTROL_ALLOW_ORIGIN"] = "Access-Control-Allow-Origin";
HttpRequestHeader["ACCESS_CONTROL_EXPOSE_HEADERS"] = "Access-Control-Expose-Headers";
HttpRequestHeader["ACCESS_CONTROL_MAX_AGE"] = "Access-Control-Max-Age";
HttpRequestHeader["ACCESS_CONTROL_REQUEST_HEADERS"] = "Access-Control-Request-Headers";
HttpRequestHeader["ACCESS_CONTROL_REQUEST_METHOD"] = "Access-Control-Request-Method";
HttpRequestHeader["AGE"] = "Age";
HttpRequestHeader["ALLOW"] = "Allow";
HttpRequestHeader["ALT_SVC"] = "Alt-Svc";
HttpRequestHeader["AUTHORIZATION"] = "Authorization";
HttpRequestHeader["CACHE_CONTROL"] = "Cache-Control";
HttpRequestHeader["CLEAR_SITE_DATA"] = "Clear-Site-Data";
HttpRequestHeader["CONNECTION"] = "Connection";
HttpRequestHeader["CONTENT_DISPOSITION"] = "Content-Disposition";
HttpRequestHeader["CONTENT_ENCODING"] = "Content-Encoding";
HttpRequestHeader["CONTENT_LANGUAGE"] = "Content-Language";
HttpRequestHeader["CONTENT_LENGTH"] = "Content-Length";
HttpRequestHeader["CONTENT_LOCATION"] = "Content-Location";
HttpRequestHeader["CONTENT_RANGE"] = "Content-Range";
HttpRequestHeader["CONTENT_SECURITY_POLICY"] = "Content-Security-Policy";
HttpRequestHeader["CONTENT_SECURITY_POLICY_REPORT_ONLY"] = "Content-Security-Policy-Report-Only";
HttpRequestHeader["CONTENT_TYPE"] = "Content-Type";
HttpRequestHeader["COOKIE"] = "Cookie";
HttpRequestHeader["COOKIE2"] = "Cookie2";
HttpRequestHeader["CROSS_ORIGIN_RESOURCE_POLICY"] = "Cross-Origin-Resource-Policy";
HttpRequestHeader["DNT"] = "DNT";
HttpRequestHeader["DPR"] = "DPR";
HttpRequestHeader["DATE"] = "Date";
HttpRequestHeader["DEVICE_MEMORY"] = "Device-Memory";
HttpRequestHeader["DIGEST"] = "Digest";
HttpRequestHeader["ETAG"] = "ETag";
HttpRequestHeader["EARLY_DATA"] = "Early-Data";
HttpRequestHeader["EXPECT"] = "Expect";
HttpRequestHeader["EXPECT_CT"] = "Expect-CT";
HttpRequestHeader["EXPIRES"] = "Expires";
HttpRequestHeader["FEATURE_POLICY"] = "Feature-Policy";
HttpRequestHeader["FORWARDED"] = "Forwarded";
HttpRequestHeader["FROM"] = "From";
HttpRequestHeader["HOST"] = "Host";
HttpRequestHeader["IF_MATCH"] = "If-Match";
HttpRequestHeader["IF_MODIFIED_SINCE"] = "If-Modified-Since";
HttpRequestHeader["IF_NONE_MATCH"] = "If-None-Match";
HttpRequestHeader["IF_RANGE"] = "If-Range";
HttpRequestHeader["IF_UNMODIFIED_SINCE"] = "If-Unmodified-Since";
HttpRequestHeader["INDEX"] = "Index";
HttpRequestHeader["KEEP_ALIVE"] = "Keep-Alive";
HttpRequestHeader["LARGE_ALLOCATION"] = "Large-Allocation";
HttpRequestHeader["LAST_MODIFIED"] = "Last-Modified";
HttpRequestHeader["LINK"] = "Link";
HttpRequestHeader["LOCATION"] = "Location";
HttpRequestHeader["ORIGIN"] = "Origin";
HttpRequestHeader["PRAGMA"] = "Pragma";
HttpRequestHeader["PROXY_AUTHENTICATE"] = "Proxy-Authenticate";
HttpRequestHeader["PROXY_AUTHORIZATION"] = "Proxy-Authorization";
HttpRequestHeader["PUBLIC_KEY_PINS"] = "Public-Key-Pins";
HttpRequestHeader["PUBLIC_KEY_PINS_REPORT_ONLY"] = "Public-Key-Pins-Report-Only";
HttpRequestHeader["RANGE"] = "Range";
HttpRequestHeader["REFERER"] = "Referer";
HttpRequestHeader["REFERRER_POLICY"] = "Referrer-Policy";
HttpRequestHeader["RETRY_AFTER"] = "Retry-After";
HttpRequestHeader["SAVE_DATA"] = "Save-Data";
HttpRequestHeader["SEC_WEBSOCKET_ACCEPT"] = "Sec-WebSocket-Accept";
HttpRequestHeader["SERVER"] = "Server";
HttpRequestHeader["SERVER_TIMING"] = "Server-Timing";
HttpRequestHeader["SET_COOKIE"] = "Set-Cookie";
HttpRequestHeader["SET_COOKIE2"] = "Set-Cookie2";
HttpRequestHeader["SOURCEMAP"] = "SourceMap";
HttpRequestHeader["STRICT_TRANSPORT_SECURITY"] = "Strict-Transport-Security";
HttpRequestHeader["TE"] = "TE";
HttpRequestHeader["TIMING_ALLOW_ORIGIN"] = "Timing-Allow-Origin";
HttpRequestHeader["TK"] = "Tk";
HttpRequestHeader["TRAILER"] = "Trailer";
HttpRequestHeader["TRANSFER_ENCODING"] = "Transfer-Encoding";
HttpRequestHeader["UPGRADE_INSECURE_REQUESTS"] = "Upgrade-Insecure-Requests";
HttpRequestHeader["USER_AGENT"] = "User-Agent";
HttpRequestHeader["VARY"] = "Vary";
HttpRequestHeader["VIA"] = "Via";
HttpRequestHeader["WWW_AUTHENTICATE"] = "WWW-Authenticate";
HttpRequestHeader["WANT_DIGEST"] = "Want-Digest";
HttpRequestHeader["WARNING"] = "Warning";
HttpRequestHeader["X_CONTENT_TYPE_OPTIONS"] = "X-Content-Type-Options";
HttpRequestHeader["X_DNS_PREFETCH_CONTROL"] = "X-DNS-Prefetch-Control";
HttpRequestHeader["X_FORWARDED_FOR"] = "X-Forwarded-For";
HttpRequestHeader["X_FORWARDED_HOST"] = "X-Forwarded-Host";
HttpRequestHeader["X_FORWARDED_PROTO"] = "X-Forwarded-Proto";
HttpRequestHeader["X_FRAME_OPTIONS"] = "X-Frame-Options";
HttpRequestHeader["X_XSS_PROTECTION"] = "X-XSS-Protection";
})(exports.HttpRequestHeader || (exports.HttpRequestHeader = {}));
(function (HttpRequestMethod) {
HttpRequestMethod["ALL"] = "all";
/**
* The CONNECT method establishes a tunnel to the server identified by the target resource.
*/
HttpRequestMethod["CONNECT"] = "connect";
/**
* The DELETE method deletes the specified resource.
*/
HttpRequestMethod["DELETE"] = "delete";
/**
* The GET method requests a representation of the specified resource. Requests using GET should only retrieve data.
*/
HttpRequestMethod["GET"] = "get";
/**
* The HEAD method asks for a response identical to that of a GET request, but without the response body.
*/
HttpRequestMethod["HEAD"] = "head";
/**
* The OPTIONS method is used to describe the communication options for the target resource.
*/
HttpRequestMethod["OPTIONS"] = "options";
/**
* The PATCH method is used to apply partial modifications to a resource.
*/
HttpRequestMethod["PATCH"] = "patch";
/**
* The POST method is used to submit an entity to the specified resource, often causing a change in state or side
* effects on the server.
*/
HttpRequestMethod["POST"] = "post";
/**
* The PUT method replaces all current representations of the target resource with the request payload.
*/
HttpRequestMethod["PUT"] = "put";
/**
* The TRACE method performs a message loop-back test along the path to the target resource.
*/
HttpRequestMethod["TRACE"] = "trace";
})(exports.HttpRequestMethod || (exports.HttpRequestMethod = {}));
(function (HttpArgumentSource) {
HttpArgumentSource["REQUEST"] = "request";
HttpArgumentSource["RESPONSE"] = "response";
})(exports.HttpArgumentSource || (exports.HttpArgumentSource = {}));
/******************************************************************************
*
* Helpers
*
*****************************************************************************/
/**
* @Body(key:? string, decoder?: RequestBodyDecoder)
*
* If key is not mentioned or `null`, will return the entire decoded body.
* If key is mentioned and not null, will return a certain property of the body, defined by the key's value.
*/
var Body = function (key, decoder) {
if (decoder === void 0) { decoder = JSON.parse; }
return function (target, methodKey, parameterIndex) {
var mapper = function (data) { return (key ? data[key] : data); };
appendParameterMapper(target, methodKey, parameterIndex, function (req) {
return readRequestBody(req)
.then(decoder)
.then(mapper);
});
};
};
/**
* Cookie(key?: string, value?: any)
* If key is not mentioned or `null`, will return the entire cookies object.
* If key is mentioned and not null, will return a certain property of the cookies object, defined by the key's
* value.
*/
var Cookie = function (key, value) {
return function (target, methodKey, parameterIndex) {
appendParameterMapper(target, methodKey, parameterIndex, function (req) {
if (!req.cookieParams) {
return null;
}
return key ? req.cookieParams[key] : req.cookieParams;
});
};
};
/**
* Header(key?: string)
* If key is not mentioned or `null`, will return the entire headers object.
* If key is mentioned and not null, will return a certain property of the headers object, defined by the key's
* value.
*/
var Header = function (key) {
return function (target, methodKey, parameterIndex) {
appendParameterMapper(target, methodKey, parameterIndex, function (req) {
return key ? req.headers[key] : req.headers;
});
};
};
/**
* @Ip()
*/
var Ip = function () {
return function (target, methodKey, parameterIndex) {
appendParameterMapper(target, methodKey, parameterIndex, function (req) { return req.headers[exports.HttpRequestHeader.X_FORWARDED_FOR.toLowerCase()]; });
};
};
/**
* @Param(key:? string)
* If key is not mentioned or `null`, will return the entire decoded parameters object.
* If key is mentioned and not null, will return a certain property of the parameters object, defined by the key's
* value.
*/
var Param = function (key) {
return function (target, methodKey, parameterIndex) {
appendParameterMapper(target, methodKey, parameterIndex, function (req) {
return key ? req.routeParams[key] : req.routeParams;
});
};
};
/**
* @Query(key:? string)
* If key is not mentioned or `null`, will return the entire query object.
* If key is mentioned and not null, will return a certain property of the query object, defined by the key's value.
*/
var Query = function (key) {
return function (target, methodKey, parameterIndex) {
appendParameterMapper(target, methodKey, parameterIndex, function (req) {
return key ? req.queryParams[key] : req.queryParams;
});
};
};
/**
* @Req()
*/
var Req = function () {
return function (target, methodKey, parameterIndex) {
appendParameterMapper(target, methodKey, parameterIndex, function (req) { return req; });
};
};
/**
* @Res()
*/
var Res = function () {
return function (target, methodKey, parameterIndex) {
appendParameterMapper(target, methodKey, parameterIndex, function (res) { return res; }, exports.HttpArgumentSource.RESPONSE);
};
};
/******************************************************************************
*
* Helpers
*
*****************************************************************************/
/**
*
* @param methodName
*/
var methodArgumentsDescriptor = function (methodName) {
return (typeof methodName === 'string' ? methodName : methodName.toString()) + "__Arguments";
};
/**
*
* @link https://nodejs.org/es/docs/guides/anatomy-of-an-http-transaction/
* @param req
*/
var readRequestBody = function (req) { return __awaiter(void 0, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, new Promise(function (resolve, reject) {
var body = [];
req
.on('error', function (err) { return reject(err); })
.on('data', function (chunk) { return body.push(chunk); })
.on('end', function () {
var str = Buffer.concat(body).toString();
resolve(str);
});
})
/**
*
* @param target
* @param methodName
* @param parameterIndex
* @param callable
* @param source
*/
];
});
}); };
/**
*
* @param target
* @param methodName
* @param parameterIndex
* @param callable
* @param source
*/
var appendParameterMapper = function (target, methodName, parameterIndex, callable, source) {
if (source === void 0) { source = exports.HttpArgumentSource.REQUEST; }
// calculate method (name) descriptor
var methodDescriptor = methodArgumentsDescriptor(methodName);
// can't set ParameterDescriptor[] type due to creation of an array of zeros
var metadata = Array(parameterIndex + 1);
// copy already discovered parameters into the new array
if (Reflect.hasMetadata(methodDescriptor, target)) {
var oldMetadata = Reflect.getMetadata(methodDescriptor, target) || [];
oldMetadata.forEach(function (data, index) {
metadata[index] = data;
});
}
// add the new discovered parameter descriptor to the array
metadata[parameterIndex] = {
callable: callable,
source: source,
};
// set the data back
Reflect.defineMetadata(methodDescriptor, metadata, target);
};
/**
* Comment
*
* @returns {MethodDecorator}
*/
var RespondWith = function (bodyEncoder) {
if (bodyEncoder === void 0) { bodyEncoder = function (data) { return data; }; }
var other = [];
for (var _i = 1; _i < arguments.length; _i++) {
other[_i - 1] = arguments[_i];
}
return function (target, propertyKey, descriptor) {
var handler = function (oldMethod) {
return function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
var result = oldMethod.apply(void 0, args);
return result instanceof Promise
? result.then(function (data) { return bodyEncoder.apply(void 0, __spreadArrays([data], other)); })
: bodyEncoder.apply(void 0, __spreadArrays([result], other));
};
};
return common.extendClassMethod(descriptor, handler);
};
};
/**
* Wrap controller respond with raw data
*
* @param args
*/
var RespondWithRaw = function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return RespondWith.apply(void 0, __spreadArrays([function (data) { return data; }], args));
};
/**
* Wrap controller action to encode response into a JSON string
*
* @param args
*/
var RespondWithJson = function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return RespondWith.apply(void 0, __spreadArrays([JSON.stringify], args));
};
/**
* Wrap controller action to encode response into a YAML string
*
* @param args
*/
var RespondWithYaml = function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return RespondWith.apply(void 0, __spreadArrays([YAML.stringify], args));
};
var HttpResponse = /** @class */ (function (_super) {
__extends(HttpResponse, _super);
function HttpResponse() {
return _super !== null && _super.apply(this, arguments) || this;
}
return HttpResponse;
}(http.ServerResponse));
var Http2Response = /** @class */ (function (_super) {
__extends(Http2Response, _super);
function Http2Response() {
return _super !== null && _super.apply(this, arguments) || this;
}
return Http2Response;
}(http2.Http2ServerResponse));
(function (HttpResponseCode) {
HttpResponseCode[HttpResponseCode["CONTINUE"] = 100] = "CONTINUE";
HttpResponseCode[HttpResponseCode["SWITCHING_PROTOCOLS"] = 101] = "SWITCHING_PROTOCOLS";
HttpResponseCode[HttpResponseCode["PROCESSING"] = 102] = "PROCESSING";
HttpResponseCode[HttpResponseCode["EARLY_HINTS"] = 103] = "EARLY_HINTS";
HttpResponseCode[HttpResponseCode["OK"] = 200] = "OK";
HttpResponseCode[HttpResponseCode["CREATED"] = 201] = "CREATED";
HttpResponseCode[HttpResponseCode["ACCEPTED"] = 202] = "ACCEPTED";
HttpResponseCode[HttpResponseCode["NON_AUTHORITATIVE_INFORMATION"] = 203] = "NON_AUTHORITATIVE_INFORMATION";
HttpResponseCode[HttpResponseCode["NO_CONTENT"] = 204] = "NO_CONTENT";
HttpResponseCode[HttpResponseCode["RESET_CONTENT"] = 205] = "RESET_CONTENT";
HttpResponseCode[HttpResponseCode["PARTIAL_CONTENT"] = 206] = "PARTIAL_CONTENT";
HttpResponseCode[HttpResponseCode["MULTI_STATUS"] = 207] = "MULTI_STATUS";
HttpResponseCode[HttpResponseCode["ALREADY_REPORTED"] = 208] = "ALREADY_REPORTED";
HttpResponseCode[HttpResponseCode["IM_USED"] = 226] = "IM_USED";
HttpResponseCode[HttpResponseCode["MULTIPLE_CHOICES"] = 300] = "MULTIPLE_CHOICES";
HttpResponseCode[HttpResponseCode["MOVED_PERMANENTLY"] = 301] = "MOVED_PERMANENTLY";
HttpResponseCode[HttpResponseCode["FOUND"] = 302] = "FOUND";
HttpResponseCode[HttpResponseCode["SEE_OTHER"] = 303] = "SEE_OTHER";
HttpResponseCode[HttpResponseCode["NOT_MODIFIED"] = 304] = "NOT_MODIFIED";
HttpResponseCode[HttpResponseCode["USE_PROXY"] = 305] = "USE_PROXY";
HttpResponseCode[HttpResponseCode["RESERVED"] = 306] = "RESERVED";
HttpResponseCode[HttpResponseCode["TEMPORARY_REDIRECT"] = 307] = "TEMPORARY_REDIRECT";
HttpResponseCode[HttpResponseCode["PERMANENTLY_REDIRECT"] = 308] = "PERMANENTLY_REDIRECT";
HttpResponseCode[HttpResponseCode["BAD_REQUEST"] = 400] = "BAD_REQUEST";
HttpResponseCode[HttpResponseCode["UNAUTHORIZED"] = 401] = "UNAUTHORIZED";
HttpResponseCode[HttpResponseCode["PAYMENT_REQUIRED"] = 402] = "PAYMENT_REQUIRED";
HttpResponseCode[HttpResponseCode["FORBIDDEN"] = 403] = "FORBIDDEN";
HttpResponseCode[HttpResponseCode["NOT_FOUND"] = 404] = "NOT_FOUND";
HttpResponseCode[HttpResponseCode["METHOD_NOT_ALLOWED"] = 405] = "METHOD_NOT_ALLOWED";
HttpResponseCode[HttpResponseCode["NOT_ACCEPTABLE"] = 406] = "NOT_ACCEPTABLE";
HttpResponseCode[HttpResponseCode["PROXY_AUTHENTICATION_REQUIRED"] = 407] = "PROXY_AUTHENTICATION_REQUIRED";
HttpResponseCode[HttpResponseCode["REQUEST_TIMEOUT"] = 408] = "REQUEST_TIMEOUT";
HttpResponseCode[HttpResponseCode["CONFLICT"] = 409] = "CONFLICT";
HttpResponseCode[HttpResponseCode["GONE"] = 410] = "GONE";
HttpResponseCode[HttpResponseCode["LENGTH_REQUIRED"] = 411] = "LENGTH_REQUIRED";
HttpResponseCode[HttpResponseCode["PRECONDITION_FAILED"] = 412] = "PRECONDITION_FAILED";
HttpResponseCode[HttpResponseCode["PAYLOAD_TOO_LARGE"] = 413] = "PAYLOAD_TOO_LARGE";
HttpResponseCode[HttpResponseCode["URI_TOO_LONG"] = 414] = "URI_TOO_LONG";
HttpResponseCode[HttpResponseCode["UNSUPPORTED_MEDIA_TYPE"] = 415] = "UNSUPPORTED_MEDIA_TYPE";
HttpResponseCode[HttpResponseCode["RANGE_NOT_SATISFIABLE"] = 416] = "RANGE_NOT_SATISFIABLE";
HttpResponseCode[HttpResponseCode["EXPECTATION_FAILED"] = 417] = "EXPECTATION_FAILED";
HttpResponseCode[HttpResponseCode["I_AM_A_TEAPOT"] = 418] = "I_AM_A_TEAPOT";
HttpResponseCode[HttpResponseCode["MISDIRECTED_REQUEST"] = 421] = "MISDIRECTED_REQUEST";
HttpResponseCode[HttpResponseCode["UNPROCESSABLE_ENTITY"] = 422] = "UNPROCESSABLE_ENTITY";
HttpResponseCode[HttpResponseCode["LOCKED"] = 423] = "LOCKED";
HttpResponseCode[HttpResponseCode["FAILED_DEPENDENCY"] = 424] = "FAILED_DEPENDENCY";
HttpResponseCode[HttpResponseCode["TOO_EARLY"] = 425] = "TOO_EARLY";
HttpResponseCode[HttpResponseCode["UPGRADE_REQUIRED"] = 426] = "UPGRADE_REQUIRED";
HttpResponseCode[HttpResponseCode["PRECONDITION_REQUIRED"] = 428] = "PRECONDITION_REQUIRED";
HttpResponseCode[HttpResponseCode["TOO_MANY_REQUESTS"] = 429] = "TOO_MANY_REQUESTS";
HttpResponseCode[HttpResponseCode["REQUEST_HEADER_FIELDS_TOO_LARGE"] = 431] = "REQUEST_HEADER_FIELDS_TOO_LARGE";
HttpResponseCode[HttpResponseCode["UNAVAILABLE_FOR_LEGAL_REASONS"] = 451] = "UNAVAILABLE_FOR_LEGAL_REASONS";
HttpResponseCode[HttpResponseCode["INTERNAL_SERVER_ERROR"] = 500] = "INTERNAL_SERVER_ERROR";
HttpResponseCode[HttpResponseCode["NOT_IMPLEMENTED"] = 501] = "NOT_IMPLEMENTED";
HttpResponseCode[HttpResponseCode["BAD_GATEWAY"] = 502] = "BAD_GATEWAY";
HttpResponseCode[HttpResponseCode["SERVICE_UNAVAILABLE"] = 503] = "SERVICE_UNAVAILABLE";
HttpResponseCode[HttpResponseCode["GATEWAY_TIMEOUT"] = 504] = "GATEWAY_TIMEOUT";
HttpResponseCode[HttpResponseCode["HTTP_VERSION_NOT_SUPPORTED"] = 505] = "HTTP_VERSION_NOT_SUPPORTED";
HttpResponseCode[HttpResponseCode["VARIANT_ALSO_NEGOTIATES"] = 506] = "VARIANT_ALSO_NEGOTIATES";
HttpResponseCode[HttpResponseCode["INSUFFICIENT_STORAGE"] = 507] = "INSUFFICIENT_STORAGE";
HttpResponseCode[HttpResponseCode["LOOP_DETECTED"] = 508] = "LOOP_DETECTED";
HttpResponseCode[HttpResponseCode["NOT_EXTENDED"] = 510] = "NOT_EXTENDED";
HttpResponseCode[HttpResponseCode["NETWORK_AUTHENTICATION_REQUIRED"] = 511] = "NETWORK_AUTHENTICATION_REQUIRED";
})(exports.HttpResponseCode || (exports.HttpResponseCode = {}));
(function (HttpResponseMessage) {
HttpResponseMessage["CONTINUE"] = "100 Continue";
HttpResponseMessage["SWITCHING_PROTOCOLS"] = "101 Switching Protocols";
HttpResponseMessage["PROCESSING"] = "102 Processing";
HttpResponseMessage["EARLY_HINTS"] = "103 Early Hints";
HttpResponseMessage["OK"] = "200 OK";
HttpResponseMessage["CREATED"] = "201 Created";
HttpResponseMessage["ACCEPTED"] = "202 Accepted";
HttpResponseMessage["NON_AUTHORITATIVE_INFORMATION"] = "203 Non-Authoritative Information";
HttpResponseMessage["NO_CONTENT"] = "204 No Content";
HttpResponseMessage["RESET_CONTENT"] = "205 Reset Content";
HttpResponseMessage["PARTIAL_CONTENT"] = "206 Partial Content";
HttpResponseMessage["MULTI_STATUS"] = "207 Multi-Status";
HttpResponseMessage["IM_USED"] = "226 IM Used";
HttpResponseMessage["ALREADY_REPORTED"] = "208 Already Reported";
HttpResponseMessage["MULTIPLE_CHOICES"] = "300 Multiple Choices";
HttpResponseMessage["MOVED_PERMANENTLY"] = "301 Moved Permanently";
HttpResponseMessage["FOUND"] = "302 Found";
HttpResponseMessage["SEE_OTHER"] = "303 See Other";
HttpResponseMessage["NOT_MODIFIED"] = "304 Not Modified";
HttpResponseMessage["USE_PROXY"] = "305 Use Proxy";
HttpResponseMessage["RESERVED"] = "306 unused";
HttpResponseMessage["TEMPORARY_REDIRECT"] = "307 Temporary Redirect";
HttpResponseMessage["PERMANENT_REDIRECT"] = "308 Permanent Redirect";
HttpResponseMessage["BAD_REQUEST"] = "400 Bad Request";
HttpResponseMessage["UNAUTHORIZED"] = "401 Unauthorized";
HttpResponseMessage["PAYMENT_REQUIRED"] = "402 Payment Required";
HttpResponseMessage["FORBIDDEN"] = "403 Forbidden";
HttpResponseMessage["NOT_FOUND"] = "404 Not Found";
HttpResponseMessage["METHOD_NOT_ALLOWED"] = "405 Method Not Allowed";
HttpResponseMessage["NOT_ACCEPTABLE"] = "406 Not Acceptable";
HttpResponseMessage["PROXY_AUTHENTICATION_REQUIRED"] = "407 Proxy Authentication Required";
HttpResponseMessage["REQUEST_TIMEOUT"] = "408 Request Timeout";
HttpResponseMessage["CONFLICT"] = "409 Conflict";
HttpResponseMessage["GONE"] = "410 Gone";
HttpResponseMessage["LENGTH_REQUIRED"] = "411 Length Required";
HttpResponseMessage["PRECONDITION_FAILED"] = "412 Precondition Failed";
HttpResponseMessage["PAYLOAD_TOO_LARGE"] = "413 Payload Too Large";
HttpResponseMessage["URI_TOO_LONG"] = "414 URI Too Long";
HttpResponseMessage["UNSUPPORTED_MEDIA_TYPE"] = "415 Unsupported Media Type";
HttpResponseMessage["RANGE_NOT_SATISFIABLE"] = "416 Range Not Satisfiable";
HttpResponseMessage["EXPECTATION_FAILED"] = "417 Expectation Failed";
HttpResponseMessage["I_AM_A_TEAPOT"] = "418 I'm a teapot";
HttpResponseMessage["MISDIRECTED_REQUEST"] = "421 Misdirected Request";
HttpResponseMessage["UNPROCESSABLE_ENTITY"] = "422 Unprocessable Entity";
HttpResponseMessage["LOCKED"] = "423 Locked";
HttpResponseMessage["FAILED_DEPENDENCY"] = "424 Failed Dependency";
HttpResponseMessage["TOO_EARLY"] = "425 Too Early";
HttpResponseMessage["UPGRADE_REQUIRED"] = "426 Upgrade Required";
HttpResponseMessage["PRECONDITION_REQUIRED"] = "428 Precondition Required";
HttpResponseMessage["TOO_MANY_REQUESTS"] = "429 Too Many Requests";
HttpResponseMessage["REQUEST_HEADER_FIELDS_TOO_LARGE"] = "431 Request Header Fields Too Large";
HttpResponseMessage["UNAVAILABLE_FOR_LEGAL_REASONS"] = "451 Unavailable For Legal Reasons";
HttpResponseMessage["INTERNAL_SERVER_ERROR"] = "500 Internal Server Error";
HttpResponseMessage["NOT_IMPLEMENTED"] = "501 Not Implemented";
HttpResponseMessage["BAD_GATEWAY"] = "502 Bad Gateway";
HttpResponseMessage["SERVICE_UNAVAILABLE"] = "503 Service Unavailable";
HttpResponseMessage["GATEWAY_TIMEOUT"] = "504 Gateway Timeout";
HttpResponseMessage["HTTP_VERSION_NOT_SUPPORTED"] = "505 HTTP Version Not Supported";
HttpResponseMessage["VARIANT_ALSO_NEGOTIATES"] = "506 Variant Also Negotiates";
HttpResponseMessage["INSUFFICIENT_STORAGE"] = "507 Insufficient Storage";
HttpResponseMessage["LOOP_DETECTED"] = "508 Loop Detected";
HttpResponseMessage["NOT_EXTENDED"] = "510 Not Extended";
HttpResponseMessage["NETWORK_AUTHENTICATION_REQUIRED"] = "511 Network Authentication Required";
})(exports.HttpResponseMessage || (exports.HttpResponseMessage = {}));
/**
* @link https://github.com/nestjs/nest/blob/master/packages/common/exceptions/http.exception.ts
*/
var HttpException = /** @class */ (function (_super) {
__extends(HttpException, _super);
function HttpException(response, code) {
var _this = _super.call(this) || this;
_this.response = response;
_this.code = code;
_this.message = response;
_this.code = code;
return _this;
}
/**
* Convert a HTTP Exception into a HTTP body to respond with.
* @param message
* @param error
* @param code
*/
HttpException.createBody = function (message, error, code) {
if (typeof message !== 'string' && !Array.isArray(message)) {
return message;
}
var theMessage = message
? {
code: code,
error: error,
message: message,
}
: {
code: code,
error: error,
};
return theMessage;
};
/**
* Overwrite Error.toString()
*/
HttpException.prototype.toString = function () {
return "Error(" + this.code + "): " + (typeof this.message === 'string' ? this.message : JSON.stringify(this.message));
};
return HttpException;
}(Error));
/**
* 401 Unauthorized Exception
*/
var UnauthorizedException = /** @class */ (function (_super) {
__extends(UnauthorizedException, _super);
function UnauthorizedException(message, error) {
if (error === void 0) { error = exports.HttpResponseMessage.UNAUTHORIZED; }
return _super.call(this, HttpException.createBody(message, error, exports.HttpResponseCode.UNAUTHORIZED), exports.HttpResponseCode.UNAUTHORIZED) || this;
}
return UnauthorizedException;
}(HttpException));
/**
* 402 Payment Required Exception
*/
var PaymentRequiredException = /** @class */ (function (_super) {
__extends(PaymentRequiredException, _super);
function PaymentRequiredException(message, error) {
if (error === void 0) { error = exports.HttpResponseMessage.PAYMENT_REQUIRED; }
return _super.call(this, HttpException.createBody(message, error, exports.HttpResponseCode.PAYMENT_REQUIRED), exports.HttpResponseCode.PAYMENT_REQUIRED) || this;
}
return PaymentRequiredException;
}(HttpException));
/**
* 403 Forbidden Exception
*/
var ForbiddenException = /** @class */ (function (_super) {
__extends(ForbiddenException, _super);
function ForbiddenException(message, error) {
if (error === void 0) { error = exports.HttpResponseMessage.FORBIDDEN; }
return _super.call(this, HttpException.createBody(message, error, exports.HttpResponseCode.FORBIDDEN), exports.HttpResponseCode.FORBIDDEN) || this;
}
return ForbiddenException;
}(HttpException));
/**
* 404 Not Found Exception
*/
var NotFoundException = /** @class */ (function (_super) {
__extends(NotFoundException, _super);
function NotFoundException(message, error) {
if (error === void 0) { error = exports.HttpResponseMessage.NOT_FOUND; }
return _super.call(this, HttpException.createBody(message, error, exports.HttpResponseCode.NOT_FOUND), exports.HttpResponseCode.NOT_FOUND) || this;
}
return NotFoundException;
}(HttpException));
/**
* 405 Method Not Allowed Exception
*/
var MethodNotAllowedException = /** @class */ (function (_super) {
__extends(MethodNotAllowedException, _super);
function MethodNotAllowedException(message, error) {
if (error === void 0) { error = exports.HttpResponseMessage.METHOD_NOT_ALLOWED; }
return _super.call(this, HttpException.createBody(message, error, exports.HttpResponseCode.METHOD_NOT_ALLOWED), exports.HttpResponseCode.METHOD_NOT_ALLOWED) || this;
}
return MethodNotAllowedException;
}(HttpException));
/**
* 406 Not Acceptable Exception
*/
var NotAcceptableException = /** @class */ (function (_super) {
__extends(NotAcceptableException, _super);
function NotAcceptableException(message, error) {
if (error === void 0) { error = exports.HttpResponseMessage.NOT_ACCEPTABLE; }
return _super.call(this, HttpException.createBody(message, error, exports.HttpResponseCode.NOT_ACCEPTABLE), exports.HttpResponseCode.NOT_ACCEPTABLE) || this;
}
return NotAcceptableException;
}(HttpException));
/**
* 407 Proxy Authentication Required Exception
*/
var ProxyAuthenticationRequiredException = /** @class */ (function (_super) {
__extends(ProxyAuthenticationRequiredException, _super);
function ProxyAuthenticationRequiredException(message, error) {
if (error === void 0) { error = exports.HttpResponseMessage.PROXY_AUTHENTICATION_REQUIRED; }
return _super.call(this, HttpException.createBody(message, error, exports.HttpResponseCode.PROXY_AUTHENTICATION_REQUIRED), exports.HttpResponseCode.PROXY_AUTHENTICATION_REQUIRED) || this;
}
return ProxyAuthenticationRequiredException;
}(HttpException));
/**
* 408 Request Timeout Exception
*/
var RequestTimeoutException = /** @class */ (function (_super) {
__extends(RequestTimeoutException, _super);
function RequestTimeoutException(message, error) {
if (error === void 0) { error = exports.HttpResponseMessage.REQUEST_TIMEOUT; }
return _super.call(this, HttpException.createBody(message, error, exports.HttpResponseCode.REQUEST_TIMEOUT), exports.HttpResponseCode.REQUEST_TIMEOUT) || this;
}
return RequestTimeoutException;
}(HttpException));
/**
* 409 Conflict Exception
*/
var ConflictException = /** @class */ (function (_super) {
__extends(ConflictException, _super);
function ConflictException(message, error) {
if (error === void 0) { error = exports.HttpResponseMessage.CONFLICT; }
return _super.call(this, HttpException.createBody(message, error, exports.HttpResponseCode.CONFLICT), exports.HttpResponseCode.CONFLICT) || this;
}
return ConflictException;
}(HttpException));
/**
* 410 Gone Exception
*/
var GoneException = /** @class */ (function (_super) {
__extends(GoneException, _super);
function GoneException(message, error) {
if (error === void 0) { error = exports.HttpResponseMessage.GONE; }
return _super.call(this, HttpException.createBody(message, error, exports.HttpResponseCode.GONE), exports.HttpResponseCode.GONE) || this;
}
return GoneException;
}(HttpException));
/**
* 411 Length Required Exception
*/
var LengthRequiredException = /** @class */ (function (_super) {
__extends(LengthRequiredException, _super);
function LengthRequiredException(message, error) {
if (error === void 0) { error = exports.HttpResponseMessage.LENGTH_REQUIRED; }
return _super.call(this, HttpException.createBody(message, error, exports.HttpResponseCode.LENGTH_REQUIRED), exports.HttpResponseCode.LENGTH_REQUIRED) || this;
}
return LengthRequiredException;
}(HttpException));
/**
* 412 Precondition Failed Exception
*/
var PreconditionFailedException = /** @class */ (function (_super) {
__extends(PreconditionFailedException, _super);
function PreconditionFailedException(message, error) {
if (error === void 0) { error = exports.HttpResponseMessage.PRECONDITION_FAILED; }
return _super.call(this, HttpException.createBody(message, error, exports.HttpResponseCode.PRECONDITION_FAILED), exports.HttpResponseCode.PRECONDITION_FAILED) || this;
}
return PreconditionFailedException;
}(HttpException));
/**
* 413 Payload Too Large Exception
*/
var PayloadTooLargeException = /** @class */ (function (_super) {
__extends(PayloadTooLargeException, _super);
function PayloadTooLargeException(message, error) {
if (error === void 0) { error = exports.HttpResponseMessage.PAYLOAD_TOO_LARGE; }
return _super.call(this, HttpException.createBody(message, error, exports.HttpResponseCode.PAYLOAD_TOO_LARGE), exports.HttpResponseCode.PAYLOAD_TOO_LARGE) || this;
}
return PayloadTooLargeException;
}(HttpException));
/**
* 414 URI Too Long Exception
*/
var URITooLongException = /** @class */ (function (_super) {
__extends(URITooLongException, _super);
function URITooLongException(message, error) {
if (error === void 0) { error = exports.HttpResponseMessage.URI_TOO_LONG; }
return _super.call(this, HttpException.createBody(message, error, exports.HttpResponseCode.URI_TOO_LONG), exports.HttpResponseCode.URI_TOO_LONG) || this;
}
return URITooLongException;
}(HttpException));
/**
* 415 Unsupported Media Type Exception
*/
var UnsupportedMediaTypeException = /** @class */ (function (_super) {
__extends(UnsupportedMediaTypeException, _super);
function UnsupportedMediaTypeException(message, error) {
if (error === void 0) { error = exports.HttpResponseMessage.UNSUPPORTED_MEDIA_TYPE; }
return _super.call(this, HttpException.createBody(message, error, exports.HttpResponseCode.UNSUPPORTED_MEDIA_TYPE), exports.HttpResponseCode.UNSUPPORTED_MEDIA_TYPE) || this;
}
return UnsupportedMediaTypeException;
}(HttpException));
/**
* 416 Range Not Satisfiable Exception
*/
var RangeNotSatisfiableException = /** @class */ (function (_super) {
__extends(RangeNotSatisfiableException, _super);
function RangeNotSatisfiableException(message, error) {
if (error === void 0) { error = exports.HttpResponseMessage.RANGE_NOT_SATISFIABLE; }
return _super.call(this, HttpException.createBody(message, error, exports.HttpResponseCode.RANGE_NOT_SATISFIABLE), exports.HttpResponseCode.RANGE_NOT_SATISFIABLE) || this;
}
return RangeNotSatisfiableException;
}(HttpException));
/**
* 417 Expectation Failed Exception
*/
var ExpectationFailedException = /** @class */ (function (_super) {
__extends(ExpectationFailedException, _super);
function ExpectationFailedException(message, error) {
if (error === void 0) { error = exports.HttpResponseMessage.EXPECTATION_FAILED; }
return _super.call(this, HttpException.createBody(message, error, exports.HttpResponseCode.EXPECTATION_FAILED), exports.HttpResponseCode.EXPECTATION_FAILED) || this;
}
return ExpectationFailedException;
}(HttpException));
/**
* 418 I'm a teapot Exception
*/
var ImateapotException = /** @class */ (function (_super) {
__extends(ImateapotException, _super);
function ImateapotException(message, error) {
if (error === void 0) { error = exports.HttpResponseMessage.I_AM_A_TEAPOT; }
return _super.call(this, HttpException.createBody(message, error, exports.HttpResponseCode.I_AM_A_TEAPOT), exports.HttpResponseCode.I_AM_A_TEAPOT) || this;
}
return ImateapotException;
}(HttpException));
/**
* 422 Unprocessable Entity Exception
*/
var UnprocessableEntityException = /** @class */ (function (_super) {
__extends(UnprocessableEntityException, _super);
function UnprocessableEntityException(message, error) {
if (error === void 0) { error = exports.HttpResponseMessage.UNPROCESSABLE_ENTITY; }
return _super.call(this, HttpException.createBody(message, error, exports.HttpResponseCode.UNPROCESSABLE_ENTITY), exports.HttpResponseCode.UNPROCESSABLE_ENTITY) || this;
}
return UnprocessableEntityException;
}(HttpException));
/**
* 425 Too Early Exception
*/
var TooEarlyException = /** @class */ (function (_super) {
__extends(TooEarlyException, _super);
function TooEarlyException(message, error) {
if (error === void 0) { error = exports.HttpResponseMessage.TOO_EARLY; }
return _super.call(this, HttpException.createBody(message, error, exports.HttpResponseCode.TOO_EARLY), exports.HttpResponseCode.TOO_EARLY) || this;
}
return TooEarlyException;
}(HttpException));
/**
* 426 Upgrade Required Exception
*/
var UpgradeRequiredException = /** @class */ (function (_super) {
__extends(UpgradeRequiredException, _super);
function UpgradeRequiredException(message, error) {
if (error === void 0) { error = exports.HttpResponseMessage.UPGRADE_REQUIRED; }
return _super.call(this, HttpException.createBody(message, error, exports.HttpResponseCode.UPGRADE_REQUIRED), exports.HttpResponseCode.UPGRADE_REQUIRED) || this;
}
return UpgradeRequiredException;
}(HttpException));
/**
* 428 Precondition Required Exception
*/
var PreconditionRequiredException = /** @class */ (function (_super) {
__extends(PreconditionRequiredException, _super);
function PreconditionRequiredException(message, error) {
if (error === void 0) { error = exports.HttpResponseMessage.PRECONDITION_REQUIRED; }
return _super.call(this, HttpException.createBody(message, error, exports.HttpResponseCode.PRECONDITION_REQUIRED), exports.HttpResponseCode.PRECONDITION_REQUIRED) || this;
}
return PreconditionRequiredException;
}(HttpException));
/**
* 429 Too Many Requests Exception
*/
var TooManyRequestsException = /** @class */ (function (_super) {
__extends(TooManyRequestsException, _super);
function TooManyRequestsException(message, error) {
if (error === void 0) { error = exports.HttpResponseMessage.TOO_MANY_REQUESTS; }
return _super.call(this, HttpException.createBody(message, error, exports.HttpResponseCode.TOO_MANY_REQUESTS), exports.HttpResponseCode.TOO_MANY_REQUESTS) || this;
}
return TooManyRequestsException;
}(HttpException));
/**
* 431 Request Header Fields Too Large Exception
*/
var RequestHeaderFieldsTooLargeException = /** @class */ (function (_super) {
__extends(RequestHeaderFieldsTooLargeException, _super);
function RequestHeaderFieldsTooLargeException(message, error) {
if (error === void 0) { error = exports.HttpResponseMessage.REQUEST_HEADER_FIELDS_TOO_LARGE; }
return _super.call(this, HttpException.createBody(message, error, exports.HttpResponseCode.REQUEST_HEADER_FIELDS_TOO_LARGE), exports.HttpResponseCode.REQUEST_HEADER_FIELDS_TOO_LARGE) || this;
}
return RequestHeaderFieldsTooLargeException;
}(HttpException));
/**
* 451 Unavailable For Legal Reasons Exception
*/
var UnavailableForLegalReasonsException = /** @class */ (function (_super) {
__extends(UnavailableForLegalReasonsException, _super);
function UnavailableForLegalReasonsException(message, error) {
if (error === void 0) { error = exports.HttpResponseMessage.UNAVAILABLE_FOR_LEGAL_REASONS; }
return _super.call(this, HttpException.createBody(message, error, exports.HttpResponseCode.UNAVAILABLE_FOR_LEGAL_REASONS), exports.HttpResponseCode.UNAVAILABLE_FOR_LEGAL_REASONS) || this;
}
return UnavailableForLegalReasonsException;
}(HttpException));
/**
* 500 Internal Server Error Exception
*/
var InternalServerErrorException = /** @class */ (function (_super) {
__extends(InternalServerErrorException, _super);
function InternalServerErrorException(message, error) {
if (error === void 0) { error = exports.HttpResponseMessage.INTERNAL_SERVER_ERROR; }
return _super.call(this, HttpException.createBody(message, error, exports.HttpResponseCode.INTERNAL_SERVER_ERROR), exports.HttpResponseCode.INTERNAL_SERVER_ERROR) || this;
}
return InternalServerErrorException;
}(HttpException));
/**
* 501 Not Implemented Exception
*/
var NotImplementedException = /** @class */ (function (_super) {
__extends(NotImplementedException, _super);
function NotImplementedException(message, error) {
if (error === void 0) { error = exports.HttpResponseMessage.NOT_IMPLEMENTED; }
return _super.call(this, HttpException.createBody(message, error, exports.HttpResponseCode.NOT_IMPLEMENTED), exports.HttpResponseCode.NOT_IMPLEMENTED) || this;
}
return NotImplementedException;
}(HttpException));
/**
* 502 Bad Gateway Exception
*/
var BadGatewayException = /** @class */ (function (_super) {
__extends(BadGatewayException, _super);
function BadGatewayException(message, error) {
if (error === void 0) { error = exports.HttpResponseMessage.BAD_GATEWAY; }
return _super.call(this, HttpException.createBody(message, error, exports.HttpResponseCode.BAD_GATEWAY), exports.HttpResponseCode.BAD_GATEWAY) || this;
}
return BadGatewayException;
}(HttpException));
/**
* 503 Service Unavailable Exception
*/
var ServiceUnavailableException = /** @class */ (function (_super) {
__extends(ServiceUnavailableException, _super);
function ServiceUnavailableException(message, error) {
if (error === void 0) { error = exports.HttpResponseMessage.SERVICE_UNAVAILABLE; }
return _super.call(this, HttpException.createBody(message, error, exports.HttpResponseCode.SERVICE_UNAVAILABLE), exports.HttpResponseCode.SERVICE_UNAVAILABLE) || this;
}
return ServiceUnavailableException;
}(HttpException));
/**
* 504 Gateway Timeout Exception
*/
var GatewayTimeoutException = /** @class */ (function (_super) {
__extends(GatewayTimeoutException, _super);
function GatewayTimeoutException(message, error) {
if (error === void 0) { error = exports.HttpResponseMessage.GATEWAY_TIMEOUT; }
return _super.call(this, HttpException.createBody(message, error, exports.HttpResponseCode.GATEWAY_TIMEOUT), exports.HttpResponseCode.GATEWAY_TIMEOUT) || this;
}
return GatewayTimeoutException;
}(HttpException));
/**
* 505 HTTP Version Not Supported Exception
*/
var HTTPVersionNotSupportedException = /** @class */ (function (_super) {
__extends(HTTPVersionNotSupportedException, _super);
function HTTPVersionNotSupportedException(message, error) {
if (error === void 0) { error = exports.HttpResponseMessage.HTTP_VERSION_NOT_SUPPORTED; }
return _super.call(this, HttpException.createBody(message, error, exports.HttpResponseCode.HTTP_VERSION_NOT_SUPPORTED), exports.HttpResponseCode.HTTP_VERSION_NOT_SUPPORTED) || this;
}
return HTTPVersionNotSupportedException;
}(HttpException));
/**
* 506 Variant Also Negotiates Exception
*/
var VariantAlsoNegotiatesException = /** @class */ (function (_super) {
__extends(VariantAlsoNegotiatesException, _super);
function VariantAlsoNegotiatesException(message, error) {
if (error === void 0) { error = exports.HttpResponseMessage.VARIANT_ALSO_NEGOTIATES; }
return _super.call(this, HttpException.createBody(message, error, exports.HttpResponseCode.VARIANT_ALSO_NEGOTIATES), exports.HttpResponseCode.VARIANT_ALSO_NEGOTIATES) || this;
}
return VariantAlsoNegotiatesException;
}(HttpException));
/**
* 507 Insufficient Storage Exception
*/
var InsufficientStorageException = /** @class */ (function (_super) {
__extends(InsufficientStorageException, _super);
function InsufficientStorageException(message, error) {
if (error === void 0) { error = exports.HttpResponseMessage.INSUFFICIENT_STORAGE; }
return _super.call(this, HttpException.createBody(message, error, exports.HttpResponseCode.INSUFFICIENT_STORAGE), exports.HttpResponseCode.INSUFFICIENT_STORAGE) || this;
}
return InsufficientStorageException;
}(HttpException));
/**
* 508 Loop Detected Exception
*/
var LoopDetectedException = /** @class */ (function (_super) {
__extends(LoopDetectedException, _super);
function LoopDetectedException(message, error) {
if (error === void 0) { error = exports.HttpResponseMessage.LOOP_DETECTED; }
return _super.call(this, HttpException.createBody(message, error, exports.HttpResponseCode.LOOP_DETECTED), exports.HttpResponseCode.LOOP_DETECTED) || this;
}
return LoopDetectedException;
}(HttpException));
/**
* 511 Network Authentication Required Exception
*/
var NetworkAuthenticationRequiredException = /** @class */ (function (_super) {
__extends(NetworkAuthenticationRequiredException, _super);
function NetworkAuthenticationRequiredException(message, error) {
if (error === void 0) { error = exports.HttpResponseMessage.NETWORK_AUTHENTICATION_REQUIRED; }
return _super.call(this, HttpException.createBody(message, error, exports.HttpResponseCode.NETWORK_AUTHENTICATION_REQUIRED), exports.HttpResponseCode.NETWORK_AUTHENTICATION_REQUIRED) || this;
}
return NetworkAuthenticationRequiredException;
}(HttpException));
var MockRequest = /** @class */ (function (_super) {
__extends(MockRequest, _super);
function MockRequest(mock, body, routeParams) {
var _this = _super.call(this, new net.Socket(), routeParams) || this;
_this.headers = mock.headers;
_this.method = mock.method;
_this.url = mock.url;
if (body) {
_this.push(body);
_this.push(null);
}
_this.cookieParams = _this.parseCookieParams();
_this.queryParams = _this.parseQueryParams();
return _this;
}
return MockRequest;
}(HttpRequest));
var MockResponse = /** @class */ (function (_super) {
__extends(MockResponse, _super);
function MockResponse(req, mock) {
var _this = _super.call(this, req) || this;
_this.statusCode = mock ? mock.statusCode : exports.HttpResponseCode.OK;
_this.statusMessage = mock ? mock.statusMessage : exports.HttpResponseMessage.OK;
return _this;
// this.writableFinished = mock ? mock.writableFinished : true
}
return MockResponse;
}(HttpResponse));
var mockReq = function (data, params) {
var _a;
return new MockRequest({
complete: true,
connection: new net.Socket(),
headers: (_a = {},
_a[exports.HttpRequestHeader.COOKIE.toLowerCase()] = 'test=testValue; test2=testValue2',
_a[exports.HttpRequestHeader.X_FORWARDED_FOR.toLowerCase()] = '8.8.8.8',
_a.test = 'testValue',
_a.test2 = 'testValue2',
_a),
httpVersion: '1.1',
httpVersionMajor: 1,
httpVersionMinor: 1,
method: 'GET',
url: '/test?test=testValue&test2=testValue2',
}, JSON.stringify(data), params);
};
var mockReqYaml = function (data, params) {
var _a;
return new MockRequest({
complete: true,
connection: new net.Socket(),
headers: (_a = {},
_a[exports.HttpRequestHeader.COOKIE.toLowerCase()] = 'test=testValue; test2=testValue2',
_a[exports.HttpRequestHeader.X_FORWARDED_FOR.toLowerCase()] = '8.8.8.8',
_a.test = 'testValue',
_a.test2 = 'testValue2',
_a),
httpVersion: '1.1',
httpVersionMajor: 1,
httpVersionMinor: 1,
method: 'GET',
url: '/test?test=testValue&test2=testValue2',
}, YAML.stringify(data), params);
};
var mockRes = function (data) { return new MockResponse(mockReq(data)); };
exports.BadGatewayException = BadGatewayException;
exports.Body = Body;
exports.ConflictException = ConflictException;
exports.Cookie = Cookie;
exports.ExpectationFailedException = ExpectationFailedException;
exports.ForbiddenException = ForbiddenException;
exports.GatewayTimeoutException = GatewayTimeoutException;
exports.GoneException = GoneException;
exports.HTTPVersionNotSupportedException = HTTPVersionNotSupportedException;
exports.Header = Header;
exports.Http2Request = Http2Request;
exports.Http2Response = Http2Response;
exports.HttpException = HttpException;
exports.HttpRequest = HttpRequest;
exports.HttpResponse = HttpResponse;
exports.ImateapotException = ImateapotException;
exports.InsufficientStorageException = InsufficientStorageException;
exports.InternalServerErrorException = InternalServerErrorException;
exports.Ip = Ip;
exports.LengthRequiredException = LengthRequiredException;
exports.LoopDetectedException = LoopDetectedException;
exports.MethodNotAllowedException = MethodNotAllowedException;
exports.MockRequest = MockRequest;
exports.MockResponse = MockResponse;
exports.NetworkAuthenticationRequiredException = NetworkAuthenticationRequiredException;
exports.NotAcceptableException = NotAcceptableException;
exports.NotFoundException = NotFoundException;
exports.NotImplementedException = NotImplementedException;
exports.Param = Param;
exports.PayloadTooLargeException = PayloadTooLargeException;
exports.PaymentRequiredException = PaymentRequiredException;
exports.PreconditionFailedException = PreconditionFailedException;
exports.PreconditionRequiredException = PreconditionRequiredException;
exports.ProxyAuthenticationRequiredException = ProxyAuthenticationRequiredException;
exports.Query = Query;
exports.RangeNotSatisfiableException = RangeNotSatisfiableException;
exports.Req = Req;
exports.RequestHeaderFieldsTooLargeException = RequestHeaderFieldsTooLargeException;
exports.RequestTimeoutException = RequestTimeoutException;
exports.Res = Res;
exports.RespondWith = RespondWith;
exports.RespondWithJson = RespondWithJson;
exports.RespondWithRaw = RespondWithRaw;
exports.RespondWithYaml = RespondWithYaml;
exports.ServiceUnavailableException = ServiceUnavailableException;
exports.TooEarlyException = TooEarlyException;
exports.TooManyRequestsException = TooManyRequestsException;
exports.URITooLongException = URITooLongException;
exports.UnauthorizedException = UnauthorizedException;
exports.UnavailableForLegalReasonsException = UnavailableForLegalReasonsException;
exports.UnprocessableEntityException = UnprocessableEntityException;
exports.UnsupportedMediaTypeException = UnsupportedMediaTypeException;
exports.UpgradeRequiredException = UpgradeRequiredException;
exports.VariantAlsoNegotiatesException = VariantAlsoNegotiatesException;
exports.methodArgumentsDescriptor = methodArgumentsDescriptor;
exports.mockReq = mockReq;
exports.mockReqYaml = mockReqYaml;
exports.mockRes = mockRes;
|
#!/usr/bin/env python2.7
# -*- coding:UTF-8 -*-2
u"""various.py
Copyright (c) 2019 Yukio Kuro
This software is released under BSD license.
様々な設定モジュール。
"""
import inventory as __inventory
import utils.const as _const
class General(__inventory.Inventory):
u"""汎用パラメータ管理。
"""
__slots__ = ()
__PLAYER_SLOT = 0
# ---- Getter ----
@classmethod
def get_player(cls):
u"""現在プレイヤー取得。
"""
return cls._general.get(cls.__PLAYER_SLOT)
@classmethod
def get_learnable(cls):
u"""プレイヤーが取得可能なスキル番号取得。
"""
return cls._players[cls.get_player()].learnable
@classmethod
def get_difficulty(cls):
u"""ゲーム難易度取得。
"""
return cls._general.get(cls._DIFFICULTY_SLOT)
@classmethod
def get_speed(cls):
u"""カーソル移動速度取得。
"""
return cls._general.get(cls._SPEED_SLOT)
@classmethod
def get_value(cls):
u"""数値取得。
"""
return sum(cls._general.raw)
# ---- Setter ----
@classmethod
def set_player(cls, value):
u"""現在プレイヤー設定。
"""
cls._general.set(cls.__PLAYER_SLOT, (
0 if value < 0 else value if value < _const.PLEYERS-1 else
_const.PLEYERS-1))
@classmethod
def set_difficulty(cls, value):
u"""ゲーム難易度設定。
"""
return cls._general.set(cls._DIFFICULTY_SLOT, value)
@classmethod
def set_speed(cls, value):
u"""カーソル移動速度設定。
"""
cls._general.set(cls._SPEED_SLOT, value)
class Level(__inventory.Inventory):
u"""レベル管理。
"""
__slots__ = ()
# ---- Getter ----
@classmethod
def has(cls, slot):
u"""位置slotのクリア状態取得。
"""
return cls._level.has(slot)
@classmethod
def get_wins(cls):
u"""デュエルモード勝利数数取得。
"""
return cls._level.bits
# ---- Setter ----
@classmethod
def on(cls, slot):
u"""位置slotのクリア状態設定。
"""
cls._level.on(slot)
class Endless(__inventory.Inventory):
u"""エンドレス管理。
"""
__PROGRESS_SLOT = 0
__REACHED_SLOT = 1
# ---- Detection ----
@classmethod
def is_cleared(cls):
u"""クリア判定。
"""
return _const.ENDLESS_LIMIT <= cls.get_reached()
# ---- Getter ----
@classmethod
def get_progress(cls):
u"""進行状態取得。
"""
return cls._endless.get(cls.__PROGRESS_SLOT)
@classmethod
def get_reached(cls):
u"""到達地点取得。
"""
return cls._endless.get(cls.__REACHED_SLOT)
# ---- Setter ----
@classmethod
def set_progress(cls, value):
u"""進行状態設定。
"""
cls._endless.set(cls.__PROGRESS_SLOT, (
0 if value < 0 else value if value < _const.ENDLESS_LIMIT else
_const.ENDLESS_LIMIT))
@classmethod
def set_reached(cls, value):
u"""到達地点設定。
"""
value = (
0 if value < 0 else value if value < _const.ENDLESS_LIMIT else
_const.ENDLESS_LIMIT)
if cls.get_reached() < value:
cls._endless.set(cls.__REACHED_SLOT, value)
|
module.exports = createTask
var fs = require('fs')
, createConfigury = require('configury')
, pick = require('lodash.pick')
function createTask (pliers) {
pliers('createBrowserConfig', function (done) {
var config = createConfigury(__dirname + '/../../config.json')(process.env.NODE_ENV)
, configWhitelist = JSON.parse(fs.readFileSync(__dirname + '/../source/config-whitelist.json', 'utf8'))
, json = JSON.stringify(pick(config, configWhitelist), null, 2)
fs.writeFileSync(__dirname + '/../source/config.json', json)
pliers.logger.trace('site config', json)
done()
})
}
|
var portal = require('/lib/xp/portal');
var thymeleaf = __non_webpack_require__('/lib/thymeleaf');
var view = resolve('first.html');
var handleRequest = function (req) {
var content = portal.getContent();
return {
postProcess: true,
body: thymeleaf.render(view, {
mainRegion: content.page.regions.main,
title: "Public page with " + req.method
})
}
};
exports.get = handleRequest;
exports.post = handleRequest;
|
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("moment"),require("fullcalendar")):"function"==typeof define&&define.amd?define(["moment","fullcalendar"],t):"object"==typeof exports?t(require("moment"),require("fullcalendar")):t(e.moment,e.FullCalendar)}("undefined"!=typeof self?self:this,function(o,n){return a={},r.m=i={0:function(e,t){e.exports=o},1:function(e,t){e.exports=n},151:function(e,t,o){Object.defineProperty(t,"__esModule",{value:!0}),o(152);var n=o(1);n.datepickerLocale("it","it",{closeText:"Chiudi",prevText:"<Prec",nextText:"Succ>",currentText:"Oggi",monthNames:["Gennaio","Febbraio","Marzo","Aprile","Maggio","Giugno","Luglio","Agosto","Settembre","Ottobre","Novembre","Dicembre"],monthNamesShort:["Gen","Feb","Mar","Apr","Mag","Giu","Lug","Ago","Set","Ott","Nov","Dic"],dayNames:["Domenica","Lunedì","Martedì","Mercoledì","Giovedì","Venerdì","Sabato"],dayNamesShort:["Dom","Lun","Mar","Mer","Gio","Ven","Sab"],dayNamesMin:["Do","Lu","Ma","Me","Gi","Ve","Sa"],weekHeader:"Sm",dateFormat:"dd/mm/yy",firstDay:1,isRTL:!1,showMonthAfterYear:!1,yearSuffix:""}),n.locale("it",{buttonText:{month:"Mese",week:"Settimana",day:"Giorno",list:"Agenda"},allDayHtml:"Tutto il<br/>giorno",eventLimitText:function(e){return"+altri "+e},noEventsMessage:"Non ci sono eventi da visualizzare"})},152:function(e,t,o){o(0).defineLocale("it",{months:"gennaio_febbraio_marzo_aprile_maggio_giugno_luglio_agosto_settembre_ottobre_novembre_dicembre".split("_"),monthsShort:"gen_feb_mar_apr_mag_giu_lug_ago_set_ott_nov_dic".split("_"),weekdays:"domenica_lunedì_martedì_mercoledì_giovedì_venerdì_sabato".split("_"),weekdaysShort:"dom_lun_mar_mer_gio_ven_sab".split("_"),weekdaysMin:"do_lu_ma_me_gi_ve_sa".split("_"),longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd D MMMM YYYY HH:mm"},calendar:{sameDay:function(){return"[Oggi a"+(1<this.hours()?"lle ":0===this.hours()?" ":"ll'")+"]LT"},nextDay:function(){return"[Domani a"+(1<this.hours()?"lle ":0===this.hours()?" ":"ll'")+"]LT"},nextWeek:function(){return"dddd [a"+(1<this.hours()?"lle ":0===this.hours()?" ":"ll'")+"]LT"},lastDay:function(){return"[Ieri a"+(1<this.hours()?"lle ":0===this.hours()?" ":"ll'")+"]LT"},lastWeek:function(){switch(this.day()){case 0:return"[La scorsa] dddd [a"+(1<this.hours()?"lle ":0===this.hours()?" ":"ll'")+"]LT";default:return"[Lo scorso] dddd [a"+(1<this.hours()?"lle ":0===this.hours()?" ":"ll'")+"]LT"}},sameElse:"L"},relativeTime:{future:function(e){return(/^[0-9].+$/.test(e)?"tra":"in")+" "+e},past:"%s fa",s:"alcuni secondi",ss:"%d secondi",m:"un minuto",mm:"%d minuti",h:"un'ora",hh:"%d ore",d:"un giorno",dd:"%d giorni",M:"un mese",MM:"%d mesi",y:"un anno",yy:"%d anni"},dayOfMonthOrdinalParse:/\d{1,2}º/,ordinal:"%dº",week:{dow:1,doy:4}})}},r.c=a,r.d=function(e,t,o){r.o(e,t)||Object.defineProperty(e,t,{configurable:!1,enumerable:!0,get:o})},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="",r(r.s=151);function r(e){if(a[e])return a[e].exports;var t=a[e]={i:e,l:!1,exports:{}};return i[e].call(t.exports,t,t.exports,r),t.l=!0,t.exports}var i,a});
|
import re
import sqlite3
import json, pickle
import unicodecsv as csv
import pandas as pd
import numpy as np
import util
from util import chinese_to_arabic
CNETER_LATITUDE = 31.2304
CNETER_LONGTITUDE = 121.4737
RADIOUS_EARTH = 1
con = sqlite3.connect("data/lianjia/lianjia.db")
cur = con.execute("select * from house_detail")
col_name_list = [tmp[0] for tmp in cur.description]
# process floor text
def get_floor_float(floor):
if floor[7].isdigit():
overall = int(floor[6:8])
else:
overall = int(floor[6])
if floor[0] == '低':
return 0
elif floor[0] == '中':
return overall * 0.5
else:
return overall
# unit funciton to process Chinese number
def get_int_from_CH(chstr):
CH_letter = ['一','二','三','四','五','六','七','八','九','十']
res = CH_letter.index(chstr)+1 if chstr != '百' else 100
return res
# process elevator rate text
def get_elevator_rate(chstr):
# use function form util.py
num = chinese_to_arabic(chstr[0])
all_int = chinese_to_arabic(chstr[2:-1])
return num / all_int
# count value scale for every attribute
col_content = {}
for key in col_name_list:
col_content[key] = []
# discrete attribute
dis_val_list = [
'community',
'district',
'location',
'huxing',
'floor',
'huxing_type',
'face_to',
'building_structure',
'building_type',
'decoration',
'elevator_rate',
'elevator',
'elevator',
# 'roperty_year',
'trade_type',
'house_usage',
# 'limit_year',
'property_belong',
'mortgage',
]
refresh = False
refresh2 = True
# count value scale for every attribute and save it
if refresh:
j = 0
for line in cur:
if j % 10000 == 0:
print(j)
j += 1
for i in range(28):
if col_name_list[i] in dis_val_list:
feature = col_name_list[i]
if line[i] not in col_content[feature]:
col_content[feature].append(line[i])
with open("data/dis_scale", 'wb') as f:
pickle.dump(col_content, f)
else:
with open('data/dis_scale', 'rb') as f:
col_content = pickle.load(f)
# station dataFram
df_station = pd.read_csv("data/metros_geo_ok.csv")
np_sta_latb = df_station['LATB'].values
np_sta_lngb = df_station['LNGB'].values
# selected attributes
target_cloumns = col_name_list + [
'dist_sta','dist_cent', 'latitude', 'longitude',
'huxing_shi', 'huxing_ting','huxing_chu','huxing_wei',
'floor_float', 'building_area_float',
'face_N','face_S','face_E','face_W',
'elevator_01', 'elevator_rate_float',
]
# Data process
if refresh2:
with open("data/csv/integral_data.csv", 'wb') as f:
# wrong data file
f_excp = open('data/csv/except_data.csv', 'wb')
excp_csv_file = csv.writer(f_excp)
excp_csv_file.writerow(target_cloumns)
# normal data file
csv_file = csv.writer(f)
cur = con.execute("select * from house_detail")
csv_file.writerow(target_cloumns)
num = 0
for line in cur:
line = list(line)
tmp_dict = dict(zip(col_name_list, line))
if num % 10000 == 0:
print(num)
num += 1
# judge attributed whether correct
if tmp_dict['building_structure'] in ['暂无数据']:
excp_csv_file.writerow(line)
continue
elif tmp_dict['building_type'] in ['暂无数据']:
excp_csv_file.writerow(line)
continue
elif tmp_dict['decoration'] not in ['精装','简装','毛坯','其他']:
excp_csv_file.writerow(line)
continue
elif tmp_dict['district'] is None:
excp_csv_file.writerow(line)
continue
elif tmp_dict['elevator'] not in ['有', '无']:
excp_csv_file.writerow(line)
continue
elif tmp_dict['elevator_rate'] in [None, '暂无数据']:
excp_csv_file.writerow(line)
continue
elif tmp_dict['face_to'] in ['毛坯','其他','精装','简装','暂无数据']:
excp_csv_file.writerow(line)
continue
elif tmp_dict['house_usage'] in ['暂无数据']:
excp_csv_file.writerow(line)
continue
elif tmp_dict['huxing_type'] not in ['平层','跃层','复式','错层',]:
excp_csv_file.writerow(line)
continue
elif tmp_dict['location'] is None:
excp_csv_file.writerow(line)
continue
elif tmp_dict['mortgage'] in ['暂无数据']:
excp_csv_file.writerow(line)
continue
elif tmp_dict['property_belong'] in ['暂无数据']:
excp_csv_file.writerow(line)
continue
else:
# process attribute to target form
url_comm = line[4]
latitude, longitude = con.execute("select longitude,latitude from community where url == '%s'"%url_comm).fetchall()[0]
dist_sat = np.min(np.abs(np_sta_latb - latitude) + np.abs(np_sta_lngb - longitude) ) * RADIOUS_EARTH
dist_cent = (abs(latitude - CNETER_LATITUDE) + abs(longitude - CNETER_LONGTITUDE) ) * RADIOUS_EARTH
hux_list = re.split('室|厅|厨|卫' , tmp_dict['huxing'])
huxing_1 = int(hux_list[0])
huxing_2 = int(hux_list[1])
huxing_3 = int(hux_list[2])
huxing_4 = int(hux_list[3])
floor_float = get_floor_float(tmp_dict['floor'])
building_area_float = float(tmp_dict['building_area'][:-1])
face_S = 1 if '南' in tmp_dict['face_to'] else 0
face_N = 1 if '北' in tmp_dict['face_to'] else 0
face_E = 1 if '东' in tmp_dict['face_to'] else 0
face_W = 1 if '西' in tmp_dict['face_to'] else 0
elevator_01 = 1 if tmp_dict['elevator'] == '有' else 0
elevator_rate = get_elevator_rate(tmp_dict['elevator_rate'])
# wirte to normal file
csv_file.writerow(line + [dist_sat, dist_cent, latitude, longitude, huxing_1, huxing_2, \
huxing_3, huxing_4, floor_float, building_area_float, face_N, face_S, \
face_E, face_W, elevator_01, elevator_rate ])
f_excp.close()
df_middle = pd.read_csv("data/csv/integral_data.csv")
df_excp = pd.read_csv("data/csv/except_data.csv")
con.close()
|
import argparse
import json
import os
import sys
from . import config, constants, update
from .config.printjson import getjson
from .messages import *
def main():
# Hack around argparse's lack of optional subparsers
if len(sys.argv) == 1:
sys.argv.append("spec")
try:
with open(config.scriptPath("..", "semver.txt")) as fh:
semver = fh.read().strip()
semverText = f"Bikeshed v{semver}: "
except FileNotFoundError:
semver = "???"
semverText = ""
argparser = argparse.ArgumentParser(
description=f"{semverText}Processes spec source files into valid HTML."
)
argparser.add_argument("--version", action="version", version=semver)
argparser.add_argument(
"-q",
"--quiet",
dest="quiet",
action="count",
default=0,
help="Silences one level of message, least-important first.",
)
argparser.add_argument(
"-s",
"--silent",
dest="silent",
action="store_true",
help="Shorthand for 'as many -q as you need to shut it up'",
)
argparser.add_argument(
"-f",
"--force",
dest="errorLevel",
action="store_const",
const="nothing",
help="Force the preprocessor to run to completion; fatal errors don't stop processing.",
)
argparser.add_argument(
"-d",
"--dry-run",
dest="dryRun",
action="store_true",
help="Prevents the processor from actually saving anything to disk, but otherwise fully runs.",
)
argparser.add_argument(
"-a",
"--ascii-only",
dest="asciiOnly",
action="store_true",
help="Force all Bikeshed messages to be ASCII-only.",
)
argparser.add_argument(
"--print",
dest="printMode",
action="store",
default=None,
help="Print mode. Options are 'plain' (just text), 'console' (colored with console color codes), 'markup', and 'json'. Defaults to 'console'.",
)
argparser.add_argument(
"--die-on",
dest="errorLevel",
choices=["nothing", "fatal", "link-error", "warning", "everything"],
help="Determines what sorts of errors cause Bikeshed to die (quit immediately with an error status code). Default is 'fatal'; the -f flag is a shorthand for 'nothing'",
)
argparser.add_argument(
"--allow-nonlocal-files",
dest="allowNonlocalFiles",
action="store_true",
help="Allows Bikeshed to see/include files from folders higher than the one your source document is in.",
)
argparser.add_argument(
"--allow-execute",
dest="allowExecute",
action="store_true",
help="Allow some features to execute arbitrary code from outside the Bikeshed codebase.",
)
subparsers = argparser.add_subparsers(title="Subcommands", dest="subparserName")
specParser = subparsers.add_parser(
"spec", help="Process a spec source file into a valid output file."
)
specParser.add_argument(
"infile", nargs="?", default=None, help="Path to the source file."
)
specParser.add_argument(
"outfile", nargs="?", default=None, help="Path to the output file."
)
specParser.add_argument(
"--debug",
dest="debug",
action="store_true",
help="Switches on some debugging tools. Don't use for production!",
)
specParser.add_argument(
"--gh-token",
dest="ghToken",
nargs="?",
help="GitHub access token. Useful to avoid API rate limits. Generate tokens: https://github.com/settings/tokens.",
)
specParser.add_argument(
"--byos",
dest="byos",
action="store_true",
help="Bring-Your-Own-Spec: turns off all the Bikeshed auto-niceties, so you can piecemeal its features into your existing doc instead. Experimental, let me know if things get crashy or weird.",
)
specParser.add_argument(
"-l",
"--line-numbers",
dest="lineNumbers",
action="store_true",
help="Hacky support for outputting line numbers on all error messages. Disables output, as this is hacky and might mess up your source.",
)
echidnaParser = subparsers.add_parser(
"echidna",
help="Process a spec source file into a valid output file and publish it according to certain automatic protocols.",
)
echidnaParser.add_argument(
"infile", nargs="?", default=None, help="Path to the source file."
)
echidnaParser.add_argument(
"--gh-token",
dest="ghToken",
nargs="?",
help="GitHub access token. Useful to avoid API rate limits. Generate tokens: https://github.com/settings/tokens.",
)
echidnaParser.add_argument(
"--u", dest="un", metavar="USERNAME", required=False, help="W3C username."
)
echidnaParser.add_argument(
"--p", dest="pw", metavar="PASSWORD", required=False, help="W3C password."
)
echidnaParser.add_argument(
"--decision",
dest="decision",
metavar="DECISION_URL",
required=False,
help="URL recording the decision to publish.",
)
echidnaParser.add_argument(
"--editorial",
dest="editorial",
action="store_true",
required=False,
help="Flags update as editorial.",
)
echidnaParser.add_argument(
"--cc",
dest="cc",
metavar="EMAIL",
required=False,
help="Comma-separated list of email addresses to ping with the publication status when complete.",
)
echidnaParser.add_argument(
"--additional-directories",
dest="additionalDirectories",
required=False,
nargs="*",
help="Directories to bundle in the tar file. Defaults to examples/, diagrams/, and images/.",
)
echidnaParser.add_argument(
"--self-contained",
dest="selfContained",
action="store_true",
help="The spec is self-contained, do not bundle any extra directories in the tar file.",
)
echidnaParser.add_argument("--just-tar", dest="justTar", action="store_true")
watchParser = subparsers.add_parser(
"watch",
help="Process a spec source file into a valid output file, automatically rebuilding when it changes.",
)
watchParser.add_argument(
"infile", nargs="?", default=None, help="Path to the source file."
)
watchParser.add_argument(
"outfile", nargs="?", default=None, help="Path to the output file."
)
watchParser.add_argument(
"--gh-token",
dest="ghToken",
nargs="?",
help="GitHub access token. Useful to avoid API rate limits. Generate tokens: https://github.com/settings/tokens.",
)
watchParser.add_argument(
"--byos",
dest="byos",
action="store_true",
help="Bring-Your-Own-Spec: turns off all the Bikeshed auto-niceties, so you can piecemeal its features into your existing doc instead. Experimental, let me know if things get crashy or weird.",
)
serveParser = subparsers.add_parser(
"serve", help="Identical to 'watch', but also serves the folder on localhost."
)
serveParser.add_argument(
"infile", nargs="?", default=None, help="Path to the source file."
)
serveParser.add_argument(
"outfile", nargs="?", default=None, help="Path to the output file."
)
serveParser.add_argument(
"--port",
dest="port",
nargs="?",
default="8000",
help="Specify the port to serve it over.",
)
serveParser.add_argument(
"--localhost",
dest="localhost",
action="store_true",
help="Only allow connections from localhost.",
)
serveParser.add_argument(
"--gh-token",
dest="ghToken",
nargs="?",
help="GitHub access token. Useful to avoid API rate limits. Generate tokens: https://github.com/settings/tokens.",
)
serveParser.add_argument(
"--byos",
dest="byos",
action="store_true",
help="Bring-Your-Own-Spec: turns off all the Bikeshed auto-niceties, so you can piecemeal its features into your existing doc instead. Experimental, let me know if things get crashy or weird.",
)
updateParser = subparsers.add_parser(
"update",
help="Update supporting files (those in /spec-data).",
epilog="If no options are specified, everything is downloaded.",
)
updateParser.add_argument(
"--skip-manifest",
dest="force",
action="store_true",
help="Forces Bikeshed to do a full update manually, rather than using the manifest to get the preprocessed update (which can be several minutes old).",
)
updateParser.add_argument(
"--anchors", action="store_true", help="Download crossref anchor data."
)
updateParser.add_argument(
"--backrefs", action="store_true", help="Download link backref data."
)
updateParser.add_argument(
"--biblio", action="store_true", help="Download biblio data."
)
updateParser.add_argument(
"--caniuse", action="store_true", help="Download Can I Use... data."
)
updateParser.add_argument(
"--mdn", action="store_true", help="Download MDN Spec Links... data."
)
updateParser.add_argument(
"--link-defaults",
dest="linkDefaults",
action="store_true",
help="Download link default data.",
)
updateParser.add_argument(
"--test-suites",
dest="testSuites",
action="store_true",
help="Download test suite data.",
)
updateParser.add_argument(
"--languages",
dest="languages",
action="store_true",
help="Download language/translation data.",
)
updateParser.add_argument(
"--wpt",
dest="wpt",
action="store_true",
help="Download web-platform-tests data.",
)
issueParser = subparsers.add_parser(
"issues-list",
help="Process a plain-text issues file into HTML. Call with no args to see an example input text.",
)
issueParser.add_argument(
"-t",
dest="printTemplate",
action="store_true",
help="Output example Issues List template.",
)
issueParser.add_argument(
"infile", nargs="?", default=None, help="Path to the plain-text issue file."
)
issueParser.add_argument(
"outfile",
nargs="?",
default=None,
help="Path to the output file. Default is file of the same name as input, with .html.",
)
debugParser = subparsers.add_parser("debug", help="Run various debugging commands.")
debugParser.add_argument(
"infile", nargs="?", default=None, help="Path to the source file."
)
debugCommands = debugParser.add_mutually_exclusive_group(required=True)
debugCommands.add_argument(
"--print-exports",
dest="printExports",
action="store_true",
help="Prints those terms that will be exported for cross-ref purposes.",
)
debugCommands.add_argument(
"--print-refs-for",
dest="linkText",
help="Prints the ref data for a given link text.",
)
debugCommands.add_argument(
"--print", dest="code", help="Runs the specified code and prints it."
)
debugCommands.add_argument(
"--print-json",
dest="jsonCode",
help="Runs the specified code and prints it as formatted JSON.",
)
debugCommands.add_argument(
"--refresh-data",
dest="refreshData",
action="store_true",
help="Clobbers the readonly data files with the mutable ones.",
)
refParser = subparsers.add_parser("refs", help="Search Bikeshed's ref database.")
refParser.add_argument(
"infile", nargs="?", default=None, help="Path to the source file."
)
refParser.add_argument("--text", dest="text", default=None)
refParser.add_argument("--type", dest="linkType", default=None)
refParser.add_argument("--for", dest="linkFor", default=None)
refParser.add_argument("--spec", dest="spec", default=None)
refParser.add_argument("--status", dest="status", default=None)
refParser.add_argument(
"--exact",
dest="exact",
action="store_true",
help="Only search for the exact text provided; don't apply Bikeshed's automatic conjugation help for plurals/etc.",
)
refParser.add_argument(
"--latest-only",
dest="latestOnly",
action="store_true",
help="Apply Bikeshed's logic for only returning the latest version of a given ref when it exists in multiple levels of a spec.",
)
sourceParser = subparsers.add_parser(
"source", help="Tools for formatting the *source* document."
)
sourceParser.add_argument(
"--big-text",
dest="bigText",
action="store_true",
help="Finds HTML comments containing 'Big Text: foo' and turns them into comments containing 'foo' in big text.",
)
sourceParser.add_argument(
"infile", nargs="?", default=None, help="Path to the source file."
)
sourceParser.add_argument(
"outfile", nargs="?", default=None, help="Path to the output file."
)
testParser = subparsers.add_parser(
"test", help="Tools for running Bikeshed's testsuite."
)
testParser.add_argument(
"--rebase",
default=False,
action="store_true",
help="Rebase the specified files.",
)
testParser.add_argument(
"--manual-only",
dest="manualOnly",
default=False,
action="store_true",
help="Skip testing the real-world files in the repo, and only run the manually-written ones.",
)
testParser.add_argument(
"testFiles",
default=[],
metavar="FILE",
nargs="*",
help="Run these tests. If called with no args, tests everything.",
)
profileParser = subparsers.add_parser(
"profile",
help="Profiling Bikeshed. Needs graphviz, gprof2dot, and xdot installed.",
)
profileParser.add_argument(
"--root",
dest="root",
default=None,
metavar="ROOTFUNC",
help="Prune the graph to start with the specified root node.",
)
profileParser.add_argument(
"--leaf",
dest="leaf",
default=None,
metavar="LEAFFUNC",
help="Prune the graph to only show ancestors of the specified leaf node.",
)
profileParser.add_argument(
"--svg",
dest="svgFile",
default=None,
help="Save the graph to a specified SVG file, rather than outputting with xdot immediately.",
)
subparsers.add_parser(
"template", help="Outputs a skeleton .bs file for you to start with."
)
wptParser = subparsers.add_parser(
"wpt", help="Tools for writing Web Platform Tests."
)
wptParser.add_argument(
"--template",
default=False,
action="store_true",
help="Outputs a skeleton WPT file for you to start with.",
)
options, extras = argparser.parse_known_args()
constants.quiet = options.quiet
if options.silent:
constants.quiet = float("infinity")
constants.setErrorLevel(options.errorLevel)
constants.dryRun = options.dryRun
constants.asciiOnly = options.asciiOnly
if options.printMode is None:
if "NO_COLOR" in os.environ or os.environ.get("TERM") == "dumb":
constants.printMode = "plain"
else:
constants.printMode = "console"
else:
constants.printMode = options.printMode
constants.chroot = not options.allowNonlocalFiles
constants.executeCode = options.allowExecute
update.fixupDataFiles()
if options.subparserName == "update":
handleUpdate(options)
elif options.subparserName == "spec":
handleSpec(options, extras)
elif options.subparserName == "echidna":
handleEchidna(options, extras)
elif options.subparserName == "watch":
handleWatch(options, extras)
elif options.subparserName == "serve":
handleServe(options, extras)
elif options.subparserName == "debug":
handleDebug(options, extras)
elif options.subparserName == "refs":
handleRefs(options, extras)
elif options.subparserName == "issues-list":
handleIssuesList(options)
elif options.subparserName == "source":
handleSource(options)
elif options.subparserName == "test":
handleTest(options, extras)
elif options.subparserName == "profile":
handleProfile(options)
elif options.subparserName == "template":
handleTemplate()
elif options.subparserName == "wpt":
handleWpt(options)
def handleUpdate(options):
update.update(
anchors=options.anchors,
backrefs=options.backrefs,
biblio=options.biblio,
caniuse=options.caniuse,
mdn=options.mdn,
linkDefaults=options.linkDefaults,
testSuites=options.testSuites,
languages=options.languages,
wpt=options.wpt,
dryRun=constants.dryRun,
force=options.force,
)
def handleSpec(options, extras):
from . import metadata
from .Spec import Spec
doc = Spec(
inputFilename=options.infile,
debug=options.debug,
token=options.ghToken,
lineNumbers=options.lineNumbers,
)
doc.mdCommandLine = metadata.fromCommandLine(extras)
if options.byos:
doc.mdCommandLine.addData("Group", "byos")
doc.preprocess()
doc.finish(outputFilename=options.outfile)
def handleEchidna(options, extras):
from . import metadata, publish
from .Spec import Spec
doc = Spec(inputFilename=options.infile, token=options.ghToken)
doc.mdCommandLine = metadata.fromCommandLine(extras)
doc.mdCommandLine.addData("Prepare For TR", "yes")
doc.preprocess()
addDirs = [] if options.selfContained else options.additionalDirectories
if options.justTar:
publish.prepareTar(doc, visibleTar=True, additionalDirectories=addDirs)
else:
publish.publishEchidna(
doc,
username=options.un,
password=options.pw,
decision=options.decision,
additionalDirectories=addDirs,
cc=options.cc,
editorial=options.editorial,
)
def handleWatch(options, extras):
from . import metadata
from .Spec import Spec
# Can't have an error killing the watcher
constants.setErrorLevel("nothing")
doc = Spec(inputFilename=options.infile, token=options.ghToken)
doc.mdCommandLine = metadata.fromCommandLine(extras)
if options.byos:
doc.mdCommandLine.addData("Group", "byos")
doc.watch(outputFilename=options.outfile)
def handleServe(options, extras):
from . import metadata
from .Spec import Spec
constants.setErrorLevel("nothing")
doc = Spec(inputFilename=options.infile, token=options.ghToken)
doc.mdCommandLine = metadata.fromCommandLine(extras)
if options.byos:
doc.mdCommandLine.addData("Group", "byos")
doc.watch(outputFilename=options.outfile, port=int(options.port))
def handleDebug(options, extras):
from . import metadata
from .Spec import Spec
constants.setErrorLevel("nothing")
constants.quiet = 2
if options.printExports:
doc = Spec(inputFilename=options.infile)
doc.mdCommandLine = metadata.fromCommandLine(extras)
doc.preprocess()
doc.printTargets()
elif options.jsonCode:
doc = Spec(inputFilename=options.infile)
doc.mdCommandLine = metadata.fromCommandLine(extras)
doc.preprocess()
exec(f"print(config.printjson({options.jsonCode}))")
elif options.code:
doc = Spec(inputFilename=options.infile)
doc.mdCommandLine = metadata.fromCommandLine(extras)
doc.preprocess()
exec(f"print({options.code})")
elif options.linkText:
doc = Spec(inputFilename=options.infile)
doc.mdCommandLine = metadata.fromCommandLine(extras)
doc.preprocess()
refs = doc.refs[options.linkText] + doc.refs[options.linkText + "\n"]
constants.quiet = options.quiet
if not constants.quiet:
p(f"Refs for '{options.linkText}':")
# Get ready for JSONing
for ref in refs:
ref["level"] = str(ref["level"])
p(config.printjson(refs))
elif options.refreshData:
constants.quiet = 0
update.updateReadonlyDataFiles()
warn("Don't forget to bump the version number!")
def handleRefs(options, extras):
from . import metadata
from .refs.ReferenceManager import ReferenceManager
from .Spec import Spec
constants.setErrorLevel("nothing")
constants.quiet = 10
doc = Spec(inputFilename=options.infile)
if doc.valid:
doc.mdCommandLine = metadata.fromCommandLine(extras)
doc.preprocess()
rm = doc.refs
else:
rm = ReferenceManager()
rm.initializeRefs()
if options.text:
options.text = options.text
refs = rm.queryAllRefs(
text=options.text,
linkFor=options.linkFor,
linkType=options.linkType,
status=options.status,
spec=options.spec,
latestOnly=options.latestOnly,
exact=options.exact,
)
if constants.printMode == "json":
p(json.dumps(refs, indent=2, default=getjson))
else:
p(config.printjson(refs))
def handleIssuesList(options):
from . import issuelist
if options.printTemplate:
issuelist.printHelpMessage()
else:
issuelist.printIssueList(options.infile, options.outfile)
def handleSource(options):
if not options.bigText: # If no options are given, do all options.
options.bigText = True
if options.bigText:
from . import fonts
font = fonts.Font()
fonts.replaceComments(
font=font, inputFilename=options.infile, outputFilename=options.outfile
)
def handleTest(options, extras):
from . import metadata, test
md = metadata.fromCommandLine(extras)
constants.setErrorLevel("nothing")
constants.quiet = 100
if options.rebase:
test.rebase(options.testFiles, md=md)
else:
result = test.runAllTests(
options.testFiles, manualOnly=options.manualOnly, md=md
)
sys.exit(0 if result else 1)
def handleProfile(options):
root = f'--root="{options.root}"' if options.root else ""
leaf = f'--leaf="{options.leaf}"' if options.leaf else ""
if options.svgFile:
os.system(
"time python -m cProfile -o stat.prof -m bikeshed -f spec && gprof2dot -f pstats --skew=.0001 {root} {leaf} stat.prof | dot -Tsvg -o {svg} && rm stat.prof".format(
root=root, leaf=leaf, svg=options.svgFile
)
)
else:
os.system(
"time python -m cProfile -o /tmp/stat.prof -m bikeshed -f spec && gprof2dot -f pstats --skew=.0001 {root} {leaf} /tmp/stat.prof | xdot &".format(
root=root, leaf=leaf
)
)
def handleTemplate():
p(
"""<pre class='metadata'>
Title: Your Spec Title
Shortname: your-spec
Level: 1
Status: ED
Group: WGNAMEORWHATEVER
URL: http://example.com/url-this-spec-will-live-at
Editor: Your Name, Your Company http://example.com/your-company, your-email@example.com, http://example.com/your-personal-website
Abstract: A short description of your spec, one or two sentences.
</pre>
Introduction {#intro}
=====================
Introduction here.
"""
)
def handleWpt(options):
if options.template:
p(
"""
<!DOCTYPE html>
<meta charset=utf-8>
<title>window.offscreenBuffering</title>
<link rel=author title="AUTHOR NAME HERE" href="mailto:AUTHOR EMAIL HERE">
<link rel=help href="LINK TO ROUGHLY WHAT'S BEING TESTED HERE">
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script>
/* Choose the test type you want: */
/* Standard, synchronous test */
test(function() {
/* test code here */
}, "TEST NAME HERE / SHORT DESCRIPTION PHRASE");
/* Async test */
let t = async_test("TEST NAME HERE / SHORT DESCRIPTION PHRASE");
somethingWithACallback( function(){ t.step(()=>{ /* test code here */}) );
something.addEventListener('foo', t.step_func(()=>{ /* test code here */}));
t.done(); // when all tests are finished running
// or call the following if there's only one test, automatically does .done() for you
something.addEventListener('foo', t.step_func_done(()=>{ /* test code here */}));
/* Promise test */
promise_test(function(){
return somePromiseFunc().then(()=>{ /* test code here */ });
}, "TEST NAME HERE / SHORT DESCRIPTION PHRASE");
// auto-finishes when the returned promise fulfills
// or if promise should reject:
promise_test(function(t){
return promise_rejects(t, new ExpectedError(), somePromiseCode());
}, "TEST NAME HERE / SHORT DESCRIPTION PHRASE");
/* "test code here" Asserts */
// Only use inside of /* test code here */ regions
assert_true(VALUE HERE, "TEST DESCRIPTION");
assert_equals(ACTUAL VALUE HERE, EXPECTED VALUE HERE, "TEST DESCRIPTION");
// lots more at http://web-platform-tests.org/writing-tests/testharness-api.html#list-of-assertions
</script>
"""
)
|
import BigNumber from 'bignumber.js'
export default function formatUnit (base) {
try {
return new BigNumber(base)
.shiftedBy(-18)
.toFixed(2)
.toString()
} catch (error) {
return 'N/A'
}
}
|
/*jshint node:true*/
/*jshint camelcase:false*/
// Generated on 2015-05-02 using
// generator-distilled 0.5.1
'use strict';
// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// If you want to recursively match all subfolders, use:
// 'test/spec/**/*.js'
module.exports = function (grunt) {
// Time how long tasks take. Can help when optimizing build times
require('time-grunt')(grunt);
// Load grunt tasks automatically
require('load-grunt-tasks')(grunt);
// Configurable paths
var config = {
app: 'app',
dist: 'dist'
};
// Define the configuration for all the tasks
grunt.initConfig({
// Project settings
config: config,
// Watches files for changes and runs tasks based on the changed files
watch: {
bower: {
files: ['bower.json'],
tasks: ['wiredep']
},
js: {
files: ['<%= config.app %>/scripts/{,*/}*.js'],
tasks: ['jshint'],
options: {
livereload: '<%= connect.options.livereload %>'
}
},
jstest: {
files: ['test/spec/{,*/}*.js'],
tasks: ['test:watch']
},
gruntfile: {
files: ['Gruntfile.js']
},
sass: {
files: ['<%= config.app %>/styles/{,*/}*.{scss,sass}'],
tasks: ['sass:server', 'autoprefixer']
},
styles: {
files: ['<%= config.app %>/styles/{,*/}*.css'],
tasks: ['newer:copy:styles', 'autoprefixer']
},
livereload: {
options: {
livereload: '<%= connect.options.livereload %>'
},
files: [
'<%= config.app %>/{,*/}*.html',
'.tmp/styles/{,*/}*.css',
'<%= config.app %>/images/{,*/}*'
]
}
},
// The actual grunt server settings
connect: {
options: {
port: 9000,
open: true,
livereload: 35729,
// Change this to '0.0.0.0' to access the server from outside
hostname: 'localhost'
},
livereload: {
options: {
middleware: function(connect) {
return [
connect.static('.tmp'),
connect().use('/bower_components', connect.static('./bower_components')),
connect.static(config.app)
];
}
}
},
test: {
options: {
open: false,
port: 9001,
middleware: function(connect) {
return [
connect.static('.tmp'),
connect.static('test'),
connect().use('/bower_components', connect.static('./bower_components')),
connect.static(config.app)
];
}
}
},
dist: {
options: {
base: '<%= config.dist %>',
livereload: false
}
}
},
// Empties folders to start fresh
clean: {
dist: {
files: [{
dot: true,
src: [
'.tmp',
'<%= config.dist %>/*',
'!<%= config.dist %>/.git*'
]
}]
},
server: '.tmp'
},
// Make sure code styles are up to par and there are no obvious mistakes
jshint: {
options: {
jshintrc: '.jshintrc',
reporter: require('jshint-stylish')
},
all: [
'Gruntfile.js',
'<%= config.app %>/scripts/{,*/}*.js',
'!<%= config.app %>/scripts/vendor/*',
'test/spec/{,*/}*.js'
]
},
// Mocha testing framework configuration options
mocha: {
all: {
options: {
run: true,
urls: ['http://<%= connect.test.options.hostname %>:<%= connect.test.options.port %>/index.html']
}
}
},
// Compiles Sass to CSS and generates necessary files if requested
sass: {
options: {
sourceMap: true,
includePaths: ['bower_components']
},
dist: {
files: [{
expand: true,
cwd: '<%= config.app %>/styles',
src: ['*.{scss,sass}'],
dest: '.tmp/styles',
ext: '.css'
}]
},
server: {
files: [{
expand: true,
cwd: '<%= config.app %>/styles',
src: ['*.{scss,sass}'],
dest: '.tmp/styles',
ext: '.css'
}]
}
},
// Add vendor prefixed styles
autoprefixer: {
options: {
browsers: ['> 1%', 'last 2 versions', 'Firefox ESR', 'Opera 12.1'],
map: {
prev: '.tmp/styles/'
}
},
dist: {
files: [{
expand: true,
cwd: '.tmp/styles/',
src: '{,*/}*.css',
dest: '.tmp/styles/'
}]
}
},
// Automatically inject Bower components into the HTML file
wiredep: {
app: {
ignorePath: /^\/|\.\.\//,
src: ['<%= config.app %>/index.html'],
exclude: ['bower_components/respond/']
},
sass: {
src: ['<%= config.app %>/styles/{,*/}*.{scss,sass}'],
ignorePath: /(\.\.\/){1,2}bower_components\//
}
},
// Renames files for browser caching purposes
rev: {
dist: {
files: {
src: [
'<%= config.dist %>/scripts/{,*/}*.js',
'<%= config.dist %>/styles/{,*/}*.css',
'<%= config.dist %>/images/{,*/}*.*',
'<%= config.dist %>/styles/fonts/{,*/}*.*',
'<%= config.dist %>/*.{ico,png}'
]
}
}
},
// Reads HTML for usemin blocks to enable smart builds that automatically
// concat, minify and revision files. Creates configurations in memory so
// additional tasks can operate on them
useminPrepare: {
options: {
dest: '<%= config.dist %>'
},
html: '<%= config.app %>/index.html'
},
// Performs rewrites based on rev and the useminPrepare configuration
usemin: {
options: {
assetsDirs: [
'<%= config.dist %>',
'<%= config.dist %>/images',
'<%= config.dist %>/styles'
]
},
html: ['<%= config.dist %>/{,*/}*.html'],
css: ['<%= config.dist %>/styles/{,*/}*.css']
},
// The following *-min tasks produce minified files in the dist folder
imagemin: {
dist: {
files: [{
expand: true,
cwd: '<%= config.app %>/images',
src: '{,*/}*.{gif,jpeg,jpg,png}',
dest: '<%= config.dist %>/images'
}]
}
},
svgmin: {
dist: {
files: [{
expand: true,
cwd: '<%= config.app %>/images',
src: '{,*/}*.svg',
dest: '<%= config.dist %>/images'
}]
}
},
htmlmin: {
dist: {
options: {
collapseBooleanAttributes: true,
// collapseWhitespace: true,
// conservativeCollapse: true,
// removeAttributeQuotes: true,
removeCommentsFromCDATA: true,
// removeEmptyAttributes: true,
// removeOptionalTags: true,
// true would impact styles with attribute selectors
removeRedundantAttributes: false,
useShortDoctype: true
},
files: [{
expand: true,
cwd: '<%= config.dist %>',
src: '{,*/}*.html',
dest: '<%= config.dist %>'
}]
}
},
// By default, your `index.html`'s <!-- Usemin block --> will take care
// of minification. These next options are pre-configured if you do not
// wish to use the Usemin blocks.
// cssmin: {
// dist: {
// files: {
// '<%= config.dist %>/styles/main.css': [
// '.tmp/styles/{,*/}*.css',
// '<%= config.app %>/styles/{,*/}*.css'
// ]
// }
// }
// },
// uglify: {
// dist: {
// files: {
// '<%= config.dist %>/scripts/scripts.js': [
// '<%= config.dist %>/scripts/scripts.js'
// ]
// }
// }
// },
// concat: {
// dist: {}
// },
// Copies remaining files to places other tasks can use
copy: {
dist: {
files: [{
expand: true,
dot: true,
cwd: '<%= config.app %>',
dest: '<%= config.dist %>',
src: [
'*.{ico,png,txt}',
'images/{,*/}*.webp',
'{,*/}*.html',
'styles/fonts/{,*/}*.*',
'social/{,*/}*.*'
]
}]
}
},
// Generates a custom Modernizr build that includes only the tests you
// reference in your app
modernizr: {
dist: {
devFile: 'bower_components/modernizr/modernizr.js',
outputFile: '<%= config.dist %>/scripts/vendor/modernizr.js',
files: {
src: [
'<%= config.dist %>/scripts/{,*/}*.js',
'<%= config.dist %>/styles/{,*/}*.css',
'!<%= config.dist %>/scripts/vendor/*'
]
},
uglify: true
}
},
// Deploy with git
buildcontrol: {
options: {
dir: '<%= config.dist %>',
commit: true,
push: true,
message: 'Built %sourceName% from commit %sourceCommit% on branch %sourceBranch%'
},
stage: {
options: {
remote: 'git@github.com:richardwestenra/repeater.git',
branch: 'gh-pages'
}
},
local: {
options: {
remote: '../',
branch: 'build'
}
}
},
// make a zipfile
compress: {
main: {
options: {
archive: 'zips/bgRepeater-'+grunt.template.today('yyyymmdd-HHMM')+'.zip'
},
files: [
{src: ['dist/**'], dest: ''}
]
}
},
notify_hooks: {
options: {
enabled: true,
max_jshint_notifications: 5, // maximum number of notifications from jshint output
}
},
notify: {
build: {
options: {
message: 'Build complete'
}
},
deploy: {
options: {
message: 'Deployment complete'
}
},
zip: {
options: {
message: 'Build compressed'
}
}
},
// Run some tasks in parallel to speed up build process
concurrent: {
server: [
'sass:server'
],
test: [
],
dist: [
'sass',
'imagemin',
'svgmin'
]
}
});
grunt.task.run('notify_hooks');
grunt.registerTask('serve', 'start the server and preview your app, --allow-remote for remote access', function (target) {
if (grunt.option('allow-remote')) {
grunt.config.set('connect.options.hostname', '0.0.0.0');
}
if (target === 'dist') {
return grunt.task.run(['build', 'connect:dist:keepalive']);
}
grunt.task.run([
'clean:server',
'wiredep',
'concurrent:server',
'autoprefixer',
'connect:livereload',
'watch'
]);
});
grunt.registerTask('server', function (target) {
grunt.log.warn('The `server` task has been deprecated. Use `grunt serve` to start a server.');
grunt.task.run([target ? ('serve:' + target) : 'serve']);
});
grunt.registerTask('test', function (target) {
if (target !== 'watch') {
grunt.task.run([
'clean:server',
'concurrent:test',
'autoprefixer'
]);
}
grunt.task.run([
'connect:test',
'mocha'
]);
});
grunt.registerTask('build', [
'clean:dist',
'wiredep',
'useminPrepare',
'concurrent:dist',
'autoprefixer',
'concat',
'cssmin',
'uglify',
'copy:dist',
'modernizr',
'rev',
'usemin',
'htmlmin',
'notify:build'
]);
grunt.registerTask('ftp', [
'default',
'ftp_push',
'notify:deploy'
]);
grunt.registerTask('deploy', [
'default',
'buildcontrol:stage',
'notify:deploy'
]);
grunt.registerTask('zip', [
'default',
'compress',
'notify:zip'
]);
grunt.registerTask('default', [
'newer:jshint',
'test',
'build'
]);
};
|
define([
'flight/lib/component'
], function(defineComponent) {
'use strict';
return defineComponent(FlightBehavior);
function FlightBehavior() {
this.attributes({
divSelector: 'div',
spanSelector: 'span'
})
this.after('initialize', function() {
this.$node.html('<div>FlightBehavior<span>mapped</span></div>')
this.on('click', {
divSelector: function(event) {
$(event.target).trigger('customBehavior', 'param1fromflight');
},
spanSelector: function(event) {
$(event.target).trigger('legacy', 'param1fromflightMapped');
}
})
});
}
});
|
'''
Now I need to improve calibration of J0132 and by extension of UV Cet. First steps:
- try concatenating the two data sets - can we force CASA to split them into scans?
- otherwise return to AIPS and try to use it to mash J0132 and UV Cet together after shifting pcen
- image J0132 and quiescent UV Cet
- try running an amplitude+phase gaincal on J0132 with no model, one soln per scan
- apply ap gains to J0132 & UV Cet and re-image, compare quality
'''
### Import J0132 and UVCet avg'd data sets ###
importuvfits(fitsfile='J0132.uvfits', vis='J0132.ms')
importuvfits(fitsfile='UVCet.uvfits', vis='UVCet.ms')
### Write my own scan numbers ###
from dynspec.tbavg import scan_reindex
scan_reindex(vis='J0132.ms',gap=50.)
scan_reindex(vis='UVCet.ms',gap=50.)
### Image J0132 and UVCet and assess sensitivity ###
# Expected sensitivity:
# time on source: J0132 - 74 scans x 50 sec = 62 min on source
# UVCet - 72 scans x 110 sec = 132 min on source
# EVN calculator, for 256 MHz dual pol:
# 62 min --> 40 uJy (-1 ant), 36 uJy (all ants)
# 132 min --> 27 uJy (-1 ant), 24 uJy (all ants)
# 2 min --> 200 uJy (all ants)
# 1 min --> 280 uJy (all ants)
## Dirty images (to look at Stokes V RMS) ##
# beam: 2.8x1.2 mas --> 0.28 pixel size is fine
clean(vis='J0132.ms',imagename='J0132/J0132_precal_dirty',cell='0.00028arcsec',niter=0,stokes='IV')
clean(vis='UVCet.ms',imagename='UVCet/UVCet_precal_dirty',cell='0.00028arcsec',niter=0,stokes='IV')
# Stokes V RMS: J0132 - 1.3 mJy (dominated by source leakage from Stokes I)
# UVCet - 62 uJy (40 in region w/o src) --> already pretty good!
# UV Cet looks resolved but is this due to phase calibration errors?
# The antennas where J0132 and J0140 gain phases are significantly different are: HN, MK
# Dirty image of UVCet w/o HN, MK:
clean(vis='UVCet.ms',imagename='UVCet/noHNMK_precal_dirty',cell='0.00028arcsec',niter=0,stokes='IV',antenna='!HN,MK')
# beam is 3.9x1.8 mas
# dirty image now looks less clearly resolved but if we clean and break it down by time it could still be
# create ms w/ pcen shifted to UVCet peak w/o HN, MK
# peak: 01:39:05.116, -17:56:51.78
fixvis(vis='UVCet.ms',outputvis='UVCet_pcen.ms',phasecenter='J2000 1h39m05.1157272 -17d56m51.7775896')
## Clean images (to look at Stokes I residual RMS) ##
# identify quiescent timerange for UVCet
t_quiet = '12:00:00~12:34:00,14:41:00~16:00:00'
# clean each field once interactively to generate mask
clean(vis='J0132.ms',imagename='J0132/J0132',cell='0.00028arcsec',interactive=True,niter=5000,cyclefactor=5,npercycle=10) # 90 iterations
clean(vis='UVCet.ms',imagename='UVCet/UVCet',timerange=t_quiet,antenna='!MK,HN',cell='0.00028arcsec',interactive=True,niter=5000,cyclefactor=5,npercycle=10)
pcal_mask = 'J0132/J0132.mask'
star_mask = 'UVCet/UVCet.mask'
# clean each field automatically using mask
clean(vis='J0132.ms',imagename='J0132/auto_precal',cell='0.00028arcsec',niter=90,cyclefactor=5,mask=pcal_mask,usescratch=True)
clean(vis='UVCet.ms',imagename='UVCet/auto_precal_v2',cell='0.00028arcsec',antenna='!MK,HN',timerange=t_quiet,threshold='0.15mJy',cyclefactor=5,mask=star_mask,usescratch=True)
# residual RMS: J0132 - 3.9 mJy (dynamic range: 1 Jy integrated, 700 mJy peak flux/3.9 = 180 --> UV Cet not dyn range limited if equally good)
# UVCet - 70 uJy (--> ~2x expected) - not bad! much worse when used full time instead of quiet
### Amp+phase gaincal w/ and w/o model ###
# split data column only for gaincal w/o model
split(vis='J0132.ms',outputvis='J0132_v2.ms',datacolumn='data')
# try phase-only gaincal first
gaincal(vis='J0132.ms',refant='LA',calmode='p',caltable='J0132.ScP0') # ScP0: phase-only self-cal #0 (with model)
gaincal(vis='J0132_v2.ms',refant='LA',calmode='p',caltable='J0132.P0') # P0: phase-only gaincal #0 (no model)
# for no-model gaincal, a few solns were flagged due to low SNR; not for selfcal w/ model - all for ant 6 (based on # pts plotted by plotcal)
plotcal(caltable='J0132.ScP0', xaxis='time',yaxis='phase',iteration='antenna',subplot=431)
plotcal(caltable='J0132.P0', xaxis='time',yaxis='phase',iteration='antenna',subplot=431)
# MK6 pretty structured over time, significantly different shape w/ and w/o model
# try amp+phase gaincal w/o phase-only cal (can we get away w/ just doing one amp+phase gaincal?)
gaincal(vis='J0132.ms',refant='LA',calmode='ap',caltable='J0132.ScAP0') # ScAP0: amp+phase self-cal #0 (with model)
gaincal(vis='J0132_v2.ms',refant='LA',calmode='ap',caltable='J0132.AP0') # AP0: amp+phase gaincal #0 (no model)
# no-model gaincal reported 1-2 solns (probably 1 or 2 pols of ant 6) flagged due to low SNR for many scans
plotcal(caltable='J0132.ScAP0', xaxis='time',yaxis='phase',iteration='antenna',subplot=431)
plotcal(caltable='J0132.AP0', xaxis='time',yaxis='phase',iteration='antenna',subplot=431)
# now model-less phases agree w/ model phases, which agree w/ phase only selfcal phases - but model-less ap phases have no solns for 1st half of obs
# model-less amp gains very low, whereas model amp gains all centered around 1
# apply caltable to J0132 and image
for exten in ['ScP0','P0','ScAP0','AP0']:
applycal(vis='J0132.ms',gaintable='J0132.'+exten,applymode='calonly')
clean(vis='J0132.ms',imagename='J0132/dirty_'+exten,cell='0.00028arcsec',niter=0,stokes='IV')
clean(vis='J0132.ms',imagename='J0132/clean_'+exten,cell='0.00028arcsec',mask=pcal_mask,niter=90,cyclefactor=5)
# dirty Stokes V RMS:
# - precal, ScP0, P0: 1.28 mJy
# - AP0: 661 uJy
# - ScAP0: 75 uJy (2x expected --> pretty good!)
# clean Stokes I residual RMS:
# - precal, ScP0: 3.9 mJy; P0: 4.0 mJy; AP0: 5.2; ScAP0: 2.6 mJy (improving mask may improve rms, but there are clear cal errors)
# ScAP0 is winner on J0132 - apply ScAP0 to UVCet and image
applycal(vis='UVCet.ms',gaintable='J0132.ScAP0',applymode='calonly')
clean(vis='UVCet.ms',imagename='UVCet/v2_dirty_ScAP0',cell='0.00028arcsec',niter=0,stokes='IV')
clean(vis='UVCet.ms',imagename='UVCet/v2_clean_ScAP0_noMKHN',cell='0.00028arcsec',antenna='!MK,HN',timerange=t_quiet,threshold='0.15mJy',cyclefactor=5,mask=star_mask,usescratch=True)
clean(vis='UVCet.ms',imagename='UVCet/v2_clean_ScAP0',cell='0.00028arcsec',timerange=t_quiet,threshold='0.15mJy',cyclefactor=5,mask=star_mask,usescratch=True)
# v2 is b/c first time I imaged I forgot to run applycal
# dirty Stokes V RMS: precal: 62 uJy; ScAP0: 60 uJy
# clean Stokes I residual RMS: precal noHNMK: 69 uJy; precal all ants: 61 (image created below)
# ScAP0 noHNMK: 66; ScAP0 all ants: 57
# --> amp+phase selfcal doesn't make huge difference to quality of UV Cet image - slight improvement, doesn't seem to hurt
# split off precal UVCet data and image
split(vis='UVCet.ms',outputvis='UVCet_nocal.ms',datacolumn='data')
clean(vis='UVCet_nocal.ms',imagename='UVCet/auto_precal_wHNMK',cell='0.00028arcsec',timerange=t_quiet,threshold='0.15mJy',cyclefactor=5,mask=star_mask)
# images: measured peak flux for UV Cet is ~20% lower w/ HN and MK than without, but integrated flux is higher
# based on this, I may want to use a uvrange cutoff or antenna cutoff when making time series
# peak flux location is same w/ and w/o HN/MK, and before and after amp+phase gaincal - we can use this as phase center for time series
# gaussfit params based on UVCet v2_clean_ScAP0 (w/ HN MK):
# --- ra: 01:39:05.1157390 +/- 0.0000039 s (0.0000561 arcsec along great circle)
# --- dec: -17.56.51.7777031 +/- 0.0001366 arcsec
# --- major axis FWHM: 2.58 +/- 0.50 marcsec
# --- minor axis FWHM: 1.71 +/- 0.21 marcsec
# --- position angle: 9.3 +/- 28.1 deg
# --- Integrated: 1.87 +/- 0.18 mJy
# --- Peak: 873 +/- 60 uJy/beam
#
# gaussfit params based on UVCet v2_clean_ScAP0_noHNMK:
# --- ra: 01:39:05.1157421 +/- 0.0000034 s (0.0000491 arcsec along great circle)
# --- dec: -017.56.51.7776495 +/- 0.0001383 arcsec
# --- major axis FWHM: 2.75 +/- 0.67 marcsec
# --- minor axis FWHM: 1.51 +/- 0.24 marcsec
# --- position angle: 9.3 +/- 20.2 deg
# --- Integrated: 1.78 +/- 0.14 mJy
# --- Peak: 1.150 +/- 0.058 mJy/beam
# Everything is consistent w/in <1sigma except peak flux (since that depends on clean beam size)
# now compare quiescent burst location to flare peak - burst peak is scan
peak_scan = '37'
clean(vis='UVCet_nocal.ms',imagename='UVCet/burst_nocal_allants_dirty',cell='0.00028arcsec',niter=0,stokes='IV',scan=peak_scan)
clean(vis='UVCet.ms',imagename='UVCet/burst_APcal_allants_dirty',cell='0.00028arcsec',niter=0,stokes='IV',scan=peak_scan)
clean(vis='UVCet_nocal.ms',imagename='UVCet/burst_nocal_noHNMK_dirty',cell='0.00028arcsec',niter=0,stokes='IV',scan=peak_scan,antenna='!MK,HN')
clean(vis='UVCet.ms',imagename='UVCet/burst_APcal_noMKHN_dirty',cell='0.00028arcsec',niter=0,stokes='IV',scan=peak_scan,antenna='!MK,HN')
# MK & HN make it look like 2 lobes instead of one - I think the reason they did not do this for the quiescent emission
# is that the quiescent emission is resolved, so the long baselines have lower amplitude and are downweighted
# conclusion: drop HN and MK for the time series
# uvrange to avoid resolved:
# largest dimension of quiescent emission is 2.75 mas
# this is 75 Mlambda, 2.7 Mm --> cutoff at 60 Mlambda, 2.2 Mm (this should include about half the data and will already cut out almost all MK,HN BLs)
# AD Leo I used 2e6m - we could just use this for both
# try imaging with this cutoff
### Try gaincal restricted to short baselines, see if it changes solutions ###
## iteration 0: < 2.2e6m ##
uvrange = '<2.2e6m'
gaincal(vis='J0132_v2.ms',refant='LA',calmode='p',caltable='J0132.shortP0',uvrange=uvrange) # shortP0: short-BL, phase-only gaincal #0 (no model)
plotcal(caltable='J0132.shortP0', xaxis='time',yaxis='phase',iteration='antenna',subplot=431)
# few to no solns for HN3, MK6, SC10
# phases look basically the same as J0132.ScP0 for other ants --> long BL antennas not messing up gain solns for short BL antennas
# image w/o HN3, MK6, SC10
anten='!HN,MK,SC'
applycal(vis='J0132.ms',gaintable='J0132.shortP0',applymode='calonly')
clean(vis='J0132.ms',imagename='J0132/shortP0_v2',cell='0.00028arcsec',niter=5000,interactive=True,npercycle=10,cyclefactor=5,usescratch=True,antenna=anten)
# I may have overcleaned... come back to this. May be beneficial to apply single amplitude cal based on J0140 first to get better dynamic range
## iteration 1: <3e6m ##
uvrange='<3e6m'
# populate model column (I'm concerned that clean may have excluded antennas)
ft(vis='J0132.ms',model='J0132/shortP0_v2.model',usescratch=True)
gaincal(vis='J0132.ms',refant='LA',calmode='p',caltable='J0132.shortP1',uvrange=uvrange) # shortP1: short-BL, phase-only selfcal #1 (w/ model)
plotcal(caltable='J0132.shortP1', xaxis='time',yaxis='phase',iteration='antenna',subplot=431)
# no solutions for SC even though there's data - probably b/c of minblperant (default is 4)
# try lower values for minblperant
gaincal(vis='J0132.ms',refant='LA',calmode='p',caltable='J0132.shortP1bl',uvrange=uvrange,minblperant=1) # shortP1bl: short-BL, phase-only selfcal #1 (w/ model, minblperant=1)
plotcal(caltable='J0132.shortP1bl', xaxis='time',yaxis='phase',iteration='antenna',subplot=431)
# solns for HN3 and SC10 don't cover full time range: need to run applycal w/ flagging before imaging
# copy data set to a version I can flag
split(vis='J0132_v2.ms',outputvis='J0132_shortP1.ms',datacolumn='data')
# applycal w/ flagging
applycal(vis='J0132_shortP1.ms',gaintable='J0132.shortP1bl',applymode='calflagstrict')
clean(vis='J0132_shortP1.ms',imagename='J0132/shortP1bl',cell='0.00028arcsec',niter=5000,interactive=True,npercycle=10,cyclefactor=5,usescratch=True)
# ft to put model in full (unflagged) data set then inspect amp vs. uvdist in plotms for model and data
ft(vis='J0132.ms',model='J0132/shortP1bl.model',usescratch=True)
# data/model amp is good out to 5e6 m, phase to 3.5e6 m (but we are trying to fix data phase)
# MK is the only antenna that strongly diverges from model at this point - b/c we did not use it to make model!
## Iteration 2: <5e6m ##
uvrange='<5e6m'
gaincal(vis='J0132.ms',refant='LA',calmode='p',caltable='J0132.shortP2',uvrange=uvrange,minblperant=1) # shortP2: short-BL, phase-only selfcal #2 (w/ model)
plotcal(caltable='J0132.shortP2', xaxis='time',yaxis='phase',iteration='antenna',subplot=431)
gaincal(vis='J0132.ms',refant='LA',calmode='p',caltable='J0132.shortP2_4e6',uvrange='<4e6m',minblperant=1) # shortP2: short-BL, phase-only selfcal #2 (w/ model)
plotcal(caltable='J0132.shortP2_4e6', xaxis='time',yaxis='phase',iteration='antenna',subplot=431)
# result is quite different for 4e6 and 5e6 --> let's go with 4e6?
split(vis='J0132_v2.ms',outputvis='J0132_shortP2.ms',datacolumn='data')
applycal(vis='J0132_shortP2.ms',gaintable='J0132.shortP2_4e6',applymode='calflagstrict')
clean(vis='J0132_shortP2.ms',imagename='J0132/shortP2_4e6',cell='0.00028arcsec',niter=5000,interactive=True,npercycle=10,cyclefactor=5,usescratch=True)
# ft to put model in full (unflagged) data set then inspect amp vs. uvdist in plotms for model and data
ft(vis='J0132.ms',model='J0132/shortP2_4e6.model',usescratch=True)
## Iteration 3: full uvdist? ##
# compare <5e6m and full #
gaincal(vis='J0132.ms',refant='LA',calmode='p',caltable='J0132.shortP3_5e6',uvrange='<5e6m',minblperant=1) # phase-only #3, <5e6m
gaincal(vis='J0132.ms',refant='LA',calmode='p',caltable='J0132.shortP3') # phase-only #3, all baselines
plotcal(caltable='J0132.shortP3_5e6', xaxis='time',yaxis='phase',iteration='antenna',subplot=431)
plotcal(caltable='J0132.shortP3', xaxis='time',yaxis='phase',iteration='antenna',subplot=431)
# looks basically the same
# apply and image to supply model for amp+phase selfcal
split(vis='J0132_v2.ms',outputvis='J0132_shortP3.ms',datacolumn='data') # shouldn't flag anything but we'll use calflagstrict to check
applycal(vis='J0132_shortP3.ms',gaintable='J0132.shortP3',applymode='calflagstrict') # no additional flagging, yay!
clean(vis='J0132_shortP3.ms',imagename='J0132/shortP3',cell='0.00028arcsec',niter=5000,interactive=True,npercycle=10,cyclefactor=5,usescratch=True)
# ft and applycal and inspect
ft(vis='J0132.ms',model='J0132/shortP3.model',usescratch=True)
applycal(vis='J0132.ms',gaintable='J0132.shortP3')
### Amplitude+phase calibration ###
# do normalized amplitude calibration (so we don't reduce source flux)
gaincal(vis='J0132.ms',refant='LA',calmode='ap',caltable='J0132.shortAP0_v2',solnorm=True) # shortAP0: all baselines
gaincal(vis='J0132.ms',refant='LA',calmode='ap',caltable='J0132.shortAP0_22e6_v2',uvrange='<2.2e6m',solnorm=True) # shortAP0_22e6: start with baselines < 2.2e6m
#v2 - for first version I forgot to use solnorm=True
plotcal(caltable='J0132.shortAP0_v2', xaxis='time',yaxis='amp',iteration='antenna',subplot=431)
plotcal(caltable='J0132.shortAP0_22e6_v2', xaxis='time',yaxis='amp',iteration='antenna',subplot=431)
# including long baselines does affect relative amps of short BL ants --> probably better to iterate but I'm tired of this!
# apply and image
split(vis='J0132_v2.ms',outputvis='J0132_shortAP0.ms',datacolumn='data') # shouldn't flag anything but we'll use calflagstrict to check
applycal(vis='J0132_shortAP0.ms',gaintable='J0132.shortAP0_v2',applymode='calflagstrict') # only 0.7% flagged
clean(vis='J0132_shortAP0.ms',imagename='J0132/shortAP0',cell='0.00028arcsec',niter=5000,interactive=True,npercycle=10,cyclefactor=5,usescratch=True)
# Stokes I residual RMS: 3.9 mJy (vs 4.0 mJy for shortP3.residual)
# --> our amplitude calibration is not improving things much
# other thing to try: clean only center component then do ap cal - maybe we are dynamic range limited because im introducing fake structure?
### Compare UVCet w/ phase-only vs. amp+phase cal ###
split(vis='UVCet.ms',outputvis='UVCet_shortP3.ms',datacolumn='data')
split(vis='UVCet.ms',outputvis='UVCet_shortAP0.ms',datacolumn='data')
applycal(vis='UVCet_shortP3.ms',gaintable='J0132.shortP3',applymode='calflagstrict')
applycal(vis='UVCet_shortAP0.ms',gaintable='J0132.shortAP0_v2',applymode='calflagstrict')
peak_scan='37'
# dirty images of burst peak
# dirty image w/ no cal: UVCet/burst_nocal_allants_dirty
# dirty image w/ AP selfcal using all baselines: UVCet/burst_APcal_allants_dirty
clean(vis='UVCet_shortP3.ms',imagename='UVCet/shortP3_burst_dirty',cell='0.00028arcsec',niter=0,stokes='IV',scan=peak_scan)
clean(vis='UVCet_shortAP0.ms',imagename='UVCet/shortAP0_burst_dirty',cell='0.00028arcsec',niter=0,stokes='IV',scan=peak_scan)
# burst peak location much closer to quiescent emission peak --> believable; but it looks like the short BLs are still slightly offset from the long BLs (unless there is resolved quiescent emission with slight offset)
### Try selfcal on J0132 w/o southwest lobe ###
clean(vis='J0132_shortP3.ms',imagename='J0132/shortP3_nolobe',cell='0.00028arcsec',niter=5000,interactive=True,npercycle=10,cyclefactor=5,usescratch=True)
gaincal(vis='J0132_shortP3.ms',refant='LA',calmode='ap',caltable='J0132.shortAP0_nolobe',solnorm=True) # shortAP0: all baselines
plotcal(caltable='J0132.shortAP0_nolobe', xaxis='time',yaxis='amp',iteration='antenna',subplot=431)
split(vis='UVCet.ms',outputvis='UVCet_shortAP0_nolobe.ms',datacolumn='data')
applycal(vis='UVCet_shortAP0_nolobe.ms',gaintable='J0132.shortAP0_nolobe',applymode='calflagstrict')
clean(vis='UVCet_shortAP0_nolobe.ms',imagename='UVCet/shortAP0_nolobe_burst_dirty',cell='0.00028arcsec',niter=0,stokes='IV',scan=peak_scan)
# absolutely identical to shortAP0 w/ lobe
# clean image of burst time
clean(vis='UVCet_shortAP0.ms',imagename='UVCet/shortAP0_burst_clean',cell='0.00028arcsec',niter=5000,interactive=True,npercycle=10,cyclefactor=5,stokes='IV',scan=peak_scan)
# clean image of quiescent emission
t_quiet = '12:00:00~12:34:00,14:41:00~16:00:00'
clean(vis='UVCet_shortAP0.ms',imagename='UVCet/shortAP0_quiet_clean',timerange=t_quiet,cell='0.00028arcsec',interactive=True,niter=5000,cyclefactor=5,npercycle=10,stokes='IV')
# shift phase center to gaussfit location of burst
# --- ra: 01:39:05.11573485 +/- 0.00000079 s (0.00001122 arcsec along great circle)
# --- dec: -017.56.51.77789101 +/- 0.00005123 arcsec
fixvis(vis='UVCet_shortAP0.ms',outputvis='UVCet_shortAP0.ms',phasecenter='J2000 01h39m05.11573485 -17d56m51.77789101')
mask = 'UVCet/shortAP0_quiet_clean.mask'
threshold='0.2mJy' # I'm guessing at what will be good
# break quiet times down into ~30 min intervals
# gave blocks of 8 scans letters (a: 1-8, b:9-16, etc)
# a-b,g-i: quiescent
# c: 17~24 - RR starting to increase
# d: 25~32 - RR almost flat at ~3 mJy
# e: 33~40 - burst peak, longer total duration b/c of bright cal obs after scan 36
# f: 41~48 - RR mostly low again
for nf in range(8,73,8):
n0 = nf-7
scan = str(n0)+'~'+str(nf)
name = 'scan'+str(n0)+'_'+str(nf)
clean(vis='UVCet_shortAP0.ms',imagename='UVCet/'+name,cell='0.00028arcsec',threshold=threshold,cyclefactor=5,mask=mask,usescratch=True,stokes='IV',scan=scan)
# uv cet appears to move by 1.1 mas during obs... check proper motion+parallax
# uv cet has huge proper motion
# load data set w/ proper motion + parallax corrected
importuvfits(fitsfile='../UVCet_shift.uvfits',vis='UVCet_shift.ms')
from dynspec.tbavg import scan_reindex
scan_reindex('UVCet_shift.ms')
applycal(vis='UVCet_shift.ms',gaintable='J0132.shortAP0_v2',applymode='calflagstrict')
for nf in range(8,73,8):
n0 = nf-7
scan = str(n0)+'~'+str(nf)
name = 'scan'+str(n0)+'_'+str(nf)
clean(vis='UVCet_shift.ms',imagename='UVCet/shift_dirty_'+name,cell='0.00028arcsec',niter=0,stokes='IV',scan=scan)
# create uncalibrated UVCet_shift to compare how src moves
split(vis='UVCet_shift.ms',outputvis='UVCet_shift_nocal.ms',datacolumn='data')
for nf in range(8,73,8):
n0 = nf-7
scan = str(n0)+'~'+str(nf)
name = 'scan'+str(n0)+'_'+str(nf)
clean(vis='UVCet_shift_nocal.ms',imagename='UVCet/shift_nocal_dirty_'+name,cell='0.00028arcsec',niter=0,stokes='IV',scan=scan)
# conclusion: motion of source during obs is not due to J0132.shortAP0 (however it could be due to problem with fringe fit that
# J0132.shortAP0 has failed to correct)
# clean once interactively to create mask
clean(vis='UVCet_shift.ms',imagename='UVCet/shift_quiet',timerange=t_quiet,interactive=True,npercycle=10,cyclefactor=5,stokes='IV',cell='0.00028arcsec')
# wow! Stokes V is positive on left side, negative on right side; both are offset slightly southeast of stokes I peak (which is direction towards burst)
clean(vis='UVCet_shift_nocal.ms',imagename='UVCet/shift_quiet_nocal',timerange=t_quiet,interactive=True,npercycle=10,cyclefactor=5,stokes='IV',cell='0.00028arcsec')
# Still there w/o cal - not some weird consequence of doing an amplitude cal
# now let's see if it's there over shorter time intervals or if it's a consequence of combining different times
mask = 'UVCet/shift_quiet.mask'
threshold='0.25mJy'
for nf in range(8,73,8):
n0 = nf-7
scan = str(n0)+'~'+str(nf)
name = 'scan'+str(n0)+'_'+str(nf)
clean(vis='UVCet_shift.ms',imagename='UVCet/v2_shift_clean_'+name,cell='0.00028arcsec',threshold=threshold,cyclefactor=5,mask=mask,stokes='IV',scan=scan)
# first 5 blocks have thing to south south east of UV Cet, in first 4 blocks peak appears to be moving in straight line - however it is at the level
# of other artifacts/noise in the background so it could be a sidelobe that moves with time; perhaps due to a bad antenna that goes away after scan 5?
# there's a lot of mucky stuff - bad data? or bad cal?
# try a phase-only selfcal (no model) on UV Cet RR during burst peak
scan = '32~39'
gaincal(vis='UVCet_shift.ms',refant='LA',calmode='p',gaintable='J0132.shortAP0_v2',caltable='UVCet.P0',scan=scan)
plotcal(caltable='UVCet.P0', xaxis='time',yaxis='phase',iteration='antenna',subplot=431)
split(vis='UVCet_shift.ms',outputvis='UVCet_burstRR.ms',datacolumn='corrected',correlation='RR',scan='32~39')
gaincal(vis='UVCet_burstRR.ms',refant='LA',calmode='p',caltable='UVCet.P0_v2')
plotcal(caltable='UVCet.P0_v2', xaxis='time',yaxis='phase',iteration='antenna',subplot=431)
# need to shift phase center to star first
# Gaussfit on scan 33-40:
# --- ra: 01:39:05.11534620 +/- 0.00000100 s (0.00001431 arcsec along great circle)
# --- dec: -017.56.51.77725822 +/- 0.00007058 arcsec
fixvis(vis='UVCet_burstRR.ms',outputvis='UVCet_burstRR.ms',phasecenter='J2000 1h39m5.11534620 -17d56m51.77725822')
gaincal(vis='UVCet_burstRR.ms',refant='LA',calmode='p',caltable='UVCet.P0_v3')
plotcal(caltable='UVCet.P0_v3', xaxis='time',yaxis='phase',iteration='antenna',subplot=431)
gaincal(vis='UVCet_burstRR.ms',refant='LA',calmode='p',caltable='UVCet.P0_v4',combine='scan')
plotcal(caltable='UVCet.P0_v4', xaxis='time',yaxis='phase',iteration='antenna',subplot=431)
gaincal(vis='UVCet_burstRR.ms',refant='LA',calmode='p',caltable='UVCet.P0_v5',combine='spw')
plotcal(caltable='UVCet.P0_v5', xaxis='time',yaxis='phase',iteration='antenna',subplot=431)
applycal(vis='UVCet_burstRR.ms',gaintable='UVCet.P0_v5',applymode='calonly',spwmap=[0,0,0,0,0,0,0,0])
clean(vis='UVCet_burstRR.ms',imagename='UVCet/burstRR',cell='0.00028arcsec',interactive=True,npercycle=10,cyclefactor=5,stokes='IV')
# the thing in the SSW goes away
# try doing selfcal on UV Cet throughout by combining spws
fixvis(vis='UVCet_shift.ms',outputvis='UVCet_shift.ms',phasecenter='J2000 1h39m5.11534620 -17d56m51.77725822')
split(vis='UVCet_shift.ms',outputvis='UVCet_shift_cal.ms',datacolumn='corrected')
gaincal(vis='UVCet_shift_cal.ms',refant='LA',calmode='p',caltable='UVCet.P0_v6',combine='spw')
plotcal(caltable='UVCet.P0_v6', xaxis='time',yaxis='phase',iteration='antenna',subplot=431)
gaincal(vis='UVCet_shift_cal.ms',refant='LA',calmode='p',caltable='UVCet.P0_v7',combine='spw,scan',solint='1440s')
plotcal(caltable='UVCet.P0_v7', xaxis='time',yaxis='phase',iteration='antenna',subplot=431)
smoothcal(vis='UVCet_shift.ms',tablein='UVCet.P0_v7',caltable='UVCet.P0_v7smooth',smoothtime=2880)
plotcal(caltable='UVCet.P0_v7smooth', xaxis='time',yaxis='phase',iteration='antenna',subplot=431)
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.deactivate = exports.activate = void 0;
const vscode = require("vscode");
const runFirstCommand_1 = require("./commands/runFirstCommand");
const openList_1 = require("./commands/openList");
const bundle_1 = require("./functions/bundle");
const showCC_1 = require("./commands/showCC");
function activate(context) {
// Get the custom commands from user;
// Create button to run custom command
// STATUSBAR ITEM
// create
var custom_command_button = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Right, 999);
// properties
custom_command_button.text = "$(run-all)";
custom_command_button.tooltip = "Click to run first-command";
custom_command_button.command = "custom_commands.run";
custom_command_button.show();
// Create cc.md File
// COMMAND
const runCommand = "custom_commands.run";
const selectCommand = "custom_commands.list";
// file create command
const fileCreateCommand = "custom_commands.create";
// Select From List
const showCommand = "custom_commands.show";
// run Command
const Run_First_Command = async () => {
runFirstCommand_1.default();
};
const Select_From_List_Func = async (name = "runc") => {
// Get The Terminal Names
openList_1.default();
};
// Task
// SUBSCRIBE TO COMMANDS
context.subscriptions.push(vscode.commands.registerCommand(runCommand, Run_First_Command));
context.subscriptions.push(vscode.commands.registerCommand(selectCommand, Select_From_List_Func));
context.subscriptions.push(vscode.commands.registerCommand(fileCreateCommand, bundle_1.default.createFile.bind(null, "cc", "")));
context.subscriptions.push(vscode.commands.registerCommand(showCommand, showCC_1.default));
}
exports.activate = activate;
function deactivate() { }
exports.deactivate = deactivate;
//# sourceMappingURL=extension.js.map
|
# -*- using: utf-8 -*-
# Author: Yahui Liu <yahui.liu@unitn.it>
import os
import glob
import cv2
import numpy as np
import statistics
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--data_path', default='',
help='/path/to/segmentation')
args = parser.parse_args()
def get_weights(labels_dict):
total_pixels = 0
for lab in labels_dict:
total_pixels += labels_dict[lab]
for lab in labels_dict:
labels_dict[lab] /= float(total_pixels)
return labels_dict
def calculate_weights(im_path):
assert os.path.isdir(im_path)
img_list = glob.glob(os.path.join(im_path, '*.png'))
labels_dict = {}
for im_path in img_list:
im = cv2.imread(im_path, cv2.IMREAD_UNCHANGED)
labels, counts = np.unique(im, return_counts=True)
for lab, cnt in zip(labels, counts):
if lab not in labels_dict:
labels_dict[lab] = 0
labels_dict[lab] += cnt
return get_weights(labels_dict)
def reverse_weight(w):
"""
Median Frequency Balancing: alpha_c = median_freq/freq(c).
median_freq is the median of these frequencies
freq(c) is the number of pixles of class c divided by the total number of pixels in images where c is present
"""
assert len(w) > 0, "Expected a non-empty weight dict."
values = [w[k] for k in w]
if len(w) == 1:
value = 1.0
elif len(w) == 2:
value = min(values)
else:
# Median Frequency Balancing
value = statistics.median(values)
for k in w:
w[k] = value/(w[k]+1e-10)
return w
if __name__ == '__main__':
weights = calculate_weights(args.data_path)
print(weights)
# {0: 0.9708725873161764, 255: 0.02912741268382353}
print(reverse_weight(weights))
# {0: 0.030001272114749396, 255: 0.9999999965668079}
|
import React from 'react';
import propTypes from 'prop-types';
import { fitContent } from '@patternfly/react-table';
import { InUseProfileLabel } from 'PresentationalComponents';
import { TableToolsTable } from 'Utilities/hooks/useTableTools';
import { renderComponent } from 'Utilities/helpers';
import { conditionalFilterType } from '@redhat-cloud-services/frontend-components/ConditionalFilter';
import PolicyTypeDetailsRow from './PolicyTypeDetailsRow';
const NameCell = ({ name, disabled }) => {
return (
<>
{name} {disabled && <InUseProfileLabel compact />}
</>
);
};
NameCell.propTypes = {
name: propTypes.string,
disabled: propTypes.boolean,
};
const PolicyTypeTable = ({ profiles, onChange, selectedProfile }) => (
<TableToolsTable
items={profiles.map((profile) => ({
...profile,
rowProps: {
selected: profile.id === selectedProfile?.id,
disableSelection: profile.disabled,
},
}))}
filters={{
filterConfig: [
{
type: conditionalFilterType.text,
label: 'Policy Name',
filter: (policyTypes, value) =>
policyTypes.filter((policyType) =>
policyType?.name.toLowerCase().includes(value.toLowerCase())
),
},
],
}}
columns={[
{
title: 'Policy name',
key: 'name',
sortByProp: 'name',
renderFunc: renderComponent(NameCell),
},
{
title: 'Supported OS versions',
transforms: [fitContent],
sortByProp: 'supportedOsVersions',
renderFunc: (_data, _id, profile) =>
profile.supportedOsVersions.join(', '),
},
]}
options={{
detailsComponent: PolicyTypeDetailsRow,
onRadioSelect: (_event, _value, _rowIdx, { itemId }) =>
onChange && onChange(profiles.find(({ id }) => id === itemId)),
sortBy: {
index: 2,
direction: 'asc',
property: 'name',
},
}}
variant="compact"
/>
);
PolicyTypeTable.propTypes = {
profiles: propTypes.array,
onChange: propTypes.func,
selectedProfile: propTypes.string,
};
export default PolicyTypeTable;
|
"""
fasta2bed.py - segment sequences
================================
:Tags: Genomics Sequences Intervals FASTA BED Conversion
Purpose
-------
This script takes a genomic sequence in :term:`fasta` format
and applies various segmentation algorithms.
The methods implemented (``--methods``) are:
cpg
output all locations of cpg in the genome
fixed-width-windows-gc
output fixed width windows of a certain size adding their
G+C content as score
gaps
ouput all locations of assembly gaps (blocks of `N`)
in the genomic sequences
ungapped
output ungapped locations in the genomic sequences
Usage
-----
Type::
python fasta2bed.py --method=gap < in.fasta > out.bed
Type::
python fasta2bed.py --help
for command line help.
Command line options
--------------------
"""
import os
import sys
import re
import tempfile
import subprocess
import glob
import collections
import pybedtools
import CGAT.Experiment as E
import CGAT.IOTools as IOTools
import CGAT.FastaIterator as FastaIterator
import CGAT.IOTools as IOTools
def segmentWithCpG(infile, with_contig_sizes=False):
'''segment a fasta file, output locations of CpG.'''
ninput, nskipped, noutput = 0, 0, 0
iterator = FastaIterator.FastaIterator(infile)
segments, contig_sizes = [], collections.OrderedDict()
for cur_record in iterator:
ninput += 1
contig = re.sub("\s.*", "", cur_record.title)
last = None
contig_sizes[contig] = (0, len(cur_record.sequence))
for pos, this in enumerate(cur_record.sequence.upper()):
if last == "C" and this == "G":
segments.append((contig, pos - 1, pos + 1, 1.0))
last = this
E.info("ninput=%i, noutput=%i, nskipped=%i" % (ninput, noutput, nskipped))
if with_contig_sizes:
return segments, contig_sizes
return segments
def segmentWindowsCpG(infile, window_size=100, min_cpg=1):
'''segment a fasta file based on the locations of CpG.
Locate all CpG in sequences and centre windows of size *window_size*
around them. Merge all windows and keep all with *min_cpg* CpG.
'''
cpgs, contig_sizes = segmentWithCpG(infile, with_contig_sizes=True)
# save cpgs to temporary file
tempf = tempfile.NamedTemporaryFile(mode="w", delete=False)
tempf.write("\n".join(["%s\t%i\t%i\n" % (contig, start, end)
for contig, start, end, gc in cpgs]) + "\n")
tempf.close()
cpgs = pybedtools.BedTool(tempf.name)
cpgs.set_chromsizes(contig_sizes)
extended = cpgs.slop(b=window_size // 2)
merged = extended.merge(o="count", c=3)
filtered = merged.filter(lambda x: int(x.name) >= min_cpg)
os.unlink(tempf.name)
# return CpG content (not C+C content)
return [(x.chrom, x.start, x.stop, float(x.name) / (x.stop - x.start) / 2)
for x in filtered]
def segmentFixedWidthWindows(infile, window_size, window_shift):
"""return a list of fixed contig sizes."""
ninput, nskipped, noutput = 0, 0, 0
iterator = FastaIterator.FastaIterator(infile)
window_shift = window_size
# at most 50% can be gap
gap_cutoff = int(window_size // 2)
segments = []
while 1:
ninput += 1
try:
cur_record = next(iterator)
except StopIteration:
break
if cur_record is None:
break
contig = re.sub("\s.*", "", cur_record.title)
seq = cur_record.sequence
size = len(cur_record.sequence)
for x in range(0, size, window_shift):
s = seq[x:x + window_size].upper()
gc, at = 0, 0
for c in s:
if c in "GC":
gc += 1
elif c in "AT":
at += 1
# skip segments containing mostly gaps
if window_size - (gc + at) > gap_cutoff:
nskipped += 1
continue
segments.append(
(contig, x, x + window_size, float(gc) / (gc + at)))
noutput += 1
E.info("ninput=%i, noutput=%i, nskipped_windows=%i" %
(ninput, noutput, nskipped))
return segments
def gapped_regions(seq, gap_chars):
'''iterator yielding gapped regions in seq.'''
is_gap = seq[0] in gap_chars
last = 0
size = len(seq)
for x, c in enumerate(seq):
if c in gap_chars:
if not is_gap:
last = x
is_gap = True
else:
if is_gap:
yield(last, x)
last = x
is_gap = False
if is_gap:
yield last, size
def segmentGaps(infile, gap_char):
iterator = FastaIterator.FastaIterator(infile)
while 1:
try:
cur_record = next(iterator)
except StopIteration:
break
if cur_record is None:
break
contig = re.sub("\s.*", "", cur_record.title)
for start, end in gapped_regions(cur_record.sequence, gap_char):
yield(contig, start, end, 0)
def segmentUngapped(infile, gap_char, min_gap_size=0):
iterator = FastaIterator.FastaIterator(infile)
while 1:
try:
cur_record = next(iterator)
except StopIteration:
break
if cur_record is None:
break
contig = re.sub("\s.*", "", cur_record.title)
size = len(cur_record.sequence)
last_end = 0
for start, end in gapped_regions(cur_record.sequence, gap_char):
if end - start < min_gap_size:
continue
if last_end != 0:
yield(contig, last_end, start, 0)
last_end = end
if last_end < size:
yield(contig, last_end, size, 0)
def main(argv=None):
"""script main.
parses command line options in sys.argv, unless *argv* is given.
"""
if not argv:
argv = sys.argv
# setup command line parser
parser = E.OptionParser(
version="%prog version: $Id",
usage=globals()["__doc__"])
parser.add_option(
"-m", "--method", dest="method", type="choice",
choices=(
"fixed-width-windows-gc",
"cpg",
"windows-cpg",
"gaps",
"ungapped",
"windows"),
help="Method to use for segmentation [default=%default]")
parser.add_option(
"-w", "--window-size=", dest="window_size",
type="int",
help="window size for fixed-width windows [default=%default].")
parser.add_option(
"-s", "--window-shift=", dest="window_shift", type="int",
help="shift size fixed-width windows [default=%default].")
parser.add_option(
"--min-cpg", dest="min_cpg", type="int",
help="minimum number of CpG for windows-cpg [default=%default]")
parser.add_option(
"--min-interval-length", dest="min_length", type="int",
help="minimum length for ungapped regions [default=%default]")
parser.set_defaults(
window_size=10000,
method="cpg",
gap_char="NnXx",
min_length=0,
window_shift=10000,
min_cpg=1,
)
# add common options (-h/--help, ...) and parse command line
(options, args) = E.Start(parser, argv=argv)
if options.method == "cpg":
segments = segmentWithCpG(options.stdin)
elif options.method == "windows-cpg":
segments = segmentWindowsCpG(options.stdin,
options.window_size,
options.min_cpg)
elif options.method == "Isoplotter":
segments = segmentWithIsoplotter(options.stdin, options)
elif options.method == "fixed-width-windows-gc":
segments = segmentFixedWidthWindows(options.stdin,
options.window_size,
options.window_shift,
)
elif options.method == "gaps":
segments = segmentGaps(options.stdin, options.gap_char)
elif options.method == "ungapped":
segments = segmentUngapped(
options.stdin, options.gap_char, options.min_length)
else:
raise ValueError("unknown method %s" % (method))
x = 0
for contig, start, end, gc in segments:
x += 1
options.stdout.write("%s\n" % "\t".join(
(contig, str(start), str(end), str(x), "%6.4f" % (100.0 * gc))))
# write footer and output benchmark information.
E.Stop()
if __name__ == "__main__":
sys.exit(main(sys.argv))
|
webpackHotUpdate("static/development/pages/index.js",{
/***/ "./pages/index.tsx":
/*!*************************!*\
!*** ./pages/index.tsx ***!
\*************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
eval("__webpack_require__.r(__webpack_exports__);\n/* WEBPACK VAR INJECTION */(function(module) {/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/regenerator */ \"./node_modules/@babel/runtime/regenerator/index.js\");\n/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__);\n/* harmony import */ var _babel_runtime_helpers_esm_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/esm/asyncToGenerator */ \"./node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js\");\n/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! react */ \"./node_modules/react/index.js\");\n/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_2__);\n/* harmony import */ var next_link__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! next/link */ \"./node_modules/next/link.js\");\n/* harmony import */ var next_link__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(next_link__WEBPACK_IMPORTED_MODULE_3__);\n/* harmony import */ var _components_Layout__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../components/Layout */ \"./components/Layout.tsx\");\n\n\n\nvar _this = undefined,\n _jsxFileName = \"/Users/lloyd/Documents/GitHub/lloyd-portfolio/pages/index.tsx\";\n\n\nvar __jsx = react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement;\n\n\n\nvar IndexPage = function IndexPage(props) {\n return __jsx(_components_Layout__WEBPACK_IMPORTED_MODULE_4__[\"default\"], {\n title: \"Home | Lloyd's Working Portfolio\",\n __self: _this,\n __source: {\n fileName: _jsxFileName,\n lineNumber: 6,\n columnNumber: 3\n }\n }, __jsx(\"h1\", {\n __self: _this,\n __source: {\n fileName: _jsxFileName,\n lineNumber: 7,\n columnNumber: 5\n }\n }, \"Lloyd's Working Portfolio\"), __jsx(\"p\", {\n __self: _this,\n __source: {\n fileName: _jsxFileName,\n lineNumber: 8,\n columnNumber: 5\n }\n }, props.weather.main), __jsx(\"ul\", {\n __self: _this,\n __source: {\n fileName: _jsxFileName,\n lineNumber: 9,\n columnNumber: 5\n }\n }, __jsx(\"li\", {\n __self: _this,\n __source: {\n fileName: _jsxFileName,\n lineNumber: 10,\n columnNumber: 7\n }\n }, __jsx(next_link__WEBPACK_IMPORTED_MODULE_3___default.a, {\n href: \"/about\",\n __self: _this,\n __source: {\n fileName: _jsxFileName,\n lineNumber: 11,\n columnNumber: 9\n }\n }, __jsx(\"a\", {\n __self: _this,\n __source: {\n fileName: _jsxFileName,\n lineNumber: 12,\n columnNumber: 11\n }\n }, \"About\"))), __jsx(\"li\", {\n __self: _this,\n __source: {\n fileName: _jsxFileName,\n lineNumber: 15,\n columnNumber: 7\n }\n }, __jsx(next_link__WEBPACK_IMPORTED_MODULE_3___default.a, {\n href: \"/experiment/001\",\n __self: _this,\n __source: {\n fileName: _jsxFileName,\n lineNumber: 16,\n columnNumber: 9\n }\n }, __jsx(\"a\", {\n __self: _this,\n __source: {\n fileName: _jsxFileName,\n lineNumber: 17,\n columnNumber: 11\n }\n }, \"001 - Setting Up with Next.js\"))), __jsx(\"li\", {\n __self: _this,\n __source: {\n fileName: _jsxFileName,\n lineNumber: 20,\n columnNumber: 7\n }\n }, __jsx(next_link__WEBPACK_IMPORTED_MODULE_3___default.a, {\n href: \"/experiment/002\",\n __self: _this,\n __source: {\n fileName: _jsxFileName,\n lineNumber: 21,\n columnNumber: 9\n }\n }, __jsx(\"a\", {\n __self: _this,\n __source: {\n fileName: _jsxFileName,\n lineNumber: 22,\n columnNumber: 11\n }\n }, \"002 - Working with API\")))));\n};\n\n_c = IndexPage;\nIndexPage.get = /*#__PURE__*/Object(_babel_runtime_helpers_esm_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__[\"default\"])( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee() {\n var res, data;\n return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) {\n while (1) {\n switch (_context.prev = _context.next) {\n case 0:\n _context.next = 2;\n return fetch(\"https://api.openweathermap.org/data/2.5/weather?q=Zurich&appid=02f471c66896a92cf74995432fba9e3c\");\n\n case 2:\n res = _context.sent;\n _context.next = 5;\n return res.json();\n\n case 5:\n data = _context.sent;\n return _context.abrupt(\"return\", {\n weather: data.weather\n });\n\n case 7:\n case \"end\":\n return _context.stop();\n }\n }\n }, _callee);\n}));\n/* harmony default export */ __webpack_exports__[\"default\"] = (IndexPage);\n\nvar _c;\n\n$RefreshReg$(_c, \"IndexPage\");\n\n;\n var _a, _b;\n // Legacy CSS implementations will `eval` browser code in a Node.js context\n // to extract CSS. For backwards compatibility, we need to check we're in a\n // browser context before continuing.\n if (typeof self !== 'undefined' &&\n // AMP / No-JS mode does not inject these helpers:\n '$RefreshHelpers$' in self) {\n var currentExports_1 = module.__proto__.exports;\n var prevExports = (_b = (_a = module.hot.data) === null || _a === void 0 ? void 0 : _a.prevExports) !== null && _b !== void 0 ? _b : null;\n // This cannot happen in MainTemplate because the exports mismatch between\n // templating and execution.\n self.$RefreshHelpers$.registerExportsForReactRefresh(currentExports_1, module.i);\n // A module can be accepted automatically based on its exports, e.g. when\n // it is a Refresh Boundary.\n if (self.$RefreshHelpers$.isReactRefreshBoundary(currentExports_1)) {\n // Save the previous exports on update so we can compare the boundary\n // signatures.\n module.hot.dispose(function (data) {\n data.prevExports = currentExports_1;\n });\n // Unconditionally accept an update to this module, we'll check if it's\n // still a Refresh Boundary later.\n module.hot.accept();\n // This field is set when the previous version of this module was a\n // Refresh Boundary, letting us know we need to check for invalidation or\n // enqueue an update.\n if (prevExports !== null) {\n // A boundary can become ineligible if its exports are incompatible\n // with the previous exports.\n //\n // For example, if you add/remove/change exports, we'll want to\n // re-execute the importing modules, and force those components to\n // re-render. Similarly, if you convert a class component to a\n // function, we want to invalidate the boundary.\n if (self.$RefreshHelpers$.shouldInvalidateReactRefreshBoundary(prevExports, currentExports_1)) {\n module.hot.invalidate();\n }\n else {\n self.$RefreshHelpers$.scheduleUpdate();\n }\n }\n }\n else {\n // Since we just executed the code for the module, it's possible that the\n // new exports made it ineligible for being a boundary.\n // We only care about the case when we were _previously_ a boundary,\n // because we already accepted this update (accidental side effect).\n var isNoLongerABoundary = prevExports !== null;\n if (isNoLongerABoundary) {\n module.hot.invalidate();\n }\n }\n }\n\n/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../node_modules/webpack/buildin/harmony-module.js */ \"./node_modules/webpack/buildin/harmony-module.js\")(module)))//# sourceURL=[module]\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9wYWdlcy9pbmRleC50c3g/ZGI3NiJdLCJuYW1lcyI6WyJJbmRleFBhZ2UiLCJwcm9wcyIsIndlYXRoZXIiLCJtYWluIiwiZ2V0IiwiZmV0Y2giLCJyZXMiLCJqc29uIiwiZGF0YSJdLCJtYXBwaW5ncyI6Ijs7Ozs7Ozs7Ozs7Ozs7Ozs7QUFDQTtBQUNBOztBQUVBLElBQU1BLFNBQTBCLEdBQUcsU0FBN0JBLFNBQTZCLENBQUNDLEtBQUQ7QUFBQSxTQUNqQyxNQUFDLDBEQUFEO0FBQVEsU0FBSyxFQUFDLGtDQUFkO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUEsS0FDRTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBLGlDQURGLEVBRUU7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQSxLQUFJQSxLQUFLLENBQUNDLE9BQU4sQ0FBY0MsSUFBbEIsQ0FGRixFQUdFO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUEsS0FDRTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBLEtBQ0UsTUFBQyxnREFBRDtBQUFNLFFBQUksRUFBQyxRQUFYO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUEsS0FDRTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBLGFBREYsQ0FERixDQURGLEVBTUU7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQSxLQUNFLE1BQUMsZ0RBQUQ7QUFBTSxRQUFJLEVBQUMsaUJBQVg7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQSxLQUNFO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUEscUNBREYsQ0FERixDQU5GLEVBV0U7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQSxLQUNFLE1BQUMsZ0RBQUQ7QUFBTSxRQUFJLEVBQUMsaUJBQVg7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQSxLQUNFO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUEsOEJBREYsQ0FERixDQVhGLENBSEYsQ0FEaUM7QUFBQSxDQUFuQzs7S0FBTUgsUztBQXVCTkEsU0FBUyxDQUFDSSxHQUFWLGlNQUFnQjtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBLGlCQUNJQyxLQUFLLENBQ3JCLGlHQURxQixDQURUOztBQUFBO0FBQ1JDLGFBRFE7QUFBQTtBQUFBLGlCQUlLQSxHQUFHLENBQUNDLElBQUosRUFKTDs7QUFBQTtBQUlSQyxjQUpRO0FBQUEsMkNBTVA7QUFDTE4sbUJBQU8sRUFBRU0sSUFBSSxDQUFDTjtBQURULFdBTk87O0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUEsQ0FBaEI7QUFXZUYsd0VBQWYiLCJmaWxlIjoiLi9wYWdlcy9pbmRleC50c3guanMiLCJzb3VyY2VzQ29udGVudCI6WyJpbXBvcnQgRmV0Y2ggZnJvbSBcImlzb21vcnBoaWMtdW5mZXRjaFwiO1xuaW1wb3J0IExpbmsgZnJvbSBcIm5leHQvbGlua1wiO1xuaW1wb3J0IExheW91dCBmcm9tIFwiLi4vY29tcG9uZW50cy9MYXlvdXRcIjtcblxuY29uc3QgSW5kZXhQYWdlOiBSZWFjdC5GQzxQcm9wcz4gPSAocHJvcHMpID0+IChcbiAgPExheW91dCB0aXRsZT1cIkhvbWUgfCBMbG95ZCdzIFdvcmtpbmcgUG9ydGZvbGlvXCI+XG4gICAgPGgxPkxsb3lkJ3MgV29ya2luZyBQb3J0Zm9saW88L2gxPlxuICAgIDxwPntwcm9wcy53ZWF0aGVyLm1haW59PC9wPlxuICAgIDx1bD5cbiAgICAgIDxsaT5cbiAgICAgICAgPExpbmsgaHJlZj1cIi9hYm91dFwiPlxuICAgICAgICAgIDxhPkFib3V0PC9hPlxuICAgICAgICA8L0xpbms+XG4gICAgICA8L2xpPlxuICAgICAgPGxpPlxuICAgICAgICA8TGluayBocmVmPVwiL2V4cGVyaW1lbnQvMDAxXCI+XG4gICAgICAgICAgPGE+MDAxIC0gU2V0dGluZyBVcCB3aXRoIE5leHQuanM8L2E+XG4gICAgICAgIDwvTGluaz5cbiAgICAgIDwvbGk+XG4gICAgICA8bGk+XG4gICAgICAgIDxMaW5rIGhyZWY9XCIvZXhwZXJpbWVudC8wMDJcIj5cbiAgICAgICAgICA8YT4wMDIgLSBXb3JraW5nIHdpdGggQVBJPC9hPlxuICAgICAgICA8L0xpbms+XG4gICAgICA8L2xpPlxuICAgIDwvdWw+XG4gIDwvTGF5b3V0PlxuKTtcbkluZGV4UGFnZS5nZXQgPSBhc3luYyBmdW5jdGlvbiAoKSB7XG4gIGNvbnN0IHJlcyA9IGF3YWl0IGZldGNoKFxuICAgIFwiaHR0cHM6Ly9hcGkub3BlbndlYXRoZXJtYXAub3JnL2RhdGEvMi41L3dlYXRoZXI/cT1adXJpY2gmYXBwaWQ9MDJmNDcxYzY2ODk2YTkyY2Y3NDk5NTQzMmZiYTllM2NcIlxuICApO1xuICBjb25zdCBkYXRhID0gYXdhaXQgcmVzLmpzb24oKTtcblxuICByZXR1cm4ge1xuICAgIHdlYXRoZXI6IGRhdGEud2VhdGhlcixcbiAgfTtcbn07XG5cbmV4cG9ydCBkZWZhdWx0IEluZGV4UGFnZTtcbiJdLCJzb3VyY2VSb290IjoiIn0=\n//# sourceURL=webpack-internal:///./pages/index.tsx\n");
/***/ })
})
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
var _default = {
key: 'D',
suffix: 'aug9',
positions: [{
frets: 'x54556',
fingers: '021334',
barres: 5
}, {
frets: 'x70576',
fingers: '030142'
}, {
frets: 'a9a9bx',
fingers: '213140',
barres: 9,
capo: true
}, {
frets: 'axabb0',
fingers: '102340'
}]
};
exports["default"] = _default;
|
export { default } from './UserInfoRequest.vue'
|
import React from 'react'
import { IframeContainer } from './elements'
const Vimeo = ({ data }) => {
const { videoId } = data
return (
<IframeContainer>
<iframe
src={`https://player.vimeo.com/video/${videoId}`}
width="640"
height="360"
frameborder="0"
title="Video presentation"
webkitallowfullscreen
mozallowfullscreen
allowfullscreen
/>
</IframeContainer>
)
}
export default Vimeo
|
import numpy as np
import torch
from src.preprocess import load_ct, preprocess_ct, crop_patches
from torch import nn
from torch.autograd import Variable
""""
Classification model from team gtr123
Code adapted from https://github.com/lfz/DSB2017
"""
config = {}
config['crop_size'] = [96, 96, 96]
config['scaleLim'] = [0.85, 1.15]
config['radiusLim'] = [6, 100]
config['stride'] = 4
config['detect_th'] = 0.05
config['conf_th'] = -1
config['nms_th'] = 0.05
config['filling_value'] = 160
config['startepoch'] = 20
config['lr_stage'] = np.array([50, 100, 140, 160])
config['lr'] = [0.01, 0.001, 0.0001, 0.00001]
config['miss_ratio'] = 1
config['miss_thresh'] = 0.03
config['anchors'] = [10, 30, 60]
class PostRes(nn.Module):
""" """
def __init__(self, n_in, n_out, stride=1):
super(PostRes, self).__init__()
self.conv1 = nn.Conv3d(n_in, n_out, kernel_size=3, stride=stride, padding=1)
self.bn1 = nn.BatchNorm3d(n_out)
self.relu = nn.ReLU(inplace=True)
self.conv2 = nn.Conv3d(n_out, n_out, kernel_size=3, padding=1)
self.bn2 = nn.BatchNorm3d(n_out)
if stride != 1 or n_out != n_in:
self.shortcut = nn.Sequential(
nn.Conv3d(n_in, n_out, kernel_size=1, stride=stride),
nn.BatchNorm3d(n_out))
else:
self.shortcut = None
def forward(self, x):
residual = x
if self.shortcut is not None:
residual = self.shortcut(x)
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
out += residual
out = self.relu(out)
return out
class Net(nn.Module):
""" """
def __init__(self):
super(Net, self).__init__()
# The first few layers consumes the most memory, so use simple
# convolution to save memory. Call these layers preBlock, i.e., before
# the residual blocks of later layers.
self.preBlock = nn.Sequential(
nn.Conv3d(1, 24, kernel_size=3, padding=1),
nn.BatchNorm3d(24),
nn.ReLU(inplace=True),
nn.Conv3d(24, 24, kernel_size=3, padding=1),
nn.BatchNorm3d(24),
nn.ReLU(inplace=True))
# 3 poolings, each pooling downsamples the feature map by a factor 2.
# 3 groups of blocks. The first block of each group has one pooling.
num_blocks_forw = [2, 2, 3, 3]
num_blocks_back = [3, 3]
self.featureNum_forw = [24, 32, 64, 64, 64]
self.featureNum_back = [128, 64, 64]
for i in range(len(num_blocks_forw)):
blocks = []
for j in range(num_blocks_forw[i]):
if j == 0:
blocks.append(PostRes(self.featureNum_forw[i], self.featureNum_forw[i + 1]))
else:
blocks.append(PostRes(self.featureNum_forw[i + 1], self.featureNum_forw[i + 1]))
setattr(self, 'forw' + str(i + 1), nn.Sequential(*blocks))
for i in range(len(num_blocks_back)):
blocks = []
for j in range(num_blocks_back[i]):
if j == 0:
if i == 0:
addition = 3
else:
addition = 0
blocks.append(PostRes(self.featureNum_back[i + 1] + self.featureNum_forw[i + 2] + addition,
self.featureNum_back[i]))
else:
blocks.append(PostRes(self.featureNum_back[i], self.featureNum_back[i]))
setattr(self, 'back' + str(i + 2), nn.Sequential(*blocks))
self.maxpool1 = nn.MaxPool3d(kernel_size=2, stride=2, return_indices=True)
self.maxpool2 = nn.MaxPool3d(kernel_size=2, stride=2, return_indices=True)
self.maxpool3 = nn.MaxPool3d(kernel_size=2, stride=2, return_indices=True)
self.maxpool4 = nn.MaxPool3d(kernel_size=2, stride=2, return_indices=True)
self.unmaxpool1 = nn.MaxUnpool3d(kernel_size=2, stride=2)
self.unmaxpool2 = nn.MaxUnpool3d(kernel_size=2, stride=2)
self.path1 = nn.Sequential(
nn.ConvTranspose3d(64, 64, kernel_size=2, stride=2),
nn.BatchNorm3d(64),
nn.ReLU(inplace=True))
self.path2 = nn.Sequential(
nn.ConvTranspose3d(64, 64, kernel_size=2, stride=2),
nn.BatchNorm3d(64),
nn.ReLU(inplace=True))
self.drop = nn.Dropout3d(p=0.2, inplace=False)
self.output = nn.Sequential(nn.Conv3d(self.featureNum_back[0], 64, kernel_size=1),
nn.ReLU(),
# nn.Dropout3d(p = 0.3),
nn.Conv3d(64, 5 * len(config['anchors']), kernel_size=1))
def forward(self, x, coord):
"""
Args:
x:
coord:
Returns:
"""
out = self.preBlock(x) # 16
out_pool, indices0 = self.maxpool1(out)
out1 = self.forw1(out_pool) # 32
out1_pool, indices1 = self.maxpool2(out1)
out2 = self.forw2(out1_pool) # 64
# out2 = self.drop(out2)
out2_pool, indices2 = self.maxpool3(out2)
out3 = self.forw3(out2_pool) # 96
out3_pool, indices3 = self.maxpool4(out3)
out4 = self.forw4(out3_pool) # 96
# out4 = self.drop(out4)
rev3 = self.path1(out4)
comb3 = self.back3(torch.cat((rev3, out3), 1)) # 96+96
# comb3 = self.drop(comb3)
rev2 = self.path2(comb3)
feat = self.back2(torch.cat((rev2, out2, coord), 1)) # 64+64
comb2 = self.drop(feat)
out = self.output(comb2)
size = out.size()
out = out.view(out.size(0), out.size(1), -1)
# out = out.transpose(1, 4).transpose(1, 2).transpose(2, 3).contiguous()
out = out.transpose(1, 2).contiguous().view(size[0], size[2], size[3], size[4], len(config['anchors']), 5)
# out = out.view(-1, 5)
return feat, out
class CaseNet(nn.Module):
"""The classification Net from the gtr123 team - part of the Winning algorithm for DSB2017"""
def __init__(self):
super(CaseNet, self).__init__()
self.NoduleNet = Net()
self.fc1 = nn.Linear(128, 64)
self.fc2 = nn.Linear(64, 1)
self.pool = nn.MaxPool3d(kernel_size=2)
self.dropout = nn.Dropout(0.5)
self.baseline = nn.Parameter(torch.Tensor([-30.0]).float())
self.Relu = nn.ReLU()
def forward(self, xlist, coordlist):
"""
Args:
xlist: Image of size n x k x 1x 96 x 96 x 96
coordlist: Coordinates of size n x k x 3 x 24 x 24 x 24
Returns:
"""
xsize = xlist.size()
corrdsize = coordlist.size()
print(xsize)
# xlist = xlist.view(-1,xsize[2],xsize[3],xsize[4],xsize[5])
# coordlist = coordlist.view(-1,corrdsize[2],corrdsize[3],corrdsize[4],corrdsize[5])
noduleFeat, nodulePred = self.NoduleNet(xlist, coordlist)
nodulePred = nodulePred.contiguous().view(corrdsize[0], corrdsize[1], -1)
featshape = noduleFeat.size() # nk x 128 x 24 x 24 x24
centerFeat = self.pool(noduleFeat[:, :, featshape[2] // 2 - 1:featshape[2] // 2 + 1,
featshape[3] // 2 - 1:featshape[3] // 2 + 1,
featshape[4] // 2 - 1:featshape[4] // 2 + 1])
centerFeat = centerFeat[:, :, 0, 0, 0]
out = self.dropout(centerFeat)
out = self.Relu(self.fc1(out))
out = torch.sigmoid(self.fc2(out))
out = out.view(xsize[0], xsize[1])
base_prob = torch.sigmoid(self.baseline)
casePred = 1 - torch.prod(1 - out, dim=1) * (1 - base_prob.expand(out.size()[0]))
return nodulePred, casePred, out
def predict(ct_path, nodule_list, model_path="src/algorithms/classify/assets/gtr123_model.ckpt"):
"""
Args:
ct_path (str): path to a MetaImage or DICOM data.
nodule_list: List of nodules
model_path: Path to the torch model (Default value = "src/algorithms/classify/assets/gtr123_model.ckpt")
Returns:
List of nodules, and probabilities
"""
if not nodule_list:
return []
casenet = CaseNet()
casenet.load_state_dict(torch.load(model_path))
casenet.eval()
if torch.cuda.is_available():
casenet = torch.nn.DataParallel(casenet).cuda()
# else:
# casenet = torch.nn.parallel.DistributedDataParallel(casenet)
preprocess = preprocess_ct.PreprocessCT(clip_lower=-1200., clip_upper=600., spacing=1., order=1,
min_max_normalize=True, scale=255, dtype='uint8')
ct_array, meta = preprocess(*load_ct.load_ct(ct_path))
patches = crop_patches.patches_from_ct(ct_array, meta, config['crop_size'], nodule_list,
stride=config['stride'], pad_value=config['filling_value'])
results = []
for nodule, (cropped_image, coords) in zip(nodule_list, patches):
cropped_image = Variable(torch.from_numpy(cropped_image[np.newaxis, np.newaxis]).float())
cropped_image.volatile = True
coords = Variable(torch.from_numpy(coords[np.newaxis]).float())
coords.volatile = True
_, pred, _ = casenet(cropped_image, coords)
results.append(
{"x": nodule["x"], "y": nodule["y"], "z": nodule["z"], "p_concerning": float(pred.data.cpu().numpy())})
return results
|
// Copyright (c) 2012 Ecma International. All rights reserved.
// Ecma International makes this code available under the terms and conditions set
// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
// "Use Terms"). Any redistribution of this code must retain the above
// copyright and this notice and otherwise comply with the Use Terms.
/*---
es5id: 15.4.4.15-8-b-i-14
description: >
Array.prototype.lastIndexOf - element to be retrieved is own
accessor property that overrides an inherited accessor property on
an Array-like object
includes: [runTestCase.js]
---*/
function testcase() {
var obj = { length: 1 };
try {
Object.defineProperty(Object.prototype, "0", {
get: function () {
return false;
},
configurable: true
});
Object.defineProperty(obj, "0", {
get: function () {
return true;
},
configurable: true
});
return 0 === Array.prototype.lastIndexOf.call(obj, true);
} finally {
delete Object.prototype[0];
}
}
runTestCase(testcase);
|
/**
* 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.
*
* @generated SignedSource<<316fb96ce91d0da571a5ab5e0d8308ef>>
* @flow
* @lightSyntaxTransform
* @nogrep
*/
/* eslint-disable */
'use strict';
/*::
import type { Fragment, ReaderFragment } from 'relay-runtime';
import type { FragmentType } from "relay-runtime";
declare export opaque type RelayMockPayloadGeneratorTest4Fragment$fragmentType: FragmentType;
export type RelayMockPayloadGeneratorTest4Fragment$data = {|
+emailAddresses: ?$ReadOnlyArray<?string>,
+name: ?string,
+username: ?string,
+$fragmentType: RelayMockPayloadGeneratorTest4Fragment$fragmentType,
|};
export type RelayMockPayloadGeneratorTest4Fragment$key = {
+$data?: RelayMockPayloadGeneratorTest4Fragment$data,
+$fragmentSpreads: RelayMockPayloadGeneratorTest4Fragment$fragmentType,
...
};
*/
var node/*: ReaderFragment*/ = {
"argumentDefinitions": [],
"kind": "Fragment",
"metadata": null,
"name": "RelayMockPayloadGeneratorTest4Fragment",
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "name",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "username",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "emailAddresses",
"storageKey": null
}
],
"type": "User",
"abstractKey": null
};
if (__DEV__) {
(node/*: any*/).hash = "c583c180a55fea0b0b4787ba9adc3642";
}
module.exports = ((node/*: any*/)/*: Fragment<
RelayMockPayloadGeneratorTest4Fragment$fragmentType,
RelayMockPayloadGeneratorTest4Fragment$data,
>*/);
|
import time
from queue import Queue
from threading import Thread
db_dir_id = []
def get_max_dir_id():
return max(db_dir_id) if db_dir_id else 0
class DirIdQueue(Thread):
"""
自动创建队列,拿到数据库最大的id,从而实现,既是自增id,又可以方便批量插入数据,但是能简单的获取到 id这一数据;假如,id需要马上用的情况,比如加入到缓存
"""
def __init__(self):
super(DirIdQueue, self).__init__()
self.dir_id_queue = Queue(maxsize=-1)
self.lock = False
self.max_id = -1
def get_lock(self):
if self.lock:
return False
else:
self.lock = True
return True
def free_lock(self):
if self.lock:
self.lock = False
return True
def put(self):
if self.lock:
return False
else:
self.get_lock()
if self.max_id == -1:
# 2020/11/5 如果还是初始值就去查数据库取max_id
max_id = get_max_dir_id()
if isinstance(max_id, int):
pass
else:
return False
for i in range(max_id+1, max_id+5001):
self.dir_id_queue.put(i)
self.max_id = max_id+5000
self.free_lock()
return True
else:
size = self.dir_id_queue.qsize()
# 2020/11/16 这里控制size 大小
if size <= 5000:
max_id_in_q = self.max_id
new_max_id_in_q = max_id_in_q + 5001
# 2020/11/16 put in 5000 id
for i in range(max_id_in_q+1, new_max_id_in_q):
self.dir_id_queue.put(i)
self.max_id = new_max_id_in_q-1
self.free_lock()
return True
else:
return True
def run(self) -> None:
while True:
if self.dir_id_queue.qsize() <= 5000:
self.put()
else:
time.sleep(0.5)
class IdConsumer(Thread):
def __init__(self, que: Queue):
self.queue = que
self.last = None
super(IdConsumer, self).__init__()
def consume(self):
qsize = self.queue.qsize()
if qsize:
dir_id = self.queue.get()
if self.last is not None:
if dir_id - self.last == 1:
pass
else:
print('last: {} dir_id: {}'.format(self.last, dir_id))
print('error')
raise Exception
pass
self.last = dir_id
else:
time.sleep(1)
print('consume qsize: {}'.format(qsize))
def run(self) -> None:
while True:
self.consume()
if __name__ == '__main__':
dq = DirIdQueue()
dq.start()
ic = IdConsumer(dq.dir_id_queue)
ic.start()
|
class Units(object):
def __init__(self):
import numpy as np
self._units = units = {}
# lengths: conversion to m
units['m'] = units['meter'] = units['meters'] = ('length', 1.0)
units['mm'] = units['millimeter'] = units['millimeters'] = ('length', units['m'][1] / 1000)
units['cm'] = units['centimeter'] = units['centimeters'] = ('length', units['m'][1] / 100)
units['in'] = units['inch'] = units['inches'] = ('length', 0.0254)
units['ft'] = units['foot'] = units['feet'] = ('length', 0.3048)
units['fathoms'] = ('length', 1.8288)
units['cubits'] = ('length', 0.4572)
# weights: conversion to kg
units['kg'] = units['kilograms'] = ('weight', 1.0)
units['g'] = units['grams'] = ('weight', units['kg'][1] / 1000)
units['lbs'] = units['pounds'] = units['lb'] = ('weight', units['kg'][1] / 2.20462)
units['stone'] = ('weight', units['kg'][1] / 0.157473)
# angles: conversion to degrees
units['deg'] = units['degrees'] = ('angle', 1.0)
units['rad'] = units['radians'] = ('angle', units['deg'][1] * 180 / np.pi)
# time: conversion to seconds
units['sec'] = units['second'] = units['seconds'] = ('time', 1.0)
units['min'] = units['minute'] = units['minutes'] = ('time', units['sec'][1] * 60)
units['hr'] = units['hour'] = units['hours'] = ('time', 60 * units['min'][1])
units['day'] = units['days'] = ('time', units['hour'][1] * 24)
units['yr'] = units['year'] = units['years'] = ('time', units['day'][1] * 365.242)
units['hours_per_week'] = ('time_rate', 1.0)
self._default_units = {
'metric': {'length': 'cm', 'weight': 'kg', 'angle': 'deg', 'time': 'yr', 'time_rate': 'hours_per_week'},
'united_states': {'length': 'in', 'weight': 'lb', 'angle': 'deg', 'time': 'yr', 'time_rate': 'hours_per_week'},
}
@property
def all_units(self):
'''
Return a list of all supported units.
'''
return self._units.keys()
@property
def all_units_classes(self):
'''
Return a list of all supported units classes, e.g.
'length', 'weight', 'angle, 'time', 'time_rate'.
'''
return list(set([item[0] for item in self._units.itervalues()]))
def units_class(self, units):
'''
Returns 'length', 'weight', 'angle', 'time', or 'time_rate'.
>>> units_class('cm')
'length'
'''
if units is None or units == '':
return None
return self._units[units][0]
def units_in_class(self, uclass):
'''
Return a list of all units in uclass, where uclass is e.g.
length', 'weight', 'angle, 'time', 'time_rate'.
'''
return [key for key, (uclass_0, _) in self._units.iteritems() if uclass_0 == uclass]
@property
def lengths(self):
'''
List of all supported lengths.
'''
return self.units_in_class('length')
@property
def weights(self):
'''
List of all supported weights.
'''
return self.units_in_class('weight')
@property
def angles(self):
'''
List of all supported angles.
'''
return self.units_in_class('angle')
@property
def times(self):
'''
List of all supported times.
'''
return self.units_in_class('time')
@property
def time_rates(self):
'''
List of all supported time rates.
'''
return self.units_in_class('time_rate')
def default_units(self, unit_system='metric', exceptions={}):
'''
Get the default unit for a given unit system. unit_class is
'length', 'weight', 'angle', or 'time'. unit_system is
either 'metric' or 'united_states'.
'''
return dict(self._default_units[unit_system].items() + exceptions.items())
def raw(self, units):
'''
Returns a raw units conversion factor. Try not to use this.
Use factor() or convert() instead.
'''
return self._units[units][1]
def factor(self, from_units, to_units, units_class=None): # FIXME pylint: disable=redefined-outer-name
'''
Return a conversion factor:
>>> value_in_cm = 25
>>> value_in_cm * factor('cm', 'mm')
250
class: If specified, the class of the units must match the class provided.
'''
if (from_units is None or not len(from_units)) and (to_units is None or not len(to_units)): # pylint: disable=len-as-condition
return 1.0
if from_units == to_units:
return 1.0
if self._units[from_units][0] != self._units[to_units][0]:
raise ValueError("Can't convert between apples and oranges (%s and %s)" % (from_units, to_units))
if units_class and self._units[from_units][0] != units_class:
raise ValueError("Units class must be %s, but got %s" % (units_class, self._units[from_units][0]))
return self._units[from_units][1] / self._units[to_units][1]
def convert(self, value, from_units, to_units, units_class=None): # FIXME pylint: disable=redefined-outer-name
'''
Convert a number from one unit to another.
class: If specified, the class of the units must match the class provided.
Returns a tuple with the converted value and the units.
>>> value_cm = 25
>>> value, units = convert(value_cm, 'cm', 'mm')
>>> value
250
>>> units
'mm'
'''
# Get factor first so we return errors for apples and oranges,
# even when value is None
factor = self.factor(from_units, to_units, units_class=units_class) # FIXME pylint: disable=redefined-outer-name
if value is None:
return None, None
return value * factor, to_units
def convert_list(self, a_list, from_units, to_units):
'''
Convenience helper to convert a list of numbers from one unit to another.
Unlike convert(), does not return a tuple.
>>> convert_list([10, 20, 30], 'cm', 'mm')
[100, 200, 300]
'''
factor = self.factor(from_units, to_units) # FIXME pylint: disable=redefined-outer-name
return map(lambda x: factor * x, a_list)
def convert_to_default(self, value, from_units, defaults):
'''
Convert a number from the given unit to a default for
the given unit system.
Returns a tuple with the converted value and the units.
>>> value_cm = 100
>>> convert_to_default(value_cm, 'cm', {'length': 'in', 'weight': 'lb', 'angle': 'deg', 'time': 'yr'})
(39.3701, 'in')
'''
units_class = self.units_class(from_units) # FIXME pylint: disable=redefined-outer-name
if units_class:
to_units = defaults[units_class]
return self.convert(value, from_units, to_units)
else:
return value, from_units
def convert_to_system_default(self, value, from_units, to_unit_system='metric'):
'''
Convert a number from the given unit to a default for
the given unit system.
Returns a tuple with the converted value and the units.
>>> value_cm = 100
>>> convert_to_system_default(value_cm, 'cm', 'united_states')
(39.3701, 'in')
'''
return self.convert_to_default(value, from_units, self.default_units(to_unit_system))
def prettify(self, value, units, precision=None):
'''
Take a value, and units, and return rounded values in the
default metric and United States units.
The default precision values vary per unit. Specifying an
integer for `precision` will override those defaults.
>>> prettify(182.13992, 'cm'),
(182.0, 'cm', 71.75, 'in')
>>> prettify(182.13992, 'cm', precision=1)
(182.1, 'cm', 71.7, 'in')
>>> prettify(182.13992, 'cm', precision=2)
(182.14, 'cm', 71.71, 'in')
'''
def round_value(value, units):
from blmath.numerics import round_to
if precision is None:
nearest = {'cm': 0.5, 'in': 0.25, 'kg': 0.5, 'lb': 1.0, 'yr': 1.0}.get(units, 0.1)
else:
# Work around weird floating point rounding issues
nearest = 1.0 / 10 ** precision
return round_to(value, nearest), units
return round_value(*self.convert_to_system_default(value, units)) + round_value(*self.convert_to_system_default(value, units, 'united_states'))
_units = Units()
all_units = _units.all_units
all_units_classes = _units.all_units_classes
units_class = _units.units_class
units_in_class = _units.units_in_class
lengths = _units.lengths
weights = _units.weights
angles = _units.angles
times = _units.times
time_rates = _units.time_rates
default_units = _units.default_units
convert_to_default = _units.convert_to_default
raw = _units.raw
factor = _units.factor
convert = _units.convert
convert_list = _units.convert_list
convert_to_system_default = _units.convert_to_system_default
prettify = _units.prettify
|
/*
* Scroll to the top
*/
$(window).bind("scroll",display);
function display () {
if($(document).scrollTop()>300) {
//$("#top").show();
$("#top").fadeIn(300);
}else {
//$("#top").hide();
$("#top").fadeOut(300);
}
}
/*
* Baidu analytics
*/
var _hmt = _hmt || [];
(function () {
var hm = document.createElement("script");
hm.src = "//hm.baidu.com/hm.js?5b31ffbbdc6cff18727f3adf75a03777";
var s = document.getElementsByTagName("script")[0];
s.parentNode.insertBefore(hm, s);
})();
/*
* Google analytics
*/
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-82494501-1', 'auto');
ga('send', 'pageview');
|
//Grab the required packages
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var bcrypt = require("bcrypt-nodejs");
// Defining the Schema
var PollSchema = new Schema({
name : {type: String, required:true, index : {unique:true}},
description : String,
eventID : String,
pollEndTime : Date,
createdOn : Date,
minParticipants : Number,
isSinglePage : Boolean,
active : Boolean
});
//Return the model
module.exports = mongoose.model('Poll',PollSchema);
|