code
stringlengths 2
1.05M
|
---|
// @flow
import type {Action} from '../actions/types';
const initialState = {
firstMonth: -1,
dates: []
};
export type State = {
firstMonth: number;
dates: Array<Array<number>>;
};
export default function calendar(state: State = initialState, action: Action) : State {
switch (action.type) {
case 'CALENDAR_UPDATE':
return action.data;
default:
return state;
}
}
|
import {Entity} from 'aframe-react';
import React from 'react';
export default class Seat extends React.Component {
constructor(props) {
super(props);
this.state = {
opacity: 1,
};
}
render() {
return (
<Entity position={this.props.seatPos} >
<Entity visible={ true }
material={{ color: this.props.buttonColor, transparent: true, shader: 'flat', opacity: this.props.Opacity }}
geometry={{ primitive: "plane", width: 0.2, height: 0.1 }}
id={this.props.componentId}
opacity={ this.props.Opacity }
onClick={ this.props.seatAnimation }
/>
</Entity>
);
}}
|
var sample5__unittest_8cc =
[
[ "QuickTest", "class_quick_test.html", "class_quick_test" ],
[ "IntegerFunctionTest", "class_integer_function_test.html", null ],
[ "QueueTest", "class_queue_test.html", "class_queue_test" ],
[ "TEST_F", "sample5__unittest_8cc.html#ad7679328025ef6d95ee2f45d5604aa89", null ],
[ "TEST_F", "sample5__unittest_8cc.html#ab941323e5a68b9aa8125cb81f5ff3d7c", null ],
[ "TEST_F", "sample5__unittest_8cc.html#ac3e547171299114162b1e8cd5946eb5c", null ],
[ "TEST_F", "sample5__unittest_8cc.html#a0149784588d6ea2a29e0f50a05ee198e", null ]
]; |
(function() {
'use strict';
angular.module('civic.events.genes', ['ui.router']);
angular.module('civic.events.assertions', ['ui.router']);
angular.module('civic.events.variants', ['ui.router']);
angular.module('civic.events.variantGroups', ['ui.router']);
angular.module('civic.events.evidence', ['ui.router']);
angular.module('civic.events.common', []);
angular.module('civic.events')
.config(EventsViewConfig);
// @ngInject
function EventsViewConfig($stateProvider) {
$stateProvider
.state('events', {
abstract: true,
url: '/events',
template: '<ui-view id="events-view"></ui-view>',
onExit: /* @ngInject */ function($deepStateRedirect) {
$deepStateRedirect.reset();
}
});
}
})();
|
// flow-typed signature: ec6537b935587fad87c821c01929901f
// flow-typed version: <<STUB>>/react-test-renderer_v^15.6.1/flow_v0.47.0
/**
* This is an autogenerated libdef stub for:
*
* 'react-test-renderer'
*
* Fill this stub out by replacing all the `any` types.
*
* Once filled out, we encourage you to share your work with the
* community by sending a pull request to:
* https://github.com/flowtype/flow-typed
*/
declare module 'react-test-renderer' {
declare module.exports: any;
}
/**
* We include stubs for each file inside this npm package in case you need to
* require those files directly. Feel free to delete any files that aren't
* needed.
*/
declare module 'react-test-renderer/lib/accumulate' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/accumulateInto' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/adler32' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/CallbackQueue' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/canDefineProperty' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/checkReactTypeSpec' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/deprecated' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/EventConstants' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/EventPluginHub' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/EventPluginRegistry' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/EventPluginUtils' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/EventPropagators' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/flattenChildren' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/forEachAccumulated' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/getHostComponentFromComposite' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/getIteratorFn' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/instantiateReactComponent' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/isTextInputElement' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/KeyEscapeUtils' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/lowPriorityWarning' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/PluginModuleType' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/PooledClass' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/ReactChildFiber' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/ReactChildReconciler' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/ReactComponentEnvironment' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/ReactCompositeComponent' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/ReactCoroutine' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/ReactDebugTool' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/ReactDefaultBatchingStrategy' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/ReactElementSymbol' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/ReactEmptyComponent' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/ReactErrorUtils' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/ReactEventEmitterMixin' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/ReactFeatureFlags' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/ReactFiber' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/ReactFiberBeginWork' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/ReactFiberCommitWork' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/ReactFiberCompleteWork' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/ReactFiberReconciler' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/ReactFiberRoot' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/ReactFiberScheduler' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/ReactFiberUpdateQueue' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/ReactHostComponent' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/ReactHostOperationHistoryHook' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/ReactInstanceMap' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/ReactInstanceType' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/ReactInstrumentation' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/ReactInvalidSetStateWarningHook' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/ReactMultiChild' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/ReactMultiChildUpdateTypes' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/ReactNodeTypes' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/ReactOwner' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/ReactPerf' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/ReactPriorityLevel' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/reactProdInvariant' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/ReactPropTypeLocationNames' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/ReactPropTypeLocations' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/ReactPropTypesSecret' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/ReactReconciler' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/ReactRef' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/ReactReifiedYield' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/ReactShallowRenderer' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/ReactSimpleEmptyComponent' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/ReactSyntheticEventType' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/ReactTestEmptyComponent' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/ReactTestMount' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/ReactTestReconcileTransaction' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/ReactTestRenderer' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/ReactTestTextComponent' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/ReactTypeOfWork' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/ReactTypes' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/ReactUpdateQueue' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/ReactUpdates' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/ReactVersion' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/ResponderEventPlugin' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/ResponderSyntheticEvent' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/ResponderTouchHistoryStore' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/accumulate' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/accumulateInto' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/adler32' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ARIADOMPropertyConfig' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/AutoFocusUtils' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/BeforeInputEventPlugin' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/CallbackQueue' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/canDefineProperty' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ChangeEventPlugin' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/checkReactTypeSpec' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/createMicrosoftUnsafeLocalFunction' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/CSSProperty' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/CSSPropertyOperations' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/Danger' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/dangerousStyleValue' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/DefaultEventPluginOrder' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/deprecated' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/DOMChildrenOperations' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/DOMLazyTree' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/DOMNamespaces' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/DOMProperty' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/DOMPropertyOperations' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/EnterLeaveEventPlugin' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/escapeTextContentForBrowser' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/EventConstants' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/EventPluginHub' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/EventPluginRegistry' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/EventPluginUtils' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/EventPropagators' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/FallbackCompositionState' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/findDOMNode' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/flattenChildren' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/forEachAccumulated' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/getEventCharCode' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/getEventKey' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/getEventModifierState' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/getEventTarget' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/getHostComponentFromComposite' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/getIteratorFn' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/getNodeForCharacterOffset' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/getTextContentAccessor' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/getVendorPrefixedEventName' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/HTMLDOMPropertyConfig' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/inputValueTracking' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/instantiateReactComponent' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/isEventSupported' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/isTextInputElement' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/KeyEscapeUtils' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/LinkedValueUtils' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/lowPriorityWarning' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/PluginModuleType' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/PooledClass' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/quoteAttributeValueForBrowser' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactBrowserEventEmitter' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactChildFiber' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactChildReconciler' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactComponentBrowserEnvironment' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactComponentEnvironment' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactCompositeComponent' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactCoroutine' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactDebugTool' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactDefaultBatchingStrategy' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactDefaultInjection' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactDOM' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactDOMComponent' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactDOMComponentFlags' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactDOMComponentTree' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactDOMContainerInfo' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactDOMEmptyComponent' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactDOMFeatureFlags' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactDOMFiber' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactDOMIDOperations' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactDOMInput' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactDOMInvalidARIAHook' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactDOMNullInputValuePropHook' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactDOMOption' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactDOMSelect' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactDOMSelection' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactDOMServer' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactDOMTextarea' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactDOMTextComponent' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactDOMTreeTraversal' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactDOMUnknownPropertyHook' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactElementSymbol' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactEmptyComponent' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactErrorUtils' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactEventEmitterMixin' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactEventListener' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactFeatureFlags' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactFiber' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactFiberBeginWork' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactFiberCommitWork' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactFiberCompleteWork' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactFiberReconciler' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactFiberRoot' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactFiberScheduler' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactFiberUpdateQueue' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactHostComponent' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactHostOperationHistoryHook' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactInjection' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactInputSelection' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactInstanceMap' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactInstanceType' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactInstrumentation' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactInvalidSetStateWarningHook' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactMarkupChecksum' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactMount' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactMultiChild' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactMultiChildUpdateTypes' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactNodeTypes' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactOwner' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactPerf' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactPriorityLevel' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/reactProdInvariant' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactPropTypeLocationNames' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactPropTypeLocations' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactPropTypesSecret' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactReconciler' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactReconcileTransaction' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactRef' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactReifiedYield' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactServerBatchingStrategy' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactServerRendering' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactServerRenderingTransaction' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactServerUpdateQueue' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactShallowRenderer' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactSimpleEmptyComponent' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactSyntheticEventType' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactTestEmptyComponent' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactTestMount' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactTestReconcileTransaction' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactTestRenderer' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactTestTextComponent' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactTypeOfWork' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactTypes' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactUpdateQueue' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactUpdates' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ReactVersion' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/renderSubtreeIntoContainer' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ResponderEventPlugin' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ResponderSyntheticEvent' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ResponderTouchHistoryStore' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/SelectEventPlugin' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/setInnerHTML' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/setTextContent' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/shouldUpdateReactComponent' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/SimpleEventPlugin' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/SVGDOMPropertyConfig' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/SyntheticAnimationEvent' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/SyntheticClipboardEvent' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/SyntheticCompositionEvent' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/SyntheticDragEvent' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/SyntheticEvent' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/SyntheticFocusEvent' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/SyntheticInputEvent' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/SyntheticKeyboardEvent' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/SyntheticMouseEvent' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/SyntheticTouchEvent' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/SyntheticTransitionEvent' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/SyntheticUIEvent' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/SyntheticWheelEvent' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/TapEventPlugin' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/TouchHistoryMath' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/Transaction' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/traverseAllChildren' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/validateDOMNesting' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shallow/ViewportMetrics' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/shouldUpdateReactComponent' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/SyntheticEvent' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/TouchHistoryMath' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/Transaction' {
declare module.exports: any;
}
declare module 'react-test-renderer/lib/traverseAllChildren' {
declare module.exports: any;
}
declare module 'react-test-renderer/shallow' {
declare module.exports: any;
}
// Filename aliases
declare module 'react-test-renderer/index' {
declare module.exports: $Exports<'react-test-renderer'>;
}
declare module 'react-test-renderer/index.js' {
declare module.exports: $Exports<'react-test-renderer'>;
}
declare module 'react-test-renderer/lib/accumulate.js' {
declare module.exports: $Exports<'react-test-renderer/lib/accumulate'>;
}
declare module 'react-test-renderer/lib/accumulateInto.js' {
declare module.exports: $Exports<'react-test-renderer/lib/accumulateInto'>;
}
declare module 'react-test-renderer/lib/adler32.js' {
declare module.exports: $Exports<'react-test-renderer/lib/adler32'>;
}
declare module 'react-test-renderer/lib/CallbackQueue.js' {
declare module.exports: $Exports<'react-test-renderer/lib/CallbackQueue'>;
}
declare module 'react-test-renderer/lib/canDefineProperty.js' {
declare module.exports: $Exports<'react-test-renderer/lib/canDefineProperty'>;
}
declare module 'react-test-renderer/lib/checkReactTypeSpec.js' {
declare module.exports: $Exports<'react-test-renderer/lib/checkReactTypeSpec'>;
}
declare module 'react-test-renderer/lib/deprecated.js' {
declare module.exports: $Exports<'react-test-renderer/lib/deprecated'>;
}
declare module 'react-test-renderer/lib/EventConstants.js' {
declare module.exports: $Exports<'react-test-renderer/lib/EventConstants'>;
}
declare module 'react-test-renderer/lib/EventPluginHub.js' {
declare module.exports: $Exports<'react-test-renderer/lib/EventPluginHub'>;
}
declare module 'react-test-renderer/lib/EventPluginRegistry.js' {
declare module.exports: $Exports<'react-test-renderer/lib/EventPluginRegistry'>;
}
declare module 'react-test-renderer/lib/EventPluginUtils.js' {
declare module.exports: $Exports<'react-test-renderer/lib/EventPluginUtils'>;
}
declare module 'react-test-renderer/lib/EventPropagators.js' {
declare module.exports: $Exports<'react-test-renderer/lib/EventPropagators'>;
}
declare module 'react-test-renderer/lib/flattenChildren.js' {
declare module.exports: $Exports<'react-test-renderer/lib/flattenChildren'>;
}
declare module 'react-test-renderer/lib/forEachAccumulated.js' {
declare module.exports: $Exports<'react-test-renderer/lib/forEachAccumulated'>;
}
declare module 'react-test-renderer/lib/getHostComponentFromComposite.js' {
declare module.exports: $Exports<'react-test-renderer/lib/getHostComponentFromComposite'>;
}
declare module 'react-test-renderer/lib/getIteratorFn.js' {
declare module.exports: $Exports<'react-test-renderer/lib/getIteratorFn'>;
}
declare module 'react-test-renderer/lib/instantiateReactComponent.js' {
declare module.exports: $Exports<'react-test-renderer/lib/instantiateReactComponent'>;
}
declare module 'react-test-renderer/lib/isTextInputElement.js' {
declare module.exports: $Exports<'react-test-renderer/lib/isTextInputElement'>;
}
declare module 'react-test-renderer/lib/KeyEscapeUtils.js' {
declare module.exports: $Exports<'react-test-renderer/lib/KeyEscapeUtils'>;
}
declare module 'react-test-renderer/lib/lowPriorityWarning.js' {
declare module.exports: $Exports<'react-test-renderer/lib/lowPriorityWarning'>;
}
declare module 'react-test-renderer/lib/PluginModuleType.js' {
declare module.exports: $Exports<'react-test-renderer/lib/PluginModuleType'>;
}
declare module 'react-test-renderer/lib/PooledClass.js' {
declare module.exports: $Exports<'react-test-renderer/lib/PooledClass'>;
}
declare module 'react-test-renderer/lib/ReactChildFiber.js' {
declare module.exports: $Exports<'react-test-renderer/lib/ReactChildFiber'>;
}
declare module 'react-test-renderer/lib/ReactChildReconciler.js' {
declare module.exports: $Exports<'react-test-renderer/lib/ReactChildReconciler'>;
}
declare module 'react-test-renderer/lib/ReactComponentEnvironment.js' {
declare module.exports: $Exports<'react-test-renderer/lib/ReactComponentEnvironment'>;
}
declare module 'react-test-renderer/lib/ReactCompositeComponent.js' {
declare module.exports: $Exports<'react-test-renderer/lib/ReactCompositeComponent'>;
}
declare module 'react-test-renderer/lib/ReactCoroutine.js' {
declare module.exports: $Exports<'react-test-renderer/lib/ReactCoroutine'>;
}
declare module 'react-test-renderer/lib/ReactDebugTool.js' {
declare module.exports: $Exports<'react-test-renderer/lib/ReactDebugTool'>;
}
declare module 'react-test-renderer/lib/ReactDefaultBatchingStrategy.js' {
declare module.exports: $Exports<'react-test-renderer/lib/ReactDefaultBatchingStrategy'>;
}
declare module 'react-test-renderer/lib/ReactElementSymbol.js' {
declare module.exports: $Exports<'react-test-renderer/lib/ReactElementSymbol'>;
}
declare module 'react-test-renderer/lib/ReactEmptyComponent.js' {
declare module.exports: $Exports<'react-test-renderer/lib/ReactEmptyComponent'>;
}
declare module 'react-test-renderer/lib/ReactErrorUtils.js' {
declare module.exports: $Exports<'react-test-renderer/lib/ReactErrorUtils'>;
}
declare module 'react-test-renderer/lib/ReactEventEmitterMixin.js' {
declare module.exports: $Exports<'react-test-renderer/lib/ReactEventEmitterMixin'>;
}
declare module 'react-test-renderer/lib/ReactFeatureFlags.js' {
declare module.exports: $Exports<'react-test-renderer/lib/ReactFeatureFlags'>;
}
declare module 'react-test-renderer/lib/ReactFiber.js' {
declare module.exports: $Exports<'react-test-renderer/lib/ReactFiber'>;
}
declare module 'react-test-renderer/lib/ReactFiberBeginWork.js' {
declare module.exports: $Exports<'react-test-renderer/lib/ReactFiberBeginWork'>;
}
declare module 'react-test-renderer/lib/ReactFiberCommitWork.js' {
declare module.exports: $Exports<'react-test-renderer/lib/ReactFiberCommitWork'>;
}
declare module 'react-test-renderer/lib/ReactFiberCompleteWork.js' {
declare module.exports: $Exports<'react-test-renderer/lib/ReactFiberCompleteWork'>;
}
declare module 'react-test-renderer/lib/ReactFiberReconciler.js' {
declare module.exports: $Exports<'react-test-renderer/lib/ReactFiberReconciler'>;
}
declare module 'react-test-renderer/lib/ReactFiberRoot.js' {
declare module.exports: $Exports<'react-test-renderer/lib/ReactFiberRoot'>;
}
declare module 'react-test-renderer/lib/ReactFiberScheduler.js' {
declare module.exports: $Exports<'react-test-renderer/lib/ReactFiberScheduler'>;
}
declare module 'react-test-renderer/lib/ReactFiberUpdateQueue.js' {
declare module.exports: $Exports<'react-test-renderer/lib/ReactFiberUpdateQueue'>;
}
declare module 'react-test-renderer/lib/ReactHostComponent.js' {
declare module.exports: $Exports<'react-test-renderer/lib/ReactHostComponent'>;
}
declare module 'react-test-renderer/lib/ReactHostOperationHistoryHook.js' {
declare module.exports: $Exports<'react-test-renderer/lib/ReactHostOperationHistoryHook'>;
}
declare module 'react-test-renderer/lib/ReactInstanceMap.js' {
declare module.exports: $Exports<'react-test-renderer/lib/ReactInstanceMap'>;
}
declare module 'react-test-renderer/lib/ReactInstanceType.js' {
declare module.exports: $Exports<'react-test-renderer/lib/ReactInstanceType'>;
}
declare module 'react-test-renderer/lib/ReactInstrumentation.js' {
declare module.exports: $Exports<'react-test-renderer/lib/ReactInstrumentation'>;
}
declare module 'react-test-renderer/lib/ReactInvalidSetStateWarningHook.js' {
declare module.exports: $Exports<'react-test-renderer/lib/ReactInvalidSetStateWarningHook'>;
}
declare module 'react-test-renderer/lib/ReactMultiChild.js' {
declare module.exports: $Exports<'react-test-renderer/lib/ReactMultiChild'>;
}
declare module 'react-test-renderer/lib/ReactMultiChildUpdateTypes.js' {
declare module.exports: $Exports<'react-test-renderer/lib/ReactMultiChildUpdateTypes'>;
}
declare module 'react-test-renderer/lib/ReactNodeTypes.js' {
declare module.exports: $Exports<'react-test-renderer/lib/ReactNodeTypes'>;
}
declare module 'react-test-renderer/lib/ReactOwner.js' {
declare module.exports: $Exports<'react-test-renderer/lib/ReactOwner'>;
}
declare module 'react-test-renderer/lib/ReactPerf.js' {
declare module.exports: $Exports<'react-test-renderer/lib/ReactPerf'>;
}
declare module 'react-test-renderer/lib/ReactPriorityLevel.js' {
declare module.exports: $Exports<'react-test-renderer/lib/ReactPriorityLevel'>;
}
declare module 'react-test-renderer/lib/reactProdInvariant.js' {
declare module.exports: $Exports<'react-test-renderer/lib/reactProdInvariant'>;
}
declare module 'react-test-renderer/lib/ReactPropTypeLocationNames.js' {
declare module.exports: $Exports<'react-test-renderer/lib/ReactPropTypeLocationNames'>;
}
declare module 'react-test-renderer/lib/ReactPropTypeLocations.js' {
declare module.exports: $Exports<'react-test-renderer/lib/ReactPropTypeLocations'>;
}
declare module 'react-test-renderer/lib/ReactPropTypesSecret.js' {
declare module.exports: $Exports<'react-test-renderer/lib/ReactPropTypesSecret'>;
}
declare module 'react-test-renderer/lib/ReactReconciler.js' {
declare module.exports: $Exports<'react-test-renderer/lib/ReactReconciler'>;
}
declare module 'react-test-renderer/lib/ReactRef.js' {
declare module.exports: $Exports<'react-test-renderer/lib/ReactRef'>;
}
declare module 'react-test-renderer/lib/ReactReifiedYield.js' {
declare module.exports: $Exports<'react-test-renderer/lib/ReactReifiedYield'>;
}
declare module 'react-test-renderer/lib/ReactShallowRenderer.js' {
declare module.exports: $Exports<'react-test-renderer/lib/ReactShallowRenderer'>;
}
declare module 'react-test-renderer/lib/ReactSimpleEmptyComponent.js' {
declare module.exports: $Exports<'react-test-renderer/lib/ReactSimpleEmptyComponent'>;
}
declare module 'react-test-renderer/lib/ReactSyntheticEventType.js' {
declare module.exports: $Exports<'react-test-renderer/lib/ReactSyntheticEventType'>;
}
declare module 'react-test-renderer/lib/ReactTestEmptyComponent.js' {
declare module.exports: $Exports<'react-test-renderer/lib/ReactTestEmptyComponent'>;
}
declare module 'react-test-renderer/lib/ReactTestMount.js' {
declare module.exports: $Exports<'react-test-renderer/lib/ReactTestMount'>;
}
declare module 'react-test-renderer/lib/ReactTestReconcileTransaction.js' {
declare module.exports: $Exports<'react-test-renderer/lib/ReactTestReconcileTransaction'>;
}
declare module 'react-test-renderer/lib/ReactTestRenderer.js' {
declare module.exports: $Exports<'react-test-renderer/lib/ReactTestRenderer'>;
}
declare module 'react-test-renderer/lib/ReactTestTextComponent.js' {
declare module.exports: $Exports<'react-test-renderer/lib/ReactTestTextComponent'>;
}
declare module 'react-test-renderer/lib/ReactTypeOfWork.js' {
declare module.exports: $Exports<'react-test-renderer/lib/ReactTypeOfWork'>;
}
declare module 'react-test-renderer/lib/ReactTypes.js' {
declare module.exports: $Exports<'react-test-renderer/lib/ReactTypes'>;
}
declare module 'react-test-renderer/lib/ReactUpdateQueue.js' {
declare module.exports: $Exports<'react-test-renderer/lib/ReactUpdateQueue'>;
}
declare module 'react-test-renderer/lib/ReactUpdates.js' {
declare module.exports: $Exports<'react-test-renderer/lib/ReactUpdates'>;
}
declare module 'react-test-renderer/lib/ReactVersion.js' {
declare module.exports: $Exports<'react-test-renderer/lib/ReactVersion'>;
}
declare module 'react-test-renderer/lib/ResponderEventPlugin.js' {
declare module.exports: $Exports<'react-test-renderer/lib/ResponderEventPlugin'>;
}
declare module 'react-test-renderer/lib/ResponderSyntheticEvent.js' {
declare module.exports: $Exports<'react-test-renderer/lib/ResponderSyntheticEvent'>;
}
declare module 'react-test-renderer/lib/ResponderTouchHistoryStore.js' {
declare module.exports: $Exports<'react-test-renderer/lib/ResponderTouchHistoryStore'>;
}
declare module 'react-test-renderer/lib/shallow/accumulate.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/accumulate'>;
}
declare module 'react-test-renderer/lib/shallow/accumulateInto.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/accumulateInto'>;
}
declare module 'react-test-renderer/lib/shallow/adler32.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/adler32'>;
}
declare module 'react-test-renderer/lib/shallow/ARIADOMPropertyConfig.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ARIADOMPropertyConfig'>;
}
declare module 'react-test-renderer/lib/shallow/AutoFocusUtils.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/AutoFocusUtils'>;
}
declare module 'react-test-renderer/lib/shallow/BeforeInputEventPlugin.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/BeforeInputEventPlugin'>;
}
declare module 'react-test-renderer/lib/shallow/CallbackQueue.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/CallbackQueue'>;
}
declare module 'react-test-renderer/lib/shallow/canDefineProperty.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/canDefineProperty'>;
}
declare module 'react-test-renderer/lib/shallow/ChangeEventPlugin.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ChangeEventPlugin'>;
}
declare module 'react-test-renderer/lib/shallow/checkReactTypeSpec.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/checkReactTypeSpec'>;
}
declare module 'react-test-renderer/lib/shallow/createMicrosoftUnsafeLocalFunction.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/createMicrosoftUnsafeLocalFunction'>;
}
declare module 'react-test-renderer/lib/shallow/CSSProperty.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/CSSProperty'>;
}
declare module 'react-test-renderer/lib/shallow/CSSPropertyOperations.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/CSSPropertyOperations'>;
}
declare module 'react-test-renderer/lib/shallow/Danger.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/Danger'>;
}
declare module 'react-test-renderer/lib/shallow/dangerousStyleValue.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/dangerousStyleValue'>;
}
declare module 'react-test-renderer/lib/shallow/DefaultEventPluginOrder.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/DefaultEventPluginOrder'>;
}
declare module 'react-test-renderer/lib/shallow/deprecated.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/deprecated'>;
}
declare module 'react-test-renderer/lib/shallow/DOMChildrenOperations.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/DOMChildrenOperations'>;
}
declare module 'react-test-renderer/lib/shallow/DOMLazyTree.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/DOMLazyTree'>;
}
declare module 'react-test-renderer/lib/shallow/DOMNamespaces.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/DOMNamespaces'>;
}
declare module 'react-test-renderer/lib/shallow/DOMProperty.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/DOMProperty'>;
}
declare module 'react-test-renderer/lib/shallow/DOMPropertyOperations.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/DOMPropertyOperations'>;
}
declare module 'react-test-renderer/lib/shallow/EnterLeaveEventPlugin.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/EnterLeaveEventPlugin'>;
}
declare module 'react-test-renderer/lib/shallow/escapeTextContentForBrowser.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/escapeTextContentForBrowser'>;
}
declare module 'react-test-renderer/lib/shallow/EventConstants.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/EventConstants'>;
}
declare module 'react-test-renderer/lib/shallow/EventPluginHub.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/EventPluginHub'>;
}
declare module 'react-test-renderer/lib/shallow/EventPluginRegistry.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/EventPluginRegistry'>;
}
declare module 'react-test-renderer/lib/shallow/EventPluginUtils.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/EventPluginUtils'>;
}
declare module 'react-test-renderer/lib/shallow/EventPropagators.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/EventPropagators'>;
}
declare module 'react-test-renderer/lib/shallow/FallbackCompositionState.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/FallbackCompositionState'>;
}
declare module 'react-test-renderer/lib/shallow/findDOMNode.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/findDOMNode'>;
}
declare module 'react-test-renderer/lib/shallow/flattenChildren.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/flattenChildren'>;
}
declare module 'react-test-renderer/lib/shallow/forEachAccumulated.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/forEachAccumulated'>;
}
declare module 'react-test-renderer/lib/shallow/getEventCharCode.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/getEventCharCode'>;
}
declare module 'react-test-renderer/lib/shallow/getEventKey.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/getEventKey'>;
}
declare module 'react-test-renderer/lib/shallow/getEventModifierState.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/getEventModifierState'>;
}
declare module 'react-test-renderer/lib/shallow/getEventTarget.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/getEventTarget'>;
}
declare module 'react-test-renderer/lib/shallow/getHostComponentFromComposite.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/getHostComponentFromComposite'>;
}
declare module 'react-test-renderer/lib/shallow/getIteratorFn.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/getIteratorFn'>;
}
declare module 'react-test-renderer/lib/shallow/getNodeForCharacterOffset.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/getNodeForCharacterOffset'>;
}
declare module 'react-test-renderer/lib/shallow/getTextContentAccessor.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/getTextContentAccessor'>;
}
declare module 'react-test-renderer/lib/shallow/getVendorPrefixedEventName.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/getVendorPrefixedEventName'>;
}
declare module 'react-test-renderer/lib/shallow/HTMLDOMPropertyConfig.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/HTMLDOMPropertyConfig'>;
}
declare module 'react-test-renderer/lib/shallow/inputValueTracking.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/inputValueTracking'>;
}
declare module 'react-test-renderer/lib/shallow/instantiateReactComponent.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/instantiateReactComponent'>;
}
declare module 'react-test-renderer/lib/shallow/isEventSupported.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/isEventSupported'>;
}
declare module 'react-test-renderer/lib/shallow/isTextInputElement.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/isTextInputElement'>;
}
declare module 'react-test-renderer/lib/shallow/KeyEscapeUtils.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/KeyEscapeUtils'>;
}
declare module 'react-test-renderer/lib/shallow/LinkedValueUtils.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/LinkedValueUtils'>;
}
declare module 'react-test-renderer/lib/shallow/lowPriorityWarning.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/lowPriorityWarning'>;
}
declare module 'react-test-renderer/lib/shallow/PluginModuleType.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/PluginModuleType'>;
}
declare module 'react-test-renderer/lib/shallow/PooledClass.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/PooledClass'>;
}
declare module 'react-test-renderer/lib/shallow/quoteAttributeValueForBrowser.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/quoteAttributeValueForBrowser'>;
}
declare module 'react-test-renderer/lib/shallow/ReactBrowserEventEmitter.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactBrowserEventEmitter'>;
}
declare module 'react-test-renderer/lib/shallow/ReactChildFiber.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactChildFiber'>;
}
declare module 'react-test-renderer/lib/shallow/ReactChildReconciler.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactChildReconciler'>;
}
declare module 'react-test-renderer/lib/shallow/ReactComponentBrowserEnvironment.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactComponentBrowserEnvironment'>;
}
declare module 'react-test-renderer/lib/shallow/ReactComponentEnvironment.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactComponentEnvironment'>;
}
declare module 'react-test-renderer/lib/shallow/ReactCompositeComponent.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactCompositeComponent'>;
}
declare module 'react-test-renderer/lib/shallow/ReactCoroutine.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactCoroutine'>;
}
declare module 'react-test-renderer/lib/shallow/ReactDebugTool.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactDebugTool'>;
}
declare module 'react-test-renderer/lib/shallow/ReactDefaultBatchingStrategy.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactDefaultBatchingStrategy'>;
}
declare module 'react-test-renderer/lib/shallow/ReactDefaultInjection.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactDefaultInjection'>;
}
declare module 'react-test-renderer/lib/shallow/ReactDOM.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactDOM'>;
}
declare module 'react-test-renderer/lib/shallow/ReactDOMComponent.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactDOMComponent'>;
}
declare module 'react-test-renderer/lib/shallow/ReactDOMComponentFlags.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactDOMComponentFlags'>;
}
declare module 'react-test-renderer/lib/shallow/ReactDOMComponentTree.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactDOMComponentTree'>;
}
declare module 'react-test-renderer/lib/shallow/ReactDOMContainerInfo.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactDOMContainerInfo'>;
}
declare module 'react-test-renderer/lib/shallow/ReactDOMEmptyComponent.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactDOMEmptyComponent'>;
}
declare module 'react-test-renderer/lib/shallow/ReactDOMFeatureFlags.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactDOMFeatureFlags'>;
}
declare module 'react-test-renderer/lib/shallow/ReactDOMFiber.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactDOMFiber'>;
}
declare module 'react-test-renderer/lib/shallow/ReactDOMIDOperations.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactDOMIDOperations'>;
}
declare module 'react-test-renderer/lib/shallow/ReactDOMInput.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactDOMInput'>;
}
declare module 'react-test-renderer/lib/shallow/ReactDOMInvalidARIAHook.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactDOMInvalidARIAHook'>;
}
declare module 'react-test-renderer/lib/shallow/ReactDOMNullInputValuePropHook.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactDOMNullInputValuePropHook'>;
}
declare module 'react-test-renderer/lib/shallow/ReactDOMOption.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactDOMOption'>;
}
declare module 'react-test-renderer/lib/shallow/ReactDOMSelect.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactDOMSelect'>;
}
declare module 'react-test-renderer/lib/shallow/ReactDOMSelection.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactDOMSelection'>;
}
declare module 'react-test-renderer/lib/shallow/ReactDOMServer.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactDOMServer'>;
}
declare module 'react-test-renderer/lib/shallow/ReactDOMTextarea.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactDOMTextarea'>;
}
declare module 'react-test-renderer/lib/shallow/ReactDOMTextComponent.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactDOMTextComponent'>;
}
declare module 'react-test-renderer/lib/shallow/ReactDOMTreeTraversal.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactDOMTreeTraversal'>;
}
declare module 'react-test-renderer/lib/shallow/ReactDOMUnknownPropertyHook.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactDOMUnknownPropertyHook'>;
}
declare module 'react-test-renderer/lib/shallow/ReactElementSymbol.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactElementSymbol'>;
}
declare module 'react-test-renderer/lib/shallow/ReactEmptyComponent.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactEmptyComponent'>;
}
declare module 'react-test-renderer/lib/shallow/ReactErrorUtils.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactErrorUtils'>;
}
declare module 'react-test-renderer/lib/shallow/ReactEventEmitterMixin.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactEventEmitterMixin'>;
}
declare module 'react-test-renderer/lib/shallow/ReactEventListener.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactEventListener'>;
}
declare module 'react-test-renderer/lib/shallow/ReactFeatureFlags.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactFeatureFlags'>;
}
declare module 'react-test-renderer/lib/shallow/ReactFiber.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactFiber'>;
}
declare module 'react-test-renderer/lib/shallow/ReactFiberBeginWork.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactFiberBeginWork'>;
}
declare module 'react-test-renderer/lib/shallow/ReactFiberCommitWork.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactFiberCommitWork'>;
}
declare module 'react-test-renderer/lib/shallow/ReactFiberCompleteWork.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactFiberCompleteWork'>;
}
declare module 'react-test-renderer/lib/shallow/ReactFiberReconciler.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactFiberReconciler'>;
}
declare module 'react-test-renderer/lib/shallow/ReactFiberRoot.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactFiberRoot'>;
}
declare module 'react-test-renderer/lib/shallow/ReactFiberScheduler.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactFiberScheduler'>;
}
declare module 'react-test-renderer/lib/shallow/ReactFiberUpdateQueue.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactFiberUpdateQueue'>;
}
declare module 'react-test-renderer/lib/shallow/ReactHostComponent.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactHostComponent'>;
}
declare module 'react-test-renderer/lib/shallow/ReactHostOperationHistoryHook.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactHostOperationHistoryHook'>;
}
declare module 'react-test-renderer/lib/shallow/ReactInjection.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactInjection'>;
}
declare module 'react-test-renderer/lib/shallow/ReactInputSelection.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactInputSelection'>;
}
declare module 'react-test-renderer/lib/shallow/ReactInstanceMap.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactInstanceMap'>;
}
declare module 'react-test-renderer/lib/shallow/ReactInstanceType.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactInstanceType'>;
}
declare module 'react-test-renderer/lib/shallow/ReactInstrumentation.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactInstrumentation'>;
}
declare module 'react-test-renderer/lib/shallow/ReactInvalidSetStateWarningHook.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactInvalidSetStateWarningHook'>;
}
declare module 'react-test-renderer/lib/shallow/ReactMarkupChecksum.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactMarkupChecksum'>;
}
declare module 'react-test-renderer/lib/shallow/ReactMount.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactMount'>;
}
declare module 'react-test-renderer/lib/shallow/ReactMultiChild.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactMultiChild'>;
}
declare module 'react-test-renderer/lib/shallow/ReactMultiChildUpdateTypes.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactMultiChildUpdateTypes'>;
}
declare module 'react-test-renderer/lib/shallow/ReactNodeTypes.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactNodeTypes'>;
}
declare module 'react-test-renderer/lib/shallow/ReactOwner.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactOwner'>;
}
declare module 'react-test-renderer/lib/shallow/ReactPerf.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactPerf'>;
}
declare module 'react-test-renderer/lib/shallow/ReactPriorityLevel.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactPriorityLevel'>;
}
declare module 'react-test-renderer/lib/shallow/reactProdInvariant.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/reactProdInvariant'>;
}
declare module 'react-test-renderer/lib/shallow/ReactPropTypeLocationNames.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactPropTypeLocationNames'>;
}
declare module 'react-test-renderer/lib/shallow/ReactPropTypeLocations.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactPropTypeLocations'>;
}
declare module 'react-test-renderer/lib/shallow/ReactPropTypesSecret.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactPropTypesSecret'>;
}
declare module 'react-test-renderer/lib/shallow/ReactReconciler.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactReconciler'>;
}
declare module 'react-test-renderer/lib/shallow/ReactReconcileTransaction.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactReconcileTransaction'>;
}
declare module 'react-test-renderer/lib/shallow/ReactRef.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactRef'>;
}
declare module 'react-test-renderer/lib/shallow/ReactReifiedYield.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactReifiedYield'>;
}
declare module 'react-test-renderer/lib/shallow/ReactServerBatchingStrategy.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactServerBatchingStrategy'>;
}
declare module 'react-test-renderer/lib/shallow/ReactServerRendering.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactServerRendering'>;
}
declare module 'react-test-renderer/lib/shallow/ReactServerRenderingTransaction.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactServerRenderingTransaction'>;
}
declare module 'react-test-renderer/lib/shallow/ReactServerUpdateQueue.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactServerUpdateQueue'>;
}
declare module 'react-test-renderer/lib/shallow/ReactShallowRenderer.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactShallowRenderer'>;
}
declare module 'react-test-renderer/lib/shallow/ReactSimpleEmptyComponent.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactSimpleEmptyComponent'>;
}
declare module 'react-test-renderer/lib/shallow/ReactSyntheticEventType.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactSyntheticEventType'>;
}
declare module 'react-test-renderer/lib/shallow/ReactTestEmptyComponent.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactTestEmptyComponent'>;
}
declare module 'react-test-renderer/lib/shallow/ReactTestMount.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactTestMount'>;
}
declare module 'react-test-renderer/lib/shallow/ReactTestReconcileTransaction.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactTestReconcileTransaction'>;
}
declare module 'react-test-renderer/lib/shallow/ReactTestRenderer.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactTestRenderer'>;
}
declare module 'react-test-renderer/lib/shallow/ReactTestTextComponent.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactTestTextComponent'>;
}
declare module 'react-test-renderer/lib/shallow/ReactTypeOfWork.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactTypeOfWork'>;
}
declare module 'react-test-renderer/lib/shallow/ReactTypes.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactTypes'>;
}
declare module 'react-test-renderer/lib/shallow/ReactUpdateQueue.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactUpdateQueue'>;
}
declare module 'react-test-renderer/lib/shallow/ReactUpdates.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactUpdates'>;
}
declare module 'react-test-renderer/lib/shallow/ReactVersion.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ReactVersion'>;
}
declare module 'react-test-renderer/lib/shallow/renderSubtreeIntoContainer.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/renderSubtreeIntoContainer'>;
}
declare module 'react-test-renderer/lib/shallow/ResponderEventPlugin.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ResponderEventPlugin'>;
}
declare module 'react-test-renderer/lib/shallow/ResponderSyntheticEvent.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ResponderSyntheticEvent'>;
}
declare module 'react-test-renderer/lib/shallow/ResponderTouchHistoryStore.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ResponderTouchHistoryStore'>;
}
declare module 'react-test-renderer/lib/shallow/SelectEventPlugin.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/SelectEventPlugin'>;
}
declare module 'react-test-renderer/lib/shallow/setInnerHTML.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/setInnerHTML'>;
}
declare module 'react-test-renderer/lib/shallow/setTextContent.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/setTextContent'>;
}
declare module 'react-test-renderer/lib/shallow/shouldUpdateReactComponent.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/shouldUpdateReactComponent'>;
}
declare module 'react-test-renderer/lib/shallow/SimpleEventPlugin.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/SimpleEventPlugin'>;
}
declare module 'react-test-renderer/lib/shallow/SVGDOMPropertyConfig.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/SVGDOMPropertyConfig'>;
}
declare module 'react-test-renderer/lib/shallow/SyntheticAnimationEvent.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/SyntheticAnimationEvent'>;
}
declare module 'react-test-renderer/lib/shallow/SyntheticClipboardEvent.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/SyntheticClipboardEvent'>;
}
declare module 'react-test-renderer/lib/shallow/SyntheticCompositionEvent.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/SyntheticCompositionEvent'>;
}
declare module 'react-test-renderer/lib/shallow/SyntheticDragEvent.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/SyntheticDragEvent'>;
}
declare module 'react-test-renderer/lib/shallow/SyntheticEvent.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/SyntheticEvent'>;
}
declare module 'react-test-renderer/lib/shallow/SyntheticFocusEvent.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/SyntheticFocusEvent'>;
}
declare module 'react-test-renderer/lib/shallow/SyntheticInputEvent.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/SyntheticInputEvent'>;
}
declare module 'react-test-renderer/lib/shallow/SyntheticKeyboardEvent.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/SyntheticKeyboardEvent'>;
}
declare module 'react-test-renderer/lib/shallow/SyntheticMouseEvent.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/SyntheticMouseEvent'>;
}
declare module 'react-test-renderer/lib/shallow/SyntheticTouchEvent.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/SyntheticTouchEvent'>;
}
declare module 'react-test-renderer/lib/shallow/SyntheticTransitionEvent.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/SyntheticTransitionEvent'>;
}
declare module 'react-test-renderer/lib/shallow/SyntheticUIEvent.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/SyntheticUIEvent'>;
}
declare module 'react-test-renderer/lib/shallow/SyntheticWheelEvent.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/SyntheticWheelEvent'>;
}
declare module 'react-test-renderer/lib/shallow/TapEventPlugin.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/TapEventPlugin'>;
}
declare module 'react-test-renderer/lib/shallow/TouchHistoryMath.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/TouchHistoryMath'>;
}
declare module 'react-test-renderer/lib/shallow/Transaction.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/Transaction'>;
}
declare module 'react-test-renderer/lib/shallow/traverseAllChildren.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/traverseAllChildren'>;
}
declare module 'react-test-renderer/lib/shallow/validateDOMNesting.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/validateDOMNesting'>;
}
declare module 'react-test-renderer/lib/shallow/ViewportMetrics.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shallow/ViewportMetrics'>;
}
declare module 'react-test-renderer/lib/shouldUpdateReactComponent.js' {
declare module.exports: $Exports<'react-test-renderer/lib/shouldUpdateReactComponent'>;
}
declare module 'react-test-renderer/lib/SyntheticEvent.js' {
declare module.exports: $Exports<'react-test-renderer/lib/SyntheticEvent'>;
}
declare module 'react-test-renderer/lib/TouchHistoryMath.js' {
declare module.exports: $Exports<'react-test-renderer/lib/TouchHistoryMath'>;
}
declare module 'react-test-renderer/lib/Transaction.js' {
declare module.exports: $Exports<'react-test-renderer/lib/Transaction'>;
}
declare module 'react-test-renderer/lib/traverseAllChildren.js' {
declare module.exports: $Exports<'react-test-renderer/lib/traverseAllChildren'>;
}
declare module 'react-test-renderer/shallow.js' {
declare module.exports: $Exports<'react-test-renderer/shallow'>;
}
|
$(document).ready(function() {
$('#login-form').on('submit', login());
function login(){
$.ajax({
url: "http://localhost:9999/main/login",
type: "GET",
data: {
username:$("#username-field").val(),
password:$("#password-field").val()
},
success: function(response) {
window.location.href = "feed.php?id="+response;
},
error: function(xhr) {
console.log("Error");
}
});
};
}); |
(function(){
'use strict';
angular
.module('app')
.constant('LSVER', 1);
angular
.module('app')
.constant('LSKEYS', {
fontSize: 'fontSize',
fontBold: 'fontBold',
themeDarK: 'themeDarK',
auth: 'auth',
data: 'data'
});
angular
.module('app')
.service('LsService', function LsService(LSKEYS, LSVER){
var svc = this;
// prefix for keys in local storage
var keyPrefix = 'ntlyrics';
// linker between prefix and provided key, eg: cs.myNewKey
var keyLink = '.';
/**
* Set value to local storage
* @param {string} key
* @param {object} value
*/
function set(key, value){
localStorage.setItem(prefixKey(key), angular.toJson(value));
}
/**
* Get value from local storage
* @param {string} key
* @returns {Object|Array|string|number|*}
*/
function get(key){
var value = localStorage.getItem(prefixKey(key));
if(value){
return angular.fromJson(value);
}
return undefined;
}
/**
* Remove value from local storage
* @param {string} key
*/
function remove(key){
localStorage.removeItem(prefixKey(key));
}
/**
* Prefix the given key with keyPrefix string + keyLink symbol
* @param {string} key
* @returns {string}
*/
function prefixKey(key){
var prefixAndLink = keyPrefix + keyLink;
if(key.indexOf(prefixAndLink) === 0){
return key;
}
return prefixAndLink + key;
}
//var lsver = get(LSKEYS.lsVersion);
//if(!lsver || LSKEYS > lsver){
// localStorage.clear();
// set(LSKEYS.lsVersion, LSVER);
//}
svc.set = set;
svc.get = get;
svc.remove = remove;
svc.prefixKey = prefixKey;
});
})();
|
'use strict';
const fs = require('fs');
const execa = require('execa');
const Bluebird = require('bluebird');
const log = require('npmlog');
const fsStatAsync = Bluebird.promisify(fs.stat);
const isWin = require('./utils/is-win')();
exports.fileExists = function fileExists(path) {
return fsStatAsync(path).then(stat => stat.isFile()).catchReturn(false);
};
exports.executableExists = function executableExists(exe, options) {
let cmd = isWin ? 'where' : 'which';
let test = execa(cmd, [exe], options);
test.on('error', error => log.error('Error spawning "' + cmd + exe + '"', error));
return test.then(result => result.code === 0, () => false);
};
|
var classowncloudsharp_1_1_exceptions_1_1_o_c_s_response_error =
[
[ "OCSResponseError", "classowncloudsharp_1_1_exceptions_1_1_o_c_s_response_error.html#a4a8be342eabdb1ff56309de41bb27376", null ],
[ "OCSResponseError", "classowncloudsharp_1_1_exceptions_1_1_o_c_s_response_error.html#abe1faed2e2f100a1d5e5c051413be70a", null ],
[ "OCSResponseError", "classowncloudsharp_1_1_exceptions_1_1_o_c_s_response_error.html#a140bbc4910589e73d076ba7a977b9e88", null ]
]; |
var config = require('./config.console'),
mongoose = require('mongoose'),
chalk = require('chalk'),
http = require('http'),
fs = require('fs');
var db = mongoose.connect(config.db, function(err) {
if (err) {
console.error(chalk.red('Could not connect to MongoDB!'));
console.log(chalk.red(err));
//process.exit();
} else {
console.log(chalk.green('Connected to MongoDB'));
console.log('Do something here');
mongoose.disconnect();
//fetchWebData();
}
}); |
(function($) {
'use strict';
Crafty.scene('editor', function editorScene () {
showEditorForm();
var _width = Crafty.viewport.width;
var _height = Crafty.viewport.height;
var bricksCreated = 0;
var lvl = {
name: "Dynamic Level",
bricks: []
};
var brickSet = {};
Crafty.e('Line, 2D, Canvas, Color')
.color('#AAAAAA')
.attr({ x:0, y:8*_height/10, w:_width, h:2});
Crafty.e('Line, 2D, Canvas, Color')
.color('#000000')
.attr({ x:0, y:8*_height/10, w:_width, h:1});
var BrickCreator = Crafty.e('BrickCreator, 2D, Canvas, Color, BrickC, Mouse');
// Adds brick to level by its ID
// It will overwrite any info already saved with this ID
var addBrickToSet = function addBrickToSet (brick) {
brickSet[brick._brickID] = {
w: brick.w,
h: brick.h,
x: brick.x,
y: brick.y
};
console.log('Added brick', brickSet[brick._brickID]);
};
var onBrickDropped = function onBrickDropped (mouseEvent) {
console.log('brick %d dropped', this._brickID);
addBrickToSet(this);
};
var createBrick = function createBrick () {
console.log('Cloning');
bricksCreated++;
var newBrick = Crafty.e('DynamicBrick'+bricksCreated+', 2D, Canvas, Color, BrickC, Draggable')
.attr({_brickID: bricksCreated})
.startDrag()
.bind('StopDrag', onBrickDropped);
};
BrickCreator.bind('MouseUp', createBrick);
// SAVE BUTTON
var saveText = Crafty.e("2D, DOM, Text, Mouse").attr({
x : 5*_width / 6 + 20 - 8,
y : 9*_height / 10 + 3
})
.text('Save')
.textFont({ size: '25px', weight: 'bold' })
.textColor('#FFFFFF');
var saveButton = Crafty.e("2D, DOM, greyBtn, SpriteAnimation, Mouse").attr({
x : 5*_width / 6 - 8,
y : 9*_height / 10 + 3,
w : 100,
h : 30
})
.bind('Click', function() {
lvl.name = getLevelName();
var lvlWithBricks = withBricks(lvl);
if (lvlWithBricks.bricks.length <= 0) {
window.alert('Your level is empty, please add at least 1 brick!');
return false;
}
var lvlData = JSON.stringify(lvlWithBricks);
console.log('Trying to save level to file. ', lvl, lvlData);
var isFileSaverSupported = false;
try { isFileSaverSupported = !!new Blob(); } catch(e){}
if (isFileSaverSupported) {
var blob = new Blob([lvlData], {type: "text/plain;charset=utf-8"});
window.saveAs(blob, lvl.name+".json");
} else {
console.warn('Blob is not supported.');
window.prompt("Copy it go! (Ctrl/Cmd + C and Enter)", lvlData);
}
})
.attach(saveText);
// CANCEL BUTTON
var cancelText = Crafty.e("2D, DOM, Text, Mouse").attr({
x : 4*_width / 6,
y : 9*_height / 10 + 3
})
.text('Cancel')
.textFont({ size: '25px', weight: 'bold' })
.textColor('#FFFFFF');
var cancelButton = Crafty.e("2D, DOM, greyBtn, SpriteAnimation, Mouse").attr({
x : 4*_width / 6 - 10,
y : 9*_height / 10 + 3,
w : 100,
h : 30
})
.bind('Click', function() {
if (window.confirm('You will lose any unsaved data if you continue, are you sure?')) {
clearLevelName();
hideEditorForm();
Crafty.scene('menu');
}
})
.attach(cancelText);
function withBricks(lvl) {
lvl.bricks = [];
for (var brick in brickSet) {
if (Object.prototype.hasOwnProperty.call(brickSet, brick)) {
lvl.bricks.push(brickSet[brick]);
}
}
return lvl;
}
});
function showEditorForm () {
var $form = $('form[name="levelNameForm"]');
if ($form) {
$form.show();
}
}
function hideEditorForm () {
var $form = $('form[name="levelNameForm"]');
if ($form) {
$form.hide();
}
}
function getLevelName () {
var $input = $('input[name="levelName"]');
if ($input) {
return $input.val() || 'dynamic_' + getRandomInt(1, 10000000);
}
}
function clearLevelName () {
var $input = $('input[name="levelName"]');
if ($input) {
$input.val('');
}
}
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
})(jQuery);
|
module.exports = cdn
var MaxCDN = require('maxcdn')
function cdn (self) {
if (self.settings.maxcdn.zoneId) {
var maxcdn = new MaxCDN(
self.settings.maxcdn.companyAlias,
self.settings.maxcdn.consumerKey,
self.settings.maxcdn.consumerSecret
)
maxcdn.del('zones/pull.json/' + self.settings.maxcdn.zoneId + '/cache', function (err, res) {
console.log('MAXCDN: STATUS')
if (err) {
console.error('PURGE ERROR: ', err.stack || err.message || err)
return
} else if (res.code !== 200) {
console.error('PURGE ERROR: ', res.code)
return
}
console.log('PURGE SUCCESS')
})
}
}
|
'use strict';
var https = require('https');
var q = require('q');
function logError(error) {
console.log("[Lightify] Error!");
if (error.statusMessage) {
console.log("[Lightify] HTTP Error: " + error.statusCode + " - " + error.statusMessage);
console.log("[Lightify] HTTP Headers: ");
console.log(error.headers);
}
else {
console.log(error);
}
}
var internal = {
// global Osram Lightify constants
lightifyBaseUrl : "us.lightify-api.org",
lightifySessionUrl : "/lightify/services/session",
lightifyDevicesUrl : "/lightify/services/devices/",
deviceSerialNumber: undefined,
username: undefined,
password: undefined,
securityToken: undefined,
getSecurityToken : function () {
var postData = JSON.stringify({
username: this.username,
password: this.password,
serialNumber: this.deviceSerialNumber
});
return this.makeLightifyRequest(this.lightifyBaseUrl, this.lightifySessionUrl, false, false, 'POST', postData)
.then((data) => {
this.securityToken = data.securityToken;
return data;
});
},
getDevices : function () {
return this.makeLightifyRequest(this.lightifyBaseUrl, this.lightifyDevicesUrl, this.securityToken, false, 'GET', undefined);
},
makeLightifyRequest : function (url, path, securityToken, returnRawBody, method, content) {
console.log("[Lightify] -------------------------")
console.log("[Lightify] method : " + method);
console.log("[Lightify] makeLightifyRequest: " + url)
console.log("[Lightify] path : " + path);
console.log("[Lightify] securityToken : " + securityToken);
var deferred = q.defer();
var requestOptions = {
protocol: 'https:',
host: url,
path: path,
method: method,
headers: {}
};
if (securityToken) {
requestOptions.headers['Authorization'] = securityToken;
}
else if (content) {
requestOptions.headers['Content-Type'] = 'application/json';
requestOptions.headers['Content-Length'] = content.length;
}
var request = https.request(requestOptions);
request.on('response', function(response) {
var body = '';
response.setEncoding('utf8');
response.on('data', function(data) {
body += data;
});
response.on('end', function() {
if (response.statusCode != 200) {
deferred.reject(new Error("Invalid HTTP response: " + response.statusCode + " - " + response.statusMessage));
} else {
if (returnRawBody) {
deferred.resolve(body);
}
else {
var parsedBody = JSON.parse(body);
deferred.resolve(parsedBody);
}
}
});
response.on('error', function(e) {
deferred.reject(e);
});
});
request.on('error', (e) => {
deferred.reject(e);
});
if (content) {
request.write(content);
}
request.end();
return deferred.promise;
},
};
module.exports = {
inputNeeded : [
{
type: 'input',
name: 'deviceSerialNumber',
message: 'Osram Lightify Device Serial Number (alpha-numeric without trailing -XX): ',
validate: function(value) {
var pass = !!value;
if (pass) {
return true;
} else {
return 'Please enter a valid Serial Number.';
}
}
},
{
type: 'input',
name: 'username',
message: 'Osram Lightify User Name (create this in the Osram Lightify app): ',
validate: function(value) {
var pass = !!value;
if (pass) {
return true;
} else {
return 'Please enter a valid User Name.';
}
}
},
{
type: 'password',
name: 'password',
message: 'Osram Lightify Password (create this in the Osram Lightify app): ',
validate: function(value) {
var pass = !!value;
if (pass) {
return true;
} else {
return 'Please enter a valid Password.';
}
}
}
],
// devices list as returned by the server
devices: undefined,
// the is the serial number of the Lightify hub device
deviceSerialNumber: undefined,
// this is the oauth security token for the current session
securityToken: undefined,
// authorizes to the server based on the properties saved in the object
authorize: function() {
// get initial set of authorization info, including account server
return internal.getSecurityToken().then((data) => {
// get the list of devices
return internal.getDevices().then((devices) => {
this.securityToken = data.securityToken;
this.devices = devices;
this.deviceSerialNumber = internal.deviceSerialNumber;
return devices;
})
});
},
// connects to the hub based on the answers provided
connect : function(answers) {
var deferred = q.defer();
console.log("[Lightify] connect");
if (!answers.deviceSerialNumber && !answers.username && ! answers.password) {
logError("Invalid input");
setImmediate(function () { deferred.reject(new Error("Invalid input")); });
}
else {
internal.username = answers.username;
internal.password = answers.password;
internal.deviceSerialNumber = answers.deviceSerialNumber;
this.authorize().then(function (data) {
deferred.resolve(data);
},
function (error) {
logError(error);
deferred.reject(error);
});
}
return deferred.promise;
},
printDevices: function (devices) {
devices.forEach(function(device) {
console.log(device.name + " (" + device.deviceId + ") - " + device.deviceType);
});
}
}; |
/* Copyright 2015 Dietrich Epp.
This file is part of Dash and the Jetpack Space Pirates. The Dash
and the Jetpack Space Pirates source code is distributed under the
terms of the MIT license. See LICENSE.txt for details. */
'use strict';
var glm = require('gl-matrix');
var vec2 = glm.vec2;
var color = require('./color');
var param = require('./param');
var physics = require('./physics');
function destroy(body) {
if (body.world) {
body.world.removeBody(body);
}
}
var Types = {};
/*
* Register entity types.
*
* category: The category name, or null.
* types: Mapping from type names to types
*/
function registerTypes(types, category) {
var prefix = category ? category + '.' : '';
_.forOwn(types, function(value, key) {
var inh = value.inherit, i;
if (inh) {
for (i = 0; i < inh.length; i++) {
_.defaults(value, inh[i]);
}
delete value.inherit;
}
var tname = prefix + key;
if (Types.hasOwnProperty(tname)) {
console.error('Duplicate type registered: ' + tname);
return;
}
Types[tname] = value;
});
}
function getType(type) {
return Types[type];
}
module.exports = {
destroy: destroy,
registerTypes: registerTypes,
getType: getType,
};
|
var searchData=
[
['parser_2ecpp',['Parser.cpp',['../_parser_8cpp.html',1,'']]],
['parser_2eh',['Parser.h',['../_parser_8h.html',1,'']]],
['parsercollision_2ecpp',['ParserCollision.cpp',['../_parser_collision_8cpp.html',1,'']]],
['parsercollision_2eh',['ParserCollision.h',['../_parser_collision_8h.html',1,'']]],
['pausemenu_2ecpp',['PauseMenu.cpp',['../_pause_menu_8cpp.html',1,'']]],
['pausemenu_2eh',['PauseMenu.h',['../_pause_menu_8h.html',1,'']]],
['physicalentity_2ecpp',['PhysicalEntity.cpp',['../_physical_entity_8cpp.html',1,'']]],
['physicalentity_2eh',['PhysicalEntity.h',['../_physical_entity_8h.html',1,'']]],
['physicalworld_2ecpp',['PhysicalWorld.cpp',['../_physical_world_8cpp.html',1,'']]],
['physicalworld_2eh',['PhysicalWorld.h',['../_physical_world_8h.html',1,'']]],
['player_2ecpp',['Player.cpp',['../_player_8cpp.html',1,'']]],
['player_2eh',['Player.h',['../_player_8h.html',1,'']]],
['power_2ecpp',['Power.cpp',['../_power_8cpp.html',1,'']]],
['power_2eh',['Power.h',['../_power_8h.html',1,'']]]
];
|
/* *************************
* "CLASS": Player
* *************************/
function Player(x, y){
/* ### ATTRIBUTES ### */
Entity.call(this, x, y);
this.vx = 0;
this.vy = 0;
this.currentMaxHealth = 2;
this.health = 2;
this.sprite = new Sprite('res/spritesheet.png', [0, 0], [32,32] , 12, [0,1,2,3,4,5,6,7]);
this.speed = STARTING_PLAYER_SPEED;
this.isBlocking = false;
this.blockRadius = (PLAYER_SPRITE_WIDTH/2) + BLOCK_RADIUS;
this.radius = PLAYER_SPRITE_WIDTH/2;
this.handle = PLAYER_HANDLE; // the ability to turn better
this.teleportRange = 100;
this.bulletRange = 180;
this.fireDelay = 3*1000000; // in microseconds
/* METHODS */
this.checkBoundaries = function(){
if(this.x + this.sprite.width >= canvas.width){
this.x = canvas.width - this.sprite.width;
this.vx /= 2;
}
else if(this.x <= 0){
this.x = 0;
this.vx /= 2;
}
if(this.y + this.sprite.height >= canvas.height){
this.y = canvas.height - this.sprite.height;
this.vy /= 2;
}
else if(this.y <= 0){
this.y = 0;
this.vy /= 2;
}
}
this.update = function(dt){
this.sprite.update(dt);
this.checkEnemiesCollision();
this.vx *= PLAYER_FRICTION;
this.vy *= PLAYER_FRICTION;
this.x += this.vx;
this.y += this.vy;
this.checkBoundaries();
};
this.render = function(){
renderEntity(this);
drawBar(this.x, this.y-12, this.sprite.width, 6, this.health, this.currentMaxHealth, true, "green");
//posx, posy, size, width, state, maxState, horizontal, colorInside
};
this.checkEnemiesCollision = function(){
for(var i = 0; i<enemies.length; i++){
var enemy = enemies[i];
if(circleCollision(this, enemy) ){
enemy.destroy();
createExplosion(enemy.x, enemy.y);
this.health--;
this.checkHealth();
}
}
};
this.checkHealth = function(){
if(this.health <= 0){
//todo upgrade menu, so game over instead
alert("Game over! You survived for " + gameTime.toFixed(2) + " seconds!");
location.reload(true);
}
}
/*this.block = function(){
this.isBlocking = true;
var blockX = this.x + (this.sprite.width/2);
var blockY = this.y + (this.sprite.height/2);
daux.beginPath();
daux.arc(blockX, blockY, this.blockRadius, 0, Math.PI*2, true);
daux.stroke();
setTimeout(function(){
daux.clearRect(0, 0, auxcanvas.width, auxcanvas.height);
}, 50);
setTimeout(function(){
player.isBlocking = false;
}, BLOCK_DELAY);
};*/
return this;
}
var PLAYER_START_X = (canvas.width/2) - 32/2;
var PLAYER_START_Y = (canvas.height/2) - 32/2;
var player = new Player(PLAYER_START_X, PLAYER_START_Y);
|
/**
* Common utilities
* @module glMatrix
*/
// Configuration Constants
export var EPSILON = 0.000001;
export var ARRAY_TYPE = typeof Float32Array !== 'undefined' ? Float32Array : Array;
export var RANDOM = Math.random;
/**
* Sets the type of array used when creating new vectors and matrices
*
* @param {Type} type Array type, such as Float32Array or Array
*/
export function setMatrixArrayType(type) {
ARRAY_TYPE = type;
}
var degree = Math.PI / 180;
/**
* Convert Degree To Radian
*
* @param {Number} a Angle in Degrees
*/
export function toRadian(a) {
return a * degree;
}
/**
* Tests whether or not the arguments have approximately the same value, within an absolute
* or relative tolerance of glMatrix.EPSILON (an absolute tolerance is used for values less
* than or equal to 1.0, and a relative tolerance is used for larger values)
*
* @param {Number} a The first number to test.
* @param {Number} b The second number to test.
* @returns {Boolean} True if the numbers are approximately equal, false otherwise.
*/
export function equals(a, b) {
return Math.abs(a - b) <= EPSILON * Math.max(1.0, Math.abs(a), Math.abs(b));
}
if (!Math.hypot) Math.hypot = function () {
var y = 0,
i = arguments.length;
while (i--) {
y += arguments[i] * arguments[i];
}
return Math.sqrt(y);
}; |
/* jshint node: true */
'use strict';
var util = require('util');
var _ = require('underscore');
var defaults = require('../defaults');
var options = require('../options');
var descriptor = defaults.defaultDescriptor({
'productName': {
name: 'Product Name',
required: true
},
'productDesc': {
name: 'Description'
},
'proxies': {
name: 'API Proxies',
required: true
},
'environments':{
name: 'Environments',
required: true
},
'approvalType': {
name: 'Approval Type',
required: true
},
'quota' : {
name: 'Quota',
},
'quotaInterval':{
name: 'Quota Interval'
},
'quotaTimeUnit': {
name:'Quota Time Unit'
},
'scopes': {
name: "Scope",
}
});
module.exports.descriptor = descriptor;
module.exports.run = function(opts, cb) {
options.validateSync(opts, descriptor);
if (opts.debug) {
console.log('createProduct: %j', opts);
}
var request = defaults.defaultRequest(opts);
createProduct(opts, request, function(err, results) {
if (err) {
cb(err);
} else {
if (opts.debug) {
console.log('results: %j', results);
}
cb(undefined, results);
}
});
};
function createProduct(opts,request,done){
var product = {
"approvalType": "auto",
"attributes":
[ {"name": "access", "value": "public"} ],
"scopes": []
}
product.name = opts.productName
product.displayName = opts.productName
product.description = opts.productDesc
product.proxies = []
if(opts.proxies){
var split = opts.proxies.split(',')
split.forEach(function(s){
if(s && s.trim()!= '') {
product.proxies.push(s.trim())
}
})
}
product.apiResources = []
if(opts.apiResources){
var split = opts.apiResources.split(',')
split.forEach(function(s){
if(s && s.trim()!= '') {
product.apiResources.push(s.trim())
}
})
}
if(opts.scopes){
var split = opts.scopes.split(',')
split.forEach(function(s){
if(s && s.trim()!= '') {
product.scopes.push(s.trim())
}
})
}
product.environments = []
if(opts.environments){
var split = opts.environments.split(',')
split.forEach(function(s){
if(s && s.trim()!= '') {
product.environments.push(s.trim())
}
})
}
if(opts.quota && opts.quotaInterval && opts.quotaTimeUnit){
product.quota = opts.quota
product.quotaInterval = opts.quotaInterval
product.quotaTimeUnit = opts.quotaTimeUnit
}
var uri = util.format('%s/v1/o/%s/apiproducts', opts.baseuri, opts.organization);
request({
uri: uri,
method:'POST',
body: product,
json:true
},function(err,res,body){
var jsonBody = body
if(err){
if (opts.debug) {
console.log('Error occured %s', err);
}
done(err)
}else if (res.statusCode === 201) {
if (opts.verbose) {
console.log('Create successful');
}
if (opts.debug) {
console.log('%s', body);
}
done(undefined, jsonBody);
}else {
if (opts.verbose) {
console.error('Create Product result: %j', body);
}
var errMsg;
if (jsonBody && (jsonBody.message)) {
errMsg = jsonBody.message;
} else {
errMsg = util.format('Create Product failed with status code %d', res.statusCode);
}
done(new Error(errMsg));
}
})
}
|
const zlib = require('zlib');
const log = require('winston');
const Mutex = require('../mutex');
const database = require('../models/mysql');
const ENV = process.env.NODE_ENV || 'development';
const config = ENV !== 'test' ? require('../config') : require('../config.sample');
// Constants
const CHARACTERS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
const SECONDS_TO_TIMESTAMP = 43.45;
const MAX_ROWS = 30;
const MIN_MATCH_PERCENT = 0.1;
const MATCH_SLOP = 2;
// Exports
exports.decodeCodeString = decodeCodeString;
exports.cutFPLength = cutFPLength;
exports.getCodesToTimes = getCodesToTimes;
exports.bestMatchForQuery = bestMatchForQuery;
exports.getTrackMetadata = getTrackMetadata;
exports.ingest = ingest;
exports.SECONDS_TO_TIMESTAMP = SECONDS_TO_TIMESTAMP;
exports.MATCH_SLOP = MATCH_SLOP;
// Globals
const gTimestamp = +new Date();
const gMutex = Mutex.getMutex();
/**
* Takes a base64 encoded representation of a zlib-compressed code string
* and passes a fingerprint object to the callback.
*/
function decodeCodeString(codeStr, callback) {
// Fix url-safe characters
codeStr = codeStr.replace(/-/g, '+').replace(/_/g, '/');
// Expand the base64 data into a binary buffer
const compressed = new Buffer(codeStr, 'base64');
// Decompress the binary buffer into ascii hex codes
zlib.inflate(compressed, function(err, uncompressed) {
if (err) return callback(err, null);
// Convert the ascii hex codes into codes and time offsets
const fp = inflateCodeString(uncompressed);
log.debug('Inflated ' + codeStr.length + ' byte code string into ' +
fp.codes.length + ' codes');
callback(null, fp);
});
}
/**
* Takes an uncompressed code string consisting of zero-padded fixed-width
* sorted hex integers and converts it to the standard code string.
*/
function inflateCodeString(buf) {
// 5 hex bytes for hash, 5 hex bytes for time (40 bits per tuple)
const count = Math.floor(buf.length / 5);
const endTimestamps = count / 2;
let i;
const codes = new Array(count / 2);
const times = new Array(count / 2);
for (i = 0; i < endTimestamps; i++) {
times[i] = parseInt(buf.toString('ascii', i * 5, i * 5 + 5), 16);
}
for (i = endTimestamps; i < count; i++) {
codes[i - endTimestamps] = parseInt(buf.toString('ascii', i * 5, i * 5 + 5), 16);
}
// Sanity check
for (i = 0; i < codes.length; i++) {
if (isNaN(codes[i]) || isNaN(times[i])) {
log.error('Failed to parse code/time index ' + i);
return { codes: [], times: [] };
}
}
return { codes: codes, times: times };
}
/**
* Clamp this fingerprint to a maximum N seconds worth of codes.
*/
function cutFPLength(fp, maxSeconds) {
if (!maxSeconds) maxSeconds = 60;
const newFP = {};
for(const key in fp) {
if (fp.hasOwnProperty(key))
newFP[key] = fp[key];
}
const firstTimestamp = fp.times[0];
const sixtySeconds = maxSeconds * SECONDS_TO_TIMESTAMP + firstTimestamp;
for (const i = 0; i < fp.times.length; i++) {
if (fp.times[i] > sixtySeconds) {
log.debug('Clamping ' + fp.codes.length + ' codes to ' + i + ' codes');
newFP.codes = fp.codes.slice(0, i);
newFP.times = fp.times.slice(0, i);
return newFP;
}
}
newFP.codes = fp.codes.slice(0);
newFP.times = fp.times.slice(0);
return newFP;
}
/**
* Finds the closest matching track, if any, to a given fingerprint.
*/
function bestMatchForQuery(fp, threshold, callback) {
fp = cutFPLength(fp);
if (!fp.codes.length)
return callback('No valid fingerprint codes specified', null);
log.debug('Starting query with ' + fp.codes.length + ' codes');
database.fpQuery(fp, MAX_ROWS, function(err, matches) {
if (err) return callback(err, null);
if (!matches || !matches.length) {
log.debug('No matched tracks');
return callback(null, { status: 'NO_RESULTS' });
}
log.debug('Matched ' + matches.length + ' tracks, top code overlap is ' +
matches[0].score);
// If the best result matched fewer codes than our percentage threshold,
// report no results
if (matches[0].score < fp.codes.length * MIN_MATCH_PERCENT)
return callback(null, { status: 'MULTIPLE_BAD_HISTOGRAM_MATCH' });
// Compute more accurate scores for each track by taking time offsets into
// account
const newMatches = [];
for (const i = 0; i < matches.length; i++) {
const match = matches[i];
match.ascore = getActualScore(fp, match, threshold, MATCH_SLOP);
if (match.ascore && match.ascore >= fp.codes.length * MIN_MATCH_PERCENT)
newMatches.push(match);
}
matches = newMatches;
if (!matches.length) {
log.debug('No matched tracks after score adjustment');
return callback(null, { status: 'NO_RESULTS_HISTOGRAM_DECREASED' });
}
// Sort the matches based on actual score
matches.sort(function(a, b) { return b.ascore - a.ascore; });
// If we only had one track match, just use the threshold to determine if
// the match is good enough
if (matches.length === 1) {
if (matches[0].ascore / fp.codes.length >= MIN_MATCH_PERCENT) {
// Fetch metadata for the single match
log.debug('Single good match with actual score ' + matches[0].ascore +
'/' + fp.codes.length);
return getTrackMetadata(matches[0], matches,
'SINGLE_GOOD_MATCH_HISTOGRAM_DECREASED', callback);
} else {
log.debug('Single bad match with actual score ' + matches[0].ascore +
'/' + fp.codes.length);
return callback(null, { status: 'SINGLE_BAD_MATCH' });
}
}
const origTopScore = matches[0].ascore;
// Sort by the new adjusted score
matches.sort(function(a, b) { return b.ascore - a.score; });
const topMatch = matches[0];
const newTopScore = topMatch.ascore;
log.debug('Actual top score is ' + newTopScore + ', next score is ' +
matches[1].ascore);
// If the best result actually matched fewer codes than our percentage
// threshold, report no results
if (newTopScore < fp.codes.length * MIN_MATCH_PERCENT)
return callback(null, { status: 'MULTIPLE_BAD_HISTOGRAM_MATCH' });
// If the actual score was not close enough, then no match
if (newTopScore <= origTopScore / 2)
return callback(null, { status: 'MULTIPLE_BAD_HISTOGRAM_MATCH' });
// If the difference in actual scores between the first and second matches
// is not significant enough, then no match
if (newTopScore - matches[1].ascore < newTopScore / 2)
return callback(null, { status: 'MULTIPLE_BAD_HISTOGRAM_MATCH' });
// Fetch metadata for the top track
getTrackMetadata(topMatch, matches,
'MULTIPLE_GOOD_MATCH_HISTOGRAM_DECREASED', callback);
});
}
/**
* Attach track metadata to a query match.
*/
function getTrackMetadata(match, allMatches, status, callback) {
database.getTrack(match.track_id, function(err, track) {
if (err) return callback(err, null);
if (!track)
return callback('Track ' + match.track_id + ' went missing', null);
match.track = track.name;
match.artist = track.artist_name;
match.artist_id = track.artist_id;
match.length = track.length;
match.import_date = track.import_date;
callback(null, { success: true, status: status, match: match },
allMatches);
});
}
/**
* Build a mapping from each code in the given fingerprint to an array of time
* offsets where that code appears, with the slop factor accounted for in the
* time offsets. Used to speed up getActualScore() calculation.
*/
function getCodesToTimes(match, slop) {
const codesToTimes = {};
for (const i = 0; i < match.codes.length; i++) {
const code = match.codes[i];
const time = Math.floor(match.times[i] / slop) * slop;
if (codesToTimes[code] === undefined)
codesToTimes[code] = [];
codesToTimes[code].push(time);
}
return codesToTimes;
}
/**
* Computes the actual match score for a track by taking time offsets into
* account.
*/
function getActualScore(fp, match, threshold, slop) {
const MAX_DIST = 32767;
if (match.codes.length < threshold)
return 0;
const timeDiffs = {};
let i, j;
const matchCodesToTimes = getCodesToTimes(match, slop);
// Iterate over each {code,time} tuple in the query
for (i = 0; i < fp.codes.length; i++) {
const code = fp.codes[i];
const time = Math.floor(fp.times[i] / slop) * slop;
const minDist = MAX_DIST;
const matchTimes = matchCodesToTimes[code];
if (matchTimes) {
for (j = 0; j < matchTimes.length; j++) {
const dist = Math.abs(time - matchTimes[j]);
// Increment the histogram bucket for this distance
if (timeDiffs[dist] === undefined)
timeDiffs[dist] = 0;
timeDiffs[dist]++;
}
}
}
match.histogram = timeDiffs;
// Convert the histogram into an array, sort it, and sum the top two
// frequencies to compute the adjusted score
const keys = Object.keys(timeDiffs);
const array = new Array(keys.length);
for (i = 0; i < keys.length; i++)
array[i] = [ keys[i], timeDiffs[keys[i]] ];
array.sort(function(a, b) { return b[1] - a[1]; });
if (array.length > 1)
return array[0][1] + array[1][1];
else if (array.length === 1)
return array[0][1];
return 0;
}
/**
* Takes a track fingerprint (includes codes and time offsets plus any
* available metadata), adds it to the database and returns a track_id,
* artist_id, and artist name if available.
*/
function ingest(fp, callback) {
const MAX_DURATION = 60 * 60 * 4;
fp.codever = fp.codever || fp.version;
log.info('Ingesting track "' + fp.track + '" by artist "' + fp.artist +
'", ' + fp.length + ' seconds, ' + fp.codes.length + ' codes (' + fp.codever + ')');
if (!fp.codes.length)
return callback('Missing "codes" array', null);
if (typeof fp.length !== 'number')
return callback('Missing or invalid "length" field', null);
if (!fp.codever)
return callback('Missing or invalid "version" field', null);
if (!fp.track)
return callback('Missing or invalid "track" field', null);
if (!fp.artist)
return callback('Missing or invalid "artist" field', null);
fp = cutFPLength(fp, MAX_DURATION);
// Acquire a lock while modifying the database
gMutex.lock(function() {
// Check if this track already exists in the database
bestMatchForQuery(fp, config.code_threshold, function(err, res) {
if (err) {
gMutex.release();
return callback('Query failed: ' + err, null);
}
if (res.success) {
const match = res.match;
log.info('Found existing match with status ' + res.status +
', track ' + match.track_id + ' ("' + match.track + '") by "' +
match.artist + '"');
const checkUpdateArtist = function() {
if (!match.artist) {
// Existing artist is unnamed but we have a name now. Check if this
// artist name already exists in the database
log.debug('Updating track artist');
database.getArtistByName(fp.artist, function(err, artist) {
if (err) { gMutex.release(); return callback(err, null); }
if (artist) {
log.debug('Setting track artist_id to ' + artist.artist_id);
// Update the track to point to the existing artist
database.updateTrack(match.track_id, match.track,
artist.artist_id, function(err)
{
if (err) { gMutex.release(); return callback(err, null); }
match.artist_id = artist.artist_id;
match.artist = artist.name;
finished(match);
});
} else {
log.debug('Setting artist ' + artist.artist_id + ' name to "' +
artist.name + '"');
// Update the artist name
database.updateArtist(match.artist_id, fp.artist,
function(err)
{
if (err) { gMutex.release(); return callback(err, null); }
match.artist = fp.artist;
finished(match);
});
}
});
} else {
if (match.artist != fp.artist) {
log.warn('New artist name "' + fp.artist + '" does not match ' +
'existing artist name "' + match.artist + '" for track ' +
match.track_id);
}
log.debug('Skipping artist update');
finished(match);
}
};
const finished = function(match) {
// Success
log.info('Track update complete');
gMutex.release();
callback(null, { track_id: match.track_id, track: match.track,
artist_id: match.artist_id, artist: match.artist });
};
if (!match.track && fp.track) {
// Existing track is unnamed but we have a name now. Update the track
log.debug('Updating track name to "' + fp.track + '"');
database.updateTrack(match.track_id, fp.track, match.artist_id,
function(err)
{
if (err) { gMutex.release(); return callback(err, null); }
match.track = fp.track;
checkUpdateArtist();
});
} else {
log.debug('Skipping track name update');
checkUpdateArtist();
}
} else {
// Track does not exist in the database yet
log.debug('Track does not exist in the database yet, status ' +
res.status);
// Does this artist already exist in the database?
database.getArtistByName(fp.artist, function(err, artist) {
if (err) { gMutex.release(); return callback(err, null); }
if (!artist)
createArtistAndTrack();
else
createTrack(artist.artist_id, artist.name);
});
}
// Function for creating a new artist and new track
function createArtistAndTrack() {
log.debug('Adding artist "' + fp.artist + '"')
database.addArtist(fp.artist, function(err, artistID) {
if (err) { gMutex.release(); return callback(err, null); }
// Success
log.info('Created artist ' + artistID + ' ("' + fp.artist + '")');
createTrack(artistID, fp.artist);
});
}
// Function for creating a new track given an artistID
function createTrack(artistID, artist) {
log.debug('Adding track "' + fp.track + '" for artist "' + artist + '" (' + artistID + ')');
database.addTrack(artistID, fp, function(err, trackID) {
if (err) { gMutex.release(); return callback(err, null); }
// Success
log.info('Created track ' + trackID + ' ("' + fp.track + '")');
gMutex.release();
callback(null, { track_id: trackID, track: fp.track,
artist_id: artistID, artist: artist });
});
}
});
});
}
|
//~ name b486
alert(b486);
//~ component b487.js
|
'use strict';
var React = require('react');
var classNames = require('classnames');
var fecha = require('fecha');
var ClassNameMixin = require('./mixins/ClassNameMixin');
var dateUtils = require('./utils/dateUtils');
var Icon = require('./Icon');
var DatePicker = React.createClass({
mixins: [ClassNameMixin],
propTypes: {
onSelect: React.PropTypes.func.isRequired,
onClose: React.PropTypes.func,
getWidget: React.PropTypes.func,
onSubtractMonth: React.PropTypes.func,
onAddMonth: React.PropTypes.func,
viewMode: React.PropTypes.string,
minViewMode: React.PropTypes.string,
daysOfWeekDisabled: React.PropTypes.array,
format: React.PropTypes.string,
date: React.PropTypes.object,
weekStart: React.PropTypes.number,
minDate: React.PropTypes.string,
maxDate: React.PropTypes.string,
locale: React.PropTypes.string
},
getDefaultProps: function() {
return {
classPrefix: 'datepicker',
date: new Date(),
daysOfWeekDisabled: [],
viewMode: 'days',
minViewMode: 'days',
format: 'YYYY-MM-DD',
displayed: {
days: {display: 'block'},
months: {display: 'none'},
years: {display: 'none'}
}
};
},
getInitialState: function() {
var displayed;
switch (this.props.viewMode) {
case 'days':
displayed = {
days: {display: 'block'},
months: {display: 'none'},
years: {display: 'none'}
};
break;
case 'months':
displayed = {
days: {display: 'none'},
months: {display: 'block'},
years: {display: 'none'}
};
break;
case 'years':
displayed = {
days: {display: 'none'},
months: {display: 'none'},
years: {display: 'block'}
};
break;
}
return {
locale: dateUtils.getLocale(this.props.locale),
viewDate: this.props.date,
selectedDate: this.props.date,
displayed: displayed
};
},
// DaysPicker props function
subtractMonth: function() {
const { prevLoading, viewDate } = this.state;
if(prevLoading){
return;
}
var newDate = new Date(viewDate.valueOf());
newDate.setMonth(viewDate.getMonth() - 1);
const { onSubtractMonth } = this.props;
if(onSubtractMonth) {
this.setState({
prevLoading: true
});
onSubtractMonth(newDate, () => {
this.setState({
viewDate: newDate,
prevLoading: false
});
});
}
else{
this.setState({
viewDate: newDate
});
}
},
addMonth: function() {
const { nextLoadingIcon, viewDate } = this.state;
if(nextLoadingIcon){
return;
}
var newDate = new Date(viewDate.valueOf());
newDate.setMonth(viewDate.getMonth() + 1);
const { onAddMonth } = this.props;
if(onAddMonth) {
this.setState({
nextLoading: true
});
onAddMonth(newDate, () => {
this.setState({
viewDate: newDate,
nextLoading: false
});
});
}
else{
this.setState({
viewDate: newDate
});
}
},
setSelectedDate: function(params) {
const { className, date } = params;
if (/disabled|new|old/ig.test(className)) {
return;
}
var viewDate = this.state.viewDate;
//if (/new/ig.test(className)) {
// viewDate.setMonth(viewDate.getMonth() + 1);
//} else if (/old/ig.test(className)) {
// viewDate.setMonth(viewDate.getMonth() - 1);
//}
viewDate.setDate(date);
this.setViewDate(viewDate);
},
setViewDate: function(viewDate) {
this.setState({
viewDate: viewDate,
selectedDate: new Date(viewDate.valueOf())
}, function() {
this.props.onSelect(this.state.selectedDate);
this.props.onClose && this.props.onClose();
});
},
showMonths: function() {
return this.setState({
displayed: {
days: {display: 'none'},
months: {display: 'block'},
years: {display: 'none'}
}
});
},
// MonthsPicker props function
subtractYear: function() {
var viewDate = this.state.viewDate;
var newDate = new Date(viewDate.valueOf());
newDate.setFullYear(viewDate.getFullYear() - 1);
return this.setState({
viewDate: newDate
});
},
addYear: function() {
var viewDate = this.state.viewDate;
var newDate = new Date(viewDate.valueOf());
newDate.setFullYear(viewDate.getFullYear() + 1);
return this.setState({
viewDate: newDate
});
},
showYears: function() {
return this.setState({
displayed: {
days: {display: 'none'},
months: {display: 'none'},
years: {display: 'block'}
}
});
},
setViewMonth: function(event) {
var viewDate = this.state.viewDate;
var month = event.target.innerHTML;
var months = this.state.locale.monthsShort;
var i = 0;
var len = months.length;
for (; i < len; i++) {
if (month === months[i]) {
viewDate.setMonth(i);
}
}
if (this.props.minViewMode === 'months') {
this.setViewDate(viewDate);
}
this.setState({
viewDate: viewDate,
displayed: {
days: {display: 'block'},
months: {display: 'none'},
years: {display: 'none'}
}
});
},
// YearsPicker props function
setViewYear: function(event) {
var year = event.target.innerHTML;
var viewDate = this.state.viewDate;
viewDate.setFullYear(year);
if (this.props.minViewMode === 'years') {
this.setViewDate(viewDate);
}
this.setState({
viewDate: viewDate,
displayed: {
days: {display: 'none'},
months: {display: 'block'},
years: {display: 'none'}
}
});
},
addDecade: function() {
var viewDate = this.state.viewDate;
var newDate = new Date(viewDate.valueOf());
newDate.setFullYear(viewDate.getFullYear() + 10);
this.setState({
viewDate: newDate
});
},
subtractDecade: function() {
var viewDate = this.state.viewDate;
var newDate = new Date(viewDate.valueOf());
newDate.setFullYear(viewDate.getFullYear() - 10);
this.setState({
viewDate: newDate
});
},
// render children
renderDays: function() {
return (
<DaysPicker
{...this.state}
subtractMonth={this.subtractMonth}
addMonth={this.addMonth}
setSelectedDate={this.setSelectedDate}
showMonths={this.showMonths}
getWidget={this.props.getWidget}
weekStart={this.props.weekStart}
daysOfWeekDisabled={this.props.daysOfWeekDisabled}
minDate={this.props.minDate}
maxDate={this.props.maxDate}
/>
);
},
renderMonths: function() {
return (
<MonthsPicker
style={this.state.displayed.months}
locale={this.state.locale}
addYear={this.addYear}
subtractYear={this.subtractYear}
viewDate={this.state.viewDate}
selectedDate={this.state.selectedDate}
showYears={this.showYears}
setViewMonth={this.setViewMonth} />
);
},
renderYears: function() {
return (
<YearsPicker
style={this.state.displayed.years}
viewDate={this.state.viewDate}
selectDate={this.state.selectedDate}
setViewYear={this.setViewYear}
addDecade={this.addDecade}
subtractDecade={this.subtractDecade} />
);
},
render: function() {
return (
<div className={this.prefixClass('body')}>
{this.renderDays()}
{this.renderMonths()}
{this.renderYears()}
</div>
);
}
});
var DaysPicker = React.createClass({
mixins: [ClassNameMixin],
//propTypes: {
// subtractMonth: React.PropTypes.func.isRequired,
// addMonth: React.PropTypes.func.isRequired,
//
// setSelectedDate: React.PropTypes.func.isRequired,
// selectedDate: React.PropTypes.object.isRequired,
//
// viewDate: React.PropTypes.object.isRequired,
// showMonths: React.PropTypes.func.isRequired,
//
// locale: React.PropTypes.object,
// weekStart: React.PropTypes.number,
// daysOfWeekDisabled: React.PropTypes.array,
// minDate: React.PropTypes.string,
// maxDate: React.PropTypes.string
//},
getInitialState: function() {
return {
prevLoading: this.props.prevLoading,
nextLoading: this.props.nextLoading
};
},
getDefaultProps: function() {
return {
classPrefix: 'datepicker'
};
},
renderDays: function(getWidget = ({year, month, date}) => date) {
var row;
var i;
var _ref;
var _i;
var _len;
var prevY;
var prevM;
var classes = {};
var html = [];
var cells = [];
var weekStart = this.props.weekStart || this.props.locale.weekStart;
var weekEnd = ((weekStart + 6) % 7);
var d = this.props.viewDate;
var year = d.getFullYear();
var month = d.getMonth();
var selectedDate = this.props.selectedDate;
var currentDate = new Date(selectedDate.getFullYear(), selectedDate.getMonth(), selectedDate.getDate(), 0, 0, 0, 0).valueOf();
var prevMonth = new Date(year, month - 1, 28, 0, 0, 0, 0);
var day = dateUtils.getDaysInMonth(prevMonth.getFullYear(), prevMonth.getMonth());
prevMonth.setDate(day);
prevMonth.setDate(day - (prevMonth.getDay() - weekStart + 7) % 7);
var nextMonth = new Date(prevMonth);
nextMonth.setDate(nextMonth.getDate() + 42);
nextMonth = nextMonth.valueOf();
var minDate = this.props.minDate && fecha.parse(this.props.minDate);
var maxDate = this.props.maxDate && fecha.parse(this.props.maxDate);
while (prevMonth.valueOf() < nextMonth) {
classes[this.prefixClass('day')] = true;
prevY = prevMonth.getFullYear();
prevM = prevMonth.getMonth();
// set className old new
if ((prevM < month && prevY === year) || prevY < year) {
classes[this.prefixClass('old')] = true;
} else if ((prevM > month && prevY === year) || prevY > year) {
classes[this.prefixClass('new')] = true;
}
// set className active
if (prevMonth.valueOf() === currentDate) {
classes[this.setClassNamespace('active')] = true;
}
// set className disabled
if ((minDate && prevMonth.valueOf() < minDate)
|| (maxDate && prevMonth.valueOf() > maxDate)) {
classes[this.setClassNamespace('disabled')] = true;
}
// week disabled
if (this.props.daysOfWeekDisabled) {
_ref = this.props.daysOfWeekDisabled;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
i = _ref[_i];
if (prevMonth.getDay() === this.props.daysOfWeekDisabled[i]) {
classes[this.setClassNamespace('disabled')] = true;
break;
}
}
}
let date = prevMonth.getDate();
let className = classNames(classes);
cells.push(
<td
key={prevMonth.getMonth() + '-' + date}
className={className}
onClick={() => this.props.setSelectedDate({
className,
date
})}>
{getWidget({
year: d.getFullYear(),
month: prevMonth.getMonth(),
date
})}
</td>
);
// add tr
if (prevMonth.getDay() === weekEnd) {
row = <tr key={prevMonth.getMonth() + '-' + prevMonth.getDate()}>{cells}</tr>;
html.push(row);
cells = [];
}
classes = {};
prevMonth.setDate(prevMonth.getDate() + 1);
}
return html;
},
renderWeek: function() {
var ths = [];
var locale = this.props.locale;
var weekStart = this.props.weekStart || this.props.locale.weekStart;
var weekEnd = weekStart + 7;
while (weekStart < weekEnd) {
ths.push(
<th key={weekStart} className={this.prefixClass('dow')}>
{locale.daysMin[weekStart++ % 7]}
</th>
);
}
return (
<tr>
{ths}
</tr>
);
},
componentWillReceiveProps: function(nextProps) {
const { prevLoading, nextLoading } = nextProps;
this.setState({
prevLoading,
nextLoading
})
},
render: function() {
var prefixClass = this.prefixClass;
var { viewDate, locale, getWidget } = this.props;
return (
<div
className={prefixClass('days')}
style={this.props.displayed.days}>
<table className={prefixClass('table')}>
<thead>
<tr className={prefixClass('header')}>
<th className={prefixClass('prev')} onClick={this.props.subtractMonth}>
{
this.state.prevLoading ?
<Icon spin icon="circle-o-notch" />
:
<i className={prefixClass('prev-icon')}></i>
}
</th>
<th
className={prefixClass('switch')}
colSpan="5"
onClick={this.props.showMonths}>
<div className={this.prefixClass('select')}>
{locale.monthsShort[viewDate.getMonth()]}
{viewDate.getFullYear()}
</div>
</th>
<th className={prefixClass('next')} onClick={this.props.addMonth}>
{
this.state.nextLoading ?
<Icon spin icon="circle-o-notch" />
:
<i className={prefixClass('next-icon')}></i>
}
</th>
</tr>
{this.renderWeek()}
</thead>
<tbody>
{this.renderDays(getWidget)}
</tbody>
</table>
</div>
);
}
});
var MonthsPicker = React.createClass({
mixins: [ClassNameMixin],
propTypes: {
locale: React.PropTypes.object,
subtractYear: React.PropTypes.func.isRequired,
addYear: React.PropTypes.func.isRequired,
viewDate: React.PropTypes.object.isRequired,
selectedDate: React.PropTypes.object.isRequired,
showYears: React.PropTypes.func.isRequired,
setViewMonth: React.PropTypes.func.isRequired,
minDate: React.PropTypes.string,
maxDate: React.PropTypes.string
},
getDefaultProps: function() {
return {
classPrefix: 'datepicker'
};
},
renderMonths: function() {
var classes = {};
var month = this.props.selectedDate.getMonth();
var year = this.props.selectedDate.getFullYear();
var i = 0;
var months = [];
var minDate = this.props.minDate && fecha.parse(this.props.minDate);
var maxDate = this.props.maxDate && fecha.parse(this.props.maxDate);
var prevMonth = new Date(year, month);
// TODO: minDate maxDate months
while (i < 12) {
classes[this.prefixClass('month')] = true;
if (this.props.viewDate.getFullYear() ===
this.props.selectedDate.getFullYear()
&& i === month) {
classes[this.setClassNamespace('active')] = true;
}
// set className disabled
if ((minDate && prevMonth.valueOf() < minDate)
|| (maxDate && prevMonth.valueOf() > maxDate)) {
classes[this.setClassNamespace('disabled')] = true;
}
months.push(
<span
className={classNames(classes)}
onClick={this.props.setViewMonth}
key={i}>
{this.props.locale.monthsShort[i]}
</span>
);
classes = {};
i++;
}
return months;
},
render: function() {
return (
<SubPicker
displayName="months"
style={this.props.style}
subtract={this.props.subtractYear}
add={this.props.addYear}
showFunc={this.props.showYears}
showText={this.props.viewDate.getFullYear()}
body={this.renderMonths()} />
);
}
});
var YearsPicker = React.createClass({
mixins: [ClassNameMixin],
propTypes: {
viewDate: React.PropTypes.object.isRequired,
selectDate: React.PropTypes.object.isRequired,
subtractDecade: React.PropTypes.func.isRequired,
addDecade: React.PropTypes.func.isRequired,
setViewYear: React.PropTypes.func.isRequired
},
getDefaultProps: function() {
return {
classPrefix: 'datepicker'
};
},
renderYears: function() {
var classes = {};
var years = [];
var i = -1;
var year = parseInt(this.props.viewDate.getFullYear() / 10, 10) * 10;
year--;
while (i < 11) {
classes[this.prefixClass('year')] = true;
if (i === -1 || i === 10) {
classes[this.prefixClass('old')] = true;
}
if (this.props.selectDate.getFullYear() === year) {
classes[this.setClassNamespace('active')] = true;
}
years.push(
<span
className={classNames(classes)}
onClick={this.props.setViewYear}
key={year}>
{year}
</span>
);
classes = {};
year++;
i++;
}
return years;
},
render: function() {
var year = parseInt(this.props.viewDate.getFullYear() / 10, 10) * 10;
var addYear = year + 9;
var showYear = year + '-' + addYear;
return (
<SubPicker
displayName="years"
style={this.props.style}
subtract={this.props.subtractDecade}
add={this.props.addDecade}
showText={showYear}
body={this.renderYears()} />
);
}
});
var SubPicker = React.createClass({
mixins: [ClassNameMixin],
getDefaultProps: function() {
return {
classPrefix: 'datepicker'
};
},
render: function() {
var prefixClass = this.prefixClass;
return (
<div
className={prefixClass(this.props.displayName)}
style={this.props.style}>
<table className={prefixClass('table')}>
<thead>
<tr className={prefixClass('header')}>
<th className={prefixClass('prev')} onClick={this.props.subtract}>
<i className={prefixClass('prev-icon')}></i>
</th>
<th
className={prefixClass('switch')}
colSpan="5"
onClick={this.props.showFunc}>
<div className={this.prefixClass('select')}>
{this.props.showText}
</div>
</th>
<th className={prefixClass('next')} onClick={this.props.add}>
<i className={prefixClass('next-icon')}></i>
</th>
</tr>
</thead>
<tbody>
<tr>
<td colSpan="7">
{this.props.body}
</td>
</tr>
</tbody>
</table>
</div>
);
}
});
module.exports = DatePicker;
|
/* ========================================================================
* DOM-based Routing
* Based on http://goo.gl/EUTi53 by Paul Irish
*
* Only fires on body classes that match. If a body class contains a dash,
* replace the dash with an underscore when adding it to the object below.
*
* .noConflict()
* The routing is enclosed within an anonymous function so that you can
* always reference jQuery with $, even when in .noConflict() mode.
* ======================================================================== */
(function($) {
// Use this variable to set up the common and page specific functions. If you
// rename this variable, you will also need to rename the namespace below.
var Gruntd = {
// All pages
'common': {
init: function() {
// JavaScript to be fired on all pages
},
finalize: function() {
// JavaScript to be fired on all pages, after page specific JS is fired
}
},
// Home page
'home': {
init: function() {
// JavaScript to be fired on the home page
},
finalize: function() {
// JavaScript to be fired on the home page, after the init JS
}
},
// About us page, note the change from about-us to about_us.
'about_us': {
init: function() {
// JavaScript to be fired on the about us page
}
}
};
// The routing fires all common scripts, followed by the page specific scripts.
// Add additional events for more control over timing e.g. a finalize event
var UTIL = {
fire: function(func, funcname, args) {
var fire;
var namespace = Gruntd;
funcname = (funcname === undefined) ? 'init' : funcname;
fire = func !== '';
fire = fire && namespace[func];
fire = fire && typeof namespace[func][funcname] === 'function';
if (fire) {
namespace[func][funcname](args);
}
},
loadEvents: function() {
// Fire common init JS
UTIL.fire('common');
// Fire page-specific init JS, and then finalize JS
$.each(document.body.className.replace(/-/g, '_').split(/\s+/), function(i, classnm) {
UTIL.fire(classnm);
UTIL.fire(classnm, 'finalize');
});
// Fire common finalize JS
UTIL.fire('common', 'finalize');
}
};
// Load Events
$(document).ready(UTIL.loadEvents);
})(jQuery); // Fully reference jQuery after this point. |
var searchData=
[
['barelog_5fbuf_5fmax_5fsize',['BARELOG_BUF_MAX_SIZE',['../barelog__internal_8h.html#a8d9cd5cdc907ebe2a557b3ab745a7da2',1,'barelog_internal.h']]],
['barelog_5fbuffer_2eh',['barelog_buffer.h',['../barelog__buffer_8h.html',1,'']]],
['barelog_5fcheck_5fmode',['BARELOG_CHECK_MODE',['../barelog__config_8h.html#a21643c66dcad774fec1747abf3f7833b',1,'barelog_config.h']]],
['barelog_5fclean',['barelog_clean',['../barelog__logger_8h.html#a35151c45dc22a94d4ef0b1e8d8da34d7',1,'barelog_logger.h']]],
['barelog_5fclean_5fbuffer',['barelog_clean_buffer',['../barelog__logger_8h.html#a38ece7d71d09e3965c534f9b39b02ebb',1,'barelog_logger.h']]],
['barelog_5fclean_5fmemory',['barelog_clean_memory',['../barelog__logger_8h.html#a18b4d799895114f1cef69879206f9c43',1,'barelog_logger.h']]],
['barelog_5fconfig_2eh',['barelog_config.h',['../barelog__config_8h.html',1,'']]],
['barelog_5fdebug_5flog',['barelog_debug_log',['../barelog__device__mem__manager_8h.html#ae41a0e6ea107251288d2e0ca4de4c81e',1,'barelog_device_mem_manager.c']]],
['barelog_5fdebug_5fmem_5fsize',['BARELOG_DEBUG_MEM_SIZE',['../barelog__internal_8h.html#a5443c867d828e16a561c6202f18a4927',1,'barelog_internal.h']]],
['barelog_5fdebug_5fmode_5fi',['BARELOG_DEBUG_MODE_I',['../barelog__internal_8h.html#ab843abc36635fd4f46988ded99b1d4a6',1,'barelog_internal.h']]],
['barelog_5fdebug_5foff',['BARELOG_DEBUG_OFF',['../barelog__internal_8h.html#a372dbd94e3623bd817e72b79208968ae',1,'barelog_internal.h']]],
['barelog_5fdevice_5fmem_5fmanager_2eh',['barelog_device_mem_manager.h',['../barelog__device__mem__manager_8h.html',1,'']]],
['barelog_5fdevice_5fmem_5fmanager_5ft',['barelog_device_mem_manager_t',['../structbarelog__device__mem__manager__t.html',1,'']]],
['barelog_5ferr',['BARELOG_ERR',['../barelog__internal_8h.html#ae86020de5c6cb50535fefba1017d4b76',1,'barelog_internal.h']]],
['barelog_5fevent_2eh',['barelog_event.h',['../barelog__event_8h.html',1,'']]],
['barelog_5fevent_5fbuffer_5ft',['barelog_event_buffer_t',['../structbarelog__event__buffer__t.html',1,'']]],
['barelog_5fevent_5fconversion_5ferr',['BARELOG_EVENT_CONVERSION_ERR',['../barelog__internal_8h.html#adf293d3662c5eb9dde0a9131b6788c5a',1,'barelog_internal.h']]],
['barelog_5fevent_5finitializer',['BARELOG_EVENT_INITIALIZER',['../barelog__event_8h.html#a2da2edea64e53dd86c4d7480987b260c',1,'barelog_event.c']]],
['barelog_5fevent_5fmax_5fsize',['BARELOG_EVENT_MAX_SIZE',['../barelog__config_8h.html#adbd7a03a709aa4ad63455907ff05b98a',1,'barelog_config.h']]],
['barelog_5fevent_5fper_5fcore_5fmax',['BARELOG_EVENT_PER_CORE_MAX',['../barelog__internal_8h.html#a0db5f41516ff95d960031b9e9710015e',1,'barelog_internal.h']]],
['barelog_5fevent_5fper_5fcore_5fshr_5fmem_5fmax',['BARELOG_EVENT_PER_CORE_SHR_MEM_MAX',['../barelog__internal_8h.html#a75ca1f6b4314062cd744575f81c95d14',1,'barelog_internal.h']]],
['barelog_5fevent_5fshared_5fmem_5fmax',['BARELOG_EVENT_SHARED_MEM_MAX',['../barelog__config_8h.html#a3678960a8851bdd48135dff9c5213e7a',1,'barelog_config.h']]],
['barelog_5fevent_5fto_5fstring',['barelog_event_to_string',['../barelog__event_8h.html#a6ab0a60f23ea76c67dd90f4cb0ee3faf',1,'barelog_event.c']]],
['barelog_5fevents_5fto_5fstrings',['barelog_events_to_strings',['../barelog__event_8h.html#a5823fda9b5116074be16949a43bb59dc',1,'barelog_event.c']]],
['barelog_5fflush',['barelog_flush',['../barelog__logger_8h.html#a4e17f1118b4323a4713ad3fd44029ad6',1,'barelog_logger.h']]],
['barelog_5fflush_5fbuffer',['barelog_flush_buffer',['../barelog__logger_8h.html#a1f8c580e0d20aa7b1e46ac6460d3dc75',1,'barelog_logger.h']]],
['barelog_5fhost_2eh',['barelog_host.h',['../barelog__host_8h.html',1,'']]],
['barelog_5fhost_5ffinalize',['barelog_host_finalize',['../barelog__host_8h.html#a251f4daf501e3e81586ebccebeacabe9',1,'barelog_host.h']]],
['barelog_5fhost_5finit',['barelog_host_init',['../barelog__host_8h.html#adc51587704401a7222bd82433c881477',1,'barelog_host.h']]],
['barelog_5fhost_5fmem_5fmanager_2eh',['barelog_host_mem_manager.h',['../barelog__host__mem__manager_8h.html',1,'']]],
['barelog_5fhost_5fmem_5fmanager_5ft',['barelog_host_mem_manager_t',['../structbarelog__host__mem__manager__t.html',1,'']]],
['barelog_5fhost_5fnb_5fmem_5fspace',['BARELOG_HOST_NB_MEM_SPACE',['../barelog__internal_8h.html#a8b7b9073115ca0b347395e670a18b5ae',1,'barelog_internal.h']]],
['barelog_5fimmediate_5flog',['barelog_immediate_log',['../barelog__logger_8h.html#a077e57831374ce9a9d03ba3f219e9aab',1,'barelog_logger.c']]],
['barelog_5finconsistent_5fparam_5ferr',['BARELOG_INCONSISTENT_PARAM_ERR',['../barelog__internal_8h.html#abe27725d8e59d581efada773fd7fb744',1,'barelog_internal.h']]],
['barelog_5finit_5ferr',['BARELOG_INIT_ERR',['../barelog__internal_8h.html#ae561d4cd02833b3e78fb34330b3c584d',1,'barelog_internal.h']]],
['barelog_5finit_5flogger',['barelog_init_logger',['../barelog__logger_8h.html#a6c9c8e207a3c017a4af8fc45740c810e',1,'barelog_logger.c']]],
['barelog_5finternal_2eh',['barelog_internal.h',['../barelog__internal_8h.html',1,'']]],
['barelog_5fis_5fbuffer_5ffull',['barelog_is_buffer_full',['../barelog__logger_8h.html#a708663a1f867c54263802c197f2ea9a9',1,'barelog_logger.h']]],
['barelog_5flocal_5fmem_5fattribute',['BARELOG_LOCAL_MEM_ATTRIBUTE',['../barelog__config_8h.html#af198078f08d5e61dc440b2cf7e31286b',1,'barelog_config.h']]],
['barelog_5flocal_5fmem_5fper_5fcore',['BARELOG_LOCAL_MEM_PER_CORE',['../barelog__config_8h.html#a46d23e6eb872fe6d3c97dbcd52005386',1,'barelog_config.h']]],
['barelog_5flog',['barelog_log',['../barelog__logger_8h.html#a3f42b27ec9aa7b19502fe9db114a39f4',1,'barelog_logger.c']]],
['barelog_5flogger_2eh',['barelog_logger.h',['../barelog__logger_8h.html',1,'']]],
['barelog_5flogger_5ft',['barelog_logger_t',['../structbarelog__logger__t.html',1,'']]],
['barelog_5flvl_5ft',['barelog_lvl_t',['../barelog__logger_8h.html#a09445da48188bdd9761a1d9bf15deade',1,'barelog_logger.h']]],
['barelog_5fmem_5fspace_2eh',['barelog_mem_space.h',['../barelog__mem__space_8h.html',1,'']]],
['barelog_5fmutex_5ftry_5fmax',['BARELOG_MUTEX_TRY_MAX',['../barelog__internal_8h.html#ad3cba03f5fc2b6448a15ea8a34f0e87c',1,'barelog_internal.h']]],
['barelog_5fnb_5fcores',['BARELOG_NB_CORES',['../barelog__config_8h.html#a3405b9c787df23d99fcc3dad7c0420fe',1,'barelog_config.h']]],
['barelog_5fnb_5fmutex_5fbytes',['BARELOG_NB_MUTEX_BYTES',['../barelog__internal_8h.html#a56153de1682f3a1ddc452d6c87c227e4',1,'barelog_internal.h']]],
['barelog_5fparallella_2eh',['barelog_parallella.h',['../barelog__parallella_8h.html',1,'']]],
['barelog_5fplatform_2eh',['barelog_platform.h',['../barelog__platform_8h.html',1,'']]],
['barelog_5fplatform_5fname_5flength',['BARELOG_PLATFORM_NAME_LENGTH',['../barelog__config_8h.html#af3972df4d0e009ef87735cebe7fe05d5',1,'barelog_config.h']]],
['barelog_5fplatform_5ft',['barelog_platform_t',['../structbarelog__platform__t.html',1,'']]],
['barelog_5fpolicy_2eh',['barelog_policy.h',['../barelog__policy_8h.html',1,'']]],
['barelog_5fpolicy_5ft',['barelog_policy_t',['../barelog__policy_8h.html#adf17e1225b1df5ab70f4acb5a0eb2492',1,'barelog_policy.h']]],
['barelog_5fread_5fdebug',['barelog_read_debug',['../barelog__host_8h.html#af16c1c90ec01a10f79c15bca92b1b4e5',1,'barelog_host.h']]],
['barelog_5fread_5flog',['barelog_read_log',['../barelog__host_8h.html#a39f8463674313efe620ad779bed94bed',1,'barelog_host.h']]],
['barelog_5fresult_5fbuffer_5ft',['barelog_result_buffer_t',['../structbarelog__result__buffer__t.html',1,'']]],
['barelog_5fsafe_5fmem_5fsize',['BARELOG_SAFE_MEM_SIZE',['../barelog__internal_8h.html#a6ba206438e1c8724ce901ff59a29569f',1,'barelog_internal.h']]],
['barelog_5fsafe_5fmode_5fi',['BARELOG_SAFE_MODE_I',['../barelog__internal_8h.html#a6719c2e921ad3698290fdfc28302c4f7',1,'barelog_internal.h']]],
['barelog_5fshared_5fmem_5fbuffer_5ft',['barelog_shared_mem_buffer_t',['../structbarelog__shared__mem__buffer__t.html',1,'']]],
['barelog_5fshared_5fmem_5fdata_5foffset',['BARELOG_SHARED_MEM_DATA_OFFSET',['../barelog__internal_8h.html#a694628a89d860b954b30562d0c201af0',1,'barelog_internal.h']]],
['barelog_5fshared_5fmem_5fmax',['BARELOG_SHARED_MEM_MAX',['../barelog__internal_8h.html#a03842085df1dfd440a5dbb0032507fdb',1,'barelog_internal.h']]],
['barelog_5fshared_5fmem_5fper_5fcore_5fmax',['BARELOG_SHARED_MEM_PER_CORE_MAX',['../barelog__internal_8h.html#a81d48d8a2d9ba70a5710be211002df02',1,'barelog_internal.h']]],
['barelog_5fshrmem_5fmutex_5ft',['barelog_shrmem_mutex_t',['../barelog__internal_8h.html#a85371d0996813ce16cd2a06e448ecb9a',1,'barelog_internal.h']]],
['barelog_5fshrmem_5fread_5ferr',['BARELOG_SHRMEM_READ_ERR',['../barelog__internal_8h.html#a04e118632fee1fd5faf8712b889416c1',1,'barelog_internal.h']]],
['barelog_5fshrmem_5fwrite_5ferr',['BARELOG_SHRMEM_WRITE_ERR',['../barelog__internal_8h.html#a26d0e9c86ed3cc25b150255627659b88',1,'barelog_internal.h']]],
['barelog_5fstart',['barelog_start',['../barelog__logger_8h.html#ad368580e97a1ce261a3172f99e11efc0',1,'barelog_logger.c']]],
['barelog_5fsuccess',['BARELOG_SUCCESS',['../barelog__internal_8h.html#a7906d289cf4c344e7e93efe1330f0182',1,'barelog_internal.h']]],
['barelog_5ftimeout_5ferr',['BARELOG_TIMEOUT_ERR',['../barelog__internal_8h.html#a7921720d17d197465d04cdb33ba1804e',1,'barelog_internal.h']]],
['barelog_5funinitialized_5fparam_5ferr',['BARELOG_UNINITIALIZED_PARAM_ERR',['../barelog__internal_8h.html#a62a01b98a93da6ef07f3019c51c43779',1,'barelog_internal.h']]],
['buffer',['buffer',['../structbarelog__event__buffer__t.html#a788be0cb9a3d0b2fa0f2267751d291fd',1,'barelog_event_buffer_t::buffer()'],['../structbarelog__result__buffer__t.html#a676e81d3d45d9e435813ed4d8b1836a6',1,'barelog_result_buffer_t::buffer()']]],
['buffer_5flength',['buffer_length',['../structbarelog__result__buffer__t.html#ad807aed2908c3ad38248e48671962732',1,'barelog_result_buffer_t']]]
];
|
// App.js
import React from 'react';
import { browserHistory } from 'react-router';
// import components
import NavBar from './navbar/components/NavBar';
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {}
this.getComponentsXHR = this.getComponentsXHR.bind(this);
this.checkUser = this.checkUser.bind(this);
this.sendComponentsToStore = this.sendComponentsToStore.bind(this);
this.getPostsXHR = this.getPostsXHR.bind(this);
this.sendPostsToStore = this.sendPostsToStore.bind(this);
}
componentDidMount() {
this.getComponentsXHR();
this.getPostsXHR();
let token = localStorage.getItem('token');
if(!token) {
this.checkUser();
}
}
checkUser() {
let that = this;
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = () => {
if(xhr.status === 200 && xhr.readyState === 4) {
that.handleUserData(JSON.parse(xhr.responseText));
}
}
xhr.open('GET', '/api/users');
xhr.send();
}
handleUserData(userData) {
if(userData.length === 0) {
browserHistory.push('/signup')
}
}
getComponentsXHR() {
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = () => {
if(xhr.status === 200 && xhr.readyState === 4) {
this.sendComponentsToStore(JSON.parse(xhr.responseText));
}
}
xhr.open('GET', '/api/plugins');
xhr.send();
}
sendComponentsToStore(pluginData) {
let plugins = [];
pluginData.forEach(plugin => {
plugins.push(plugin);
})
this.props.getComponents(plugins);
}
getPostsXHR() {
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = () => {
if(xhr.status === 200 && xhr.readyState === 4) {
this.sendPostsToStore(JSON.parse(xhr.responseText));
}
}
xhr.open('GET', '/api/posts');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send();
}
sendPostsToStore(postData) {
let posts = {};
postData.forEach(post => {
posts[post._id] = post;
})
this.props.getPosts(posts);
}
logoutUser() {
localStorage.removeItem('token');
localStorage.removeItem('userId')
}
render() {
return (
<div>
<NavBar hasToken={this.props.user} logoutUser={this.logoutUser} />
<div className="container-fluid">
{React.cloneElement(this.props.children, this.props)}
</div>
</div>
)
}
}
|
const vboxm = require('./vboxm.js');
//vboxm.clone('8a07a800-4bef-4cc7-9581-6d03a2fab45f', 'vboxm.cloneテスト');
// vboxm.delete('db7cd51b-ac5b-4915-859e-20b88bcf68c2');
let name = 'aiueo,kakikukeko???kdfajlsd';
let regResult = name.match(/^[a-zA-Z0-9!\(\)-=^~\\|@`\[{;+:*\]},<.>/?\_ ]+$/);
console.log(regResult);
|
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "default", {
enumerable: true,
get: function get() {
return _uxcorePopover.default;
}
});
var _uxcorePopover = _interopRequireDefault(require("uxcore-popover"));
module.exports = exports.default; |
/*
Load a block from github.io.
Accepts a url as a parameter which can include url parameters e.g. https://megjlow.github.io/extension2.js?name=SUN&ip=10.0.0.1
*/
new (function() {
var ext = this;
var descriptor = {
blocks: [
[' ', 'Load extension block ip %s', 'loadBlock', 'ip', 'ip'],
[' ', 'Load extension block name %s', 'loadBlock', 'name', 'name'],
],
url: 'http://www.warwick.ac.uk/tilesfortales'
};
ext._shutdown = function() {};
ext._getStatus = function() {
return {status: 2, msg: 'Device connected'}
};
ext.loadBlock = function(ip) {
ScratchExtensions.loadExternalJS("https://megjlow.github.io/socket.js?ip=" + ip);
};
ext.loadBlockName = function(name) {
ScratchExtensions.loadExternalJS("https://megjlow.github.io/socket.js?name=" + name);
};
ScratchExtensions.register("extensionloader", descriptor, ext);
}); |
/*! @license pzprv3-ui.js v<%= pkg.version %> (c) 2009-<%= grunt.template.today('yyyy') %> <%= pkg.author %>, MIT license
* https://bitbucket.org/sabo2/pzprv3 */
|
const test = require('tape')
const nlp = require('../_lib')
test('number-tag:', function (t) {
let arr = [
['16.125', 'Cardinal'],
['+160.125', 'Cardinal'],
['-0.1', 'Cardinal'],
['.13', 'Cardinal'],
['(127.54)', 'Cardinal'],
['16.125th', 'Ordinal'],
['161,253th', 'Ordinal'],
['+160.125th', 'Ordinal'],
['-0.2nd', 'Ordinal'],
['(127.54th)', 'Ordinal'],
// ['(127.54)', 'Money'],
['-0.1%', 'Percent'],
['.1%', 'Percent'],
['+2,340.91%', 'Percent'],
['-2340%', 'Percent'],
['$-2340.01', 'Money'],
['-$2340', 'Money'],
['+$2340.01', 'Money'],
['$2340.01', 'Money'],
['£1,000,000', 'Money'],
['$19', 'Money'],
['($127.54)', 'Money'],
['2,000₽', 'Money'],
['2000₱', 'Money'],
['2000௹', 'Money'],
['₼2000', 'Money'],
['2.23₽', 'Money'],
['₺50', 'Money'],
['$47.5m', 'Money'],
['$47.5bn', 'Money'],
// ['1,000,000p', 'Cardinal'],
]
arr.forEach(function (a) {
let doc = nlp(a[0])
t.equal(doc.has('#' + a[1]), true, a[0] + ' is #' + a[1])
})
t.end()
})
|
(function($) {
module("autocomplete: options");
test('setAttributes', function() {
var source = $('#autocomplete').autocomplete("option", "source");
equals(source.join(','), ['ActionScript','AppleScript','Asp','BASIC','C','C++','Clojure','COBOL','ColdFusion','Erlang','Fortran','Groovy','Haskell','Java','JavaScript','Lisp','Perl','PHP','Python','Ruby','Scala','Scheme'].join(','), 'Array property');
var autoFocus = $('#autocomplete').autocomplete("option", "autoFocus");
equals(autoFocus, true, 'Boolean property');
var appendTo = $('#autocomplete').autocomplete("option", "appendTo");
equals(appendTo, '#destination', 'String property');
var minLength = $('#autocomplete').autocomplete("option", "minLength");
equals(minLength, 2, 'Number property');
});
})(jQuery); |
'use strict'
const t = require('tap')
const test = t.test
const FindMyWay = require('../')
test('case insensitive static routes of level 1', t => {
t.plan(1)
const findMyWay = FindMyWay({
caseSensitive: false,
defaultRoute: (req, res) => {
t.fail('Should not be defaultRoute')
}
})
findMyWay.on('GET', '/woo', (req, res, params) => {
t.pass('we should be here')
})
findMyWay.lookup({ method: 'GET', url: '/WOO', headers: {} }, null)
})
test('case insensitive static routes of level 2', t => {
t.plan(1)
const findMyWay = FindMyWay({
caseSensitive: false,
defaultRoute: (req, res) => {
t.fail('Should not be defaultRoute')
}
})
findMyWay.on('GET', '/foo/woo', (req, res, params) => {
t.pass('we should be here')
})
findMyWay.lookup({ method: 'GET', url: '/FoO/WOO', headers: {} }, null)
})
test('case insensitive static routes of level 3', t => {
t.plan(1)
const findMyWay = FindMyWay({
caseSensitive: false,
defaultRoute: (req, res) => {
t.fail('Should not be defaultRoute')
}
})
findMyWay.on('GET', '/foo/bar/woo', (req, res, params) => {
t.pass('we should be here')
})
findMyWay.lookup({ method: 'GET', url: '/Foo/bAR/WoO', headers: {} }, null)
})
test('parametric case insensitive', t => {
t.plan(1)
const findMyWay = FindMyWay({
caseSensitive: false,
defaultRoute: (req, res) => {
t.fail('Should not be defaultRoute')
}
})
findMyWay.on('GET', '/foo/:param', (req, res, params) => {
t.equal(params.param, 'bAR')
})
findMyWay.lookup({ method: 'GET', url: '/Foo/bAR', headers: {} }, null)
})
test('parametric case insensitive with a static part', t => {
t.plan(1)
const findMyWay = FindMyWay({
caseSensitive: false,
defaultRoute: (req, res) => {
t.fail('Should not be defaultRoute')
}
})
findMyWay.on('GET', '/foo/my-:param', (req, res, params) => {
t.equal(params.param, 'bAR')
})
findMyWay.lookup({ method: 'GET', url: '/Foo/MY-bAR', headers: {} }, null)
})
test('parametric case insensitive with capital letter', t => {
t.plan(1)
const findMyWay = FindMyWay({
caseSensitive: false,
defaultRoute: (req, res) => {
t.fail('Should not be defaultRoute')
}
})
findMyWay.on('GET', '/foo/:Param', (req, res, params) => {
t.equal(params.Param, 'bAR')
})
findMyWay.lookup({ method: 'GET', url: '/Foo/bAR', headers: {} }, null)
})
test('case insensitive with capital letter in static path with param', t => {
t.plan(1)
const findMyWay = FindMyWay({
caseSensitive: false,
defaultRoute: (req, res) => {
t.fail('Should not be defaultRoute')
}
})
findMyWay.on('GET', '/Foo/bar/:param', (req, res, params) => {
t.equal(params.param, 'baZ')
})
findMyWay.lookup({ method: 'GET', url: '/foo/bar/baZ', headers: {} }, null)
})
test('case insensitive with multiple paths containing capital letter in static path with param', t => {
/*
* This is a reproduction of the issue documented at
* https://github.com/delvedor/find-my-way/issues/96.
*/
t.plan(2)
const findMyWay = FindMyWay({
caseSensitive: false,
defaultRoute: (req, res) => {
t.fail('Should not be defaultRoute')
}
})
findMyWay.on('GET', '/Foo/bar/:param', (req, res, params) => {
t.equal(params.param, 'baZ')
})
findMyWay.on('GET', '/Foo/baz/:param', (req, res, params) => {
t.equal(params.param, 'baR')
})
findMyWay.lookup({ method: 'GET', url: '/foo/bar/baZ', headers: {} }, null)
findMyWay.lookup({ method: 'GET', url: '/foo/baz/baR', headers: {} }, null)
})
test('case insensitive with multiple mixed-case params within same slash couple', t => {
t.plan(2)
const findMyWay = FindMyWay({
caseSensitive: false,
defaultRoute: (req, res) => {
t.fail('Should not be defaultRoute')
}
})
findMyWay.on('GET', '/foo/:param1-:param2', (req, res, params) => {
t.equal(params.param1, 'My')
t.equal(params.param2, 'bAR')
})
findMyWay.lookup({ method: 'GET', url: '/FOO/My-bAR', headers: {} }, null)
})
test('case insensitive with multiple mixed-case params', t => {
t.plan(2)
const findMyWay = FindMyWay({
caseSensitive: false,
defaultRoute: (req, res) => {
t.fail('Should not be defaultRoute')
}
})
findMyWay.on('GET', '/foo/:param1/:param2', (req, res, params) => {
t.equal(params.param1, 'My')
t.equal(params.param2, 'bAR')
})
findMyWay.lookup({ method: 'GET', url: '/FOO/My/bAR', headers: {} }, null)
})
test('case insensitive with wildcard', t => {
t.plan(1)
const findMyWay = FindMyWay({
caseSensitive: false,
defaultRoute: (req, res) => {
t.fail('Should not be defaultRoute')
}
})
findMyWay.on('GET', '/foo/*', (req, res, params) => {
t.equal(params['*'], 'baR')
})
findMyWay.lookup({ method: 'GET', url: '/FOO/baR', headers: {} }, null)
})
test('parametric case insensitive with multiple routes', t => {
t.plan(6)
const findMyWay = FindMyWay({
caseSensitive: false,
defaultRoute: (req, res) => {
t.fail('Should not be defaultRoute')
}
})
findMyWay.on('POST', '/foo/:param/Static/:userId/Save', (req, res, params) => {
t.equal(params.param, 'bAR')
t.equal(params.userId, 'one')
})
findMyWay.on('POST', '/foo/:param/Static/:userId/Update', (req, res, params) => {
t.equal(params.param, 'Bar')
t.equal(params.userId, 'two')
})
findMyWay.on('POST', '/foo/:param/Static/:userId/CANCEL', (req, res, params) => {
t.equal(params.param, 'bAR')
t.equal(params.userId, 'THREE')
})
findMyWay.lookup({ method: 'POST', url: '/foo/bAR/static/one/SAVE', headers: {} }, null)
findMyWay.lookup({ method: 'POST', url: '/fOO/Bar/Static/two/update', headers: {} }, null)
findMyWay.lookup({ method: 'POST', url: '/Foo/bAR/STATIC/THREE/cAnCeL', headers: {} }, null)
})
|
var entityMap = {
"&": "&",
"<": "<",
">": ">",
'"': '"',
"'": ''',
"/": '/'
};
function escapeHTML(string) {
return String(string).replace(/[&<>"'\/]/g, function (s) {
return entityMap[s];
});
}
function escapeCodeBlocks() {
var sections = document.querySelectorAll('.page-section');
[].forEach.call(sections, function (section) {
var sectionCodeBlocks = section.querySelectorAll('.section-code');
if (sectionCodeBlocks.length) {
[].forEach.call(sectionCodeBlocks, function (codeBlock) {
codeBlock.innerHTML = escapeHTML(codeBlock.innerHTML);
})
}
});
}
function formatCodeBlocks() {
[].forEach.call(document.querySelectorAll('code'), function($code) {
var lines = $code.textContent.split('\n');
if (lines[0] === '') {
lines.shift()
}
var matches;
var indentation = (matches = /^[\s\t]+/.exec(lines[0])) !== null ? matches[0] : null;
if (!!indentation) {
lines = lines.map(function(line) {
line = line.replace(indentation, '')
return line.replace(/\t/g, ' ')
});
$code.textContent = lines.join('\n').trim();
}
});
}
function toggleMenu() {
}
function createMenu() {
var menuList = document.querySelector('.menu-list'),
menuItems = document.querySelectorAll('a[name]'),
menuToggle = document.querySelector('.menu-toggle');
menuToggle.addEventListener('click', function () {
var menu = document.querySelector('.menu');
if (menu.classList.contains('menu-open')) {
menu.classList.remove('menu-open');
this.classList.remove('menu-toggle-open');
} else {
menu.classList.add('menu-open');
this.classList.add('menu-toggle-open');
}
});
[].forEach.call(menuItems, function (menuItem) {
var menuText = menuItem.name.charAt(0).toUpperCase() + menuItem.name.slice(1);
var anchor = document.createElement('a');
anchor.href = '#' + menuText.toLowerCase();
var listItemEl = document.createElement('li');
listItemEl.classList.add('menu-list-item');
listItemEl.innerHTML = '<a class="menu-list-link" href="#' + menuText.toLowerCase() + '""><a>' + menuText;
menuList.appendChild(listItemEl)
});
}
(function init() {
createMenu();
escapeCodeBlocks();
formatCodeBlocks();
hljs.initHighlightingOnLoad();
})();
|
'use es6';
const dotenv = require('dotenv');
const Lyft = require('./build/index');
dotenv.load();
const lyft = new Lyft(process.env.LYFT_CLIENT_ID, process.env.LYFT_CLIENT_SECRET);
const query = {
start: {
latitude: 37.7833,
longitude: -122.4167,
},
end: {
latitude: 37.7922,
longitude: -122.4012,
},
rideType: 'lyft_line',
};
lyft.getRideEstimates(query)
.then((result) => {
console.log(result);
})
.catch((error) => {
console.log(error);
});
|
;(function () {
'use strict';
angular.module('angularGAPI')
.factory('User', ['GAPI', userFact]);
function userFact(GAPI) {
var User = new GAPI('plus', 'v1', {});
User.getUserInfo = function(params) {
return User.get('people', 'me', undefined, params);
};
return User;
}
})();
|
import {
GET_POSTS,
GET_POST,
GET_POST_SLUG,
GET_TAGS,
GET_TAG,
GET_TAG_SLUG,
GET_USERS,
GET_USER,
GET_USER_SLUG,
RESET,
} from './action-types';
const initialData = { data: null, error: null, loading: false, meta: null };
const initialState = {
posts: initialData,
post: initialData,
tags: initialData,
tag: initialData,
users: initialData,
user: initialData,
};
const createStateHandler = (state, action) => (key) => {
const isSingle = !(key.substr(key.length - 1) === 's');
const statusHandlers = {
error: () => ({
...state,
[key]: {
...state[key],
data: null,
error: action.error || 'Unknown Error',
loading: false,
},
}),
loading: () => ({
...state,
[key]: {
...state[key],
loading: true,
error: null,
},
}),
success: () => ({
...state,
[key]: {
...state[key],
data: isSingle ? action.data[isSingle ? `${key}s` : key][0] : action.data[isSingle ? `${key}s` : key],
meta: action.data.meta || null,
error: null,
loading: false,
},
}),
};
return statusHandlers[action.status] ? statusHandlers[action.status]() : state;
};
const reducer = (state, action) => {
if (typeof state === 'undefined') {
return initialState;
}
const updateKey = createStateHandler(state, action);
const reducers = {
[GET_POSTS]: () => updateKey('posts'),
[GET_POST]: () => updateKey('post'),
[GET_POST_SLUG]: () => updateKey('post'),
[GET_TAGS]: () => updateKey('tags'),
[GET_TAG]: () => updateKey('tag'),
[GET_TAG_SLUG]: () => updateKey('tag'),
[GET_USERS]: () => updateKey('users'),
[GET_USER]: () => updateKey('user'),
[GET_USER_SLUG]: () => updateKey('user'),
[RESET]: () => ({
...initialState,
}),
};
return reducers[action.type] ? reducers[action.type]() : state;
};
export default reducer;
|
// COPYRIGHT © 2017 Esri
//
// All rights reserved under the copyright laws of the United States
// and applicable international laws, treaties, and conventions.
//
// This material is licensed for use under the Esri Master License
// Agreement (MLA), and is bound by the terms of that agreement.
// You may redistribute and use this code without modification,
// provided you adhere to the terms of the MLA and include this
// copyright notice.
//
// See use restrictions at http://www.esri.com/legal/pdfs/mla_e204_e300/english
//
// For additional information, contact:
// Environmental Systems Research Institute, Inc.
// Attn: Contracts and Legal Services Department
// 380 New York Street
// Redlands, California, USA 92373
// USA
//
// email: [email protected]
//
// See http://js.arcgis.com/4.4/esri/copyright.txt for details.
define(["require","exports","../../core/Warning","../PointCloudClassBreaksRenderer","../PointCloudRGBRenderer","../PointCloudStretchRenderer","../PointCloudUniqueValueRenderer"],function(e,r,n,o,t,u,d){function i(e){return e?a[e.type]||null:null}function l(e,r,o){var t=i(e);if(t){var u=new t;return u.read(e,o),u}return o&&o.messages&&e&&o.messages.push(new n("renderer:unsupported","Renderers of type '"+(e.type||"unknown")+"' are not supported",{definition:e,context:o})),null}function s(e){var r=i(e);return r?r.fromJSON(e):null}Object.defineProperty(r,"__esModule",{value:!0});var a={pointCloudClassBreaksRenderer:o,pointCloudRGBRenderer:t,pointCloudStretchRenderer:u,pointCloudUniqueValueRenderer:d};r.read=l,r.fromJSON=s}); |
/**
* Created by gbaldeck on 4/17/2017.
*/
var prototype = Object.create(HTMLElement.prototype)
console.log("prototype: ", prototype) |
var fs = require('fs'),
path = require('path'),
cleanCSS = require('clean-css'),
rjs = require('requirejs');
module.exports = function(grunt) {
// **css* task works pretty much the same as grunt's min task. The task
// target is the destination, data is an array of glob patterns. These
// files are concataned and run through requirejs optimizer to handle
// @import inlines in CSS files.
grunt.task.registerMultiTask('css', 'Concats, replaces @imports and minifies the CSS files', function() {
this.requiresConfig('staging');
// if defined, files get prepended by the output config value
var files = this.data;
// subtarget name is the output destination
var target = this.target;
// async task
var cb = this.async();
// concat prior to rjs optimize css, and before min max info
grunt.log.write('Writing css files to ' + target + '...');
var out = grunt.helper('mincss', files);
// only go through if their's file to process
if(!out) {
return cb();
}
// write minified file before going through rjs:optimize to possibly inline
// @imports (that are not handled by compass within .scss or .sass files)
grunt.file.write(target, out);
// replace @import statements
//
// XXX no error handling in this helper so far..
// Check that rjs returns an error when something wrong (if it throws...)
// if it is bubble the error back here
grunt.helper('rjs:optimize:css', target, function() {
// do the minification once inline imports are done
grunt.log.ok();
cb();
});
});
//
// **mincss** basic utility to concat CSS files and run them through
// [cleanCSS](https://github.com/GoalSmashers/clean-css), might opt to use
// [https://github.com/jzaefferer/grunt-css] plugin.
//
grunt.registerHelper('mincss', function(files, o) {
o = o || {};
files = grunt.file.expandFiles(files);
return files.map(function(filepath) {
var content = grunt.file.read(filepath);
return o.nocompress ? content : cleanCSS.process(content);
}).join('');
});
// **rjs:optimize:css** is an helper using rjs to optimize a single file,
// mainly to properly import multi-level of @import statements, which can be
// tricky with all the url rewrites.
//
// file - Path to the css file to optimize
// options - (optional) rjs configuration
// cb - callback function to call on completion
grunt.registerHelper('rjs:optimize:css', function(file, options, cb) {
if(!cb) { cb = options; options = {}; }
options.cssIn = file;
options.out = options.out || file;
options.optimizeCss = 'standard.keepComments.keepLines';
var before = grunt.file.read(file);
rjs.optimize(options, function() {
grunt.helper('min_max_info', grunt.file.read(file), before);
cb();
});
});
};
|
// Place all the behaviors and hooks related to the matching controller here.
// All this logic will automatically be available in application.js.
/* fix vertical when not overflow
call fullscreenFix() if .fullscreen content changes */
function fullscreenFix(){
var h = $('body').height();
// set .fullscreen height
$(".content-b").each(function(i){
if($(this).innerHeight() <= h){
$(this).closest(".fullscreen").addClass("not-overflow");
}
});
}
$(window).resize(fullscreenFix);
fullscreenFix();
/* resize background images */
function backgroundResize(){
var windowH = $(window).height();
$(".background").each(function(i){
var path = $(this);
// variables
var contW = path.width();
var contH = path.height();
var imgW = path.attr("data-img-width");
var imgH = path.attr("data-img-height");
var ratio = imgW / imgH;
// overflowing difference
var diff = parseFloat(path.attr("data-diff"));
diff = diff ? diff : 0;
// remaining height to have fullscreen image only on parallax
var remainingH = 0;
if(path.hasClass("parallax")){
var maxH = contH > windowH ? contH : windowH;
remainingH = windowH - contH;
}
// set img values depending on cont
imgH = contH + remainingH + diff;
imgW = imgH * ratio;
// fix when too large
if(contW > imgW){
imgW = contW;
imgH = imgW / ratio;
}
//
path.data("resized-imgW", imgW);
path.data("resized-imgH", imgH);
path.css("background-size", imgW + "px " + imgH + "px");
});
}
$(window).resize(backgroundResize);
$(window).focus(backgroundResize);
backgroundResize(); |
// PYRAMID
// Constants
const path = require("path");
const DATA_ROOT = path.join(__dirname, "..", "data");
module.exports = {
DEBUG: false,
FILE_ENCODING: "utf8",
PROJECT_ROOT: path.join(__dirname, ".."),
DATA_ROOT,
LOG_ROOT: path.join(__dirname, "..", "public", "data", "logs"),
DB_FILENAME: path.join(DATA_ROOT, "pyramid.db"),
RELATIONSHIP_NONE: 0,
RELATIONSHIP_FRIEND: 1,
RELATIONSHIP_BEST_FRIEND: 2,
CACHE_LINES: 150,
CONTEXT_CACHE_LINES: 40,
CONTEXT_CACHE_MINUTES: 60,
LAST_SEEN_UPDATE_RATE: 500,
LOG_PAGE_SIZE: 300,
BUNCHED_EVENT_SIZE: 50,
USER_MODIFYING_EVENT_TYPES:
["join", "part", "quit", "kick", "kill", "mode"],
PART_EVENT_TYPES:
["part", "quit", "kick", "kill"],
BUNCHABLE_EVENT_TYPES:
["join", "part", "quit", "kill", "mode"],
SUPPORTED_CATEGORY_NAMES: ["highlights", "allfriends", "system"],
TOKEN_COOKIE_NAME: "token",
TOKEN_COOKIE_SECONDS: 86400 * 365,
PAGE_TYPES: {
CATEGORY: "category",
CHANNEL: "channel",
USER: "user"
},
CONNECTION_STATUS: {
ABORTED: "aborted",
CONNECTED: "connected",
DISCONNECTED: "disconnected",
FAILED: "failed",
REJECTED: "rejected"
},
CHANNEL_TYPES: {
PUBLIC: 0,
PRIVATE: 1
},
USER_EVENT_VISIBILITY: {
OFF: 0,
COLLAPSE_PRESENCE: 1,
COLLAPSE_MESSAGES: 2,
SHOW_ALL: 3
},
RETAIN_DB_TYPES: {
LINES: 0,
DAYS: 1
}
};
|
document.addEventListener('DOMContentLoaded', function() {
photoKeys = Object.keys(TRAVEL_PHOTOS);
function injectRandomPhotos() {
figures = document.getElementsByClassName('figure-placeholder');
[].forEach.call(figures, function(fig) {
var randomPhotoKey = photoKeys[Math.floor(Math.random() * photoKeys.length)];
var randomPhoto = TRAVEL_PHOTOS[randomPhotoKey];
var page = TRAVEL_PAGES[randomPhoto.pageKey];
fig.innerHTML = (
'<a href="' + page + '#' + randomPhoto.hash + '">' +
'<i style="background-image:url(\'/img/res/400/' + randomPhotoKey + '\')"></i>' +
'</a>');
});
}
shuffleButton = document.getElementById('shuffle-button');
shuffleButton.addEventListener('click', injectRandomPhotos);
injectRandomPhotos();
});
|
/**
* @author Richard Davey <[email protected]>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* The Input Handler is bound to a specific Sprite and is responsible for managing all Input events on that Sprite.
* @class Phaser.InputHandler
* @constructor
* @param {Phaser.Sprite} sprite - The Sprite object to which this Input Handler belongs.
*/
Phaser.InputHandler = function (sprite) {
/**
* @property {Phaser.Sprite} sprite - The Sprite object to which this Input Handler belongs.
*/
this.sprite = sprite;
/**
* @property {Phaser.Game} game - A reference to the currently running game.
*/
this.game = sprite.game;
/**
* @property {boolean} enabled - If enabled the Input Handler will process input requests and monitor pointer activity.
* @default
*/
this.enabled = false;
/**
* The priorityID is used to determine which game objects should get priority when input events occur. For example if you have
* several Sprites that overlap, by default the one at the top of the display list is given priority for input events. You can
* stop this from happening by controlling the priorityID value. The higher the value, the more important they are considered to the Input events.
* @property {number} priorityID
* @default
*/
this.priorityID = 0;
/**
* @property {boolean} useHandCursor - On a desktop browser you can set the 'hand' cursor to appear when moving over the Sprite.
* @default
*/
this.useHandCursor = false;
/**
* @property {boolean} _setHandCursor - Did this Sprite trigger the hand cursor?
* @private
*/
this._setHandCursor = false;
/**
* @property {boolean} isDragged - true if the Sprite is being currently dragged.
* @default
*/
this.isDragged = false;
/**
* @property {boolean} allowHorizontalDrag - Controls if the Sprite is allowed to be dragged horizontally.
* @default
*/
this.allowHorizontalDrag = true;
/**
* @property {boolean} allowVerticalDrag - Controls if the Sprite is allowed to be dragged vertically.
* @default
*/
this.allowVerticalDrag = true;
/**
* @property {boolean} bringToTop - If true when this Sprite is clicked or dragged it will automatically be bought to the top of the Group it is within.
* @default
*/
this.bringToTop = false;
/**
* @property {Phaser.Point} snapOffset - A Point object that contains by how far the Sprite snap is offset.
* @default
*/
this.snapOffset = null;
/**
* @property {boolean} snapOnDrag - When the Sprite is dragged this controls if the center of the Sprite will snap to the pointer on drag or not.
* @default
*/
this.snapOnDrag = false;
/**
* @property {boolean} snapOnRelease - When the Sprite is dragged this controls if the Sprite will be snapped on release.
* @default
*/
this.snapOnRelease = false;
/**
* @property {number} snapX - When a Sprite has snapping enabled this holds the width of the snap grid.
* @default
*/
this.snapX = 0;
/**
* @property {number} snapY - When a Sprite has snapping enabled this holds the height of the snap grid.
* @default
*/
this.snapY = 0;
/**
* @property {number} snapOffsetX - This defines the top-left X coordinate of the snap grid.
* @default
*/
this.snapOffsetX = 0;
/**
* @property {number} snapOffsetY - This defines the top-left Y coordinate of the snap grid..
* @default
*/
this.snapOffsetY = 0;
/**
* Set to true to use pixel perfect hit detection when checking if the pointer is over this Sprite.
* The x/y coordinates of the pointer are tested against the image in combination with the InputHandler.pixelPerfectAlpha value.
* Warning: This is expensive, especially on mobile (where it's not even needed!) so only enable if required. Also see the less-expensive InputHandler.pixelPerfectClick.
* @property {number} pixelPerfectOver - Use a pixel perfect check when testing for pointer over.
* @default
*/
this.pixelPerfectOver = false;
/**
* Set to true to use pixel perfect hit detection when checking if the pointer is over this Sprite when it's clicked or touched.
* The x/y coordinates of the pointer are tested against the image in combination with the InputHandler.pixelPerfectAlpha value.
* Warning: This is expensive so only enable if you really need it.
* @property {number} pixelPerfectClick - Use a pixel perfect check when testing for clicks or touches on the Sprite.
* @default
*/
this.pixelPerfectClick = false;
/**
* @property {number} pixelPerfectAlpha - The alpha tolerance threshold. If the alpha value of the pixel matches or is above this value, it's considered a hit.
* @default
*/
this.pixelPerfectAlpha = 255;
/**
* @property {boolean} draggable - Is this sprite allowed to be dragged by the mouse? true = yes, false = no
* @default
*/
this.draggable = false;
/**
* @property {Phaser.Rectangle} boundsRect - A region of the game world within which the sprite is restricted during drag.
* @default
*/
this.boundsRect = null;
/**
* @property {Phaser.Sprite} boundsSprite - A Sprite the bounds of which this sprite is restricted during drag.
* @default
*/
this.boundsSprite = null;
/**
* If this object is set to consume the pointer event then it will stop all propogation from this object on.
* For example if you had a stack of 6 sprites with the same priority IDs and one consumed the event, none of the others would receive it.
* @property {boolean} consumePointerEvent
* @default
*/
this.consumePointerEvent = false;
/**
* @property {boolean} _wasEnabled - Internal cache var.
* @private
*/
this._wasEnabled = false;
/**
* @property {Phaser.Point} _tempPoint - Internal cache var.
* @private
*/
this._tempPoint = new Phaser.Point();
/**
* @property {array} _pointerData - Internal cache var.
* @private
*/
this._pointerData = [];
this._pointerData.push({
id: 0,
x: 0,
y: 0,
isDown: false,
isUp: false,
isOver: false,
isOut: false,
timeOver: 0,
timeOut: 0,
timeDown: 0,
timeUp: 0,
downDuration: 0,
isDragged: false
});
};
Phaser.InputHandler.prototype = {
/**
* Starts the Input Handler running. This is called automatically when you enable input on a Sprite, or can be called directly if you need to set a specific priority.
* @method Phaser.InputHandler#start
* @param {number} priority - Higher priority sprites take click priority over low-priority sprites when they are stacked on-top of each other.
* @param {boolean} useHandCursor - If true the Sprite will show the hand cursor on mouse-over (doesn't apply to mobile browsers)
* @return {Phaser.Sprite} The Sprite object to which the Input Handler is bound.
*/
start: function (priority, useHandCursor) {
priority = priority || 0;
if (typeof useHandCursor === 'undefined') { useHandCursor = false; }
// Turning on
if (this.enabled === false)
{
// Register, etc
this.game.input.interactiveItems.add(this);
this.useHandCursor = useHandCursor;
this.priorityID = priority;
for (var i = 0; i < 10; i++)
{
this._pointerData[i] = {
id: i,
x: 0,
y: 0,
isDown: false,
isUp: false,
isOver: false,
isOut: false,
timeOver: 0,
timeOut: 0,
timeDown: 0,
timeUp: 0,
downDuration: 0,
isDragged: false
};
}
this.snapOffset = new Phaser.Point();
this.enabled = true;
this._wasEnabled = true;
// Create the signals the Input component will emit
if (this.sprite.events && this.sprite.events.onInputOver === null)
{
this.sprite.events.onInputOver = new Phaser.Signal();
this.sprite.events.onInputOut = new Phaser.Signal();
this.sprite.events.onInputDown = new Phaser.Signal();
this.sprite.events.onInputUp = new Phaser.Signal();
this.sprite.events.onDragStart = new Phaser.Signal();
this.sprite.events.onDragStop = new Phaser.Signal();
}
}
this.sprite.events.onAddedToGroup.add(this.addedToGroup, this);
this.sprite.events.onRemovedFromGroup.add(this.removedFromGroup, this);
return this.sprite;
},
/**
* Handles when the parent Sprite is added to a new Group.
*
* @method Phaser.InputHandler#addedToGroup
* @private
*/
addedToGroup: function () {
if (this._wasEnabled && !this.enabled)
{
this.start();
}
},
/**
* Handles when the parent Sprite is removed from a Group.
*
* @method Phaser.InputHandler#removedFromGroup
* @private
*/
removedFromGroup: function () {
if (this.enabled)
{
this._wasEnabled = true;
this.stop();
}
else
{
this._wasEnabled = false;
}
},
/**
* Resets the Input Handler and disables it.
* @method Phaser.InputHandler#reset
*/
reset: function () {
this.enabled = false;
for (var i = 0; i < 10; i++)
{
this._pointerData[i] = {
id: i,
x: 0,
y: 0,
isDown: false,
isUp: false,
isOver: false,
isOut: false,
timeOver: 0,
timeOut: 0,
timeDown: 0,
timeUp: 0,
downDuration: 0,
isDragged: false
};
}
},
/**
* Stops the Input Handler from running.
* @method Phaser.InputHandler#stop
*/
stop: function () {
// Turning off
if (this.enabled === false)
{
return;
}
else
{
// De-register, etc
this.enabled = false;
this.game.input.interactiveItems.remove(this);
}
},
/**
* Clean up memory.
* @method Phaser.InputHandler#destroy
*/
destroy: function () {
if (this.sprite)
{
if (this._setHandCursor)
{
this.game.canvas.style.cursor = "default";
this._setHandCursor = false;
}
this.enabled = false;
this.game.input.interactiveItems.remove(this);
this._pointerData.length = 0;
this.boundsRect = null;
this.boundsSprite = null;
this.sprite = null;
}
},
/**
* Checks if the object this InputHandler is bound to is valid for consideration in the Pointer move event.
* This is called by Phaser.Pointer and shouldn't typically be called directly.
*
* @method Phaser.InputHandler#validForInput
* @protected
* @param {number} highestID - The highest ID currently processed by the Pointer.
* @param {number} highestRenderID - The highest Render Order ID currently processed by the Pointer.
* @return {boolean} True if the object this InputHandler is bound to should be considered as valid for input detection.
*/
validForInput: function (highestID, highestRenderID) {
if (this.sprite.scale.x === 0 || this.sprite.scale.y === 0)
{
return false;
}
if (this.pixelPerfectClick || this.pixelPerfectOver)
{
return true;
}
if (this.priorityID > highestID || (this.priorityID === highestID && this.sprite._cache[3] < highestRenderID))
{
return true;
}
return false;
},
/**
* The x coordinate of the Input pointer, relative to the top-left of the parent Sprite.
* This value is only set when the pointer is over this Sprite.
* @method Phaser.InputHandler#pointerX
* @param {Phaser.Pointer} pointer
* @return {number} The x coordinate of the Input pointer.
*/
pointerX: function (pointer) {
pointer = pointer || 0;
return this._pointerData[pointer].x;
},
/**
* The y coordinate of the Input pointer, relative to the top-left of the parent Sprite
* This value is only set when the pointer is over this Sprite.
* @method Phaser.InputHandler#pointerY
* @param {Phaser.Pointer} pointer
* @return {number} The y coordinate of the Input pointer.
*/
pointerY: function (pointer) {
pointer = pointer || 0;
return this._pointerData[pointer].y;
},
/**
* If the Pointer is touching the touchscreen, or the mouse button is held down, isDown is set to true.
* @method Phaser.InputHandler#pointerDown
* @param {Phaser.Pointer} pointer
* @return {boolean}
*/
pointerDown: function (pointer) {
pointer = pointer || 0;
return this._pointerData[pointer].isDown;
},
/**
* If the Pointer is not touching the touchscreen, or the mouse button is up, isUp is set to true
* @method Phaser.InputHandler#pointerUp
* @param {Phaser.Pointer} pointer
* @return {boolean}
*/
pointerUp: function (pointer) {
pointer = pointer || 0;
return this._pointerData[pointer].isUp;
},
/**
* A timestamp representing when the Pointer first touched the touchscreen.
* @method Phaser.InputHandler#pointerTimeDown
* @param {Phaser.Pointer} pointer
* @return {number}
*/
pointerTimeDown: function (pointer) {
pointer = pointer || 0;
return this._pointerData[pointer].timeDown;
},
/**
* A timestamp representing when the Pointer left the touchscreen.
* @method Phaser.InputHandler#pointerTimeUp
* @param {Phaser.Pointer} pointer
* @return {number}
*/
pointerTimeUp: function (pointer) {
pointer = pointer || 0;
return this._pointerData[pointer].timeUp;
},
/**
* Is the Pointer over this Sprite?
* @method Phaser.InputHandler#pointerOver
* @param {number} [index] - The ID number of a Pointer to check. If you don't provide a number it will check all Pointers.
* @return {boolean} True if the given pointer (if a index was given, or any pointer if not) is over this object.
*/
pointerOver: function (index) {
if (this.enabled)
{
if (typeof index === 'undefined')
{
for (var i = 0; i < 10; i++)
{
if (this._pointerData[i].isOver)
{
return true;
}
}
}
else
{
return this._pointerData[index].isOver;
}
}
return false;
},
/**
* Is the Pointer outside of this Sprite?
* @method Phaser.InputHandler#pointerOut
* @param {number} [index] - The ID number of a Pointer to check. If you don't provide a number it will check all Pointers.
* @return {boolean} True if the given pointer (if a index was given, or any pointer if not) is out of this object.
*/
pointerOut: function (index) {
if (this.enabled)
{
if (typeof index === 'undefined')
{
for (var i = 0; i < 10; i++)
{
if (this._pointerData[i].isOut)
{
return true;
}
}
}
else
{
return this._pointerData[index].isOut;
}
}
return false;
},
/**
* A timestamp representing when the Pointer first touched the touchscreen.
* @method Phaser.InputHandler#pointerTimeOver
* @param {Phaser.Pointer} pointer
* @return {number}
*/
pointerTimeOver: function (pointer) {
pointer = pointer || 0;
return this._pointerData[pointer].timeOver;
},
/**
* A timestamp representing when the Pointer left the touchscreen.
* @method Phaser.InputHandler#pointerTimeOut
* @param {Phaser.Pointer} pointer
* @return {number}
*/
pointerTimeOut: function (pointer) {
pointer = pointer || 0;
return this._pointerData[pointer].timeOut;
},
/**
* Is this sprite being dragged by the mouse or not?
* @method Phaser.InputHandler#pointerDragged
* @param {Phaser.Pointer} pointer
* @return {boolean} True if the pointer is dragging an object, otherwise false.
*/
pointerDragged: function (pointer) {
pointer = pointer || 0;
return this._pointerData[pointer].isDragged;
},
/**
* Checks if the given pointer is over this Sprite and can click it.
* @method Phaser.InputHandler#checkPointerDown
* @param {Phaser.Pointer} pointer
* @return {boolean} True if the pointer is down, otherwise false.
*/
checkPointerDown: function (pointer) {
if (!this.enabled || !this.sprite || !this.sprite.parent || !this.sprite.visible || !this.sprite.parent.visible)
{
return false;
}
// Need to pass it a temp point, in case we need it again for the pixel check
if (this.game.input.hitTest(this.sprite, pointer, this._tempPoint))
{
if (this.pixelPerfectClick)
{
return this.checkPixel(this._tempPoint.x, this._tempPoint.y);
}
else
{
return true;
}
}
return false;
},
/**
* Checks if the given pointer is over this Sprite.
* @method Phaser.InputHandler#checkPointerOver
* @param {Phaser.Pointer} pointer
* @return {boolean}
*/
checkPointerOver: function (pointer) {
if (!this.enabled || !this.sprite || !this.sprite.parent || !this.sprite.visible || !this.sprite.parent.visible)
{
return false;
}
// Need to pass it a temp point, in case we need it again for the pixel check
if (this.game.input.hitTest(this.sprite, pointer, this._tempPoint))
{
if (this.pixelPerfectOver)
{
return this.checkPixel(this._tempPoint.x, this._tempPoint.y);
}
else
{
return true;
}
}
return false;
},
/**
* Runs a pixel perfect check against the given x/y coordinates of the Sprite this InputHandler is bound to.
* It compares the alpha value of the pixel and if >= InputHandler.pixelPerfectAlpha it returns true.
* @method Phaser.InputHandler#checkPixel
* @param {number} x - The x coordinate to check.
* @param {number} y - The y coordinate to check.
* @param {Phaser.Pointer} [pointer] - The pointer to get the x/y coordinate from if not passed as the first two parameters.
* @return {boolean} true if there is the alpha of the pixel is >= InputHandler.pixelPerfectAlpha
*/
checkPixel: function (x, y, pointer) {
// Grab a pixel from our image into the hitCanvas and then test it
if (this.sprite.texture.baseTexture.source)
{
this.game.input.hitContext.clearRect(0, 0, 1, 1);
if (x === null && y === null)
{
// Use the pointer parameter
this.game.input.getLocalPosition(this.sprite, pointer, this._tempPoint);
var x = this._tempPoint.x;
var y = this._tempPoint.y;
}
if (this.sprite.anchor.x !== 0)
{
x -= -this.sprite.texture.frame.width * this.sprite.anchor.x;
}
if (this.sprite.anchor.y !== 0)
{
y -= -this.sprite.texture.frame.height * this.sprite.anchor.y;
}
x += this.sprite.texture.frame.x;
y += this.sprite.texture.frame.y;
this.game.input.hitContext.drawImage(this.sprite.texture.baseTexture.source, x, y, 1, 1, 0, 0, 1, 1);
var rgb = this.game.input.hitContext.getImageData(0, 0, 1, 1);
if (rgb.data[3] >= this.pixelPerfectAlpha)
{
return true;
}
}
return false;
},
/**
* Update.
* @method Phaser.InputHandler#update
* @protected
* @param {Phaser.Pointer} pointer
*/
update: function (pointer) {
if (this.sprite === null || this.sprite.parent === undefined)
{
// Abort. We've been destroyed.
return;
}
if (!this.enabled || !this.sprite.visible || !this.sprite.parent.visible)
{
this._pointerOutHandler(pointer);
return false;
}
if (this.draggable && this._draggedPointerID == pointer.id)
{
return this.updateDrag(pointer);
}
else if (this._pointerData[pointer.id].isOver === true)
{
if (this.checkPointerOver(pointer))
{
this._pointerData[pointer.id].x = pointer.x - this.sprite.x;
this._pointerData[pointer.id].y = pointer.y - this.sprite.y;
return true;
}
else
{
this._pointerOutHandler(pointer);
return false;
}
}
},
/**
* Internal method handling the pointer over event.
* @method Phaser.InputHandler#_pointerOverHandler
* @private
* @param {Phaser.Pointer} pointer
*/
_pointerOverHandler: function (pointer) {
if (this.sprite === null)
{
// Abort. We've been destroyed.
return;
}
if (this._pointerData[pointer.id].isOver === false)
{
this._pointerData[pointer.id].isOver = true;
this._pointerData[pointer.id].isOut = false;
this._pointerData[pointer.id].timeOver = this.game.time.now;
this._pointerData[pointer.id].x = pointer.x - this.sprite.x;
this._pointerData[pointer.id].y = pointer.y - this.sprite.y;
if (this.useHandCursor && this._pointerData[pointer.id].isDragged === false)
{
this.game.canvas.style.cursor = "pointer";
this._setHandCursor = true;
}
if (this.sprite && this.sprite.events)
{
this.sprite.events.onInputOver.dispatch(this.sprite, pointer);
}
}
},
/**
* Internal method handling the pointer out event.
* @method Phaser.InputHandler#_pointerOutHandler
* @private
* @param {Phaser.Pointer} pointer
*/
_pointerOutHandler: function (pointer) {
if (this.sprite === null)
{
// Abort. We've been destroyed.
return;
}
this._pointerData[pointer.id].isOver = false;
this._pointerData[pointer.id].isOut = true;
this._pointerData[pointer.id].timeOut = this.game.time.now;
if (this.useHandCursor && this._pointerData[pointer.id].isDragged === false)
{
this.game.canvas.style.cursor = "default";
this._setHandCursor = false;
}
if (this.sprite && this.sprite.events)
{
this.sprite.events.onInputOut.dispatch(this.sprite, pointer);
}
},
/**
* Internal method handling the touched event.
* @method Phaser.InputHandler#_touchedHandler
* @private
* @param {Phaser.Pointer} pointer
*/
_touchedHandler: function (pointer) {
if (this.sprite === null)
{
// Abort. We've been destroyed.
return;
}
if (this._pointerData[pointer.id].isDown === false && this._pointerData[pointer.id].isOver === true)
{
if (this.pixelPerfectClick && !this.checkPixel(null, null, pointer))
{
return;
}
this._pointerData[pointer.id].isDown = true;
this._pointerData[pointer.id].isUp = false;
this._pointerData[pointer.id].timeDown = this.game.time.now;
if (this.sprite && this.sprite.events)
{
this.sprite.events.onInputDown.dispatch(this.sprite, pointer);
}
// Start drag
if (this.draggable && this.isDragged === false)
{
this.startDrag(pointer);
}
if (this.bringToTop)
{
this.sprite.bringToTop();
}
}
// Consume the event?
return this.consumePointerEvent;
},
/**
* Internal method handling the pointer released event.
* @method Phaser.InputHandler#_releasedHandler
* @private
* @param {Phaser.Pointer} pointer
*/
_releasedHandler: function (pointer) {
if (this.sprite === null)
{
// Abort. We've been destroyed.
return;
}
// If was previously touched by this Pointer, check if still is AND still over this item
if (this._pointerData[pointer.id].isDown && pointer.isUp)
{
this._pointerData[pointer.id].isDown = false;
this._pointerData[pointer.id].isUp = true;
this._pointerData[pointer.id].timeUp = this.game.time.now;
this._pointerData[pointer.id].downDuration = this._pointerData[pointer.id].timeUp - this._pointerData[pointer.id].timeDown;
// Only release the InputUp signal if the pointer is still over this sprite
if (this.checkPointerOver(pointer))
{
// Release the inputUp signal and provide optional parameter if pointer is still over the sprite or not
if (this.sprite && this.sprite.events)
{
this.sprite.events.onInputUp.dispatch(this.sprite, pointer, true);
}
}
else
{
// Release the inputUp signal and provide optional parameter if pointer is still over the sprite or not
if (this.sprite && this.sprite.events)
{
this.sprite.events.onInputUp.dispatch(this.sprite, pointer, false);
}
// Pointer outside the sprite? Reset the cursor
if (this.useHandCursor)
{
this.game.canvas.style.cursor = "default";
this._setHandCursor = false;
}
}
// Stop drag
if (this.draggable && this.isDragged && this._draggedPointerID == pointer.id)
{
this.stopDrag(pointer);
}
}
},
/**
* Updates the Pointer drag on this Sprite.
* @method Phaser.InputHandler#updateDrag
* @param {Phaser.Pointer} pointer
* @return {boolean}
*/
updateDrag: function (pointer) {
if (pointer.isUp)
{
this.stopDrag(pointer);
return false;
}
if (this.sprite.fixedToCamera)
{
if (this.allowHorizontalDrag)
{
this.sprite.cameraOffset.x = pointer.x + this._dragPoint.x + this.dragOffset.x;
}
if (this.allowVerticalDrag)
{
this.sprite.cameraOffset.y = pointer.y + this._dragPoint.y + this.dragOffset.y;
}
if (this.boundsRect)
{
this.checkBoundsRect();
}
if (this.boundsSprite)
{
this.checkBoundsSprite();
}
if (this.snapOnDrag)
{
this.sprite.cameraOffset.x = Math.round((this.sprite.cameraOffset.x - (this.snapOffsetX % this.snapX)) / this.snapX) * this.snapX + (this.snapOffsetX % this.snapX);
this.sprite.cameraOffset.y = Math.round((this.sprite.cameraOffset.y - (this.snapOffsetY % this.snapY)) / this.snapY) * this.snapY + (this.snapOffsetY % this.snapY);
}
}
else
{
if (this.allowHorizontalDrag)
{
this.sprite.x = pointer.x + this._dragPoint.x + this.dragOffset.x;
}
if (this.allowVerticalDrag)
{
this.sprite.y = pointer.y + this._dragPoint.y + this.dragOffset.y;
}
if (this.boundsRect)
{
this.checkBoundsRect();
}
if (this.boundsSprite)
{
this.checkBoundsSprite();
}
if (this.snapOnDrag)
{
this.sprite.x = Math.round((this.sprite.x - (this.snapOffsetX % this.snapX)) / this.snapX) * this.snapX + (this.snapOffsetX % this.snapX);
this.sprite.y = Math.round((this.sprite.y - (this.snapOffsetY % this.snapY)) / this.snapY) * this.snapY + (this.snapOffsetY % this.snapY);
}
}
return true;
},
/**
* Returns true if the pointer has entered the Sprite within the specified delay time (defaults to 500ms, half a second)
* @method Phaser.InputHandler#justOver
* @param {Phaser.Pointer} pointer
* @param {number} delay - The time below which the pointer is considered as just over.
* @return {boolean}
*/
justOver: function (pointer, delay) {
pointer = pointer || 0;
delay = delay || 500;
return (this._pointerData[pointer].isOver && this.overDuration(pointer) < delay);
},
/**
* Returns true if the pointer has left the Sprite within the specified delay time (defaults to 500ms, half a second)
* @method Phaser.InputHandler#justOut
* @param {Phaser.Pointer} pointer
* @param {number} delay - The time below which the pointer is considered as just out.
* @return {boolean}
*/
justOut: function (pointer, delay) {
pointer = pointer || 0;
delay = delay || 500;
return (this._pointerData[pointer].isOut && (this.game.time.now - this._pointerData[pointer].timeOut < delay));
},
/**
* Returns true if the pointer has touched or clicked on the Sprite within the specified delay time (defaults to 500ms, half a second)
* @method Phaser.InputHandler#justPressed
* @param {Phaser.Pointer} pointer
* @param {number} delay - The time below which the pointer is considered as just over.
* @return {boolean}
*/
justPressed: function (pointer, delay) {
pointer = pointer || 0;
delay = delay || 500;
return (this._pointerData[pointer].isDown && this.downDuration(pointer) < delay);
},
/**
* Returns true if the pointer was touching this Sprite, but has been released within the specified delay time (defaults to 500ms, half a second)
* @method Phaser.InputHandler#justReleased
* @param {Phaser.Pointer} pointer
* @param {number} delay - The time below which the pointer is considered as just out.
* @return {boolean}
*/
justReleased: function (pointer, delay) {
pointer = pointer || 0;
delay = delay || 500;
return (this._pointerData[pointer].isUp && (this.game.time.now - this._pointerData[pointer].timeUp < delay));
},
/**
* If the pointer is currently over this Sprite this returns how long it has been there for in milliseconds.
* @method Phaser.InputHandler#overDuration
* @param {Phaser.Pointer} pointer
* @return {number} The number of milliseconds the pointer has been over the Sprite, or -1 if not over.
*/
overDuration: function (pointer) {
pointer = pointer || 0;
if (this._pointerData[pointer].isOver)
{
return this.game.time.now - this._pointerData[pointer].timeOver;
}
return -1;
},
/**
* If the pointer is currently over this Sprite this returns how long it has been there for in milliseconds.
* @method Phaser.InputHandler#downDuration
* @param {Phaser.Pointer} pointer
* @return {number} The number of milliseconds the pointer has been pressed down on the Sprite, or -1 if not over.
*/
downDuration: function (pointer) {
pointer = pointer || 0;
if (this._pointerData[pointer].isDown)
{
return this.game.time.now - this._pointerData[pointer].timeDown;
}
return -1;
},
/**
* Make this Sprite draggable by the mouse. You can also optionally set mouseStartDragCallback and mouseStopDragCallback
* @method Phaser.InputHandler#enableDrag
* @param {boolean} [lockCenter=false] - If false the Sprite will drag from where you click it minus the dragOffset. If true it will center itself to the tip of the mouse pointer.
* @param {boolean} [bringToTop=false] - If true the Sprite will be bought to the top of the rendering list in its current Group.
* @param {boolean} [pixelPerfect=false] - If true it will use a pixel perfect test to see if you clicked the Sprite. False uses the bounding box.
* @param {boolean} [alphaThreshold=255] - If using pixel perfect collision this specifies the alpha level from 0 to 255 above which a collision is processed.
* @param {Phaser.Rectangle} [boundsRect=null] - If you want to restrict the drag of this sprite to a specific Rectangle, pass the Phaser.Rectangle here, otherwise it's free to drag anywhere.
* @param {Phaser.Sprite} [boundsSprite=null] - If you want to restrict the drag of this sprite to within the bounding box of another sprite, pass it here.
*/
enableDrag: function (lockCenter, bringToTop, pixelPerfect, alphaThreshold, boundsRect, boundsSprite) {
if (typeof lockCenter == 'undefined') { lockCenter = false; }
if (typeof bringToTop == 'undefined') { bringToTop = false; }
if (typeof pixelPerfect == 'undefined') { pixelPerfect = false; }
if (typeof alphaThreshold == 'undefined') { alphaThreshold = 255; }
if (typeof boundsRect == 'undefined') { boundsRect = null; }
if (typeof boundsSprite == 'undefined') { boundsSprite = null; }
this._dragPoint = new Phaser.Point();
this.draggable = true;
this.bringToTop = bringToTop;
this.dragOffset = new Phaser.Point();
this.dragFromCenter = lockCenter;
this.pixelPerfect = pixelPerfect;
this.pixelPerfectAlpha = alphaThreshold;
if (boundsRect)
{
this.boundsRect = boundsRect;
}
if (boundsSprite)
{
this.boundsSprite = boundsSprite;
}
},
/**
* Stops this sprite from being able to be dragged. If it is currently the target of an active drag it will be stopped immediately. Also disables any set callbacks.
* @method Phaser.InputHandler#disableDrag
*/
disableDrag: function () {
if (this._pointerData)
{
for (var i = 0; i < 10; i++)
{
this._pointerData[i].isDragged = false;
}
}
this.draggable = false;
this.isDragged = false;
this._draggedPointerID = -1;
},
/**
* Called by Pointer when drag starts on this Sprite. Should not usually be called directly.
* @method Phaser.InputHandler#startDrag
* @param {Phaser.Pointer} pointer
*/
startDrag: function (pointer) {
this.isDragged = true;
this._draggedPointerID = pointer.id;
this._pointerData[pointer.id].isDragged = true;
if (this.sprite.fixedToCamera)
{
if (this.dragFromCenter)
{
this.sprite.centerOn(pointer.x, pointer.y);
this._dragPoint.setTo(this.sprite.cameraOffset.x - pointer.x, this.sprite.cameraOffset.y - pointer.y);
}
else
{
this._dragPoint.setTo(this.sprite.cameraOffset.x - pointer.x, this.sprite.cameraOffset.y - pointer.y);
}
}
else
{
if (this.dragFromCenter)
{
var bounds = this.sprite.getBounds();
this.sprite.x = pointer.x + (this.sprite.x - bounds.centerX);
this.sprite.y = pointer.y + (this.sprite.y - bounds.centerY);
this._dragPoint.setTo(this.sprite.x - pointer.x, this.sprite.y - pointer.y);
}
else
{
this._dragPoint.setTo(this.sprite.x - pointer.x, this.sprite.y - pointer.y);
}
}
this.updateDrag(pointer);
if (this.bringToTop)
{
this.sprite.bringToTop();
}
this.sprite.events.onDragStart.dispatch(this.sprite, pointer);
},
/**
* Called by Pointer when drag is stopped on this Sprite. Should not usually be called directly.
* @method Phaser.InputHandler#stopDrag
* @param {Phaser.Pointer} pointer
*/
stopDrag: function (pointer) {
this.isDragged = false;
this._draggedPointerID = -1;
this._pointerData[pointer.id].isDragged = false;
if (this.snapOnRelease)
{
if (this.sprite.fixedToCamera)
{
this.sprite.cameraOffset.x = Math.round((this.sprite.cameraOffset.x - (this.snapOffsetX % this.snapX)) / this.snapX) * this.snapX + (this.snapOffsetX % this.snapX);
this.sprite.cameraOffset.y = Math.round((this.sprite.cameraOffset.y - (this.snapOffsetY % this.snapY)) / this.snapY) * this.snapY + (this.snapOffsetY % this.snapY);
}
else
{
this.sprite.x = Math.round((this.sprite.x - (this.snapOffsetX % this.snapX)) / this.snapX) * this.snapX + (this.snapOffsetX % this.snapX);
this.sprite.y = Math.round((this.sprite.y - (this.snapOffsetY % this.snapY)) / this.snapY) * this.snapY + (this.snapOffsetY % this.snapY);
}
}
this.sprite.events.onDragStop.dispatch(this.sprite, pointer);
if (this.checkPointerOver(pointer) === false)
{
this._pointerOutHandler(pointer);
}
},
/**
* Restricts this sprite to drag movement only on the given axis. Note: If both are set to false the sprite will never move!
* @method Phaser.InputHandler#setDragLock
* @param {boolean} [allowHorizontal=true] - To enable the sprite to be dragged horizontally set to true, otherwise false.
* @param {boolean} [allowVertical=true] - To enable the sprite to be dragged vertically set to true, otherwise false.
*/
setDragLock: function (allowHorizontal, allowVertical) {
if (typeof allowHorizontal == 'undefined') { allowHorizontal = true; }
if (typeof allowVertical == 'undefined') { allowVertical = true; }
this.allowHorizontalDrag = allowHorizontal;
this.allowVerticalDrag = allowVertical;
},
/**
* Make this Sprite snap to the given grid either during drag or when it's released.
* For example 16x16 as the snapX and snapY would make the sprite snap to every 16 pixels.
* @method Phaser.InputHandler#enableSnap
* @param {number} snapX - The width of the grid cell to snap to.
* @param {number} snapY - The height of the grid cell to snap to.
* @param {boolean} [onDrag=true] - If true the sprite will snap to the grid while being dragged.
* @param {boolean} [onRelease=false] - If true the sprite will snap to the grid when released.
* @param {number} [snapOffsetX=0] - Used to offset the top-left starting point of the snap grid.
* @param {number} [snapOffsetX=0] - Used to offset the top-left starting point of the snap grid.
*/
enableSnap: function (snapX, snapY, onDrag, onRelease, snapOffsetX, snapOffsetY) {
if (typeof onDrag == 'undefined') { onDrag = true; }
if (typeof onRelease == 'undefined') { onRelease = false; }
if (typeof snapOffsetX == 'undefined') { snapOffsetX = 0; }
if (typeof snapOffsetY == 'undefined') { snapOffsetY = 0; }
this.snapX = snapX;
this.snapY = snapY;
this.snapOffsetX = snapOffsetX;
this.snapOffsetY = snapOffsetY;
this.snapOnDrag = onDrag;
this.snapOnRelease = onRelease;
},
/**
* Stops the sprite from snapping to a grid during drag or release.
* @method Phaser.InputHandler#disableSnap
*/
disableSnap: function () {
this.snapOnDrag = false;
this.snapOnRelease = false;
},
/**
* Bounds Rect check for the sprite drag
* @method Phaser.InputHandler#checkBoundsRect
*/
checkBoundsRect: function () {
if (this.sprite.fixedToCamera)
{
if (this.sprite.cameraOffset.x < this.boundsRect.left)
{
this.sprite.cameraOffset.x = this.boundsRect.cameraOffset.x;
}
else if ((this.sprite.cameraOffset.x + this.sprite.width) > this.boundsRect.right)
{
this.sprite.cameraOffset.x = this.boundsRect.right - this.sprite.width;
}
if (this.sprite.cameraOffset.y < this.boundsRect.top)
{
this.sprite.cameraOffset.y = this.boundsRect.top;
}
else if ((this.sprite.cameraOffset.y + this.sprite.height) > this.boundsRect.bottom)
{
this.sprite.cameraOffset.y = this.boundsRect.bottom - this.sprite.height;
}
}
else
{
if (this.sprite.x < this.boundsRect.left)
{
this.sprite.x = this.boundsRect.x;
}
else if ((this.sprite.x + this.sprite.width) > this.boundsRect.right)
{
this.sprite.x = this.boundsRect.right - this.sprite.width;
}
if (this.sprite.y < this.boundsRect.top)
{
this.sprite.y = this.boundsRect.top;
}
else if ((this.sprite.y + this.sprite.height) > this.boundsRect.bottom)
{
this.sprite.y = this.boundsRect.bottom - this.sprite.height;
}
}
},
/**
* Parent Sprite Bounds check for the sprite drag.
* @method Phaser.InputHandler#checkBoundsSprite
*/
checkBoundsSprite: function () {
if (this.sprite.fixedToCamera && this.boundsSprite.fixedToCamera)
{
if (this.sprite.cameraOffset.x < this.boundsSprite.camerOffset.x)
{
this.sprite.cameraOffset.x = this.boundsSprite.camerOffset.x;
}
else if ((this.sprite.cameraOffset.x + this.sprite.width) > (this.boundsSprite.camerOffset.x + this.boundsSprite.width))
{
this.sprite.cameraOffset.x = (this.boundsSprite.camerOffset.x + this.boundsSprite.width) - this.sprite.width;
}
if (this.sprite.cameraOffset.y < this.boundsSprite.camerOffset.y)
{
this.sprite.cameraOffset.y = this.boundsSprite.camerOffset.y;
}
else if ((this.sprite.cameraOffset.y + this.sprite.height) > (this.boundsSprite.camerOffset.y + this.boundsSprite.height))
{
this.sprite.cameraOffset.y = (this.boundsSprite.camerOffset.y + this.boundsSprite.height) - this.sprite.height;
}
}
else
{
if (this.sprite.x < this.boundsSprite.x)
{
this.sprite.x = this.boundsSprite.x;
}
else if ((this.sprite.x + this.sprite.width) > (this.boundsSprite.x + this.boundsSprite.width))
{
this.sprite.x = (this.boundsSprite.x + this.boundsSprite.width) - this.sprite.width;
}
if (this.sprite.y < this.boundsSprite.y)
{
this.sprite.y = this.boundsSprite.y;
}
else if ((this.sprite.y + this.sprite.height) > (this.boundsSprite.y + this.boundsSprite.height))
{
this.sprite.y = (this.boundsSprite.y + this.boundsSprite.height) - this.sprite.height;
}
}
}
};
Phaser.InputHandler.prototype.constructor = Phaser.InputHandler;
|
var WorldClocks = {};
(function(w) {
function empty() {};
function msg(key, args) {
if (typeof(chrome) != "undefined" && typeof(chrome.i18n) != "undefined") {
return chrome.i18n.getMessage(key, args);
}
return key;
}
function setPref(key, value) {
try {
if (window.localStorage) {
localStorage[key] = value;
}
} catch (e) {
}
}
function getPref(key, defaultValue) {
var value = defaultValue;
try {
if (window.localStorage) {
value = localStorage[key] || defaultValue;
}
} catch (e) {
}
return value;
}
function log() {
console.log.apply(console, arguments);
}
w.msg = msg;
w.pref = {get:getPref, set:setPref};
w.log = (typeof(console) != "undefined" && typeof(console.log) != "undefined") ? log : empty;
})(WorldClocks);
|
Cypress.Commands.add('fetchQuery', (query, variables) => {
cy.request({
url: '/graphql',
method: 'POST',
body: JSON.stringify({ query, variables }),
headers: {
'Content-Type': 'application/json'
}
});
});
|
// This is the wrapper for custom tests, called upon web components ready state
function runCustomTests() {
// Place any setup steps like variable declaration and initialization here
// This is the placeholder suite to place custom tests in
// Use testCase(options) for a more convenient setup of the test cases
suite('Custom Automation Tests for px-validation', function() {
var px_validation = document.getElementById('px_validation_1');
suiteSetup(function(done){
flush(function(){
done();
});
});
test('Check there is a single px-validator child defined on test fixture', function(){
assert.lengthOf(Polymer.dom(px_validation).children, 1);
});
test('Integer isNumber validation returns true', function() {
assert.isTrue(px_validation.validate(2).passedValidation);
});
test('String representation of number via isNumber validation returns true', function() {
assert.isTrue(px_validation.validate('2').passedValidation);
});
});
}
|
import React from 'react';
class MyPropertiesExample extends React.Component {
render() {
return (
<div>
<h1>Properties</h1>
My favourite dish is {this.props.dish}.
</div>
);
}
}
MyPropertiesExample.defaultProps = {
dish: 'shrimp with pasta'
};
MyPropertiesExample.propTypes = {
dish: React.PropTypes.string.isRequired
};
class MyVodooComponent extends React.Component {
render() {
return (
<MyPropertiesExample dish="chicken"/>
);
}
}
export default MyPropertiesExample;
|
export App from './App'
export Home from './Home'
export List from './List'
export Login from './Login'
export Chats from './Chats'
|
//Form JS File
function frmHome_stopWatch_onClick_seq0() {
alert("You clicked on stop watch");
};
function frmHome_button214149106640_onClick_seq0(eventobject) {
var a = frmHome.stopWatch.stopWatch();
alert(a);
};
function frmHome_button214149106641_onClick_seq0(eventobject) {
frmHome.stopWatch.startWatch();
};
function addWidgetsfrmHome() {
var stopWatch = new CustomStopWatch.StopWatch({
"id": "stopWatch",
"image": null,
"isVisible": true,
"hExpand": true,
"vExpand": false,
"textSize": 35,
"bgTransparancy": 0,
"onClick": frmHome_stopWatch_onClick_seq0
}, {
"widgetAlign": 5,
"containerWeight": 6,
"margin": [5, 5, 5, 5],
"marginInPixel": false,
"padding": [15, 15, 15, 15],
"paddingInPixel": false
}, {
"widgetName": "StopWatch"
});
var button214149106640 = new kony.ui.Button({
"id": "button214149106640",
"isVisible": true,
"text": "Stop Watch",
"skin": "sknBtnKonyThemeNormal",
"focusSkin": "sknBtnKonyThemeFocus",
"onClick": frmHome_button214149106640_onClick_seq0
}, {
"widgetAlignment": constants.WIDGET_ALIGN_CENTER,
"vExpand": false,
"hExpand": true,
"margin": [3, 2, 3, 2],
"padding": [2, 3, 2, 3],
"contentAlignment": constants.CONTENT_ALIGN_CENTER,
"displayText": true,
"marginInPixel": false,
"paddingInPixel": false,
"containerWeight": 6
}, {
"glowEffect": false,
"showProgressIndicator": true
});
var button214149106641 = new kony.ui.Button({
"id": "button214149106641",
"isVisible": true,
"text": "Start Watch",
"skin": "sknBtnKonyThemeNormal",
"focusSkin": "sknBtnKonyThemeFocus",
"onClick": frmHome_button214149106641_onClick_seq0
}, {
"widgetAlignment": constants.WIDGET_ALIGN_CENTER,
"vExpand": false,
"hExpand": true,
"margin": [3, 2, 3, 2],
"padding": [2, 3, 2, 3],
"contentAlignment": constants.CONTENT_ALIGN_CENTER,
"displayText": true,
"marginInPixel": false,
"paddingInPixel": false,
"containerWeight": 6
}, {
"glowEffect": false,
"showProgressIndicator": true
});
frmHome.add(
stopWatch, button214149106640, button214149106641);
};
function frmHomeGlobals() {
var MenuId = [];
frmHome = new kony.ui.Form2({
"id": "frmHome",
"needAppMenu": true,
"title": "StopWatch",
"enabledForIdleTimeout": false,
"skin": "frm",
"addWidgets": addWidgetsfrmHome
}, {
"padding": [0, 0, 0, 0],
"displayOrientation": constants.FORM_DISPLAY_ORIENTATION_PORTRAIT,
"paddingInPixel": false,
"layoutType": constants.CONTAINER_LAYOUT_BOX
}, {
"retainScrollPosition": false,
"needsIndicatorDuringPostShow": true,
"formTransparencyDuringPostShow": "100",
"inputAccessoryViewType": constants.FORM_INPUTACCESSORYVIEW_DEFAULT,
"bounces": true,
"configureExtendTop": false,
"configureExtendBottom": false,
"configureStatusBarStyle": false,
"titleBar": true,
"titleBarSkin": "titleBar",
"titleBarConfig": {
"renderTitleText": true,
"titleBarRightSideView": "title",
"titleBarLeftSideView": "none",
"closureRightSideView": navigateToSettings,
"labelRightSideView": "Settings"
},
"footerOverlap": false,
"headerOverlap": false,
"inTransitionConfig": {
"transitionDirection": "none",
"transitionEffect": "none"
},
"outTransitionConfig": {
"transitionDirection": "none",
"transitionEffect": "none"
},
"deprecated": {
"titleBarBackGroundImage": "blue_pixel.png"
}
});
}; |
// Generated by CoffeeScript 1.4.0
/* 2D Vector
*/
var Vector;
Vector = (function() {
/* Adds two vectors and returns the product.
*/
Vector.add = function(v1, v2) {
return new Vector(v1.x + v2.x, v1.y + v2.y);
};
/* Subtracts v2 from v1 and returns the product.
*/
Vector.sub = function(v1, v2) {
return new Vector(v1.x - v2.x, v1.y - v2.y);
};
/* Projects one vector (v1) onto another (v2)
*/
Vector.project = function(v1, v2) {
return v1.clone().scale((v1.dot(v2)) / v1.magSq());
};
/* Creates a new Vector instance.
*/
function Vector(x, y) {
this.x = x != null ? x : 0.0;
this.y = y != null ? y : 0.0;
}
/* Sets the components of this vector.
*/
Vector.prototype.set = function(x, y) {
this.x = x;
this.y = y;
return this;
};
/* Add a vector to this one.
*/
Vector.prototype.add = function(v) {
this.x += v.x;
this.y += v.y;
return this;
};
/* Subtracts a vector from this one.
*/
Vector.prototype.sub = function(v) {
this.x -= v.x;
this.y -= v.y;
return this;
};
/* Scales this vector by a value.
*/
Vector.prototype.scale = function(f) {
this.x *= f;
this.y *= f;
return this;
};
/* Computes the dot product between vectors.
*/
Vector.prototype.dot = function(v) {
return this.x * v.x + this.y * v.y;
};
/* Computes the cross product between vectors.
*/
Vector.prototype.cross = function(v) {
return (this.x * v.y) - (this.y * v.x);
};
/* Computes the magnitude (length).
*/
Vector.prototype.mag = function() {
return Math.sqrt(this.x * this.x + this.y * this.y);
};
/* Computes the squared magnitude (length).
*/
Vector.prototype.magSq = function() {
return this.x * this.x + this.y * this.y;
};
/* Computes the distance to another vector.
*/
Vector.prototype.dist = function(v) {
var dx, dy;
dx = v.x - this.x;
dy = v.y - this.y;
return Math.sqrt(dx * dx + dy * dy);
};
/* Computes the squared distance to another vector.
*/
Vector.prototype.distSq = function(v) {
var dx, dy;
dx = v.x - this.x;
dy = v.y - this.y;
return dx * dx + dy * dy;
};
/* Normalises the vector, making it a unit vector (of length 1).
*/
Vector.prototype.norm = function() {
var m;
m = Math.sqrt(this.x * this.x + this.y * this.y);
this.x /= m;
this.y /= m;
return this;
};
/* Limits the vector length to a given amount.
*/
Vector.prototype.limit = function(l) {
var m, mSq;
mSq = this.x * this.x + this.y * this.y;
if (mSq > l * l) {
m = Math.sqrt(mSq);
this.x /= m;
this.y /= m;
this.x *= l;
this.y *= l;
return this;
}
};
/* Copies components from another vector.
*/
Vector.prototype.copy = function(v) {
this.x = v.x;
this.y = v.y;
return this;
};
/* Clones this vector to a new itentical one.
*/
Vector.prototype.clone = function() {
return new Vector(this.x, this.y);
};
/* Resets the vector to zero.
*/
Vector.prototype.clear = function() {
this.x = 0.0;
this.y = 0.0;
return this;
};
return Vector;
})();
|
'use strict';
const Utils = require('./utils');
const _ = require('lodash');
const DataTypes = require('./data-types');
const SQLiteQueryInterface = require('./dialects/sqlite/query-interface');
const MSSSQLQueryInterface = require('./dialects/mssql/query-interface');
const MySQLQueryInterface = require('./dialects/mysql/query-interface');
const Transaction = require('./transaction');
const Promise = require('./promise');
const QueryTypes = require('./query-types');
/**
* The interface that Sequelize uses to talk to all databases
* @class QueryInterface
* @private
*/
class QueryInterface {
constructor(sequelize) {
this.sequelize = sequelize;
this.QueryGenerator = this.sequelize.dialect.QueryGenerator;
}
createSchema(schema, options) {
options = options || {};
const sql = this.QueryGenerator.createSchema(schema);
return this.sequelize.query(sql, options);
}
dropSchema(schema, options) {
options = options || {};
const sql = this.QueryGenerator.dropSchema(schema);
return this.sequelize.query(sql, options);
}
dropAllSchemas(options) {
options = options || {};
if (!this.QueryGenerator._dialect.supports.schemas) {
return this.sequelize.drop(options);
} else {
return this.showAllSchemas(options).map(schemaName => this.dropSchema(schemaName, options));
}
}
showAllSchemas(options) {
options = _.assign({}, options, {
raw: true,
type: this.sequelize.QueryTypes.SELECT
});
const showSchemasSql = this.QueryGenerator.showSchemasQuery();
return this.sequelize.query(showSchemasSql, options).then(schemaNames => Utils._.flatten(
Utils._.map(schemaNames, value => (!!value.schema_name ? value.schema_name : value))
));
}
databaseVersion(options) {
return this.sequelize.query(
this.QueryGenerator.versionQuery(),
_.assign({}, options, { type: QueryTypes.VERSION })
);
}
createTable(tableName, attributes, options, model) {
const keys = Object.keys(attributes);
const keyLen = keys.length;
let sql = '';
let i = 0;
options = _.clone(options) || {};
attributes = Utils._.mapValues(attributes, attribute => {
if (!Utils._.isPlainObject(attribute)) {
attribute = { type: attribute, allowNull: true };
}
attribute = this.sequelize.normalizeAttribute(attribute);
return attribute;
});
// Postgres requires a special SQL command for enums
if (this.sequelize.options.dialect === 'postgres') {
const promises = [];
for (i = 0; i < keyLen; i++) {
if (attributes[keys[i]].type instanceof DataTypes.ENUM) {
sql = this.QueryGenerator.pgListEnums(tableName, attributes[keys[i]].field || keys[i], options);
promises.push(this.sequelize.query(
sql,
_.assign({}, options, { plain: true, raw: true, type: QueryTypes.SELECT })
));
}
}
return Promise.all(promises).then(results => {
const promises = [];
let enumIdx = 0;
for (i = 0; i < keyLen; i++) {
if (attributes[keys[i]].type instanceof DataTypes.ENUM) {
// If the enum type doesn't exist then create it
if (!results[enumIdx]) {
sql = this.QueryGenerator.pgEnum(tableName, attributes[keys[i]].field || keys[i], attributes[keys[i]], options);
promises.push(this.sequelize.query(
sql,
_.assign({}, options, { raw: true })
));
} else if (!!results[enumIdx] && !!model) {
const enumVals = this.QueryGenerator.fromArray(results[enumIdx].enum_value);
const vals = model.rawAttributes[keys[i]].values;
vals.forEach((value, idx) => {
// reset out after/before options since it's for every enum value
const valueOptions = _.clone(options);
valueOptions.before = null;
valueOptions.after = null;
if (enumVals.indexOf(value) === -1) {
if (!!vals[idx + 1]) {
valueOptions.before = vals[idx + 1];
}
else if (!!vals[idx - 1]) {
valueOptions.after = vals[idx - 1];
}
valueOptions.supportsSearchPath = false;
promises.push(this.sequelize.query(this.QueryGenerator.pgEnumAdd(tableName, keys[i], value, valueOptions), valueOptions));
}
});
enumIdx++;
}
}
}
if (!tableName.schema &&
(options.schema || (!!model && model._schema))) {
tableName = this.QueryGenerator.addSchema({
tableName,
_schema: (!!model && model._schema) || options.schema
});
}
attributes = this.QueryGenerator.attributesToSQL(attributes, {
context: 'createTable'
});
sql = this.QueryGenerator.createTableQuery(tableName, attributes, options);
return Promise.all(promises).then(() => {
return this.sequelize.query(sql, options);
});
});
} else {
if (!tableName.schema &&
(options.schema || (!!model && model._schema))) {
tableName = this.QueryGenerator.addSchema({
tableName,
_schema: (!!model && model._schema) || options.schema
});
}
attributes = this.QueryGenerator.attributesToSQL(attributes, {
context: 'createTable'
});
sql = this.QueryGenerator.createTableQuery(tableName, attributes, options);
return this.sequelize.query(sql, options);
}
}
dropTable(tableName, options) {
// if we're forcing we should be cascading unless explicitly stated otherwise
options = _.clone(options) || {};
options.cascade = options.cascade || options.force || false;
let sql = this.QueryGenerator.dropTableQuery(tableName, options);
return this.sequelize.query(sql, options).then(() => {
const promises = [];
// Since postgres has a special case for enums, we should drop the related
// enum type within the table and attribute
if (this.sequelize.options.dialect === 'postgres') {
const instanceTable = this.sequelize.modelManager.getModel(tableName, { attribute: 'tableName' });
if (!!instanceTable) {
const getTableName = (!options || !options.schema || options.schema === 'public' ? '' : options.schema + '_') + tableName;
const keys = Object.keys(instanceTable.rawAttributes);
const keyLen = keys.length;
for (let i = 0; i < keyLen; i++) {
if (instanceTable.rawAttributes[keys[i]].type instanceof DataTypes.ENUM) {
sql = this.QueryGenerator.pgEnumDrop(getTableName, keys[i]);
options.supportsSearchPath = false;
promises.push(this.sequelize.query(sql, _.assign({}, options, { raw: true })));
}
}
}
}
return Promise.all(promises).get(0);
});
}
dropAllTables(options) {
options = options || {};
const skip = options.skip || [];
const dropAllTables = tableNames => Promise.each(tableNames, tableName => {
// if tableName is not in the Array of tables names then dont drop it
if (skip.indexOf(tableName.tableName || tableName) === -1) {
return this.dropTable(tableName, _.assign({}, options, { cascade: true }) );
}
});
return this.showAllTables(options).then(tableNames => {
if (this.sequelize.options.dialect === 'sqlite') {
return this.sequelize.query('PRAGMA foreign_keys;', options).then(result => {
const foreignKeysAreEnabled = result.foreign_keys === 1;
if (foreignKeysAreEnabled) {
return this.sequelize.query('PRAGMA foreign_keys = OFF', options)
.then(() => dropAllTables(tableNames))
.then(() => this.sequelize.query('PRAGMA foreign_keys = ON', options));
} else {
return dropAllTables(tableNames);
}
});
} else {
return this.getForeignKeysForTables(tableNames, options).then(foreignKeys => {
const promises = [];
tableNames.forEach(tableName => {
let normalizedTableName = tableName;
if (Utils._.isObject(tableName)) {
normalizedTableName = tableName.schema + '.' + tableName.tableName;
}
foreignKeys[normalizedTableName].forEach(foreignKey => {
const sql = this.QueryGenerator.dropForeignKeyQuery(tableName, foreignKey);
promises.push(this.sequelize.query(sql, options));
});
});
return Promise.all(promises).then(() => dropAllTables(tableNames));
});
}
});
}
dropAllEnums(options) {
if (this.sequelize.getDialect() !== 'postgres') {
return Promise.resolve();
}
options = options || {};
return this.pgListEnums(null, options).map(result => this.sequelize.query(
this.QueryGenerator.pgEnumDrop(null, null, this.QueryGenerator.pgEscapeAndQuote(result.enum_name)),
_.assign({}, options, { raw: true })
));
}
pgListEnums(tableName, options) {
options = options || {};
const sql = this.QueryGenerator.pgListEnums(tableName);
return this.sequelize.query(sql, _.assign({}, options, { plain: false, raw: true, type: QueryTypes.SELECT }));
}
renameTable(before, after, options) {
options = options || {};
const sql = this.QueryGenerator.renameTableQuery(before, after);
return this.sequelize.query(sql, options);
}
showAllTables(options) {
options = _.assign({}, options, {
raw: true,
type: QueryTypes.SHOWTABLES
});
let showTablesSql = null;
if (options.schema)
showTablesSql = this.QueryGenerator.showTablesQuery(options.schema);
else
showTablesSql = this.QueryGenerator.showTablesQuery();
return this.sequelize.query(showTablesSql, options).then(tableNames => Utils._.flatten(tableNames));
}
describeTable(tableName, options) {
let schema = null;
let schemaDelimiter = null;
if (typeof options === 'string') {
schema = options;
} else if (typeof options === 'object' && options !== null) {
schema = options.schema || null;
schemaDelimiter = options.schemaDelimiter || null;
}
if (typeof tableName === 'object' && tableName !== null) {
schema = tableName.schema;
tableName = tableName.tableName;
}
const sql = this.QueryGenerator.describeTableQuery(tableName, schema, schemaDelimiter);
return this.sequelize.query(
sql,
_.assign({}, options, { type: QueryTypes.DESCRIBE })
).then(data => {
// If no data is returned from the query, then the table name may be wrong.
// Query generators that use information_schema for retrieving table info will just return an empty result set,
// it will not throw an error like built-ins do (e.g. DESCRIBE on MySql).
if (Utils._.isEmpty(data)) {
return Promise.reject('No description found for "' + tableName + '" table. Check the table name and schema; remember, they _are_ case sensitive.');
} else {
return Promise.resolve(data);
}
});
}
addColumn(table, key, attribute, options) {
if (!table || !key || !attribute) {
throw new Error('addColumn takes atleast 3 arguments (table, attribute name, attribute definition)');
}
options = options || {};
attribute = this.sequelize.normalizeAttribute(attribute);
return this.sequelize.query(this.QueryGenerator.addColumnQuery(table, key, attribute), options);
}
removeColumn(tableName, attributeName, options) {
options = options || {};
switch (this.sequelize.options.dialect) {
case 'sqlite':
// sqlite needs some special treatment as it cannot drop a column
return SQLiteQueryInterface.removeColumn.call(this, tableName, attributeName, options);
case 'mssql':
// mssql needs special treatment as it cannot drop a column with a default or foreign key constraint
return MSSSQLQueryInterface.removeColumn.call(this, tableName, attributeName, options);
case 'mysql':
// mysql needs special treatment as it cannot drop a column with a foreign key constraint
return MySQLQueryInterface.removeColumn.call(this, tableName, attributeName, options);
default:
return this.sequelize.query(this.QueryGenerator.removeColumnQuery(tableName, attributeName), options);
}
}
changeColumn(tableName, attributeName, dataTypeOrOptions, options) {
const attributes = {};
options = options || {};
if (Utils._.values(DataTypes).indexOf(dataTypeOrOptions) > -1) {
attributes[attributeName] = { type: dataTypeOrOptions, allowNull: true };
} else {
attributes[attributeName] = dataTypeOrOptions;
}
attributes[attributeName].type = this.sequelize.normalizeDataType(attributes[attributeName].type);
if (this.sequelize.options.dialect === 'sqlite') {
// sqlite needs some special treatment as it cannot change a column
return SQLiteQueryInterface.changeColumn.call(this, tableName, attributes, options);
} else {
const query = this.QueryGenerator.attributesToSQL(attributes);
const sql = this.QueryGenerator.changeColumnQuery(tableName, query);
return this.sequelize.query(sql, options);
}
}
renameColumn(tableName, attrNameBefore, attrNameAfter, options) {
options = options || {};
return this.describeTable(tableName, options).then(data => {
data = data[attrNameBefore] || {};
const _options = {};
_options[attrNameAfter] = {
attribute: attrNameAfter,
type: data.type,
allowNull: data.allowNull,
defaultValue: data.defaultValue
};
// fix: a not-null column cannot have null as default value
if (data.defaultValue === null && !data.allowNull) {
delete _options[attrNameAfter].defaultValue;
}
if (this.sequelize.options.dialect === 'sqlite') {
// sqlite needs some special treatment as it cannot rename a column
return SQLiteQueryInterface.renameColumn.call(this, tableName, attrNameBefore, attrNameAfter, options);
} else {
const sql = this.QueryGenerator.renameColumnQuery(
tableName,
attrNameBefore,
this.QueryGenerator.attributesToSQL(_options)
);
return this.sequelize.query(sql, options);
}
});
}
addIndex(tableName, attributes, options, rawTablename) {
// Support for passing tableName, attributes, options or tableName, options (with a fields param which is the attributes)
if (!Array.isArray(attributes)) {
rawTablename = options;
options = attributes;
attributes = options.fields;
}
// testhint argsConform.end
if (!rawTablename) {
// Map for backwards compat
rawTablename = tableName;
}
options = Utils.cloneDeep(options);
options.fields = attributes;
const sql = this.QueryGenerator.addIndexQuery(tableName, options, rawTablename);
return this.sequelize.query(sql, _.assign({}, options, { supportsSearchPath: false }));
}
showIndex(tableName, options) {
const sql = this.QueryGenerator.showIndexesQuery(tableName, options);
return this.sequelize.query(sql, _.assign({}, options, { type: QueryTypes.SHOWINDEXES }));
}
nameIndexes(indexes, rawTablename) {
return this.QueryGenerator.nameIndexes(indexes, rawTablename);
}
getForeignKeysForTables(tableNames, options) {
options = options || {};
if (tableNames.length === 0) {
return Promise.resolve({});
}
return Promise.map(tableNames, tableName =>
this.sequelize.query(this.QueryGenerator.getForeignKeysQuery(tableName, this.sequelize.config.database), options).get(0)
).then(results => {
const result = {};
tableNames.forEach((tableName, i) => {
if (Utils._.isObject(tableName)) {
tableName = tableName.schema + '.' + tableName.tableName;
}
result[tableName] = Utils._.compact(results[i]).map(r => r.constraint_name);
});
return result;
});
}
removeIndex(tableName, indexNameOrAttributes, options) {
options = options || {};
const sql = this.QueryGenerator.removeIndexQuery(tableName, indexNameOrAttributes);
return this.sequelize.query(sql, options);
}
insert(instance, tableName, values, options) {
options = Utils.cloneDeep(options);
options.hasTrigger = instance && instance.constructor.options.hasTrigger;
const sql = this.QueryGenerator.insertQuery(tableName, values, instance && instance.constructor.rawAttributes, options);
options.type = QueryTypes.INSERT;
options.instance = instance;
return this.sequelize.query(sql, options).then(results => {
if (instance) results[0].isNewRecord = false;
return results;
});
}
upsert(tableName, valuesByField, updateValues, where, model, options) {
const wheres = [];
const attributes = Object.keys(valuesByField);
let indexes = [];
let indexFields;
options = _.clone(options);
if (!Utils._.isEmpty(where)) {
wheres.push(where);
}
// Lets combine uniquekeys and indexes into one
indexes = Utils._.map(model.options.uniqueKeys, value => {
return value.fields;
});
Utils._.each(model.options.indexes, value => {
if (value.unique === true) {
// fields in the index may both the strings or objects with an attribute property - lets sanitize that
indexFields = Utils._.map(value.fields, field => {
if (Utils._.isPlainObject(field)) {
return field.attribute;
}
return field;
});
indexes.push(indexFields);
}
});
for (const index of indexes) {
if (Utils._.intersection(attributes, index).length === index.length) {
where = {};
for (const field of index) {
where[field] = valuesByField[field];
}
wheres.push(where);
}
}
where = { $or: wheres };
options.type = QueryTypes.UPSERT;
options.raw = true;
const sql = this.QueryGenerator.upsertQuery(tableName, valuesByField, updateValues, where, model.rawAttributes, options);
return this.sequelize.query(sql, options).then(rowCount => {
if (rowCount === undefined) {
return rowCount;
}
// MySQL returns 1 for inserted, 2 for updated http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html. Postgres has been modded to do the same
return rowCount === 1;
});
}
bulkInsert(tableName, records, options, attributes) {
options = _.clone(options) || {};
options.type = QueryTypes.INSERT;
const sql = this.QueryGenerator.bulkInsertQuery(tableName, records, options, attributes);
return this.sequelize.query(sql, options).then(results => results[0]);
}
update(instance, tableName, values, identifier, options) {
options = _.clone(options || {});
options.hasTrigger = !!(instance && instance._modelOptions && instance._modelOptions.hasTrigger);
const sql = this.QueryGenerator.updateQuery(tableName, values, identifier, options, instance.constructor.rawAttributes);
let restrict = false;
options.type = QueryTypes.UPDATE;
// Check for a restrict field
if (instance.constructor && instance.constructor.associations) {
const keys = Object.keys(instance.constructor.associations);
const length = keys.length;
for (let i = 0; i < length; i++) {
if (instance.constructor.associations[keys[i]].options && instance.constructor.associations[keys[i]].options.onUpdate && instance.constructor.associations[keys[i]].options.onUpdate === 'restrict') {
restrict = true;
}
}
}
options.instance = instance;
return this.sequelize.query(sql, options);
}
bulkUpdate(tableName, values, identifier, options, attributes) {
options = Utils.cloneDeep(options);
if (typeof identifier === 'object') identifier = Utils.cloneDeep(identifier);
const sql = this.QueryGenerator.updateQuery(tableName, values, identifier, options, attributes);
const table = Utils._.isObject(tableName) ? tableName : { tableName };
const model = Utils._.find(this.sequelize.modelManager.models, { tableName: table.tableName });
options.model = model;
return this.sequelize.query(sql, options);
}
delete(instance, tableName, identifier, options) {
const cascades = [];
const sql = this.QueryGenerator.deleteQuery(tableName, identifier, null, instance.constructor);
options = _.clone(options) || {};
// Check for a restrict field
if (!!instance.constructor && !!instance.constructor.associations) {
const keys = Object.keys(instance.constructor.associations);
const length = keys.length;
let association;
for (let i = 0; i < length; i++) {
association = instance.constructor.associations[keys[i]];
if (association.options && association.options.onDelete &&
association.options.onDelete.toLowerCase() === 'cascade' &&
association.options.useHooks === true) {
cascades.push(association.accessors.get);
}
}
}
return Promise.each(cascades, cascade => {
return instance[cascade](options).then(instances => {
// Check for hasOne relationship with non-existing associate ("has zero")
if (!instances) {
return Promise.resolve();
}
if (!Array.isArray(instances)) instances = [instances];
return Promise.each(instances, instance => instance.destroy(options));
});
}).then(() => {
options.instance = instance;
return this.sequelize.query(sql, options);
});
}
bulkDelete(tableName, identifier, options, model) {
options = Utils.cloneDeep(options);
options = _.defaults(options, {limit: null});
if (typeof identifier === 'object') identifier = Utils.cloneDeep(identifier);
const sql = this.QueryGenerator.deleteQuery(tableName, identifier, options, model);
return this.sequelize.query(sql, options);
}
select(model, tableName, options) {
options = Utils.cloneDeep(options);
options.type = QueryTypes.SELECT;
options.model = model;
return this.sequelize.query(
this.QueryGenerator.selectQuery(tableName, options, model),
options
);
}
increment(instance, tableName, values, identifier, options) {
const sql = this.QueryGenerator.arithmeticQuery('+', tableName, values, identifier, options.attributes);
options = _.clone(options) || {};
options.type = QueryTypes.UPDATE;
options.instance = instance;
return this.sequelize.query(sql, options);
}
decrement(instance, tableName, values, identifier, options) {
const sql = this.QueryGenerator.arithmeticQuery('-', tableName, values, identifier, options.attributes);
options = _.clone(options) || {};
options.type = QueryTypes.UPDATE;
options.instance = instance;
return this.sequelize.query(sql, options);
}
rawSelect(tableName, options, attributeSelector, Model) {
if (options.schema) {
tableName = this.QueryGenerator.addSchema({
tableName,
_schema: options.schema
});
}
options = Utils.cloneDeep(options);
options = _.defaults(options, {
raw: true,
plain: true,
type: QueryTypes.SELECT
});
const sql = this.QueryGenerator.selectQuery(tableName, options, Model);
if (attributeSelector === undefined) {
throw new Error('Please pass an attribute selector!');
}
return this.sequelize.query(sql, options).then(data => {
if (!options.plain) {
return data;
}
let result = data ? data[attributeSelector] : null;
if (options && options.dataType) {
const dataType = options.dataType;
if (dataType instanceof DataTypes.DECIMAL || dataType instanceof DataTypes.FLOAT) {
result = parseFloat(result);
} else if (dataType instanceof DataTypes.INTEGER || dataType instanceof DataTypes.BIGINT) {
result = parseInt(result, 10);
} else if (dataType instanceof DataTypes.DATE) {
if (!Utils._.isNull(result) && !Utils._.isDate(result)) {
result = new Date(result);
}
} else if (dataType instanceof DataTypes.STRING) {
// Nothing to do, result is already a string.
}
}
return result;
});
}
createTrigger(tableName, triggerName, timingType, fireOnArray, functionName, functionParams, optionsArray, options) {
const sql = this.QueryGenerator.createTrigger(tableName, triggerName, timingType, fireOnArray, functionName, functionParams, optionsArray);
options = options || {};
if (sql) {
return this.sequelize.query(sql, options);
} else {
return Promise.resolve();
}
}
dropTrigger(tableName, triggerName, options) {
const sql = this.QueryGenerator.dropTrigger(tableName, triggerName);
options = options || {};
if (sql) {
return this.sequelize.query(sql, options);
} else {
return Promise.resolve();
}
}
renameTrigger(tableName, oldTriggerName, newTriggerName, options) {
const sql = this.QueryGenerator.renameTrigger(tableName, oldTriggerName, newTriggerName);
options = options || {};
if (sql) {
return this.sequelize.query(sql, options);
} else {
return Promise.resolve();
}
}
createFunction(functionName, params, returnType, language, body, options) {
const sql = this.QueryGenerator.createFunction(functionName, params, returnType, language, body, options);
options = options || {};
if (sql) {
return this.sequelize.query(sql, options);
} else {
return Promise.resolve();
}
}
dropFunction(functionName, params, options) {
const sql = this.QueryGenerator.dropFunction(functionName, params);
options = options || {};
if (sql) {
return this.sequelize.query(sql, options);
} else {
return Promise.resolve();
}
}
renameFunction(oldFunctionName, params, newFunctionName, options) {
const sql = this.QueryGenerator.renameFunction(oldFunctionName, params, newFunctionName);
options = options || {};
if (sql) {
return this.sequelize.query(sql, options);
} else {
return Promise.resolve();
}
}
// Helper methods useful for querying
/**
* Escape an identifier (e.g. a table or attribute name). If force is true,
* the identifier will be quoted even if the `quoteIdentifiers` option is
* false.
* @private
*/
quoteIdentifier(identifier, force) {
return this.QueryGenerator.quoteIdentifier(identifier, force);
}
quoteTable(identifier) {
return this.QueryGenerator.quoteTable(identifier);
}
/**
* Split an identifier into .-separated tokens and quote each part.
* If force is true, the identifier will be quoted even if the
* `quoteIdentifiers` option is false.
* @private
*/
quoteIdentifiers(identifiers, force) {
return this.QueryGenerator.quoteIdentifiers(identifiers, force);
}
/**
* Escape a value (e.g. a string, number or date)
* @private
*/
escape(value) {
return this.QueryGenerator.escape(value);
}
setAutocommit(transaction, value, options) {
if (!transaction || !(transaction instanceof Transaction)) {
throw new Error('Unable to set autocommit for a transaction without transaction object!');
}
if (transaction.parent) {
// Not possible to set a seperate isolation level for savepoints
return Promise.resolve();
}
options = _.assign({}, options, {
transaction: transaction.parent || transaction
});
const sql = this.QueryGenerator.setAutocommitQuery(value, {
parent: transaction.parent
});
if (!sql) return Promise.resolve();
return this.sequelize.query(sql, options);
}
setIsolationLevel(transaction, value, options) {
if (!transaction || !(transaction instanceof Transaction)) {
throw new Error('Unable to set isolation level for a transaction without transaction object!');
}
if (transaction.parent || !value) {
// Not possible to set a seperate isolation level for savepoints
return Promise.resolve();
}
options = _.assign({}, options, {
transaction: transaction.parent || transaction
});
const sql = this.QueryGenerator.setIsolationLevelQuery(value, {
parent: transaction.parent
});
if (!sql) return Promise.resolve();
return this.sequelize.query(sql, options);
}
startTransaction(transaction, options) {
if (!transaction || !(transaction instanceof Transaction)) {
throw new Error('Unable to start a transaction without transaction object!');
}
options = _.assign({}, options, {
transaction: transaction.parent || transaction
});
options.transaction.name = transaction.parent ? transaction.name : undefined;
const sql = this.QueryGenerator.startTransactionQuery(transaction);
return this.sequelize.query(sql, options);
}
deferConstraints(transaction, options) {
options = _.assign({}, options, {
transaction: transaction.parent || transaction
});
const sql = this.QueryGenerator.deferConstraintsQuery(options);
if (sql) {
return this.sequelize.query(sql, options);
}
return Promise.resolve();
}
commitTransaction(transaction, options) {
if (!transaction || !(transaction instanceof Transaction)) {
throw new Error('Unable to commit a transaction without transaction object!');
}
if (transaction.parent) {
// Savepoints cannot be committed
return Promise.resolve();
}
options = _.assign({}, options, {
transaction: transaction.parent || transaction,
supportsSearchPath: false
});
const sql = this.QueryGenerator.commitTransactionQuery(transaction);
const promise = this.sequelize.query(sql, options);
transaction.finished = 'commit';
return promise;
}
rollbackTransaction(transaction, options) {
if (!transaction || !(transaction instanceof Transaction)) {
throw new Error('Unable to rollback a transaction without transaction object!');
}
options = _.assign({}, options, {
transaction: transaction.parent || transaction,
supportsSearchPath: false
});
options.transaction.name = transaction.parent ? transaction.name : undefined;
const sql = this.QueryGenerator.rollbackTransactionQuery(transaction);
const promise = this.sequelize.query(sql, options);
transaction.finished = 'rollback';
return promise;
}
}
module.exports = QueryInterface;
module.exports.QueryInterface = QueryInterface;
module.exports.default = QueryInterface;
|
'use strict'
const t = require('tcomb')
const fetch = require('node-fetch')
const { requestProperties, validateResponse, parseJSON } = require('../utils')
const PATH = '/designs'
module.exports = function getDesign(id) {
t.String(id)
return new Promise((resolve, reject) => {
const { href, headers } = requestProperties(
this.token, this.version, [PATH, id].join('/')
)
fetch(href, { headers })
.then(validateResponse)
.then(parseJSON)
.then(resolve)
.catch(reject)
})
}
|
'use strict';
const appErrorsFactory = require('../../app-errors/app-errors-factory');
/**
*
*/
function setup(req, res, next) {
if (!req.currentUser) {
next(appErrorsFactory.createAppError({ statusCode: 401 }));
}
else {
next();
}
}
module.exports = setup;
|
/*global $, google, InfoBox */
var simulation_manager = (function(){
google.maps.visualRefresh = true;
var ua_is_mobile = navigator.userAgent.indexOf('iPhone') !== -1 || navigator.userAgent.indexOf('Android') !== -1;
var config = (function(){
var params = {};
return {
init: function() {
$.ajax({
url: 'static/js/config.js',
dataType: 'json',
async: false,
success: function(config_params) {
params = config_params;
// Override config with the QS params
var url_parts = window.location.href.split('?');
if (url_parts.length === 2) {
var qs_groups = url_parts[1].split('&');
$.each(qs_groups, function(index, qs_group){
var qs_parts = qs_group.split('=');
var key = qs_parts[0];
// Backwards compatibility
switch (key) {
case 'zoom':
key = 'zoom.start';
break;
case 'x':
key = 'center.x';
break;
case 'y':
key = 'center.y';
break;
}
var param_value = decodeURIComponent(qs_parts[1]);
params[key] = param_value;
});
}
},
error: function(a) {
alert('Broken JSON in static/js/config.js');
}
});
},
getParam: function(key) {
return (typeof params[key] === 'undefined') ? null : params[key];
}
};
})();
var map = null;
var simulation_vehicles = {};
var listener_helpers = (function(){
var listeners = {};
function notify(type) {
if (typeof listeners[type] === 'undefined') {
return;
}
$.each(listeners[type], function(i, fn){
fn();
});
}
function subscribe(type, fn) {
if (typeof listeners[type] === 'undefined') {
listeners[type] = [];
}
listeners[type].push(fn);
}
return {
notify: notify,
subscribe: subscribe
};
})();
var stationsPool = (function(){
var stations = {};
function get(id) {
return (typeof stations[id]) === 'undefined' ? '' : stations[id].get('name');
}
function location_get(id) {
return (typeof stations[id]) === 'undefined' ? '' : stations[id].get('location');
}
function addFeatures(features) {
$.each(features, function(index, feature) {
var station_id, station_name;
if (typeof(feature.properties.stop_id) === 'undefined') {
// Custom GeoJSON support
station_id = feature.properties.station_id;
station_name = feature.properties.name;
} else {
// GTFS support
station_id = feature.properties.stop_id;
station_name = feature.properties.stop_name;
}
var station = new google.maps.MVCObject();
station.set('name', station_name);
var station_x = parseFloat(feature.geometry.coordinates[0]);
var station_y = parseFloat(feature.geometry.coordinates[1]);
station.set('location', new google.maps.LatLng(station_y, station_x));
stations[station_id] = station;
});
}
return {
get: get,
addFeatures: addFeatures,
location_get: location_get
};
})();
// Routes manager.
// Roles:
// - keep a reference for the routes between stations
// i.e. (Zürich HB-Bern, Zürich HB-Olten, Olten-Bern)
// Note: one route can contain one or more edges (the low-level entity in the simulation graph)
// - interpolate position at given percent along a route
var linesPool = (function() {
var network_lines = {};
var routes = {};
var route_highlight = new google.maps.Polyline({
path: [],
strokeColor: "white",
strokeOpacity: 0.8,
strokeWeight: 3,
map: null,
icons: [{
icon: {
path: 'M 0,-2 0,2',
strokeColor: 'black',
strokeOpacity: 1.0
},
repeat: '40px'
}],
timer: null
});
// TODO - that can be a nice feature request for google.maps.geometry lib
function positionOnRouteAtPercentGet(ab_edges, percent) {
function routeIsDetailedAtPercent() {
for (var k=0; k<route.detailed_parts.length; k++) {
if ((percent >= route.detailed_parts[k].start) && (percent < route.detailed_parts[k].end)) {
return true;
}
}
return false;
}
var route = routes[ab_edges];
var dAC = route.length*percent;
var is_detailed = map_helpers.isDetailView() ? routeIsDetailedAtPercent() : false;
var position_data = positionDataGet(route, dAC, is_detailed);
if (position_data !== null) {
position_data.is_detailed = is_detailed;
}
return position_data;
}
function routeAdd(ab_edges) {
if (typeof routes[ab_edges] !== 'undefined') {
return;
}
var edges = ab_edges.split(',');
var routePoints = [];
var dAB = 0;
$.each(edges, function(k, edgeID) {
if (edgeID.substr(0, 1) === '-') {
edgeID = edgeID.substr(1);
var points = network_lines[edgeID]?network_lines[edgeID].points.slice().reverse():[];
} else {
var points = network_lines[edgeID]?network_lines[edgeID].points: [];
}
routePoints = routePoints.concat(points);
dAB += network_lines[edgeID]? network_lines[edgeID].length: 0;
});
var routeDetailedParts = [];
var routeDetailedParts_i = 0;
var is_detailed_prev = false;
var dAC = 0;
$.each(edges, function(k, edgeID) {
if (edgeID.substr(0, 1) === '-') {
edgeID = edgeID.substr(1);
}
var is_detailed = network_lines[edgeID] && network_lines[edgeID].is_detailed;
if (is_detailed) {
if (is_detailed_prev === false) {
routeDetailedParts[routeDetailedParts_i] = {
start: dAC / dAB,
end: 1
};
}
} else {
if (is_detailed_prev) {
routeDetailedParts[routeDetailedParts_i].end = dAC / dAB;
routeDetailedParts_i += 1;
}
}
is_detailed_prev = is_detailed;
dAC += network_lines[edgeID] ? network_lines[edgeID].length :0;
});
var route = {
points: routePoints,
length: dAB,
detailed_parts: routeDetailedParts
};
routes[ab_edges] = route;
}
function lengthGet(ab_edges) {
return routes[ab_edges].length;
}
function routeHighlight(vehicle) {
var points = [];
if (vehicle.source === 'gtfs') {
points = routes[vehicle.shape_id].points;
} else {
$.each(vehicle.edges, function(k, ab_edges){
if (k === 0) { return; }
points = points.concat(routes[ab_edges].points);
});
}
route_highlight.setPath(points);
route_highlight.setMap(map);
var icon_offset = 0;
route_highlight.set('timer', setInterval(function(){
if (icon_offset > 39) {
icon_offset = 0;
} else {
icon_offset += 2;
}
var icons = route_highlight.get('icons');
icons[0].offset = icon_offset + 'px';
route_highlight.set('icons', icons);
}, 20));
}
function routeHighlightRemove() {
route_highlight.setMap(null);
clearInterval(route_highlight.get('timer'));
}
function loadEncodedEdges(edges) {
$.each(edges, function(edge_id, encoded_edge) {
network_lines[edge_id] = {
points: google.maps.geometry.encoding.decodePath(encoded_edge),
is_detailed: false
};
});
}
function loadGeoJSONEdges(features) {
$.each(features, function(index, feature) {
var edge_coords = [];
$.each(feature.geometry.coordinates, function(i2, feature_coord){
edge_coords.push(new google.maps.LatLng(feature_coord[1], feature_coord[0]));
});
var edge_id = feature.properties.edge_id || feature.properties.shape_id;
network_lines[edge_id] = {
points: edge_coords,
is_detailed: feature.properties.detailed === 'yes',
length: parseFloat(google.maps.geometry.spherical.computeLength(edge_coords).toFixed(3))
};
});
}
function loadGeoJSONShapes(features) {
$.each(features, function(index, feature) {
var shape_id = feature.properties.shape_id;
var points = [];
$.each(feature.geometry.coordinates, function(i2, feature_coord){
points.push(new google.maps.LatLng(feature_coord[1], feature_coord[0]));
});
var dAB = parseFloat(google.maps.geometry.spherical.computeLength(points).toFixed(3));
var route = {
points: points,
length: dAB,
detailed_parts: []
};
routes[shape_id] = route;
});
}
function positionDataGet(route, dAC, is_detailed) {
var dC = 0;
for (var i=1; i<route.points.length; i++) {
var pA = route.points[i-1];
var pB = route.points[i];
var d12 = google.maps.geometry.spherical.computeDistanceBetween(pA, pB);
if ((dC + d12) > dAC) {
var data = {
position: google.maps.geometry.spherical.interpolate(pA, pB, (dAC - dC)/d12)
};
if (is_detailed) {
data.heading = google.maps.geometry.spherical.computeHeading(pA, pB);
}
return data;
}
dC += d12;
}
return null;
}
function projectDistanceAlongRoute(ab_edges, dAC) {
var route = routes[ab_edges];
return positionDataGet(route, dAC, true);
}
return {
positionGet: positionOnRouteAtPercentGet,
routeAdd: routeAdd,
lengthGet: lengthGet,
routeHighlight: routeHighlight,
routeHighlightRemove: routeHighlightRemove,
loadEncodedEdges: loadEncodedEdges,
loadGeoJSONEdges: loadGeoJSONEdges,
loadGeoJSONShapes: loadGeoJSONShapes,
projectDistanceAlongRoute: projectDistanceAlongRoute
};
})();
// Time manager
// Roles:
// - manages the current number of seconds that passed since midnight
var timer = (function(){
var timer_refresh = 100;
var ts_midnight = null;
var ts_now = null;
var ts_minute = null;
var seconds_multiply = null;
function init() {
(function(){
var d = new Date();
var hms = config.getParam('hms');
// Demo data is set for 9 AM
if (config.getParam('api_paths.trips') === 'api/demo/trips.json') {
hms = '09:00:00';
}
if (hms !== null) {
var hms_matches = hms.match(/^([0-9]{2}):([0-9]{2}):([0-9]{2})$/);
if (hms_matches) {
d.setHours(parseInt(hms_matches[1], 10));
d.setMinutes(parseInt(hms_matches[2], 10));
d.setSeconds(parseInt(hms_matches[3], 10));
}
}
ts_now = d.getTime() / 1000;
d.setHours(0);
d.setMinutes(0);
d.setSeconds(0);
d.setMilliseconds(0);
ts_midnight = d.getTime() / 1000;
})();
seconds_multiply = parseFloat($('#time_multiply').val());
$('#time_multiply').change(function(){
seconds_multiply = parseInt($(this).val(), 10);
});
var timeContainer = $('#day_time');
function timeIncrement() {
var d_now = new Date(ts_now * 1000);
var ts_minute_new = d_now.getMinutes();
if (ts_minute !== ts_minute_new) {
if (ts_minute !== null) {
listener_helpers.notify('minute_changed');
}
ts_minute = ts_minute_new;
}
timeContainer.text(getHMS());
ts_now += (timer_refresh / 1000) * seconds_multiply;
setTimeout(timeIncrement, timer_refresh);
}
timeIncrement();
}
function pad2Dec(what) {
return (what < 10 ? '0' + what : what);
}
function getHMS(ts) {
ts = ts || ts_now;
var d = new Date(ts * 1000);
var hours = pad2Dec(d.getHours());
var minutes = pad2Dec(d.getMinutes());
var seconds = pad2Dec(d.getSeconds());
return hours + ':' + minutes + ':' + seconds;
}
return {
init: init,
getTS: function(ts) {
return ts_now;
},
getHM: function(ts) {
var hms = getHMS(ts);
return hms.substring(0, 2) + ':' + hms.substring(3, 5);
},
getTSMidnight: function() {
return ts_midnight;
},
getRefreshValue: function() {
return timer_refresh;
},
getHMS2TS: function(hms) {
var hms_parts = hms.split(':');
var hours = parseInt(hms_parts[0], 10);
var minutes = parseInt(hms_parts[1], 10);
var seconds = parseInt(hms_parts[2], 10);
return ts_midnight + hours * 3600 + minutes * 60 + seconds;
}
};
})();
var simulation_panel = (function(){
var selected_vehicle = null;
function Toggler(el_id) {
var el = $(el_id);
el.attr('data-value-original', el.val());
var subscriber_types = {
'enable': [function(){
el.addClass('toggled');
el.val(el.attr('data-value-toggle'));
}],
'disable': [function(){
el.removeClass('toggled');
el.val(el.attr('data-value-original'));
}]
};
this.subscriber_types = subscriber_types;
el.click(function(){
var subscribers = el.hasClass('toggled') ? subscriber_types.disable : subscriber_types.enable;
$.each(subscribers, function(index, fn){
fn();
});
});
}
Toggler.prototype.subscribe = function(type, fn) {
this.subscriber_types[type].push(fn);
};
Toggler.prototype.trigger = function(type) {
$.each(this.subscriber_types[type], function(index, fn){
fn();
});
};
var vehicle_follow = (function(){
listener_helpers.subscribe('map_init', function(){
function stop_following() {
if (selected_vehicle === null) {
return;
}
stop();
}
google.maps.event.addListener(map, 'dragstart', stop_following);
google.maps.event.addListener(map, 'click', stop_following);
google.maps.event.addListener(map, 'dblclick', stop_following);
});
var toggler;
function init() {
toggler = new Toggler('#follow_trigger');
toggler.subscribe('enable', function(){
selected_vehicle.marker.set('follow', 'yes-init');
});
toggler.subscribe('disable', function(){
if (selected_vehicle) {
selected_vehicle.marker.set('follow', 'no');
}
map.unbind('center');
});
}
function start(vehicle) {
selected_vehicle = vehicle;
toggler.trigger('enable');
}
function stop() {
toggler.trigger('disable');
}
return {
init: init,
start: start,
stop: stop
};
})();
var vehicle_route = (function(){
var toggler;
function init() {
toggler = new Toggler('#route_show_trigger');
toggler.subscribe('enable', function(){
linesPool.routeHighlight(selected_vehicle);
});
toggler.subscribe('disable', function(){
linesPool.routeHighlightRemove();
});
}
function hide() {
toggler.trigger('disable');
}
return {
init: init,
hide: hide
};
})();
function station_info_hide() {
$('#station_info').addClass('hidden');
}
function vehicle_info_display(vehicle) {
if ((selected_vehicle !== null) && (selected_vehicle.id === vehicle.id)) {
if (selected_vehicle.marker.get('follow') === 'no') {
vehicle_follow.start(selected_vehicle);
}
if (selected_vehicle.marker.get('follow') === 'yes') {
vehicle_follow.stop();
}
return;
}
selected_vehicle = vehicle;
vehicle_follow.stop();
station_info_hide();
vehicle_route.hide();
$('.vehicle_name', $('#vehicle_info')).text(vehicle.name + ' (' + vehicle.id + ')');
var route_config = config.getParam('routes')[vehicle.route_icon];
if (route_config) {
$('.vehicle_name', $('#vehicle_info')).css('background-color', route_config.route_color);
$('.vehicle_name', $('#vehicle_info')).css('color', route_config.route_text_color);
}
var ts = timer.getTS();
var html_rows = [];
$.each(vehicle.stations, function(index, stop_id) {
var s_dep = (typeof vehicle.depS[index] === 'undefined') ? "n/a" : vehicle.depS[index];
var html_row = '<tr data-dep-sec="' + s_dep + '"><td>' + (index + 1) + '.</td>';
var station_location = stationsPool.location_get(stop_id);
if (station_location === null) {
html_row += '<td>' + stationsPool.get(stop_id) + '</td>';
} else {
html_row += '<td><a href="#station_id=' + stop_id + '" data-station-id="' + stop_id + '">' + stationsPool.get(stop_id) + '</a></td>';
}
var hm_arr = (typeof vehicle.arrS[index - 1] === 'undefined') ? '' : timer.getHM(vehicle.arrS[index - 1]);
html_row += '<td>' + hm_arr + '</td>';
var hm_dep = (typeof vehicle.depS[index] === 'undefined') ? '' : timer.getHM(vehicle.depS[index]);
html_row += '<td>' + hm_dep + '</td></tr>';
html_rows.push(html_row);
});
$('#vehicle_timetable > tbody').html(html_rows.join(''));
$('#vehicle_timetable tbody tr').each(function(){
var row_dep_sec = $(this).attr('data-dep-sec');
if (row_dep_sec === "n/a") {
return;
}
if (row_dep_sec < ts) {
$(this).addClass('passed');
}
});
$('#vehicle_info').removeClass('hidden');
}
function vehicle_info_hide() {
vehicle_follow.stop();
vehicle_route.hide();
selected_vehicle = null;
$('#vehicle_info').addClass('hidden');
}
function station_info_display(station_id) {
var hm = timer.getHM();
var url = config.getParam('api_paths.departures');
if (url === null) {
return;
}
url = url.replace(/\[station_id\]/, station_id);
url = url.replace(/\[hhmm\]/, hm.replace(':', ''));
$.ajax({
url: url,
dataType: 'json',
success: function(vehicles) {
vehicle_info_hide();
var html_rows = [];
$.each(vehicles, function(index, vehicle) {
var html_row = '<tr><td>' + (index + 1) + '.</td>';
if (typeof simulation_vehicles[vehicle.id] === 'undefined') {
html_row += '<td>' + vehicle.name + '</td>';
} else {
html_row += '<td><a href="#vehicle_id=' + vehicle.id + '" data-vehicle-id="' + vehicle.id + '">' + vehicle.name + '</a></td>';
}
html_row += '<td>' + stationsPool.get(vehicle.st_b) + '</td>';
html_row += '<td>' + timer.getHM(vehicle.dep) + '</td>';
html_rows.push(html_row);
});
$('#station_departures > tbody').html(html_rows.join(''));
$('#station_info').removeClass('hidden');
$('.station_name', $('#station_info')).text(stationsPool.get(station_id));
}
});
}
function init() {
vehicle_follow.init();
vehicle_route.init();
$(document).on("click", '#station_departures tbody tr a', function(){
var vehicle_id = $(this).attr('data-vehicle-id');
var vehicle = simulation_vehicles[vehicle_id];
simulation_panel.displayVehicle(vehicle);
simulation_panel.followVehicle(vehicle);
return false;
});
$(document).on("click", '#vehicle_timetable tbody tr a', function(){
var station_id = $(this).attr('data-station-id');
var station_location = stationsPool.location_get(station_id);
if (station_location === null) {
return false;
}
map.setCenter(station_location);
if (map.getZoom() < config.getParam('zoom.to_stops')) {
map.setZoom(config.getParam('zoom.to_stops'));
}
vehicle_info_hide();
station_info_display(station_id);
return false;
});
(function(){
var location_el = $('#user_location');
var geolocation_marker = new google.maps.Marker({
icon: {
url: 'static/images/geolocation-bluedot.png',
size: new google.maps.Size(17, 17),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(8, 8)
},
map: null,
position: new google.maps.LatLng(0, 0)
});
var geocoder = new google.maps.Geocoder();
function zoom_to_geometry(geometry) {
if (geometry.viewport) {
map.fitBounds(geometry.viewport);
} else {
map.setCenter(geometry.location);
map.setZoom(15);
}
}
$('#geolocation_click').click(function(){
if (navigator.geolocation) {
location_el.val('...getting location');
navigator.geolocation.getCurrentPosition(function (position) {
var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
zoom_to_geometry({location: latlng});
geolocation_marker.setPosition(latlng);
if (geolocation_marker.getMap() === null) {
geolocation_marker.setMap(map);
}
geocoder.geocode({latLng: latlng}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
location_el.val(results[0].formatted_address);
}
});
});
}
});
var autocomplete = new google.maps.places.Autocomplete($('#user_location')[0], {
types: ['geocode']
});
autocomplete.bindTo('bounds', map);
google.maps.event.addListener(autocomplete, 'place_changed', function(){
var place = autocomplete.getPlace();
if (place.geometry) {
zoom_to_geometry(place.geometry);
} else {
geocoder.geocode({address: place.name}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
zoom_to_geometry(results[0].geometry);
location_el.val(results[0].formatted_address);
}
});
}
});
})();
$('input.panel_collapsible').click(function() {
var panel_content = $(this).closest('div[data-type="panel"]').children('div.panel_content');
if ($(this).hasClass('expanded')) {
$(this).removeClass('expanded');
panel_content.addClass('hidden');
} else {
$(this).addClass('expanded');
panel_content.removeClass('hidden');
}
});
}
return {
init: init,
displayVehicle: vehicle_info_display,
followVehicle: vehicle_follow.start,
displayStation: station_info_display
};
})();
var map_helpers = (function(){
var has_detail_view = false;
var extended_bounds = null;
function init(){
var mapStyles = [
{
featureType: "poi.business",
stylers: [
{ visibility: "off" }
]
},{
featureType: "road",
elementType: "labels",
stylers: [
{ visibility: "off" }
]
},{
featureType: "road",
elementType: "labels",
stylers: [
{ visibility: "off" }
]
},{
featureType: "road",
elementType: "geometry",
stylers: [
{ visibility: "simplified" },
{ lightness: 70 }
]
},{
featureType: "transit.line",
stylers: [
{ visibility: "off" }
]
},{
featureType: "transit.station.bus",
stylers: [
{ visibility: "off" }
]
}
];
var map_inited = false;
var map_options = {
zoom: parseInt(config.getParam('zoom.start'), 10),
center: new google.maps.LatLng(parseFloat(config.getParam('center.y')), parseFloat(config.getParam('center.x'))),
mapTypeId: config.getParam('map_type_id'),
styles: mapStyles,
disableDefaultUI: true,
zoomControl: true,
scaleControl: true,
streetViewControl: true,
overviewMapControl: true,
rotateControl: true,
mapTypeControl: true,
mapTypeControlOptions: {
position: google.maps.ControlPosition.TOP_LEFT,
mapTypeIds: [google.maps.MapTypeId.ROADMAP, google.maps.MapTypeId.TERRAIN, google.maps.MapTypeId.SATELLITE, 'stamen']
}
};
if (config.getParam('tilt') !== null) {
map_options.tilt = parseInt(config.getParam('tilt'), 10);
}
if (config.getParam('zoom.min') !== null) {
map_options.minZoom = parseInt(config.getParam('zoom.min'), 10);
}
if (config.getParam('zoom.max') !== null) {
map_options.maxZoom = parseInt(config.getParam('zoom.max'), 10);
}
map = new google.maps.Map(document.getElementById("map_canvas"), map_options);
/*
var kmlLayer = new google.maps.KmlLayer();
var kmlUrl = 'http://beta.ctweb.inweb.org.br/publico/stops.kml';
var kmlOptions = {
//suppressInfoWindows: true,
//preserveViewport: false,
map: map,
url: kmlUrl
};
var kmlLayer = new google.maps.KmlLayer(kmlOptions);
*/
var stamen_map = new google.maps.StamenMapType('watercolor');
stamen_map.set('name', 'Stamen watercolor');
map.mapTypes.set('stamen', stamen_map);
function map_layers_add(){
var edges_layer;
var stations_layer;
var ft_id;
// Graph topology layers - EDGES
ft_id = config.getParam('ft_layer_ids.topology_edges');
if (ft_id !== null) {
edges_layer = new google.maps.FusionTablesLayer({
query: {
select: 'geometry',
from: ft_id
},
clickable: false,
map: map,
styles: [
{
polylineOptions: {
strokeColor: "#FF0000",
strokeWeight: 2
}
},{
where: "type = 'tunnel'",
polylineOptions: {
strokeColor: "#FAAFBE",
strokeWeight: 1.5
}
}
]
});
}
// Graph topology layers - STATIONS
ft_id = config.getParam('ft_layer_ids.topology_stations');
if (ft_id !== null) {
stations_layer = new google.maps.FusionTablesLayer({
query: {
select: 'geometry',
from: ft_id
},
suppressInfoWindows: true,
map: map
});
google.maps.event.addListener(stations_layer, 'click', function(ev){
var station_id = ev.row.id.value;
simulation_panel.displayStation(station_id);
});
}
// GTFS layers - shapes.txt
ft_id = config.getParam('ft_layer_ids.gtfs_shapes');
if (ft_id !== null) {
edges_layer = new google.maps.FusionTablesLayer({
query: {
select: 'geometry',
from: ft_id
},
clickable: false,
map: map
});
}
// GTFS layers - stops.txt
ft_id = config.getParam('ft_layer_ids.gtfs_stops');
if (ft_id !== null) {
stations_layer = new google.maps.FusionTablesLayer({
query: {
select: 'geometry',
from: ft_id
},
suppressInfoWindows: true,
map: map
});
google.maps.event.addListener(stations_layer, 'click', function(ev){
var station_id = ev.row.stop_id.value;
simulation_panel.displayStation(station_id);
});
}
// Area mask
ft_id = config.getParam('ft_layer_ids.mask');
if (ft_id !== null) {
var layer = new google.maps.FusionTablesLayer({
query: {
select: 'geometry',
from: ft_id
},
clickable: false,
map: map
});
}
function trigger_toggleLayerVisibility() {
if (config.getParam('debug') !== null) {
console.log('Center: ' + map.getCenter().toUrlValue());
console.log('Zoom: ' + map.getZoom());
}
function toggleLayerVisibility(layer, hide) {
if ((typeof layer) === 'undefined') {
return;
}
if (hide) {
if (layer.getMap() !== null) {
layer.setMap(null);
}
} else {
if (layer.getMap() === null) {
layer.setMap(map);
}
}
}
var map_type_id = map.getMapTypeId();
var is_satellite = (map_type_id === google.maps.MapTypeId.SATELLITE) && (map.getTilt() === 0);
var config_preffix = is_satellite ? 'zoom.satellite' : 'zoom.roadmap';
var zoom = map.getZoom();
$.each(['stops', 'shapes'], function(k, layer_type){
var zoom_min = config.getParam(config_preffix + '.' + layer_type + '_min');
if (zoom_min === null) {
zoom_min = 0;
}
var zoom_max = config.getParam(config_preffix + '.' + layer_type + '_max');
if (zoom_max === null) {
zoom_max = 30;
}
var hide_layer = (zoom < zoom_min) || (zoom > zoom_max);
if (layer_type === 'stops') {
toggleLayerVisibility(stations_layer, hide_layer);
}
if (layer_type === 'shapes') {
toggleLayerVisibility(edges_layer, hide_layer);
}
});
}
google.maps.event.addListener(map, 'idle', trigger_toggleLayerVisibility);
google.maps.event.addListener(map, 'maptypeid_changed', trigger_toggleLayerVisibility);
trigger_toggleLayerVisibility();
}
google.maps.event.addListener(map, 'idle', function() {
if (map_inited === false) {
// TODO - FIXME later ?
// Kind of a hack, getBounds is ready only after a while since loading, so we hook in the 'idle' event
map_inited = true;
map_layers_add();
listener_helpers.notify('map_init');
function update_detail_view_state() {
if (map.getMapTypeId() !== google.maps.MapTypeId.SATELLITE) {
has_detail_view = false;
return;
}
if (map.getZoom() < 17) {
has_detail_view = false;
return;
}
if (map.getTilt() !== 0) {
has_detail_view = false;
return;
}
has_detail_view = true;
}
google.maps.event.addListener(map, 'zoom_changed', update_detail_view_state);
google.maps.event.addListener(map, 'tilt_changed', update_detail_view_state);
google.maps.event.addListener(map, 'maptypeid_changed', update_detail_view_state);
update_detail_view_state();
function update_extended_bounds() {
var map_bounds = map.getBounds();
var bounds_point = map_bounds.getSouthWest();
var new_bounds_sw = new google.maps.LatLng(bounds_point.lat() - map_bounds.toSpan().lat(), bounds_point.lng() - map_bounds.toSpan().lng());
bounds_point = map_bounds.getNorthEast();
var new_bounds_ne = new google.maps.LatLng(bounds_point.lat() + map_bounds.toSpan().lat(), bounds_point.lng() + map_bounds.toSpan().lng());
extended_bounds = new google.maps.LatLngBounds(new_bounds_sw, new_bounds_ne);
}
google.maps.event.addListener(map, 'bounds_changed', update_extended_bounds);
update_extended_bounds();
}
});
}
return {
init: init,
isDetailView: function() {
return has_detail_view;
},
getExtendedBounds: function() {
return extended_bounds;
}
};
})();
// Vehicle helpers
// Roles:
// - check backend for new vehicles
// - manages vehicle objects(class Vehicle) and animates them (see Vehicle.render method)
var vehicle_helpers = (function(){
var vehicle_detect = (function(){
var track_vehicle_name = null;
var track_vehicle_id = null;
function match_by_name(vehicle_name) {
if (track_vehicle_name === null) {
return false;
}
vehicle_name = vehicle_name.replace(/[^A-Z0-9]/i, '');
if (track_vehicle_name !== vehicle_name) {
return false;
}
return true;
}
function match(vehicle_name, vehicle_id) {
if (track_vehicle_id === null) {
track_vehicle_name = config.getParam('vehicle_name');
if (track_vehicle_name !== null) {
track_vehicle_name = track_vehicle_name.replace(/[^A-Z0-9]/i, '');
}
track_vehicle_id = config.getParam('vehicle_id');
}
if (track_vehicle_id === vehicle_id) {
return true;
}
return match_by_name(vehicle_name);
}
listener_helpers.subscribe('vehicles_load', function(){
if (config.getParam('action') !== 'vehicle_add') {
return;
}
function str_hhmm_2_sec_ar(str_hhmm) {
var sec_ar = [];
$.each(str_hhmm.split('_'), function(index, hhmm){
var hhmm_matches = hhmm.match(/([0-9]{2})([0-9]{2})/);
sec_ar.push(timer.getHMS2TS(hhmm_matches[1] + ':' + hhmm_matches[2] + ':00'));
});
return sec_ar;
}
var station_ids = config.getParam('station_ids').split('_');
$.each(station_ids, function(index, station_id_s){
station_ids[index] = station_id_s;
});
var vehicle_data = {
arrs: str_hhmm_2_sec_ar(config.getParam('arrs')),
deps: str_hhmm_2_sec_ar(config.getParam('deps')),
id: 'custom_vehicle',
name: decodeURIComponent(config.getParam('vehicle_name')),
sts: station_ids,
type: config.getParam('vehicle_type'),
edges: []
};
var v = new Vehicle(vehicle_data);
simulation_vehicles[vehicle_data.id] = v;
v.render();
simulation_panel.displayVehicle(v);
simulation_panel.followVehicle(v);
});
return {
match: match
};
})();
// Vehicle icons manager.
// Roles:
// - keep a reference for each vehicle type (IC, ICE, etc..)
var imagesPool = (function(){
var icons = {};
function iconGet(type) {
if (icons[type]) {
return icons[type];
}
var routes_config = config.getParam('routes');
if ((typeof routes_config[type]) === 'undefined') {
return null;
}
if (routes_config[type].icon === false) {
return null;
}
var url = routes_config[type].icon;
var icon = {
url: url,
size: new google.maps.Size(20, 20),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(10, 10)
};
icons[type] = icon;
return icon;
}
var vehicle_detail_base_zoom = 17;
var vehicle_detail_config = {
"s-bahn-rear": {
base_zoom_width: 33,
width: 228
},
"s-bahn-middle": {
base_zoom_width: 33,
width: 247
},
"s-bahn-front": {
base_zoom_width: 33,
width: 239
},
"s-bahn_old-rear": {
base_zoom_width: 26,
width: 153
},
"s-bahn_old-middle": {
base_zoom_width: 35,
width: 228
},
"s-bahn_old-front": {
base_zoom_width: 35,
width: 224
},
"ic-loco-c2": {
base_zoom_width: 36,
width: 225
},
"ic-coach": {
base_zoom_width: 36,
width: 254
},
"ic-loco": {
base_zoom_width: 19,
width: 126
},
"icn-rear": {
base_zoom_width: 32,
width: 207
},
"icn-middle": {
base_zoom_width: 32,
width: 218
},
"icn-front": {
base_zoom_width: 32,
width: 207
},
"ir-coach": {
base_zoom_width: 32,
width: 223
}
};
var vehicle_detail_icons = {};
var service_parts = {
s: {
offsets: [-40, -13, 14, 41],
vehicles: ['s-bahn-rear', 's-bahn-middle', 's-bahn-middle', 's-bahn-front']
},
sbahn_old: {
offsets: [-39, -14, 15, 44],
vehicles: ['s-bahn_old-rear', 's-bahn_old-middle', 's-bahn_old-middle', 's-bahn_old-front']
},
ic: {
offsets: [-110, -87, -58, -29, 0, 29, 58, 87],
vehicles: ['ic-loco', 'ic-coach', 'ic-coach', 'ic-coach', 'ic-coach', 'ic-coach', 'ic-coach', 'ic-loco-c2']
},
icn: {
offsets: [-78, -52, -26, 0, 26, 52, 78],
vehicles: ['icn-rear', 'icn-middle', 'icn-middle', 'icn-middle', 'icn-middle', 'icn-middle', 'icn-front']
},
ir: {
offsets: [-93, -67, -41, -15, 11, 37, 63, 84],
vehicles: ['ir-coach', 'ir-coach', 'ir-coach', 'ir-coach', 'ir-coach', 'ir-coach', 'ir-coach', 'ic-loco']
}
};
function getVehicleIcon(zoom, type, heading) {
var key = zoom + '_' + type + '_' + heading;
if (typeof vehicle_detail_icons[key] === 'undefined') {
var original_width = vehicle_detail_config[type].width;
var icon_width = vehicle_detail_config[type].base_zoom_width * Math.pow(2, parseInt(zoom - vehicle_detail_base_zoom, 10));
var base_url = 'http://static.vasile.ch/simcity/service-vehicle-detail';
var icon = {
url: base_url + '/' + type + '/' + heading + '.png',
size: new google.maps.Size(original_width, original_width),
origin: new google.maps.Point(0, 0),
scaledSize: new google.maps.Size(icon_width, icon_width),
anchor: new google.maps.Point(parseInt(icon_width/2, 10), parseInt(icon_width/2, 10))
};
vehicle_detail_icons[key] = icon;
}
return vehicle_detail_icons[key];
}
return {
iconGet: iconGet,
getServicePartsConfig: function(key) {
if ((typeof service_parts[key]) === 'undefined') {
key = 's';
}
return service_parts[key];
},
getVehicleIcon: getVehicleIcon
};
})();
var vehicle_ib = new InfoBox({
disableAutoPan: true,
pixelOffset: new google.maps.Size(10, 10),
vehicle_id: 0,
closeBoxURL: ''
});
var vehicleIDs = [];
function Vehicle(params) {
function parseTimes(times) {
var time_ar = [];
$.each(times, function(k, time){
// 32855 = 9 * 3600 + 7 * 60 + 35
if ((typeof time) === 'number') {
if (time < (2 * 24 * 3600)) {
time += timer.getTSMidnight();
}
time_ar.push(time);
return;
}
// 09:07:35
if (time.match(/^[0-9]{2}:[0-9]{2}:[0-9]{2}$/) !== null) {
time = timer.getHMS2TS(time);
time_ar.push(time);
return;
}
// 09:07
if (time.match(/^[0-9]{2}:[0-9]{2}$/) !== null) {
var hms = time + ':00';
time = timer.getHMS2TS(hms);
time_ar.push(time);
return;
}
});
return time_ar;
}
if ((typeof params.trip_id) === 'undefined') {
this.source = 'custom';
this.id = params.id;
this.name = params.name;
this.stations = params.sts;
this.edges = params.edges;
this.depS = parseTimes(params.deps);
this.arrS = parseTimes(params.arrs);
this.route_icon = params.type;
this.service_type = params.service_type;
$.each(params.edges, function(k, edges) {
if (k === 0) { return; }
linesPool.routeAdd(edges);
});
} else {
// GTFS approach
this.source = 'gtfs';
this.id = params.trip_id;
this.name = params.route_short_name;
this.service_type = '';
this.edges = [];
this.shape_id = params.shape_id;
var departures = [];
var arrivals = [];
var stations = [];
var shape_percent = [];
$.each(params.stops, function(k, stop){
if (k < (params.stops.length - 1)) {
departures.push(stop.departure_time);
}
if (k > 0) {
arrivals.push(stop.arrival_time);
}
stations.push(stop.stop_id);
shape_percent.push(stop.stop_shape_percent);
});
this.stations = stations;
this.depS = parseTimes(departures);
this.arrS = parseTimes(arrivals);
this.shape_percent = shape_percent;
this.route_icon = params.type;
}
var marker = new google.maps.Marker({
position: new google.maps.LatLng(0, 0),
map: null,
speed: null,
status: 'not on map'
});
var icon = imagesPool.iconGet(this.route_icon);
if (icon !== null) {
marker.setIcon(icon);
}
this.marker = marker;
this.detail_markers = [];
// TODO - FIXME .apply
var that = this;
google.maps.event.addListener(marker, 'click', function() {
simulation_panel.displayVehicle(that);
});
this.mouseOverMarker = function() {
if (map.getZoom() < config.getParam('zoom.vehicle_mouseover_min')) {
return;
}
if (vehicle_ib.get('vehicle_id') === that.id) { return; }
vehicle_ib.set('vehicle_id', that.id);
vehicle_ib.close();
var popup_div = $('#vehicle_popup');
$('span.vehicle_name', popup_div).text(that.name);
var route_config = config.getParam('routes')[that.route_icon];
if (route_config) {
$('span.vehicle_name', popup_div).css('background-color', route_config.route_color);
$('span.vehicle_name', popup_div).css('color', route_config.route_text_color);
}
$('.status', popup_div).html(marker.get('status'));
vehicle_ib.setContent($('#vehicle_popup_container').html());
vehicle_ib.open(map, this);
};
this.mouseOutMarker = function() {
vehicle_ib.set('vehicle_id', null);
vehicle_ib.close();
};
google.maps.event.addListener(marker, 'mouseover', this.mouseOverMarker);
google.maps.event.addListener(marker, 'mouseout', this.mouseOutMarker);
if (vehicle_detect.match(this.name, this.id)) {
simulation_panel.displayVehicle(this);
simulation_panel.followVehicle(this);
}
}
Vehicle.prototype.render = function() {
// TODO - FIXME .apply
var that = this;
function animate() {
var ts = timer.getTS();
var vehicle_position = null;
var route_percent = 0;
var d_AC = 0;
var animation_timeout = 1000;
for (var i=0; i<that.arrS.length; i++) {
if (ts < that.arrS[i]) {
var station_a = that.stations[i];
var station_b = that.stations[i+1];
var route_id = (that.source === 'gtfs') ? that.shape_id : that.edges[i+1];
var speed = that.marker.get('speed');
if (ts > that.depS[i]) {
var routeLength = linesPool.lengthGet(route_id);
// Vehicle is in motion between two stations
if ((speed === 0) || (speed === null)) {
var trackLength = routeLength;
if (that.source === 'gtfs') {
trackLength = routeLength * (that.shape_percent[i+1] - that.shape_percent[i]) / 100;
}
var speed = trackLength * 0.001 * 3600 / (that.arrS[i] - that.depS[i]);
that.marker.set('speed', parseInt(speed, 10));
that.marker.set('status', 'Heading to ' + stationsPool.get(station_b) + '(' + timer.getHM(that.arrS[i]) + ')<br/>Speed: ' + that.marker.get('speed') + ' km/h');
}
route_percent = (ts - that.depS[i])/(that.arrS[i] - that.depS[i]);
if (that.source === 'gtfs') {
route_percent = (that.shape_percent[i] + route_percent * (that.shape_percent[i+1] - that.shape_percent[i])) / 100;
}
d_AC = routeLength * route_percent;
} else {
// Vehicle is in a station
if ((speed !== 0) || (speed === null)) {
that.marker.set('status', 'Departing ' + stationsPool.get(station_a) + ' at ' + timer.getHM(that.depS[i]));
that.marker.set('speed', 0);
}
if (that.source === 'gtfs') {
route_percent = that.shape_percent[i] / 100;
}
}
var vehicle_position_data = linesPool.positionGet(route_id, route_percent);
if (vehicle_position_data === null) {
break;
}
var vehicle_position = vehicle_position_data.position;
if (that.marker.get('follow') === 'yes-init') {
that.marker.set('follow', 'yes');
map.panTo(vehicle_position);
if (map.getZoom() < config.getParam('zoom.vehicle_follow')) {
map.setZoom(config.getParam('zoom.vehicle_follow'));
}
map.setMapTypeId(google.maps.MapTypeId.SATELLITE);
map.bindTo('center', that.marker, 'position');
}
that.updateIcon(vehicle_position_data, d_AC, i);
if (map.getZoom() >= 12) {
animation_timeout = timer.getRefreshValue();
}
setTimeout(animate, animation_timeout);
break;
}
} // end arrivals loop
if (vehicle_position === null) {
that.marker.setMap(null);
delete simulation_vehicles[that.id];
}
}
animate();
};
Vehicle.prototype.updateIcon = function(data, d_AC, i) {
var service_parts = imagesPool.getServicePartsConfig(this.service_type);
var render_in_detail = data.is_detailed && (service_parts !== null);
var vehicle_position = data.position;
this.marker.setPosition(data.position);
if (render_in_detail) {
if (this.marker.getMap() !== null) {
this.marker.setMap(null);
}
if (map_helpers.getExtendedBounds().contains(vehicle_position)) {
var that = this;
$.each(service_parts.offsets, function(k, offset){
if ((typeof that.detail_markers[k]) === 'undefined') {
that.detail_markers[k] = new google.maps.Marker({
map: null
});
var marker = that.detail_markers[k];
google.maps.event.addListener(marker, 'mouseover', that.mouseOverMarker);
google.maps.event.addListener(marker, 'mouseout', that.mouseOutMarker);
google.maps.event.addListener(marker, 'click', function(){
simulation_panel.displayVehicle(that);
});
}
var marker = that.detail_markers[k];
var route = that.edges[i+1];
var route_length = linesPool.lengthGet(route);
var d_AC_new = d_AC + offset;
if ((d_AC + offset) > route_length) {
d_AC_new -= route_length;
route = that.edges[i+2];
}
var position_data = linesPool.projectDistanceAlongRoute(route, d_AC_new);
if (position_data === null) {
marker.setMap(null);
return;
}
var heading = parseInt(position_data.heading, 10);
if (heading < 0) {
heading += 360;
}
heading = ('00' + heading).slice(-3);
var zoom = map.getZoom();
var icon = imagesPool.getVehicleIcon(zoom, service_parts.vehicles[k], heading);
if (((typeof marker.getIcon()) === 'undefined') || (marker.getIcon().url !== icon.url) || (marker.get('zoom') !== zoom)) {
marker.setIcon(icon);
marker.set('zoom', map.getZoom());
}
marker.setPosition(position_data.position);
if (marker.getMap() === null) {
marker.setMap(map);
}
});
} else {
$.each(this.detail_markers, function(k, marker){
marker.setMap(null);
});
this.detail_markers = [];
}
} else {
$.each(this.detail_markers, function(k, marker){
marker.setMap(null);
});
this.detail_markers = [];
if (map.getBounds().contains(vehicle_position)) {
if (this.marker.getMap() === null) {
this.marker.setMap(map);
}
} else {
if (this.marker.getMap() !== null) {
this.marker.setMap(null);
}
}
}
};
return {
load: function() {
var hm = timer.getHM();
var url = config.getParam('api_paths.trips');
url = url.replace(/\[hhmm\]/, hm.replace(':', ''));
$.ajax({
url: url,
dataType: 'json',
success: function(vehicles) {
$.each(vehicles, function(index, data) {
var vehicle_id = ((typeof data.trip_id) === 'undefined') ? data.id : data.trip_id;
if ((typeof simulation_vehicles[vehicle_id]) !== 'undefined') {
return;
}
var v = new Vehicle(data);
v.render();
simulation_vehicles[vehicle_id] = v;
});
listener_helpers.notify('vehicles_load');
}
});
}
};
})();
listener_helpers.subscribe('map_init', function(){
function loadStations(url) {
if (url === null) {
return;
}
$.ajax({
url: url,
dataType: 'json',
success: function(geojson) {
if (typeof(geojson.features) === 'undefined') {
console.log('Malformed GeoJSON. URL: ' + url);
return;
}
stationsPool.addFeatures(geojson.features);
vehicle_helpers.load();
listener_helpers.subscribe('minute_changed', vehicle_helpers.load);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log('Error from server ' + textStatus + ' for url: ' + url);
}
});
}
// GTFS approach
var url = config.getParam('geojson.gtfs_shapes');
if (url !== null) {
$.ajax({
url: url,
dataType: 'json',
async: false,
success: function(geojson) {
if (typeof(geojson.features) === 'undefined') {
console.log('Malformed GeoJSON. URL: ' + url);
} else {
linesPool.loadGeoJSONShapes(geojson.features);
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.log('Error from server ' + textStatus + ' for url: ' + url);
}
});
}
loadStations(config.getParam('geojson.gtfs_stops'));
// Custom topology approach
var url = config.getParam('geojson.topology_edges');
if (url !== null) {
$.ajax({
url: url,
dataType: 'json',
async: false,
success: function(geojson) {
if (typeof(geojson.features) === 'undefined') {
console.log('Malformed GeoJSON. URL: ' + url);
} else {
linesPool.loadGeoJSONEdges(geojson.features);
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.log('Error from server ' + textStatus + ' for url: ' + url);
}
});
}
loadStations(config.getParam('geojson.topology_stations'));
});
function ui_init() {
var view_mode = config.getParam('view_mode');
var panel_display = (ua_is_mobile === false) && (view_mode !== 'iframe');
if (panel_display) {
$('#panel').removeClass('hidden');
}
var time_multiply = config.getParam('time_multiply');
if (time_multiply !== null) {
$('#time_multiply').val(time_multiply);
}
}
return {
init: function(){
config.init();
ui_init();
timer.init();
map_helpers.init();
simulation_panel.init();
},
getMap: function(){
return map;
}
};
})();
$(document).ready(simulation_manager.init);
|
version https://git-lfs.github.com/spec/v1
oid sha256:2c648d581addc08fbd0fe28ad0d26ba08942ebfe6be59756e11ff9abcd9d3bbd
size 23184
|
describe('minTime', function() {
beforeEach(function() {
affix('#cal');
});
var numToStringConverter = function(timeIn, mins) {
var time = (timeIn % 12) || 12;
var amPm = 'am';
if ((timeIn % 24) > 11) {
amPm = 'pm';
}
return time + (mins != null ? ':' + mins : '') + amPm;
};
describe('when using the default settings', function() {
describe('in agendaWeek', function() {
it('should start at 12am', function() {
var options = {
defaultView: 'agendaWeek'
};
$('#cal').njCalendar(options);
var firstSlotText = $('.fc-slats tr:eq(0) .fc-time').text();
expect(firstSlotText).toEqual('12am');
});
});
describe('in agendaDay', function() {
it('should start at 12am', function() {
var options = {
defaultView: 'agendaDay'
};
$('#cal').njCalendar(options);
var firstSlotText = $('.fc-slats tr:eq(0) .fc-time').text();
expect(firstSlotText).toEqual('12am');
});
});
});
describe('when using a whole number', function() {
var hourNumbers = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ];
describe('in agendaWeek', function() {
beforeEach(function() {
affix('#cal2');
});
hourNumbers.forEach(function(hourNumber) {
it('should start at ' + hourNumber, function() {
var options = {
defaultView: 'agendaWeek',
minTime: { hours: hourNumber }
};
$('#cal2').njCalendar(options);
var firstSlotText = $('.fc-slats tr:eq(0) .fc-time').text();
var expected = numToStringConverter(hourNumber);
expect(firstSlotText).toEqual(expected);
});
});
});
describe('in agendaDay', function() {
beforeEach(function() {
affix('#cal2');
});
hourNumbers.forEach(function(hourNumber) {
it('should start at ' + hourNumber, function() {
var options = {
defaultView: 'agendaDay',
minTime: hourNumber + ':00' // in addition, test string duration input
};
$('#cal2').njCalendar(options);
var firstSlotText = $('.fc-slats tr:eq(0) .fc-time').text();
var expected = numToStringConverter(hourNumber);
expect(firstSlotText).toEqual(expected);
});
});
});
});
describe('when using default slotInterval and \'uneven\' minTime', function() {
var hourNumbers = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ];
describe('in agendaWeek', function() {
beforeEach(function() {
affix('#cal2');
});
hourNumbers.forEach(function(hourNumber) {
it('should start at ' + hourNumber + ':20', function() {
var options = {
defaultView: 'agendaWeek',
minTime: { hours: hourNumber, minutes: 20 }
};
$('#cal2').njCalendar(options);
var slatRows = $('.fc-slats tr');
expect(slatRows.eq(0)).toHaveClass('fc-minor');
expect(slatRows.eq(1)).toHaveClass('fc-minor');
expect(slatRows.eq(2)).toHaveClass('fc-minor');
// TODO: fix bad behavior in src where no slots have text
});
});
});
describe('in agendaDay', function() {
beforeEach(function() {
affix('#cal2');
});
hourNumbers.forEach(function(hourNumber) {
it('should start at ' + hourNumber + ':20', function() {
var options = {
defaultView: 'agendaDay',
minTime: { hours: hourNumber, minutes: 20 }
};
$('#cal2').njCalendar(options);
var slatRows = $('.fc-slats tr');
expect(slatRows.eq(0)).toHaveClass('fc-minor');
expect(slatRows.eq(1)).toHaveClass('fc-minor');
expect(slatRows.eq(2)).toHaveClass('fc-minor');
// TODO: fix bad behavior in src where no slots have text
});
});
});
});
}); |
'use strict';
/*
* Regex
*/
var regex = {
facebookPattern: /(?:https?:\/\/)?(?:[\w\-]+\.)?facebook\.com\/(?:(?:\w)*#!\/)?(?:pages\/)?(?:[\w\-]*\/)*([\w\-\.]*)/, // jshint ignore:line
facebookPluginPattern: /.*%2F(\w+?)&/
};
module.exports = {
/**
* Returns the page id for a given URL
* e.g. : https://www.facebook.com/my_page_id => my_page_id
* http://www.facebook.com/pages/foo/Bar/123456 => 123456
*
* @param String URL FacebookURL
* @return Page ID
*/
getPageId: function (url) {
if (typeof url !== 'string') {
return null;
}
var match = url.replace(/\/$/, '').match(regex.facebookPattern);
if (match) {
var short_url = match[0],
id = match[1];
if (/plugins/.test(short_url)) {
var likeMatch = regex.facebookPluginPattern.exec(match.input);
if (likeMatch) { return likeMatch[1]; }
} else {
return id;
}
}
return null;
}
};
|
"use strict";
exports.hmrReducer = function (appReducer) { return function (state, _a) {
var type = _a.type, payload = _a.payload;
switch (type) {
case 'HMR_SET_STATE': return payload;
default: return appReducer(state, { type: type, payload: payload });
}
}; };
//# sourceMappingURL=hmr-reducer.js.map |
var url = require('url');
var semver = require('semver');
var nijs = require('nijs');
var inherit = require('nijs/lib/ast/util/inherit.js').inherit;
var base64js = require('base64-js');
/**
* Creates a new source instance. This function should never be used directly,
* instead use: Source.constructSource to construct a source object.
*
* @class Source
* @extends NixASTNode
* @classdesc Represents a file that is obtained from an external source
*
* @constructor
* @param {String} baseDir Directory in which the referrer's package.json configuration resides
* @param {String} dependencyName Name of the dependency
* @param {String} versionSpec Version specifier of the Node.js package to fetch
*/
function Source(baseDir, dependencyName, versionSpec) {
this.baseDir = baseDir;
this.dependencyName = dependencyName;
this.versionSpec = versionSpec;
}
/* Source inherits from NixASTNode */
inherit(nijs.NixASTNode, Source);
/**
* Constructs a specific kind of source by inspecting the version specifier.
*
* @param {String} registryURL URL of the NPM registry
* @param {?String} registryAuthToken Auth token for private NPM registry
* @param {String} baseDir Directory in which the referrer's package.json configuration resides
* @param {String} outputDir Directory in which the nix expression will be written
* @param {String} dependencyName Name of the dependency
* @param {String} versionSpec Version specifier of the Node.js package to fetch
* @param {Boolean} stripOptionalDependencies When enabled, the optional
* dependencies are stripped from the regular dependencies in the NPM registry
*/
Source.constructSource = function(registryURL, registryAuthToken, baseDir, outputDir, dependencyName, versionSpec, stripOptionalDependencies) {
// Load modules here, to prevent cycles in the include process
var GitSource = require('./GitSource.js').GitSource;
var HTTPSource = require('./HTTPSource.js').HTTPSource;
var LocalSource = require('./LocalSource.js').LocalSource;
var NPMRegistrySource = require('./NPMRegistrySource.js').NPMRegistrySource;
var parsedVersionSpec = semver.validRange(versionSpec, true);
var parsedUrl = url.parse(versionSpec);
if(parsedVersionSpec !== null) { // If the version is valid semver range, fetch the package from the NPM registry
return new NPMRegistrySource(baseDir, dependencyName, parsedVersionSpec, registryURL, registryAuthToken, stripOptionalDependencies);
} else if(parsedUrl.protocol == "github:") { // If the version is a GitHub repository, compose the corresponding Git URL and do a Git checkout
return new GitSource(baseDir, dependencyName, GitSource.composeGitURL("git://github.com", parsedUrl));
} else if(parsedUrl.protocol == "gist:") { // If the version is a GitHub gist repository, compose the corresponding Git URL and do a Git checkout
return new GitSource(baseDir, dependencyName, GitSource.composeGitURL("https://gist.github.com", parsedUrl));
} else if(parsedUrl.protocol == "bitbucket:") { // If the version is a Bitbucket repository, compose the corresponding Git URL and do a Git checkout
return new GitSource(baseDir, dependencyName, GitSource.composeGitURL("git://bitbucket.org", parsedUrl));
} else if(parsedUrl.protocol == "gitlab:") { // If the version is a Gitlab repository, compose the corresponding Git URL and do a Git checkout
return new GitSource(baseDir, dependencyName, GitSource.composeGitURL("https://gitlab.com", parsedUrl));
} else if(typeof parsedUrl.protocol == "string" && parsedUrl.protocol.substr(0, 3) == "git") { // If the version is a Git URL do a Git checkout
return new GitSource(baseDir, dependencyName, versionSpec);
} else if(parsedUrl.protocol == "http:" || parsedUrl.protocol == "https:") { // If the version is an HTTP URL do a download
return new HTTPSource(baseDir, dependencyName, versionSpec);
} else if(versionSpec.match(/^[a-zA-Z0-9_\-]+\/[a-zA-Z0-9\.]+[#[a-zA-Z0-9_\-]+]?$/)) { // If the version is a GitHub repository, compose the corresponding Git URL and do a Git checkout
return new GitSource(baseDir, dependencyName, "git://github.com/"+versionSpec);
} else if(parsedUrl.protocol == "file:") { // If the version is a file URL, simply compose a Nix path
return new LocalSource(baseDir, dependencyName, outputDir, parsedUrl.path);
} else if(versionSpec.substr(0, 3) == "../" || versionSpec.substr(0, 2) == "~/" || versionSpec.substr(0, 2) == "./" || versionSpec.substr(0, 1) == "/") { // If the version is a path, simply compose a Nix path
return new LocalSource(baseDir, dependencyName, outputDir, versionSpec);
} else { // In all other cases, just try the registry. Sometimes invalid semver ranges are encountered or a tag has been provided (e.g. 'latest', 'unstable')
return new NPMRegistrySource(baseDir, dependencyName, versionSpec, registryURL, registryAuthToken, stripOptionalDependencies);
}
};
/**
* Fetches the package metadata from the external source.
*
* @method
* @param {function(String)} callback Callback that gets invoked when the work
* is done. In case of an error, it will set the first parameter to contain
* an error message.
*/
Source.prototype.fetch = function(callback) {
callback("fetch() is not implemented, please use a prototype that inherits from Source");
};
/**
* Takes a dependency object from a lock file and converts it into a source object.
*
* @param {Object} dependencyObj Dependency object from the lock file
* @param {function(String)} callback Callback that gets invoked when the work
* is done. In case of an error, it will set the first parameter to contain
* an error message.
*/
Source.prototype.convertFromLockedDependency = function(dependencyObj, callback) {
callback("convertFromLockedDependency() is not implemented, please use a prototype that inherits from Source");
};
/**
* Converts NPM's integrity strings that have the following format:
* <algorithm>-<base64 hash> to a hash representation that Nix understands.
*
* @method
* @param {String} integrity NPM integrity string
*/
Source.prototype.convertIntegrityStringToNixHash = function(integrity) {
if(integrity.substr(0, 5) === "sha1-") {
var hash = base64js.toByteArray(integrity.substring(5));
this.hashType = "sha1";
this.sha1 = new Buffer(hash).toString('hex');
} else if(integrity.substr(0, 7) === "sha512-") {
this.hashType = "sha512";
this.sha512 = integrity.substring(7);
} else {
throw "Unknown integrity string: "+integrity;
}
};
/**
* @see NixASTNode#toNixAST
*/
Source.prototype.toNixAST = function() {
return {
name: this.config.name.replace("@", "_at_").replace("/", "_slash_"), // Escape characters from scoped package names that aren't allowed
packageName: this.config.name,
version: this.config.version
};
};
exports.Source = Source;
|
import React, { PropTypes } from 'react';
import EventImage from '../components/EventImage';
const Event = ({ eventUrl, images, ingress, startDate, title }) => (
<div>
<div className="col-sm-8 col-md-4">
<div className="hero-title">
<a href={eventUrl}>
<p>{ title }</p>
</a>
</div>
<div className="hero-ingress hidden-xs">
<p>{ ingress }</p>
</div>
</div>
<EventImage
date={startDate}
images={images}
eventUrl={eventUrl}
/>
</div>
);
Event.propTypes = {
eventUrl: PropTypes.string.isRequired,
images: EventImage.propTypes.images,
ingress: PropTypes.string.isRequired,
startDate: PropTypes.string.isRequired,
title: PropTypes.string.isRequired,
};
export default Event;
|
'use strict';
function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }
/**
*
* saluki api 查看
*
* Created by joe on 16/12/26.
*/
var services = require('../grpc/index').services();
var consul = require('../grpc/consul');
module.exports = function () {
var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
return function () {
var _ref = _asyncToGenerator(function* (ctx, next) {
var url = ctx.url;
ctx.services = services;
if (url.endsWith('/saluki')) {
ctx.body = JSON.stringify(consul.getALL());
return;
}
yield next();
});
function saluki(_x2, _x3) {
return _ref.apply(this, arguments);
}
return saluki;
}();
}; |
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} t
* @return {string}
*/
const tree2str = (t) => {
let ret = '';
if (t) {
ret += t.val;
if (t.left || t.right) {
ret += '(';
ret += tree2str(t.left);
ret += ')';
}
if (t.right) {
ret += `(${tree2str(t.right)})`;
}
}
return ret;
};
|
export const IIcon = {
name: 'i-icon',
};
export default IIcon;
|
import Objects from './'
import Character from './Character'
import Actions from '../actions'
import Attacks from '../actions/Attacks'
import Dash from '../actions/Dash'
const addMoveAnimations = function () {
Object.keys(this.directions).map(
(direction) => this.atlasAnimations.add({
action: Actions.move,
direction,
speed: 8
})
)
}
const addAtkAnimations = function () {
Object.keys(this.directions).map(
(direction) => this.atlasAnimations.add({
action: Actions.atk,
direction,
speed: 13
})
)
}
export default class extends Character {
constructor ({
game, x, y, name
}) {
super({
game,
x,
y,
name,
type: Objects.npc,
firstSprite: `${name}-move-down-1`
})
this.setActions([
new Attacks({
character: this,
attacks: [{id: 0, type: 'normal', time: 24, speed: 13, cooldown: 15}]
}),
new Dash({
character: this,
dash: {time: 15, speed: 300, cooldown: 15}
})
])
this.speed = 140
addMoveAnimations.call(this)
addAtkAnimations.call(this)
}
update () {
super.update()
}
}
|
var passport = require('passport');
var Auth0Strategy = require('passport-auth0');
var credentials = require('../config/credentials.js');
var strategy = new Auth0Strategy({
domain: credentials.domain,
clientID: credentials.clientID,
clientSecret: credentials.clientSecret,
callbackURL: '/callback'
}, function(accessToken, refreshToken, profile, done) {
//Some tracing info
console.log('profile is', profile);
return done(null, profile);
});
passport.use(strategy);
// This is not a best practice, but we want to keep things simple for now
passport.serializeUser(function(user, done) {
done(null, user);
});
passport.deserializeUser(function(user, done) {
done(null, user);
});
module.exports = strategy; |
module.exports = require('../crud/list')({
view: 'users/manage',
model: require('../../models/user'),
sort: {
name: 1
}
});
|
var goods = [
{ GoodId: 1, Name: '玫瑰', Price: 100, Total: 100, SellCount: 0 },
{ GoodId: 2, Name: '康乃馨', Price: 200, Total: 50, SellCount: 0 },
{ GoodId: 3, Name: '满天星', Price: 100, Total: 50, SellCount: 0 },
{ GoodId: 4, Name: '百合', Price: 500, Total: 200, SellCount: 0 }
];
function randomGood() {
var good = goods[Math.floor(Math.random() * 4)];
var buyCount = Math.ceil(Math.random() * (good.Total - good.SellCount < 10 ? good.Total - good.SellCount : 10));
good.SellCount += buyCount;
return { GoodId: goog.GoodId, BuyCount: buyCount };
}
var buyers = [];
function randomBuyer() {
if (Math.random() * 10 > 3 || buyers.length == 0) {
var buyerId = buyers.length + 1
var buyer = { BuyerId: buyerId, Name: 'buyer' + buyerId, Region: Math.floor(Math.random() * 34) };
buyers.push(buyer);
return buyer;
} else {
return buyers[Math.floor(Math.random() * buyers.length)];
}
}
var trades = [];
function randomTrade() {
var buyer = randomBuyer();
var good = randomGood();
// goods
}
function trade1() {
}
function dashboard(id, fData) {
var barColor = 'steelblue';
function segColor(c) { return { low: "#807dba", mid: "#e08214", high: "#41ab5d" }[c]; }
// compute total for each state.
fData.forEach(function (d) { d.total = d.freq.low + d.freq.mid + d.freq.high; });
// function to handle histogram.
function histoGram(fD) {
var hG = {}, hGDim = { t: 60, r: 0, b: 30, l: 0 };
hGDim.w = 500 - hGDim.l - hGDim.r,
hGDim.h = 300 - hGDim.t - hGDim.b;
//create svg for histogram.
var hGsvg = d3.select(id).append("svg")
.attr("width", hGDim.w + hGDim.l + hGDim.r)
.attr("height", hGDim.h + hGDim.t + hGDim.b).append("g")
.attr("transform", "translate(" + hGDim.l + "," + hGDim.t + ")");
// create function for x-axis mapping.
var x = d3.scale.ordinal().rangeRoundBands([0, hGDim.w], 0.1)
.domain(fD.map(function (d) { return d[0]; }));
// Add x-axis to the histogram svg.
hGsvg.append("g").attr("class", "x axis")
.attr("transform", "translate(0," + hGDim.h + ")")
.call(d3.svg.axis().scale(x).orient("bottom"));
// Create function for y-axis map.
var y = d3.scale.linear().range([hGDim.h, 0])
.domain([0, d3.max(fD, function (d) { return d[1]; })]);
// Create bars for histogram to contain rectangles and freq labels.
var bars = hGsvg.selectAll(".bar").data(fD).enter()
.append("g").attr("class", "bar");
//create the rectangles.
bars.append("rect")
.attr("x", function (d) { return x(d[0]); })
.attr("y", function (d) { return y(d[1]); })
.attr("width", x.rangeBand())
.attr("height", function (d) { return hGDim.h - y(d[1]); })
.attr('fill', barColor)
.on("mouseover", mouseover)// mouseover is defined below.
.on("mouseout", mouseout);// mouseout is defined below.
//Create the frequency labels above the rectangles.
bars.append("text").text(function (d) { return d3.format(",")(d[1]) })
.attr("x", function (d) { return x(d[0]) + x.rangeBand() / 2; })
.attr("y", function (d) { return y(d[1]) - 5; })
.attr("text-anchor", "middle");
function mouseover(d) { // utility function to be called on mouseover.
// filter for selected state.
var st = fData.filter(function (s) { return s.State == d[0]; })[0],
nD = d3.keys(st.freq).map(function (s) { return { type: s, freq: st.freq[s] }; });
// call update functions of pie-chart and legend.
pC.update(nD);
leg.update(nD);
}
function mouseout(d) { // utility function to be called on mouseout.
// reset the pie-chart and legend.
pC.update(tF);
leg.update(tF);
}
// create function to update the bars. This will be used by pie-chart.
hG.update = function (nD, color) {
// update the domain of the y-axis map to reflect change in frequencies.
y.domain([0, d3.max(nD, function (d) { return d[1]; })]);
// Attach the new data to the bars.
var bars = hGsvg.selectAll(".bar").data(nD);
// transition the height and color of rectangles.
bars.select("rect").transition().duration(500)
.attr("y", function (d) { return y(d[1]); })
.attr("height", function (d) { return hGDim.h - y(d[1]); })
.attr("fill", color);
// transition the frequency labels location and change value.
bars.select("text").transition().duration(500)
.text(function (d) { return d3.format(",")(d[1]) })
.attr("y", function (d) { return y(d[1]) - 5; });
}
return hG;
}
// function to handle pieChart.
function pieChart(pD) {
var pC = {}, pieDim = { w: 250, h: 250 };
pieDim.r = Math.min(pieDim.w, pieDim.h) / 2;
// create svg for pie chart.
var piesvg = d3.select(id).append("svg")
.attr("width", pieDim.w).attr("height", pieDim.h).append("g")
.attr("transform", "translate(" + pieDim.w / 2 + "," + pieDim.h / 2 + ")");
// create function to draw the arcs of the pie slices.
var arc = d3.svg.arc().outerRadius(pieDim.r - 10).innerRadius(0);
// create a function to compute the pie slice angles.
var pie = d3.layout.pie().sort(null).value(function (d) { return d.freq; });
// Draw the pie slices.
piesvg.selectAll("path").data(pie(pD)).enter().append("path").attr("d", arc)
.each(function (d) { this._current = d; })
.style("fill", function (d) { return segColor(d.data.type); })
.on("mouseover", mouseover).on("mouseout", mouseout);
// create function to update pie-chart. This will be used by histogram.
pC.update = function (nD) {
piesvg.selectAll("path").data(pie(nD)).transition().duration(500)
.attrTween("d", arcTween);
}
// Utility function to be called on mouseover a pie slice.
function mouseover(d) {
// call the update function of histogram with new data.
hG.update(fData.map(function (v) {
return [v.State, v.freq[d.data.type]];
}), segColor(d.data.type));
}
//Utility function to be called on mouseout a pie slice.
function mouseout(d) {
// call the update function of histogram with all data.
hG.update(fData.map(function (v) {
return [v.State, v.total];
}), barColor);
}
// Animating the pie-slice requiring a custom function which specifies
// how the intermediate paths should be drawn.
function arcTween(a) {
var i = d3.interpolate(this._current, a);
this._current = i(0);
return function (t) { return arc(i(t)); };
}
return pC;
}
// function to handle legend.
function legend(lD) {
var leg = {};
// create table for legend.
var legend = d3.select(id).append("table").attr('class', 'legend');
// create one row per segment.
var tr = legend.append("tbody").selectAll("tr").data(lD).enter().append("tr");
// create the first column for each segment.
tr.append("td").append("svg").attr("width", '16').attr("height", '16').append("rect")
.attr("width", '16').attr("height", '16')
.attr("fill", function (d) { return segColor(d.type); });
// create the second column for each segment.
tr.append("td").text(function (d) { return d.type; });
// create the third column for each segment.
tr.append("td").attr("class", 'legendFreq')
.text(function (d) { return d3.format(",")(d.freq); });
// create the fourth column for each segment.
tr.append("td").attr("class", 'legendPerc')
.text(function (d) { return getLegend(d, lD); });
// Utility function to be used to update the legend.
leg.update = function (nD) {
// update the data attached to the row elements.
var l = legend.select("tbody").selectAll("tr").data(nD);
// update the frequencies.
l.select(".legendFreq").text(function (d) { return d3.format(",")(d.freq); });
// update the percentage column.
l.select(".legendPerc").text(function (d) { return getLegend(d, nD); });
}
function getLegend(d, aD) { // Utility function to compute percentage.
return d3.format("%")(d.freq / d3.sum(aD.map(function (v) { return v.freq; })));
}
return leg;
}
// calculate total frequency by segment for all state.
var tF = ['low', 'mid', 'high'].map(function (d) {
return { type: d, freq: d3.sum(fData.map(function (t) { return t.freq[d]; })) };
});
// calculate total frequency by state for all segment.
var sF = fData.map(function (d) { return [d.State, d.total]; });
var hG = histoGram(sF), // create the histogram.
pC = pieChart(tF), // create the pie-chart.
leg = legend(tF); // create the legend.
}
var freqData = [
{ State: 'AL', freq: { low: 4786, mid: 1319, high: 249 } }
, { State: 'AZ', freq: { low: 1101, mid: 412, high: 674 } }
, { State: 'CT', freq: { low: 932, mid: 2149, high: 418 } }
, { State: 'DE', freq: { low: 832, mid: 1152, high: 1862 } }
, { State: 'FL', freq: { low: 4481, mid: 3304, high: 948 } }
, { State: 'GA', freq: { low: 1619, mid: 167, high: 1063 } }
, { State: 'IA', freq: { low: 1819, mid: 247, high: 1203 } }
, { State: 'IL', freq: { low: 4498, mid: 3852, high: 942 } }
, { State: 'IN', freq: { low: 797, mid: 1849, high: 1534 } }
, { State: 'KS', freq: { low: 162, mid: 379, high: 471 } }
];
dashboard('#dashboard', freqData);
nv.addGraph(function () {
var chart = nv.models.scatterChart()
.showDistX(true) //showDist, when true, will display those little distribution lines on the axis.
.showDistY(true)
.transitionDuration(350)
.color(d3.scale.category10().range());
//Configure how the tooltip looks.
chart.tooltipContent(function (key) {
return '<h3>' + key + '</h3>';
});
//Axis settings
chart.xAxis.tickFormat(d3.format('.02f'));
chart.yAxis.tickFormat(d3.format('.02f'));
//We want to show shapes other than circles.
chart.scatter.onlyCircles(false);
var myData = randomData(4, 40);
d3.select('#chart svg')
.datum(myData)
.call(chart);
nv.utils.windowResize(chart.update);
return chart;
});
/**************************************
* Simple test data generator
*/
function randomData(groups, points) { //# groups,# points per group
var data = [],
shapes = ['circle', 'cross', 'triangle-up', 'triangle-down', 'diamond', 'square'],
random = d3.random.normal();
for (i = 0; i < groups; i++) {
data.push({
key: 'Group ' + i,
values: []
});
for (j = 0; j < points; j++) {
data[i].values.push({
x: random()
, y: random()
, size: Math.random() //Configure the size of each scatter point
, shape: (Math.random() > 0.95) ? shapes[j % 6] : "circle" //Configure the shape of each scatter point.
});
}
}
return data;
}
|
module.exports = NotImplementedError => {
const throwNotImplemented = function () {
throw new NotImplementedError()
};
/**
* Controller control interface
*
* @interface
* @memberof module:client.synth
*/
var Controller = throwNotImplemented;
/**
* Asks the controller to start capturing control events
*
* @memberof module:client.synth.Controller
*
* @return {Promise}
*/
Controller.prototype.attach = throwNotImplemented;
/**
* Asks the controller to stop capturing control events
*
* @memberof module:client.synth.Controller
*
* @return {Promise}
*/
Controller.prototype.detach = throwNotImplemented;
return Controller;
};
|
import Ember from 'ember';
import { stack } from 'd3-shape';
import addOptionsToStack from '../utils/add-options-to-stack';
export function d3Stack( [ data, args ], hash={}) {
return addOptionsToStack(stack(data, args), hash);
}
export default Ember.Helper.helper(d3Stack);
|
var PROPS = injectProps;
var hookOnReload = injectOnReload;
const io = require('socket.io-client');
const socket = io(`http://127.0.0.1:${PROPS.port}`);
const { id: ext_id } = chrome.runtime;
const onReload = (query = {}, cb) => {
query = Object.assign({
url: [`chrome-extension://${ext_id}/*`]
}, query);
chrome.tabs.query(query, (tabs) => {
cb(tabs);
hookOnReload();
chrome.runtime.reload();
});
};
const onReopen = (tabs = [], cb) => {
tabs.forEach((tab) => {
var { windowId, index, url, active, pinned, openerTabId } = tab;
var new_tab = { windowId, index, url, active, pinned, openerTabId };
chrome.tabs.create(new_tab);
});
cb(tabs);
}
socket.on('reload', onReload);
socket.on('reopen', onReopen); |
define(['views/Index','views/Cart','views/CategoryEdit','views/Categories','views/Product','views/Products','views/ProductEdit','views/ProductDetail','views/admin/Index','models/Product','models/Category','models/CartCollection','models/ProductCollection','models/CategoryCollection'], function(IndexView,CartView,CategoryEditView,CategoriesView,ProductView,ProductsView,ProductEditView,ProductDetailView,AdminIndexView,Product,Category,CartCollection,ProductCollection,CategoryCollection){
var BizRouter = Backbone.Router.extend({
currentView : null,
routes: {
'': 'index',
'index': 'index',
'cart': 'myCart',
'products(/:id)': 'products',
'product/add(/:cid)': 'productAdd',
'product/edit/:id': 'productEdit',
'product/view/:id': 'productView',
'categories(/:id)': 'categories',
'category/add(/:pid)': 'categoryAdd',
'category/edit/:id': 'categoryEdit',
'admin/index': 'adminIndex',
},
changeView: function(view){
if(null != this.currentView){
this.currentView.undelegateEvents();
}
this.currentView = view;
this.currentView.render();
},
index: function(){
this.changeView(new IndexView());
},
myCart: function(){
var cartCollection = new CartCollection();
cartCollection.url = '/cart';
this.changeView(new CartView({collection:cartCollection}));
cartCollection.fetch();
},
/** product related */
products: function(id){
var cid = id || '';
var productCollection = new ProductCollection();
productCollection.url = '/products?cid=' + cid;;
this.changeView(new ProductsView({collection: productCollection}));
productCollection.fetch();
},
productAdd: function(categoryId){
var cid = categoryId || '';
var productModel = new Product({
main_cat_id: cid,
});
this.changeView(new ProductEditView({model: productModel}));
},
productEdit: function(id){
var product = new Product();
product.url = '/products/' + id;
this.changeView(new ProductEditView({model: product}));
product.fetch();
},
productView: function(id){
var product = new Product();
product.url = '/products/' + id;
this.changeView(new ProductDetailView({model: product}));
product.fetch();
},
/** category related */
categories: function(id){
var pid = id || '';
var categoryCollection = new CategoryCollection();
categoryCollection.url = '/categories?pid=' + pid;
this.changeView(new CategoriesView({collection: categoryCollection}));
categoryCollection.fetch();
},
categoryAdd: function(parentId){
var pid = parentId || '';
var categoryModel = new Category({
parent: pid
});
this.changeView(new CategoryEditView({model: categoryModel}));
},
categoryEdit: function(id){
var category = new Category();
category.url = '/categories/' + id;
this.changeView(new CategoryEditView({model: category}));
category.fetch();
},
adminIndex: function(){
this.changeView(new AdminIndexView());
}
});
return new BizRouter();
}); |
import authorAPI from '../api/mock/mockAuthorAPI';
import * as types from './actionTypes';
import { beginAjaxCall } from './ajaxStatusActions';
const loadAuthorSuccess = (courses) => {
return {type : types.LOAD_AUTHOR_SUCCESS, courses };
};
const loadAuthors = () => {
return (dispatch) => {
dispatch(beginAjaxCall());
return authorAPI.getAllAuthors().then(authors => {
dispatch(loadAuthorSuccess(authors));
}).catch(error => {
throw(error);
});
};
};
export {
loadAuthors,
loadAuthorSuccess
};
|
function extensibleObject() {
let obj = {
extend: function(template){
for(let parentProp of Object.keys(template)){
if(typeof(template[parentProp]) == 'function'){
Object.getPrototypeOf(obj)[parentProp] = template[parentProp];
} else {
obj[parentProp] = template[parentProp];
}
}
}
};
return obj;
} |
'use strict';
const migrate = require('../scripts/migrate-sql');
exports.up = db => migrate.migrate(db, '20180515155000-app-features.sql');
|
const path = require('path');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const resolve = (dir) => {
return path.join(__dirname, '..', dir)
};
const isProduction = process.env.NODE_ENV === 'production';
const config = {
output: {
path: path.join(__dirname, '..', 'dist', 'assets'),
filename: '[name].[hash].js',
publicPath: '/assets/',
},
resolve: {
extensions: ['.js', '.vue', '.json'],
alias: {
'~': resolve('src'),
'vue$': 'vue/dist/vue.runtime.esm.js',
'vuex$': 'vuex/dist/vuex.esm.js',
},
},
module: {
rules: [
{
test: /\.js$/,
include: [
resolve('src'),
resolve('node_modules/@material'),
],
use: ['babel-loader'],
},
{
test: /\.vue$/,
loader: 'vue-loader',
options: {
extractCSS: isProduction,
postcss: [
require('autoprefixer')({
browsers: ['IE 9', 'IE 10', 'IE 11', 'last 2 versions'],
}),
],
},
},
],
},
plugins: [
new CopyWebpackPlugin([
{
from: resolve('src/static'),
to: resolve('dist'),
},
]),
],
};
module.exports = config;
|
var expect = require("chai").expect;
var MoodleExporter = require('../../MoodleExporter');
var xml2js = require('xml2js');
describe('MoodleExporter', function () {
var validSeed = 'abcd1234';
var validQD = {
"version": "0.1",
"questions": [{
"question": "mc-change-of-base",
"repeat": 2,
}]
};
describe('generateMoodleXML(qd, seed)', function () {
describe('throwing errors', function () {
describe('when qd is invalid problemType', function () {
it('should throw an error.', function () {
expect(function () {
MoodleExporter.generateMoodleXML({ "invalid": "qd" }, validSeed)
}).to.throw(Error);
});
});
describe('invalid seed', function () {
it("should throw an error", function () {
expect(function () {
MoodleExporter.generateMoodleXML(validQD, "invalid-seed");
}).to.throw(Error);
});
});
});
describe('successful conversion', function () {
var xmlResult, xmlString;
describe('general requirements', function () {
beforeEach(function (done) {
try {
xmlString = MoodleExporter.generateMoodleXML(validQD, validSeed);
} catch(e) {
console.log(e);
throw e;
}
xml2js.parseString(xmlString, function (err, result) {
xmlResult = result;
done();
});
});
describe('xml quiz tag', function () {
it('should set the quiz tag', function () {
expect(xmlResult.quiz).to.exist;
});
});
describe('xml question', function () {
it('should have the # of questions specified by the count parameter', function () {
expect(xmlResult.quiz.question.length).to.equal(2);
});
});
});
describe('multiple problemTypes', function () {
beforeEach(function (done) {
var qd = {
"version": "0.1",
"questions": [{
"question": "mc-change-of-base",
"repeat": 1,
},
{
"question": "fr-change-of-base",
"repeat": 1,
}]
};
xmlString = MoodleExporter.generateMoodleXML(qd, validSeed);
xml2js.parseString(xmlString, function (err, result) {
xmlResult = result;
done();
});
});
describe('first question title', function () {
it('should be Change of Base Multiple Choice', function () {
expect(xmlResult.quiz.question[0].name[0].text[0]).to.equal("Change of Base Multiple Choice");
});
});
describe('second question title', function () {
it('should be Change of Base Free Response', function () {
expect(xmlResult.quiz.question[1].name[0].text[0]).to.equal("Change of Base Free Response");
});
});
});
describe('different formats', function () {
describe('multiple choice format', function () {
beforeEach(function (done) {
problemTypeRequested = 'mc-change-of-base';
count = 2;
questionName = 'Sample Question Name';
var qd = {
"version": "0.1",
"questions": [{
"question": problemTypeRequested,
"repeat": count,
}]
};
xmlString = MoodleExporter.generateMoodleXML(qd, validSeed);
xml2js.parseString(xmlString, function (err, result) {
xmlResult = result;
done();
});
});
//TODO: fix output type references -- previously may have been question type MC vs free response
describe('xml output type', function () {
it('should have set the output type attribute to multichoice', function () {
for (var i = 0; xmlResult.quiz.question.length > i; i++)
expect(xmlResult.quiz.question[i].$.type).to.equal('multichoice');
});
});
describe('xml question title', function () {
it('should be Change of Base Multiple Choice', function () {
expect(xmlResult.quiz.question[0].name[0].text[0]).to.equal("Change of Base Multiple Choice");
});
});
});
describe('input format', function () {
beforeEach(function (done) {
problemTypeRequested = 'fr-change-of-base';
count = 2;
questionName = 'Sample Question Name';
var qd = {
"version": "0.1",
"questions": [{
"question": problemTypeRequested,
"repeat": count,
}]
};
xmlString = MoodleExporter.generateMoodleXML(qd, validSeed);
xml2js.parseString(xmlString, function (err, result) {
xmlResult = result;
done();
});
});
//TODO: fix output type references -- previously may have been question type MC vs free response
//TODO: shortanswer vs free-response
describe('xml output type property', function () {
it('should have set the output type attribute to shortanswer', function () {
for (var i = 0; xmlResult.quiz.question.length > i; i++)
expect(xmlResult.quiz.question[i].$.type).to.equal('shortanswer');
});
});
describe('xml question title', function () {
it('should be Change of Base Free Response', function () {
expect(xmlResult.quiz.question[0].name[0].text[0]).to.equal("Change of Base Free Response");
});
});
describe('question.answer.text', function () {
it('should exist', function () {
expect(xmlResult.quiz.question[0].answer[0].text).to.exist;
});
});
});
});
});
});
});
|
import { expect } from 'chai';
import Urlsparser from '../src/app.js';
describe('wrong', () => {
it('...', () => {
const caps = () => {new Urlsparser('...')};
expect(caps).to.throw();
});
it('+++abs+', () => {
const caps = () => {new Urlsparser('+++abs+')};
expect(caps).to.throw();
});
it('0:5:92', () => {
const caps = () => {new Urlsparser('0:5:92')};
expect(caps).to.throw();
});
});
|
import chai from 'chai';
import chaiAsPromised from 'chai-as-promised';
import sinon from 'sinon';
import sinonChai from 'sinon-chai';
import {BasePaginator, errors} from './base-paginator';
import PaginatorError from '../paginator-error';
import * as queryHandler from '../helpers/query-handler-stub';
import * as request from '../helpers/request-spy';
const {assert, expect} = chai;
chai.use(chaiAsPromised);
chai.use(sinonChai);
describe('drf-paginator', function() {
afterEach(function() {
request.spy.reset();
queryHandler.resetSpies();
});
describe('BasePaginator', function() {
let paginator;
const makePaginator = function(queryParams) {
paginator = new BasePaginator(request.spy)
.setQueryHandler(queryHandler.stub);
if (queryParams) {
paginator.setQueryParams(queryParams);
}
};
describe('page', function() {
beforeEach(function() {
makePaginator();
});
it('defaults to zero', function() {
expect(paginator.page).to.equal(0);
});
});
describe('queryHandler', function() {
beforeEach(function() {
paginator = new BasePaginator(request.spy);
});
it('defaults to `null`', function() {
expect(paginator.page).to.equal(0);
});
});
describe('next', function() {
beforeEach(function() {
makePaginator();
});
it('returns a promise that resolves', function() {
const promise = paginator.next();
return expect(promise).to.eventually.resolve;
});
it('returns a promise with a response object', function() {
const response = paginator.next();
return expect(response).to.eventually.be.an('object');
});
it('increments the page', function() {
expect(paginator.page).to.equal(0);
const page = paginator.next()
.then(() => paginator.page);
return expect(page).to.eventually.equal(1);
});
it('sends a request using the request function', function() {
const requestCallCount = paginator.next()
.then(request.getCallCount);
return expect(requestCallCount).to.eventually.equal(1);
});
});
describe('prev', function() {
beforeEach(function() {
makePaginator({ page: 2 });
});
it('returns a promise that resolves', function() {
const promise = paginator.prev();
return expect(promise).to.eventually.resolve;
});
it('returns a promise with a response object', function() {
const response = paginator.prev();
return expect(response).to.eventually.be.an('object');
});
it('decrements the page', function() {
expect(paginator.page).to.equal(2);
const page = paginator.prev()
.then(() => paginator.page);
return expect(page).to.eventually.equal(1);
});
it('sends a request using the request function', function() {
const requestCallCount = paginator.prev()
.then(request.getCallCount);
return expect(requestCallCount).to.eventually.equal(1);
});
});
describe('first', function() {
beforeEach(function() {
makePaginator();
});
it('returns a promise that resolves', function() {
const promise = paginator.first();
return expect(promise).to.eventually.resolve;
});
it('returns a promise with a response object', function() {
const response = paginator.first();
return expect(response).to.eventually.be.an('object');
});
it('sets the page to the first page ', function() {
expect(paginator.page).to.equal(0);
const page = paginator.first()
.then(() => paginator.page);
return expect(page).to.eventually.equal(1);
});
it('sends a request using the request function', function() {
const requestCallCount = paginator.first()
.then(request.getCallCount);
return expect(requestCallCount).to.eventually.equal(1);
});
});
describe('last', function() {
beforeEach(function() {
makePaginator();
});
it('returns a promise that resolves', function() {
const promise = paginator.last();
return expect(promise).to.eventually.resolve;
});
it('returns a promise with a response object', function() {
const response = paginator.last();
return expect(response).to.eventually.be.an('object');
});
it('sets the paginator\'s current page to the last page', function() {
expect(paginator.page).to.equal(0);
const page = paginator.last()
.then(() => paginator.page);
return expect(page).to.eventually.equal(10);
});
it('sends requests to get the page count and the last page.',
function() {
const requestCallCount = paginator.last()
.then(request.getCallCount);
return expect(requestCallCount).to.eventually.equal(2);
});
});
describe('current', function() {
beforeEach(function() {
makePaginator({ page: 1 });
});
it('returns a promise that resolves', function() {
const promise = paginator.current();
return expect(promise).to.eventually.resolve;
});
it('doesn\'t change the page', function() {
expect(paginator.page).to.equal(1);
const page = paginator.current()
.then(() => paginator.page);
return expect(page).to.eventually.equal(1);
});
it('sends a request using the request function', function() {
const requestCallCount = paginator.current()
.then(request.getCallCount);
return expect(requestCallCount).to.eventually.equal(1);
});
});
describe('fetchPage', function() {
beforeEach(function() {
makePaginator();
});
it('returns a promise that resolves', function() {
const promise = paginator.fetchPage(1);
return expect(promise).to.eventually.resolve;
});
it('returns a promise with a response object', function() {
const response = paginator.fetchPage(1);
return expect(response).to.eventually.be.an('object');
});
it('sends a request using the request function', function() {
const requestCallCount = paginator.fetchPage(1)
.then(request.getCallCount);
return expect(requestCallCount).to.eventually.equal(1);
});
it('returns a rejected promise for pages before the first page',
function() {
const promise = paginator.fetchPage(0);
return expect(promise).to.eventually.be.rejectedWith(Error);
});
it('rejects pages after the last page when the page count is known',
function() {
// The max page of the fixture is 10
const promise = paginator.fetchPageCount()
.then(() => paginator.fetchPage(13));
return expect(promise).to.eventually.be.rejectedWith(Error);
});
it('accepts pages after the last page when the page count is unknown',
function() {
const promise = paginator.fetchPage(13);
return expect(promise).to.eventually.resolve;
});
it('clone responses', function() {
const first = paginator.fetchPage(1);
const second = first.then(() => paginator.fetchPage(1));
return Promise.all([first, second])
.spread(assert.notStrictEqual);
});
it('caches requests', function() {
const first = paginator.fetchPage(1)
.then((res) => res.uniqueValue);
const second = first.then(() => paginator.fetchPage(1))
.then((res) => res.uniqueValue);
return Promise.all([first, second])
.spread(assert.strictEqual);
});
it('calls the query handler\'s `onResponse` method', function() {
const onResponseCallCount = paginator.fetchPage(1)
.then(() => queryHandler.stub.onResponse.callCount);
return expect(onResponseCallCount).to.eventually.equal(1);
});
it('throws an error if the query handler isn\'t set', function() {
paginator.queryHandler = null;
const check = function() {
paginator.fetchPage(1);
};
const msg = errors.queryHandlerMissing;
return expect(check).to.throw(PaginatorError, msg);
});
});
describe('fetchPageCount', function() {
beforeEach(function() {
makePaginator();
sinon.spy(paginator, 'fetchPage');
});
afterEach(function() {
paginator.fetchPage.restore();
});
it('returns a promise that resolves', function() {
const promise = paginator.fetchPageCount();
return expect(promise).to.eventually.resolve;
});
it('returns a promise with the paginator\'s page count', function() {
const pageCount = paginator.fetchPageCount();
return expect(pageCount).to.eventually.equal(10);
});
it('caches the page count', function() {
const fetchPageCallCount = paginator.fetchPageCount()
.then(() => paginator.fetchPageCount())
.then(() => paginator.fetchPage.callCount);
return expect(fetchPageCallCount).to.eventually.equal(1);
});
});
describe('setQueryHandler', function() {
beforeEach(function() {
paginator = new BasePaginator(request.spy);
});
it('sets the query handler', function() {
const obj = {};
paginator.setQueryHandler(obj);
expect(paginator.queryHandler).to.equal(obj);
});
it('is a fluent method', function() {
var result = paginator.setQueryHandler({});
expect(result).to.equal(paginator);
});
});
describe('setQueryParams', function() {
beforeEach(function() {
makePaginator();
});
it('sets the parameters in the query handler', function() {
const queryParams = { page: 42 };
paginator.setQueryParams(queryParams);
expect(paginator.queryHandler.setParams)
.to.have.been.calledWithMatch(queryParams);
});
it('updates the paginator\'s page based on the given parameters',
function() {
expect(paginator.page).to.equal(0);
paginator.setQueryParams({ page: 42 });
expect(paginator.page).to.equal(42);
});
it('is a fluent method', function() {
var result = paginator.setQueryParams({});
expect(result).to.equal(paginator);
});
});
});
});
|
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zm6.93 6h-2.95c-.32-1.25-.78-2.45-1.38-3.56 1.84.63 3.37 1.91 4.33 3.56zM12 4.04c.83 1.2 1.48 2.53 1.91 3.96h-3.82c.43-1.43 1.08-2.76 1.91-3.96zM4.26 14C4.1 13.36 4 12.69 4 12s.1-1.36.26-2h3.38c-.08.66-.14 1.32-.14 2s.06 1.34.14 2H4.26zm.82 2h2.95c.32 1.25.78 2.45 1.38 3.56-1.84-.63-3.37-1.9-4.33-3.56zm2.95-8H5.08c.96-1.66 2.49-2.93 4.33-3.56C8.81 5.55 8.35 6.75 8.03 8zM12 19.96c-.83-1.2-1.48-2.53-1.91-3.96h3.82c-.43 1.43-1.08 2.76-1.91 3.96zM14.34 14H9.66c-.09-.66-.16-1.32-.16-2s.07-1.35.16-2h4.68c.09.65.16 1.32.16 2s-.07 1.34-.16 2zm.25 5.56c.6-1.11 1.06-2.31 1.38-3.56h2.95c-.96 1.65-2.49 2.93-4.33 3.56zM16.36 14c.08-.66.14-1.32.14-2s-.06-1.34-.14-2h3.38c.16.64.26 1.31.26 2s-.1 1.36-.26 2h-3.38z" />
, 'LanguageSharp');
|
var keypress = require("keypress");
// var Spark = require("spark-io");
var Spark = require("../");
var five = require("johnny-five");
var Sumobot = require("sumobot")(five);
keypress(process.stdin);
var board = new five.Board({
io: new Spark({
token: process.env.SPARK_TOKEN,
deviceId: process.env.SPARK_DEVICE_2
})
});
board.on("ready", function() {
console.log("Welcome to Sumobot Jr: Light Bot!");
var bot = new Sumobot({
left: "D0",
right: "D1",
speed: 0.50
});
var light = new five.Sensor("A0");
var isQuitting = false;
light.on("change", function() {
if (isQuitting || this.value === null) {
return;
}
if (this.value < 512) {
bot.fwd();
} else {
bot.rev();
}
});
// Ensure the bot is stopped
bot.stop();
});
|
require([
'app/LoginRegisterCloudRequestPane',
'dojo/dom-construct',
'dojo/query'
], function(
WidgetUnderTest,
domConstruct,
query
) {
describe('app/LoginRegisterCloudRequestPane', function() {
var widget;
var destroy = function(widget) {
widget.destroyRecursive();
widget = null;
};
beforeEach(function() {
widget = new WidgetUnderTest(null, domConstruct.create('div', null, document.body));
query(
'input[type="text"], input[type="password"], input[type="email"]',
widget.domNode
).forEach(function(node) {
node.value = 'anything';
});
});
afterEach(function() {
if (widget) {
destroy(widget);
}
});
describe('Sanity', function() {
it('should create a LoginRegisterCloudRequestPane', function() {
expect(widget).toEqual(jasmine.any(WidgetUnderTest));
});
});
describe('Password Restrictions', function() {
it('should be 8 characters in length', function() {
expect(widget.validate('aB1234$&').result).toEqual(true);
expect(widget.validate('aB1&').result).toEqual(false);
});
it('should have one uppercase letter', function() {
expect(widget.validate('aB1234$&').result).toEqual(true);
expect(widget.validate('ab1234$&').result).toEqual(false);
});
it('should have one lowercase letter', function() {
expect(widget.validate('aB1234$&').result).toEqual(true);
expect(widget.validate('AB1234$&').result).toEqual(false);
});
it('should have one special character', function() {
expect(widget.validate('aB1234$&').result).toEqual(true);
expect(widget.validate('aB123456').result).toEqual(false);
});
it('should have one number', function() {
expect(widget.validate('aB1234$&').result).toEqual(true);
expect(widget.validate('aB!@#$%^').result).toEqual(false);
});
});
});
}); |
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var makeCommandAbsolute = exports.makeCommandAbsolute = function makeCommandAbsolute(p, c) {
switch (c.c) {
case 'm':
return { c: 'M', x: p.x + c.dx, y: p.y + c.dy };
case 'z':
return { c: 'Z' };
case 'l':
return { c: 'L', x: p.x + c.dx, y: p.y + c.dy };
case 'h':
return { c: 'L', x: p.x + c.dx, y: p.y };
case 'v':
return { c: 'L', y: p.y + c.dy, x: p.x };
case 'H':
return { c: 'L', x: c.x, y: p.y };
case 'V':
return { c: 'L', y: c.y, x: p.x };
case 'c':
return { c: 'C', x1: p.x + c.dx1, y1: p.y + c.dy1, x2: p.x + c.dx2, y2: p.y + c.dy2, x: p.x + c.dx, y: p.y + c.dy };
case 's':
return { c: 'S', x2: p.x + c.dx2, y2: p.y + c.dy2, x: p.x + c.dx, y: p.y + c.dy };
case 'q':
return { c: 'Q', x1: p.x + c.dx1, y1: p.y + c.dy1, x: p.x + c.dx, y: p.y + c.dy };
case 't':
return { c: 'T', x: p.x + c.dx, y: p.y + c.dy };
case 'a':
return { c: 'A', rx: c.rx, ry: c.ry, xAxisRotation: c.xAxisRotation, largeArcFlag: c.largeArcFlag, sweepFlag: c.sweepFlag, x: p.x + c.dx, y: p.y + c.dy };
default:
return c;
}
};
var applyCommand = exports.applyCommand = function applyCommand(position, begin, c) {
var dif = { dx: 0, dy: 0 };
if (c.c === 'm') dif = c;else if (c.c === 'l') dif = c;else if (c.c === 'c') dif = c;else if (c.c === 's') dif = c;else if (c.c === 'q') dif = c;else if (c.c === 't') dif = c;else if (c.c === 'a') dif = c;else if (c.c === 'h') dif = { dx: c.dx, dy: 0 };else if (c.c === 'v') dif = { dx: 0, dy: c.dy };else if (c.c === 'z') dif = { dx: begin.x - position.x, dy: begin.y - position.y };else if (c.c === 'V') return { x: position.x, y: c.y };else if (c.c === 'H') return { x: c.x, y: position.y };else if (c.c === 'Z') return begin;else {
return c;
}
return { x: position.x + dif.dx, y: position.y + dif.dy };
};
var normalizeData = exports.normalizeData = function normalizeData(d) {
var begin = { x: 0, y: 0 };
var position = { x: 0, y: 0 };
var result = [];
for (var i = 0; i < d.length; i++) {
var command = d[i];
var absoluteCommand = makeCommandAbsolute(position, command);
var newPosition = applyCommand(position, begin, absoluteCommand);
// Filter line commands which doesn't change position
var isLineCommand = absoluteCommand.c === 'L' || absoluteCommand.c === 'Z';
if (!isLineCommand || !pointEquals(newPosition, position)) {
result.push(absoluteCommand);
position = newPosition;
}
if (absoluteCommand.c === 'M') {
begin = absoluteCommand;
} else if (absoluteCommand.c === 'm') {
begin = applyCommand(position, begin, absoluteCommand);
}
}
return result;
};
var getSubPaths = exports.getSubPaths = function getSubPaths(d) {
if (d.length === 0) {
return [];
} else if (d[0].c !== 'M' && d[0].c !== 'm') {
throw new Error('Path must start with an "M" or "m" command, not "' + d[0].c + '" ');
}
var result = [];
var nextSubPath = [];
var lastM = { c: 'M', x: 0, y: 0 };
d.forEach(function (command) {
if (command.c === 'M') {
if (nextSubPath.length > 0) {
result.push(nextSubPath);
}
nextSubPath = [command];
lastM = command;
} else if (command.c === 'Z') {
nextSubPath.push(command);
result.push(nextSubPath);
nextSubPath = [];
} else {
if (nextSubPath.length === 0) {
nextSubPath.push(lastM);
}
nextSubPath.push(command);
}
});
if (nextSubPath.length > 0) {
result.push(nextSubPath);
}
return result;
};
var isSubPathClosed = exports.isSubPathClosed = function isSubPathClosed(begin, d) {
if (d.length < 2) {
return true;
}
var lastCommand = d[d.length - 1];
if (lastCommand.c === 'Z') {
return true;
}
return lastCommand.x === begin.x && lastCommand.y === begin.y;
};
var pointEquals = exports.pointEquals = function pointEquals(p1, p2) {
return p1.x === p2.x && p1.y === p2.y;
}; |
"use strict"
/**
* `format` constructor.
*
* @api public
*/
const checkStatusCode = require('./helpers');
module.exports = {
create : (statusCode, error, message, data) => {
if(!statusCode) throw new Error('Status code is required')
if( isNaN( Number( statusCode))) throw new Error('Status code not a number')
this.statusCode = statusCode
this.error = error || null
this.data = data || null
this.message = checkStatusCode(this.statusCode, message)
return this
},
success: (message, data) => {
this.statusCode = 200
this.error = false
this.data = data || null
this.message = message || 'OK'
return this
},
badRequest: (message, data) => {
this.statusCode = 400
this.error = true
this.data = data || null
this.message = message || 'Bad Request'
return this
},
unAuthorized: (message, data) => {
this.statusCode = 401
this.error = true
this.data = data || null
this.message = message || 'Unauthorized'
return this
},
forbidden: (message, data) => {
this.statusCode = 403
this.error = true
this.data = data || null
this.message = message || 'Forbidden'
return this
},
notFound: (message, data) => {
this.statusCode = 404
this.error = true
this.data = data || null
this.message = message || 'Not Found'
return this
},
notAllowed: (message, data) => {
this.statusCode = 405
this.error = true
this.data = data || null
this.message = message || 'Method Not Allowed'
return this
},
requestTimeout: (message, data) => {
this.statusCode = 408
this.error = true
this.data = data || null
this.message = message || 'Request Timeout'
return this
},
internalError: (message, data) => {
this.statusCode = 500
this.error = true
this.data = data || null
this.message = message || 'Internal Server Error'
return this
},
badGateway: (message, data) => {
this.statusCode = 502
this.error = true
this.data = data || null
this.message = message || 'Bad Gateway'
return this
},
unavailable: (message, data) => {
this.statusCode = 503
this.error = true
this.data = data || null
this.message = message || 'Service Unavailable'
return this
},
gatewayTimeout: (message, data) => {
this.statusCode = 504
this.error = true
this.data = data || null
this.message = message || 'Gateway Timeout'
return this
}
}
|
'use strict';
var request = require('supertest'),
chai = require('chai'),
expect = chai.expect,
routeValidator = require('../lib/index'),
validator = require('validator'),
express = require('express'),
bodyParser = require('body-parser'),
async = require('async');
describe('INTEGRATION index', function () {
describe('#validates(config)', function () {
describe('basic route validation', function () {
var app;
before( function () {
app = express();
app.get('/items/:item', routeValidator.validate({
params: {
item: { isMongoId: true, isRequired: true }
}
}), function (req, res) {
return res.status(200).end();
});
});
it('should send a 400 when route fails validation', function (done) {
request(app)
.get('/items/aasdklfjklsadlfjik')
.expect(400, done);
});
it('should send a 200 when route passes validation', function (done) {
request(app)
.get('/items/507f1f77bcf86cd799439011')
.expect(200, done);
});
it('should not care if you pass in properties it does not know about', function (done) {
request(app)
.get('/items/507f1f77bcf86cd799439011')
.query({
foo: 'bar',
notes: ''
})
.expect(200, done);
});
it('should ignore properties that you configure that it does not have a method to do' , function (done) {
// i.e. 'description' is set on the validation config object for documentation purposes,
// but routeValidator doesn't care and just ignores it
request(app)
.get('/items/507f1f77bcf86cd799439011')
.expect(200, done);
});
});
describe('validates req.params', function () {
var app;
before( function () {
app = express();
app.get('/items/:item', routeValidator.validate({
params: {
item: { isMongoId: true, isRequired: true }
}
}), function (req, res) {
return res.status(200).end();
});
app.get('/items/:item/messages/:message', routeValidator.validate({
params: {
item: { isMongoId: true, isRequired: true },
message: { isMongoId: true, isRequired: true }
}
}), function (req, res) {
return res.status(200).end();
});
});
it('should validate params passed into route, on success', function (done) {
request(app)
.get('/items/507f1f77bcf86cd799439011')
.expect(200, done);
});
it('should validate params passed into route, on failure', function (done) {
request(app)
.get('/items/banana')
.expect(400, function (err, res) {
if (err) return done(err);
expect(res.body).to.have.property('error').that.contains('params.item');
return done();
});
});
it('should handle multiple params passed into route, on success', function (done) {
request(app)
.get('/items/507f1f77bcf86cd799439011/messages/407f1f77bcf86cd799439011')
.expect(200, done);
});
it('should handle multiple params passed into route, on failure', function (done) {
request(app)
.get('/items/507f1f77bcf86cd799439011/messages/banana')
.expect(400, function (err, res) {
if (err) return done(err);
expect(res.body).to.have.property('error').that.contains('params.message');
return done();
});
});
});
describe('validates req.body', function () {
var app;
before( function () {
app = express();
app.use(bodyParser.json());
app.post('/items', routeValidator.validate({
body: {
name: { isRequired: true },
date: { isRequired: true, isDate: true },
type: { isRequired: true, isIn: ['lawn', 'garden', 'tools'] },
user: { isRequired: true, isEmail: true },
uuid: { isRequired: false, isUUID: true },
url: { isURL: true },
rate: { isInt: true, toInt: true }
}
}), function (req, res) {
return res.status(200).end();
});
});
it('should validate params passed into body, on success', function (done) {
request(app)
.post('/items')
.send({
name: 'Chainsaw',
date: new Date(),
type: 'tools',
user: '[email protected]',
uuid: 'A987FBC9-4BED-3078-CF07-9141BA07C9F3',
url: 'http://tool.com/chainsaw/real-big'
})
.expect(200, done);
});
it('should validate params passed into body, on failure', function (done) {
request(app)
.post('/items')
.send({
name: 'Chainsaw',
date: new Date(),
type: 'tool', // invalid
user: '[email protected]',
uuid: 'A987FBC9-4BED-3078-CF07-9141BA07C9F3',
url: 'http://tool.com/chainsaw/real-big'
})
.expect(400, function (err, res) {
if (err) return done(err);
expect(res.body).to.have.property('error').that.contains('body.type');
return done();
});
});
it('should enforce isRequired', function (done) {
request(app)
.post('/items')
.send({
name: 'Chainsaw',
date: new Date(),
type: 'tools',
// user: '[email protected]',
uuid: 'A987FBC9-4BED-3078-CF07-9141BA07C9F3',
url: 'http://tool.com/chainsaw/real-big'
})
.expect(400, function (err, res) {
if (err) return done(err);
expect(res.body).to.have.property('error').that.contains('body.user');
return done();
});
});
it('should not fail validation when isRequired is set to false and param is not set', function (done) {
request(app)
.post('/items')
.send({
name: 'Chainsaw',
date: new Date(),
type: 'tools',
user: '[email protected]',
// uuid: 'A987FBC9-4BED-3078-CF07-9141BA07C9F3',
url: 'http://tool.com/chainsaw/real-big'
})
.set('Authorization', 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==')
.expect(200, done);
});
it('should not fail validation when isRequired is not set and param is not set', function (done) {
request(app)
.post('/items')
.send({
name: 'Chainsaw',
date: new Date(),
type: 'tools',
user: '[email protected]',
uuid: 'A987FBC9-4BED-3078-CF07-9141BA07C9F3',
// url: 'http://tool.com/chainsaw/real-big'
})
.expect(200, done);
});
it('should validate params if they exist, even if isRequired is set to false', function (done) {
request(app)
.post('/items')
.send({
name: 'Chainsaw',
date: new Date(),
type: 'tools',
user: '[email protected]',
uuid: 'banana', // invalid and not required
url: 'http://tool.com/chainsaw/real-big'
})
.expect(400, function (err, res) {
if (err) return done(err);
expect(res.body).to.have.property('error').that.contains('body.uuid');
return done();
});
});
});
describe('validates req.query', function () {
var app;
before( function () {
app = express();
app.use(bodyParser.json());
app.get('/items', routeValidator.validate({
query: {
since: { isDate: true },
limit: { isInt: true, isRequired: true },
page: { isInt: true, isRequired: false },
sort: { isRequired: true }
}
}), function (req, res) {
return res.status(200).end();
});
});
it('should validate query params, on success', function (done) {
request(app)
.get('/items')
.query({
since: new Date(),
limit: 20,
page: 1,
sort: 'date'
})
.expect(200, done);
});
it('should validate query params, on failure', function (done) {
request(app)
.get('/items')
.query({
since: new Date(),
limit: 'get me all of it', // invalid
page: 1,
sort: 'date'
})
.expect(400, function (err, res) {
if (err) return done(err);
expect(res.body).to.have.property('error').that.contains('query.limit');
return done();
});
});
it('should enforce isRequired', function (done) {
request(app)
.get('/items')
.query({
since: new Date(),
// limit: 20,
page: 1,
sort: 'date'
})
.expect(400, function (err, res) {
if (err) return done(err);
expect(res.body).to.have.property('error').that.contains('query.limit');
return done();
});
});
it('should not fail validation when isRequired is set to false and param is not set', function (done) {
request(app)
.get('/items')
.query({
since: new Date(),
limit: 20,
// page: 1,
sort: 'date'
})
.expect(200, done);
});
it('should not fail validation when isRequired is not set and param is not set', function (done) {
request(app)
.get('/items')
.query({
// since: new Date(),
limit: 20,
page: 1,
sort: 'date'
})
.expect(200, done);
});
it('should validate params if they exist, even if isRequired is set to false', function (done) {
request(app)
.get('/items')
.query({
since: 'yesterday', // invalid
limit: 20,
page: 1,
sort: 'date'
})
.expect(400, function (err, res) {
if (err) return done(err);
expect(res.body).to.have.property('error').that.contains('query.since');
return done();
});
});
});
describe('validates req.headers', function () {
var app;
before( function () {
app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.post('/items', routeValidator.validate({
body: {
name: { isRequired: true }
},
headers: {
'content-type': { isRequired: true, equals: 'application/json' },
'authorization': { isRequired: true },
'accept-version': { isRequired: false, isIn: ['1.0', '2.0'] }
}
}), function (req, res) {
return res.status(200).end();
});
});
it('should validate headers, on success', function (done) {
request(app)
.post('/items')
.send({
name: 'Chainsaw'
})
.set('Authorization', 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==')
.set('Accept-Version', '1.0')
.expect(200, done);
});
it('should validate headers, on failure', function (done) {
request(app)
.post('/items')
.type('form')
.send({
name: 'Chainsaw'
})
.set('Authorization', 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==')
.expect(400, function (err, res) {
if (err) return done(err);
expect(res.body).to.have.property('error').that.contains('headers.content-type');
return done();
});
});
it('should enforce isRequired', function (done) {
request(app)
.post('/items')
.send({
name: 'Chainsaw'
})
.expect(400, function (err, res) {
if (err) return done(err);
expect(res.body).to.have.property('error').that.contains('headers.authorization');
return done();
});
});
it('should validate headers if they exist, even if isRequired is set to false', function (done) {
request(app)
.post('/items')
.send({
name: 'Chainsaw'
})
.set('Authorization', 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==')
.set('Accept-Version', '0.0')
.expect(400, function (err, res) {
if (err) return done(err);
expect(res.body).to.have.property('error').that.contains('headers.accept-version');
return done();
});
});
});
describe('with default coercers', function () {
var app;
before( function () {
app = express();
app.use(bodyParser.json());
app.put('/items/:item', routeValidator.validate({
body: {
user: { isRequired: false, isEmail: true, normalizeEmail: true },
rate: { isRequired: true, isInt: true, toInt: true }
},
params: {
item: { isMongoId: true, isRequired: true }
}
}), function (req, res) {
// Make sure values are coerced
if (typeof req.body.rate !== 'number' || !validator.isLowercase(req.body.user)) {
console.log(JSON.stringify(req.body, null, 2));
return res.status(500).end();
}
return res.status(200).end();
});
});
it('should coerce values when configured with coercers', function (done) {
request(app)
.put('/items/507f1f77bcf86cd799439011')
.send({
user: '[email protected]',
rate: '100'
})
.expect(200, done);
});
});
describe('set callNext in route', function () {
var app;
before( function () {
app = express();
app.use(bodyParser.json());
app.get('/users', routeValidator.validate({
query: {
since: { isDate: true },
limit: { isInt: true, isRequired: true },
page: { isInt: true, isRequired: false },
sort: { isRequired: true }
},
callNext: true
}), function (req, res) {
return res.status(200).end();
});
app.use( function (err, req, res, next) { // jshint ignore:line
return res.status(400).send({
error: err.message,
message: 'calledNext'
});
});
});
it('should do nothing different if callNext is set to true and validation passes', function (done) {
request(app)
.get('/users')
.query({
since: new Date(),
limit: 20,
page: 1,
sort: 'email'
})
.expect(200, done);
});
it('should call next(err) if validation fails and callNext is set to true', function (done) {
request(app)
.get('/users')
.query({
since: new Date(),
limit: 'twenty', // invalid
page: 1,
sort: 'email'
})
.expect(400, function (err, res) {
console.log(JSON.stringify(res.body, null, 2));
if (err) return done(err);
expect(res.body).to.have.property('message').that.equals('calledNext');
expect(res.body).to.have.property('error').that.contains('query.limit');
return done();
});
});
});
describe('set errorHandler in route', function () {
var app;
before( function () {
app = express();
app.get('/users/:user', routeValidator.validate({
params: {
user: { isRequired: true, isEmail: true }
},
errorHandler: function (err, req, res) {
return res.status(400).send({
message: 'routeErrorHandler',
error: err.message
});
}
}), function (req, res) {
return res.status(200).end();
});
});
it('should do nothing different if errorHandler is set to true and validation passes', function (done) {
request(app)
.get('/users/[email protected]')
.expect(200, done);
});
it('should call errorHandler(err, req, res, next) if validation fails and errorHandler is set to true', function (done) {
request(app)
.get('/users/banana')
.expect(400, function (err, res) {
if (err) return done(err);
expect(res.body).to.have.property('message').that.equals('routeErrorHandler');
expect(res.body).to.have.property('error').that.contains('params.user');
return done();
});
});
});
describe('when configured scope is undefined', function () {
var app;
before( function () {
app = express();
// req.body will always be undefined because there is no body parser
app.post('/items', routeValidator.validate({
body: {
name: { isRequired: true }
}
}), function (req, res) {
return res.status(200).end();
});
app.post('/users', routeValidator.validate({
body: {
email: { isRequired: false }
}
}), function (req, res) {
return res.status(200).end();
});
});
it('should invalidate the request if config has required field', function (done) {
request(app)
.post('/items')
.send({
name: 'Chainsaw'
})
.expect(400, function (err, res) {
if (err) return done(err);
expect(res.body).to.have.property('error').that.contains('body.name');
return done();
});
});
it('should not invalidate the request if config has no required fields', function (done) {
request(app)
.post('/users')
.expect(200, done);
});
});
describe('prop.message is set', function () {
var app, message = 'Custom Message';
before( function () {
app = express();
app.get('/items/:item', routeValidator.validate({
params: {
item: { isRequired: true, isMongoId: false, message: message }
}
}), function (req, res) {
return res.status(200).end();
});
});
it('should send prop.message as a custom error message', function (done) {
request(app)
.get('/items/abc')
.expect(400, function (err, res) {
if (err) return done(err);
expect(res.body).to.have.property('error').that.equals(message);
return done();
});
});
});
});
/***********
NEEDS TO TEST PRECENDENCE OF ERROR HANDLING DECISIONS
1. config.errorHandler
2. config.callNext
3. routeValidator._callNext
4. routeValidator._errorHandler
Test Cases
1. callNext set to false in config, true in app
***********/
describe('#set(key, value)', function () {
var errorHandler, callNext;
before( function () {
errorHandler = routeValidator._errorHandler;
callNext = routeValidator._callNext;
});
after( function () {
routeValidator._errorHandler = errorHandler;
routeValidator._callNext = callNext;
});
it('should allow setting callNext to pass err into next rather than default behavior', function () {
routeValidator.set('callNext', true);
expect(routeValidator).to.have.property('_callNext').that.is.true;
});
it('should allow setting the errorHandler to override default behavior', function () {
var newErrorHandler = function (err, req, res) {
return res.status(404).send({
message: 'errorHandled'
});
};
routeValidator.set('errorHandler', newErrorHandler);
expect(routeValidator).to.have.property('_errorHandler').that.equals(newErrorHandler);
});
it('should do nothing if key is not recognized', function () {
routeValidator.set('invalid', 'banana');
expect(routeValidator).to.not.have.property('invalid');
});
});
describe('#addValidator(name, fn)', function () {
var isNumeric, app;
before( function () {
isNumeric = routeValidator._validators.isNumeric;
app = express();
app.use(bodyParser.json());
app.post('/users', routeValidator.validate({
body: {
name: { isRequired: true },
age: { isRequired: true, isValidAge: true },
email: { isRequired: true, isEmail: true }
}
}), function (req, res) {
return res.status(200).end();
});
app.put('/users/:user', routeValidator.validate({
body: {
age: { isNumeric: true, isRequired: true }
}
}), function (req, res) {
return res.status(200).end();
});
});
after( function () {
routeValidator._validators.isNumeric = isNumeric;
});
it('should not add validator or break if not passed a function', function () {
routeValidator.addValidator('isNotFunction', 'banana');
expect(routeValidator._validators).to.not.have.property('isNotFunction');
});
it('should allow adding a custom validator', function (done) {
routeValidator.addValidator('isValidAge', function (str) {
var age = +str;
return age ? (age > 0 && age < 120) : false;
});
expect(routeValidator._validators).to.have.property('isValidAge');
async.parallel([
function (callback) {
request(app)
.post('/users')
.send({
name: 'Billy',
age: 23,
email: '[email protected]'
})
.expect(200, function (err, res) {
console.log(JSON.stringify(res.body,null,2));
return done(err);
});
},
function (callback) {
request(app)
.post('/users')
.send({
name: 'Invalid',
age: 2000,
email: '[email protected]'
})
.expect(400, function (err, res) {
if (err) return callback(err);
expect(res.body).to.have.property('error').that.contains('body.age');
return callback();
});
}
], done);
});
it('should override existing validators of the same name', function (done) {
// Overrides existing validator
routeValidator.addValidator('isNumeric', function (str) {
var validNumbers = ['one', 'two', 'three', 'four', 'five', 'six', 'seven'];
return validNumbers.indexOf(str) !== -1;
});
expect(routeValidator._validators).to.have.property('isNumeric');
async.parallel([
function (callback) {
request(app)
.put('/users/billy')
.send({
age: 'seven'
})
.expect(200, callback);
},
function (callback) {
request(app)
.put('/users/invalid')
.send({
age: 20
})
.expect(400, function (err, res) {
if (err) return callback(err);
expect(res.body).to.have.property('error').that.contains('body.age');
return callback();
});
}
], done);
});
});
describe('#addValidators(obj)', function () {
var isNumeric, app;
before( function () {
isNumeric = routeValidator._validators.isNumeric;
app = express();
app.use(bodyParser.json());
app.post('/turtles', routeValidator.validate({
body: {
size: { isRequired: true, isNumeric: true },
weight: { isRequired: true, isTurtleWeight: true },
name: { isRequired: true }
}
}), function (req, res) {
return res.status(200).end();
});
});
after( function () {
routeValidator._validators.isNumeric = isNumeric;
});
it('should not break if passing in an empty object', function () {
routeValidator.addValidators({});
});
it('should not add validator or break if key is not function', function () {
routeValidator.addValidators({
// Adds invalid
isNotValidator: 'oops'
});
expect(routeValidator._validators).to.not.have.property('isNotValidator');
});
it('should allow passing in an object of validators and set them internally', function (done) {
routeValidator.addValidators({
// Overrides existing
isNumeric: function (str) {
var validNumbers = ['eight', 'nine', 'ten'];
return validNumbers.indexOf(str) !== -1;
},
// Adds new
isTurtleWeight: function (str) {
var weight = +str;
return weight ? (weight > 10 && weight < 800) : false;
}
});
expect(routeValidator._validators).to.have.property('isNumeric');
expect(routeValidator._validators).to.have.property('isTurtleWeight');
async.parallel([
function (callback) {
request(app)
.post('/turtles')
.send({
size: 'nine',
weight: 500,
name: 'Stanley'
})
.expect(200, callback);
},
function (callback) {
request(app)
.post('/turtles')
.send({
size: 9,
weight: 600,
name: 'Loopie'
})
.expect(400, function (err, res) {
if (err) return callback(err);
expect(res.body).to.have.property('error').that.contains('body.size');
return callback();
});
},
function (callback) {
request(app)
.post('/turtles')
.send({
size: 'ten',
weight: 60000,
name: 'Loopie'
})
.expect(400, function (err, res) {
if (err) return callback(err);
expect(res.body).to.have.property('error').that.contains('body.weight');
return callback();
});
}
], done);
});
});
describe('addCoercer()', function () {
var app;
before( function () {
app = express();
app.get('/turtles', routeValidator.validate({
query: {
sizeStr: { isRequired: false, toLowerCaseSize: true, isIn: ['eight', 'nine', 'ten'] },
weightRange: { isRequired: false, isWeightRange: true, toRangeArray: true }
}
}), function (req, res) {
if (req.query.weightRange) {
// Make sure that it was converted properly
// '100-500' -> [100, 500]
var range = req.query.weightRange;
if (!(range instanceof Array) || range.length !== 2 ||
typeof range[0] !== 'number' || typeof range[1] !== 'number') {
return res.status(500).end();
}
}
return res.status(200).end();
});
});
describe('config.stage === "before"', function () {
it('should be able to add a custom coercer run before validation', function (done) {
routeValidator.addCoercer('toLowerCaseSize', {
stage: 'before',
coerce: function (str) {
return str.toLowerCase();
}
});
expect(routeValidator._before).to.have.property('toLowerCaseSize');
async.parallel([
function (callback) {
request(app)
.get('/turtles')
.query({
sizeStr: 'EIGHT'
})
.expect(200, callback);
},
function (callback) {
request(app)
.get('/turtles')
.query({
sizeStr: 'nine'
})
.expect(200, callback);
}
], done);
});
it('should not add coercer if it is not a function', function () {
routeValidator.addCoercer('apple', {
stage: 'before',
coerce: 'apple'
});
expect(routeValidator._before).to.not.have.property('apple');
});
});
describe('config.stage === "after"', function () {
it('should be able to add a custom coercer run before validation', function (done) {
routeValidator.addValidator('isWeightRange', function (str) {
var arr = str.split('-');
return +arr[0] && +arr[1];
});
routeValidator.addCoercer('toRangeArray', {
stage: 'after',
coerce: function (str) {
var arr = str.split('-');
arr[0] = +arr[0];
arr[1] = +arr[1];
return arr;
}
});
expect(routeValidator._after).to.have.property('toRangeArray');
async.parallel([
function (callback) {
request(app)
.get('/turtles')
.query({
weightRange: '500'
})
.expect(400, callback);
},
function (callback) {
request(app)
.get('/turtles')
.query({
weightRange: '100-500'
})
.expect(200, callback);
}
], done);
});
it('should not add coercer if it is not a function', function () {
routeValidator.addCoercer('peach', {
stage: 'after',
coerce: 'peach'
});
expect(routeValidator._before).to.not.have.property('peach');
});
});
describe('invalid config.stage', function () {
it('should do nothing if config.stage is invalid', function () {
routeValidator.addCoercer('banana', {
stage: 'banana',
coerce: function () {
return 'banana';
}
});
expect(routeValidator._before).to.not.have.property('banana');
});
it('should do nothing if config.stage is not set', function () {
routeValidator.addCoercer('pear', {
coerce: function () {
return 'pear';
}
});
expect(routeValidator._before).to.not.have.property('pear');
});
});
});
describe('#addCoercers(obj)', function () {
var toDate, app;
before( function () {
toDate = routeValidator._before.toDate;
app = express();
app.get('/turtles', routeValidator.validate({
query: {
slug: { isRequired: false, toLowerCase: true, replaceSpaces: true },
minDate: { toDate: true }
}
}), function (req, res) {
if (req.query.slug && req.query.slug.indexOf(' ') !== -1) {
return res.status(500).end();
}
return res.status(200).end();
});
});
after( function () {
routeValidator._before.toDate = toDate;
});
it('should not break if passing in an empty object', function () {
routeValidator.addCoercers({});
});
it('should not add coercer or break if key is not a config object', function () {
routeValidator.addCoercers({
// Adds invalid
isNotCoercer: 'oops',
alsoNotCoercer: {
stage: 'notAstage',
coerce: function () {
return true;
}
},
andNotOne: {
stage: 'before',
coerce: 'funky'
}
});
expect(routeValidator._before).to.not.have.property('isNotCoercer');
expect(routeValidator._after).to.not.have.property('isNotCoercer');
expect(routeValidator._before).to.not.have.property('alsoNotCoercer');
expect(routeValidator._after).to.not.have.property('alsoNotCoercer');
expect(routeValidator._before).to.not.have.property('addNotOne');
expect(routeValidator._after).to.not.have.property('addNotOne');
});
it('should allow passing in an object of validators and set them internally', function (done) {
routeValidator.addCoercers({
// Overrides existing
toDate: {
stage: 'after',
coerce: function () {
return 'date';
}
},
// Adds new
toLowerCase: {
stage: 'before',
coerce: function (str) {
return str.toLowerCase();
}
},
replaceSpaces: {
stage: 'after',
coerce: function (str) {
return str.replace(/\s/g, '-');
}
}
});
expect(routeValidator._after).to.have.property('toDate');
expect(routeValidator._before).to.have.property('toLowerCase');
expect(routeValidator._after).to.have.property('replaceSpaces');
async.parallel([
function (callback) {
request(app)
.get('/turtles')
.query({
minDate: new Date()
})
.expect(200, callback);
},
function (callback) {
request(app)
.get('/turtles')
.query({
name: 'Mr Turtles'
})
.expect(200, callback);
},
function (callback) {
request(app)
.get('/turtles')
.query({
slug: 'My Sweet Turtle'
})
.expect(200, callback);
}
], done);
});
});
}); |
'use strict';
var async = require('async');
var _ = require('lodash');
var yamlReader = require('./yaml-reader/yaml-reader');
var fliprValidation = require('flipr-validation');
module.exports = validateConfig;
function validateConfig(options, cb) {
var validateOptions = {
rules: options.rules,
};
async.auto({
config: _.partial(yamlReader, options),
validate: ['config', function(callback, results){
validateOptions.config = results.config;
callback(null, fliprValidation(validateOptions));
}]
}, function(err, results){
if(err)
return void cb(err);
return void cb(null, results.validate);
});
} |
const { Device, UdpServer } = require('tplink-smarthome-simulator');
function startSimulator() {
const port = null;
const emeter = {
realtime: {
current: 1.1256,
voltage: 122.049119,
power: 3.14,
total: 51.493,
},
};
const devices = [];
devices.push(
new Device({
port,
model: 'hs100',
data: { alias: 'Mock HS100', mac: 'aa:aa:aa:8f:58:18', deviceId: 'A100' },
})
);
devices.push(
new Device({
port,
model: 'hs105',
data: { alias: 'Mock HS105', mac: 'aa:aa:aa:d8:bf:d4', deviceId: 'A105' },
})
);
devices.push(
new Device({
port,
model: 'hs110',
data: {
alias: 'Mock HS110',
mac: 'aa:aa:aa:0d:91:8c',
deviceId: 'A110',
emeter,
},
})
);
devices.push(
new Device({
port,
model: 'hs110v2',
data: {
alias: 'Mock HS110v2',
mac: 'aa:aa:aa:B7:F3:50',
deviceId: 'A110F2',
emeter,
},
})
);
devices.push(
new Device({
port,
model: 'hs200',
data: { alias: 'Mock HS200', mac: 'aa:aa:aa:46:b4:24', deviceId: 'A200' },
})
);
devices.push(
new Device({
port,
model: 'hs220',
data: { alias: 'Mock HS220', mac: 'aa:aa:aa:46:b5:34', deviceId: 'A220' },
})
);
devices.push(
new Device({
port,
model: 'hs300',
data: {
alias: 'Mock HS300',
mac: 'aa:aa:aa:EE:0C:9D',
deviceId: 'A300',
emeter,
},
})
);
devices.push(
new Device({
port,
model: 'lb100',
data: {
alias: 'Mock LB100',
mac: 'aa:aa:aa:49:ca:42',
deviceId: 'BB100',
},
})
);
devices.push(
new Device({
port,
model: 'lb120',
data: {
alias: 'Mock LB120',
mac: 'aa:aa:aa:90:9b:da',
deviceId: 'BB120',
},
})
);
devices.push(
new Device({
port,
model: 'lb130',
data: {
alias: 'Mock LB130',
mac: 'aa:aa:aa:b1:04:d3',
deviceId: 'BB130',
},
})
);
devices.forEach((d) => {
d.start();
});
UdpServer.start();
}
module.exports = { startSimulator };
|
function foo() {
var x = 2;
var xxx = 1;
if (xxx) {
console.log(xxx + x);
}
}
|
const Room = ({routeParams}) => <h1>{routeParams.name} Room</h1>
module.exports = Room |
'use strict';
var storageKey = 'VN_TRANSLATE';
// ReSharper disable once InconsistentNaming
function Translate($translate, $translatePartialLoader, storage, options, disableTranslations) {
this.$translate = $translate;
this.$translatePartialLoader = $translatePartialLoader;
this.storage = storage;
this.disableTranslations = disableTranslations;
this.configure(angular.extend(options, this.getConfig()));
this.addPart = $translatePartialLoader.addPart;
}
Translate.prototype.getConfig = function() {
var storage = this.storage;
var config = JSON.parse(storage.get(storageKey)) || {};
var lang = storage.get('NG_TRANSLATE_LANG_KEY');
if (!this.disableTranslations && lang && lang !== 'undefined') {
config.lang = lang;
}
return config;
};
Translate.prototype.configure = function(config) {
config = angular.extend(this.getConfig(), config);
this.storage.set(storageKey, JSON.stringify(config));
this.$translate.use(config.lang);
};
Translate.prototype.addParts = function() {
if (this.disableTranslations) {
return true;
}
var loader = this.$translatePartialLoader;
angular.forEach(arguments, function(part) {
loader.addPart(part);
});
return this.$translate.refresh();
};
function TranslateProvider($translateProvider) {
this.$translateProvider = $translateProvider;
this.setPreferredLanguage = $translateProvider.preferredLanguage;
}
TranslateProvider.prototype.$get = [
'$translate', '$translatePartialLoader', 'storage',
function($translate, $translatePartialLoader, storage) {
var options = this.options;
return new Translate($translate, $translatePartialLoader, storage, {
region: options.region,
lang: options.lang,
country: options.country
}, options.disableTranslations);
}
];
TranslateProvider.prototype.configure = function(options) {
options = angular.extend({ region: 'us', lang: 'en', country: 'us' }, options);
if (options.lang) {
this.setPreferredLanguage(options.lang);
}
this.options = options;
if (!options.disableTranslations) {
this.initTranslateProvider(options.lang);
}
};
TranslateProvider.prototype.initTranslateProvider = function(lang) {
var $translateProvider = this.$translateProvider;
$translateProvider.useLoader('$translatePartialLoader', {
urlTemplate: '/translations/{part}/{lang}.json'
});
if (lang === 'en') {
$translateProvider.useMessageFormatInterpolation();
}
$translateProvider.useMissingTranslationHandlerLog();
$translateProvider.useLocalStorage();
};
angular.module('Volusion.toolboxCommon')
.provider('translate', ['$translateProvider', TranslateProvider]);
|
import Database from "almaden";
import Collection from "../../lib/collection.js";
import Model from "../../../";
import {ModelQuery} from "../../lib/modelFinder.js";
import {User} from "../testClasses.js";
import databaseConfig from "../databaseConfig.json";
let userFixtures = require("../fixtures/users.json");
describe("Model.find", () => {
let users,
userCollection;
before(() => {
Model.database = new Database(databaseConfig);
Model.database.mock({}); // Catch-all for database
});
after(() => {
// Remove database from model to prevent
// polluting another file via the prototype
Model.database = undefined;
});
beforeEach(done => {
userCollection = new Collection(User);
userFixtures.forEach((userFiture) => {
userCollection.push(new User(userFiture));
});
Model.database.mock({
"select * from `users` where `mom_id` = 1":
userFixtures
});
User
.find
.where("momId", "=", 1)
.results((error, fetchedUsers) => {
users = fetchedUsers;
done();
});
});
it("should return a ModelQuery instance", () => {
User.find.should.be.instanceOf(ModelQuery);
});
it("should return a collection", () => {
users.should.be.instanceOf(Collection);
});
it("should return the right collection", () => {
users.should.eql(userCollection);
});
it("should allow to search all models that matchs a certain condition", () => {
users.length.should.equal(5);
});
describe(".all", () => {
beforeEach(done => {
User.find
.all
.where("momId", 1)
.results((error, fetchedUsers) => {
users = fetchedUsers;
done();
});
});
it("should return just all users matching the condition", () => {
users.length.should.equal(5);
});
});
describe(".deleted", () => {
class SoftUser extends Model {
initialize() {
this.softDelete;
}
}
beforeEach(done => {
Model.database.mock({
"select * from `soft_users` where `mom_id` = 1 and `deleted_at` is not null":
userFixtures
});
SoftUser.find
.all
.where("momId", 1)
.deleted
.results((error, fetchedUsers) => {
users = fetchedUsers;
done();
});
});
it("should return just all users matching the condition", () => {
users.length.should.equal(5);
});
});
describe("(with a different database for a model)", () => {
class Car extends Model {}
let car,
database,
query;
describe("(static way)", () => {
beforeEach(() => {
database = new Database(databaseConfig);
Car.database = database;
query = database.spy("select * from `cars`", []);
car = new Car();
});
it("should use the specific model class database", (done) => {
Car.find.all.results(() => {
query.callCount.should.equal(1);
done();
});
});
});
describe("(instance way)", () => {
beforeEach(() => {
database = new Database(databaseConfig);
Car.database = null;
car = new Car({id: 2}, {database: database});
query = database.spy("select * from `cars` where `id` = 2 limit 1", []);
});
it("should use the specific model instance database", (done) => {
car.fetch(() => {
query.callCount.should.equal(1);
done();
});
});
});
});
});
|
this.recline = this.recline || {};
this.recline.Backend = this.recline.Backend || {};
this.recline.Backend.Memory = this.recline.Backend.Memory || {};
(function(my, recline) {
"use strict";
my.__type__ = 'memory';
// private data - use either jQuery or Underscore Deferred depending on what is available
var Deferred = (typeof jQuery !== "undefined" && jQuery.Deferred) || _.Deferred;
// ## Data Wrapper
//
// Turn a simple array of JS objects into a mini data-store with
// functionality like querying, faceting, updating (by ID) and deleting (by
// ID).
//
// @param records list of hashes for each record/row in the data ({key:
// value, key: value})
// @param fields (optional) list of field hashes (each hash defining a field
// as per recline.Model.Field). If fields not specified they will be taken
// from the data.
my.Store = function(records, fields) {
var self = this;
this.records = records;
// backwards compatability (in v0.5 records was named data)
this.data = this.records;
if (fields) {
this.fields = fields;
} else {
if (records) {
this.fields = _.map(records[0], function(value, key) {
return {id: key, type: 'string'};
});
}
}
this.update = function(doc) {
_.each(self.records, function(internalDoc, idx) {
if(doc.id === internalDoc.id) {
self.records[idx] = doc;
}
});
};
this.remove = function(doc) {
var newdocs = _.reject(self.records, function(internalDoc) {
return (doc.id === internalDoc.id);
});
this.records = newdocs;
};
this.save = function(changes, dataset) {
var self = this;
var dfd = new Deferred();
// TODO _.each(changes.creates) { ... }
_.each(changes.updates, function(record) {
self.update(record);
});
_.each(changes.deletes, function(record) {
self.remove(record);
});
dfd.resolve();
return dfd.promise();
},
this.query = function(queryObj) {
var dfd = new Deferred();
var numRows = queryObj.size || this.records.length;
var start = queryObj.from || 0;
var results = this.records;
results = this._applyFilters(results, queryObj);
results = this._applyFreeTextQuery(results, queryObj);
// TODO: this is not complete sorting!
// What's wrong is we sort on the *last* entry in the sort list if there are multiple sort criteria
_.each(queryObj.sort, function(sortObj) {
var fieldName = sortObj.field;
results = _.sortBy(results, function(doc) {
var _out = doc[fieldName];
return _out;
});
if (sortObj.order == 'desc') {
results.reverse();
}
});
var facets = this.computeFacets(results, queryObj);
var out = {
total: results.length,
hits: results.slice(start, start+numRows),
facets: facets
};
dfd.resolve(out);
return dfd.promise();
};
// in place filtering
this._applyFilters = function(results, queryObj) {
var filters = queryObj.filters;
// register filters
var filterFunctions = {
term : term,
terms : terms,
range : range,
geo_distance : geo_distance
};
var dataParsers = {
integer: function (e) { return parseFloat(e, 10); },
'float': function (e) { return parseFloat(e, 10); },
number: function (e) { return parseFloat(e, 10); },
string : function (e) { return e.toString(); },
date : function (e) { return moment(e).valueOf(); },
datetime : function (e) { return new Date(e).valueOf(); }
};
var keyedFields = {};
_.each(self.fields, function(field) {
keyedFields[field.id] = field;
});
function getDataParser(filter) {
var fieldType = keyedFields[filter.field].type || 'string';
return dataParsers[fieldType];
}
// filter records
return _.filter(results, function (record) {
var passes = _.map(filters, function (filter) {
return filterFunctions[filter.type](record, filter);
});
// return only these records that pass all filters
return _.all(passes, _.identity);
});
// filters definitions
function term(record, filter) {
var parse = getDataParser(filter);
var value = parse(record[filter.field]);
var term = parse(filter.term);
return (value === term);
}
function terms(record, filter) {
var parse = getDataParser(filter);
var value = parse(record[filter.field]);
var terms = parse(filter.terms).split(",");
return (_.indexOf(terms, value) >= 0);
}
function range(record, filter) {
var fromnull = (_.isUndefined(filter.from) || filter.from === null || filter.from === '');
var tonull = (_.isUndefined(filter.to) || filter.to === null || filter.to === '');
var parse = getDataParser(filter);
var value = parse(record[filter.field]);
var from = parse(fromnull ? '' : filter.from);
var to = parse(tonull ? '' : filter.to);
// if at least one end of range is set do not allow '' to get through
// note that for strings '' <= {any-character} e.g. '' <= 'a'
if ((!fromnull || !tonull) && value === '') {
return false;
}
return ((fromnull || value >= from) && (tonull || value <= to));
}
function geo_distance() {
// TODO code here
}
};
// we OR across fields but AND across terms in query string
this._applyFreeTextQuery = function(results, queryObj) {
if (queryObj.q) {
var terms = queryObj.q.split(' ');
var patterns=_.map(terms, function(term) {
return new RegExp(term.toLowerCase());
});
results = _.filter(results, function(rawdoc) {
var matches = true;
_.each(patterns, function(pattern) {
var foundmatch = false;
_.each(self.fields, function(field) {
var value = rawdoc[field.id];
if ((value !== null) && (value !== undefined)) {
value = value.toString();
} else {
// value can be null (apparently in some cases)
value = '';
}
// TODO regexes?
foundmatch = foundmatch || (pattern.test(value.toLowerCase()));
// TODO: early out (once we are true should break to spare unnecessary testing)
// if (foundmatch) return true;
});
matches = matches && foundmatch;
// TODO: early out (once false should break to spare unnecessary testing)
// if (!matches) return false;
});
return matches;
});
}
return results;
};
this.computeFacets = function(records, queryObj) {
var facetResults = {};
if (!queryObj.facets) {
return facetResults;
}
_.each(queryObj.facets, function(query, facetId) {
// TODO: remove dependency on recline.Model
facetResults[facetId] = new recline.Model.Facet({id: facetId}).toJSON();
facetResults[facetId].termsall = {};
});
// faceting
_.each(records, function(doc) {
_.each(queryObj.facets, function(query, facetId) {
var fieldId = query.terms.field;
var val = doc[fieldId];
var tmp = facetResults[facetId];
if (val) {
tmp.termsall[val] = tmp.termsall[val] ? tmp.termsall[val] + 1 : 1;
} else {
tmp.missing = tmp.missing + 1;
}
});
});
_.each(queryObj.facets, function(query, facetId) {
var tmp = facetResults[facetId];
var terms = _.map(tmp.termsall, function(count, term) {
return { term: term, count: count };
});
tmp.terms = _.sortBy(terms, function(item) {
// want descending order
return -item.count;
});
tmp.terms = tmp.terms.slice(0, 10);
});
return facetResults;
};
};
}(this.recline.Backend.Memory, this.recline));
|
var fs = require('fs');
/*var mulu = fs.readFileSync('./mulu.html','utf8');
var sutra = mulu.replace(/<sutra>/g,'#<sutra>').split(/#/);
var vol = function(sutra){
for (var i in sutra){
var vol = sutra[i].match(/<vol>(.+)<\/vol>/);
var sutraid = sutra[i].match(/<sutraid n="(.+)"\/>/);
if (vol == null || sutraid == null) {
console.log('');
} else {
console.log(sutraid[1],vol[0]);
}
}
}
var cname = function(sutra){
for (var i in sutra){
var cname = sutra[i].match(/<taisho.+chi="(.+)\/">/g);
var sutraid = sutra[i].match(/<sutraid n="(.+)"\/>/);
if (cname == null || sutraid == null) {
console.log('');
} else {
console.log(sutraid[1],cname.map(function(cname){
var chiname = cname.replace(/<taisho.+chi="(.+)\/>/g,"$1");
return chiname;
}));
}
}
}*/
///////////////////////////////////////////////////////////
fs.readdir('input',function(err,files){
if (files[0] == ".DS_Store") files.splice(0,1);
//console.log(files,files.length);
files.map(persutra);
})
var persutra = function(fn){
var text = fs.readFileSync('./input/'+fn,'utf8');
var sutra = JSON.parse(text);
console.log(sutraid(fn));
console.log(findeachtag(sutra));
//var sutra = arr[3]['མདོ་མིང་།'];
//console.log(sutra);
}
var sutraid = function(id){
var sutraid = id.match(/J\d+((\([a-z]\))|(\,\d+))*/)[0];
return ('<sutra>' + breakline + '<sutraid n="' + sutraid + '"/>');
}
var findeachtag = function(arr){
var trans = 'translator';
var tname = arr[3]['མདོ་མིང་།'];
var aname = arr[3]['མདོ་མིང་གཞན།'];
var sname = arr[3]['རྒྱ་གར་མདོ་མིང་།'];
var homage = arr[3]['བསྒྱུར་ཕྱག'];
var subject = arr[3]['བརྗོད་བྱ།'];
var yana = arr[3]['ཐེག་པ།'];
var charka = arr[3]['དཀའ། འཁོར་ལོ།'];
var location = arr[3]['གནས་ཕུན་སུམ་ཚོགས་པ།'];
var audience = arr[3]['འཁོར་ཕུན་སུམ་ཚོགས་པ།'];
var aurthor = arr[3]['སྟོན་པ་ཕུན་སུམ་ཚོགས་པ།'];
var requester = arr[3]['ཞུ་བ་པོ་ཕུན་སུམ་ཚོགས་པ།'];
var dharma = arr[3]['ཆོས་ཕུན་སུམ་ཚོགས་པ།'];
var purpose = arr[3]['ཆོས་ཀྱི་དགོས་དོན།'];
var collect = arr[3]['བསྡུས་པའི་དོན། ལེའུ།'];
var bampo = arr[3]['བམ་པོ། ཤོ་ལོ་ཀ'];
var relation = arr[3]['མཚམས་སྦྱར་བའི་གོ་རིམ།'];
var debate = arr[3]['རྒལ་ལན།'];
var translator = arr[3]['ལོ་ཙཱ་བ།'];
var reviser = arr[3]['ཞུ་དག་པ།'];
//var cname = arr[3]['རྒྱ་ནག་མདོ་མིང་།'];
if (arr[1]['ལོ་ཙཱ་བ།'] == 'translator_revisor' || arr[2]['ལོ་ཙཱ་བ།'] == 'translator_revisor') trans = 'translator_reviser';
return "<tname>" + tname + "</tname>" + breakline + "<aname>" + aname + "</aname>" + breakline +
"<sname>" + sname + "</sname>" + breakline + "<cname></cname>" + breakline + "<vol></vol>" + breakline +
"<homage>" + homage + "</homage>" + breakline + "<subject>" + subject + "</subject>" + breakline +
"<yana>" + yana + "</yana>" + breakline + "<charka>" + charka + "</charka>" + breakline + "<location>" +
location + "</location>" + breakline + "<audience>" + audience + "</audience>" + breakline + "<aurthor>" +
aurthor + "</aurthor>" + breakline + "<requester>" + requester + "</requester>" + breakline + "<dharma>" +
dharma + "</dharma>" + breakline + "<purpose>" + purpose + "</purpose>" + breakline + "<collect>" + collect +
"</collect>" + breakline + "<bampo>" + bampo + "</bampo>" + breakline + "<relation>" + relation + "</relation>" +
breakline + "<debate>" + debate + "</debate>" + breakline + "<" + trans + ">" + translator + "</" + trans + ">" +
breakline + "<reviser>" + reviser + "</reviser>" + breakline + "</sutra>";
}
var breakline = RegExp('\n');
/*var writexml = function(xml){
fs.writeFileSync('bio.xml',JSON.stringify(xml,'',' '),'utf8');
}*/
|
/*
* grunt-simple-templates
* https://github.com/jclem/grunt-simple-templates
*
* Copyright (c) 2013 Jonathan Clem
* Licensed under the MIT license.
*/
'use strict';
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
jshint: {
all: [
'Gruntfile.js',
'tasks/*.js',
'<%= nodeunit.tests %>',
],
options: {
jshintrc: '.jshintrc',
},
},
// Before generating any new files, remove any previously-created files.
clean: {
tests: ['tmp'],
},
// Configuration to be run (and then tested).
templates: {
default_options: {
src: "test/fixtures/",
dest: "tmp/default_options"
},
custom_options: {
src: "test/fixtures/",
dest: "tmp/custom_options",
options: {
namespace: "CUSTOM_TEMPLATES",
extension: "hbs"
}
}
},
// Unit tests.
nodeunit: {
tests: ['test/*_test.js'],
},
});
// Actually load this plugin's task(s).
grunt.loadTasks('tasks');
// These plugins provide necessary tasks.
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-nodeunit');
// Whenever the "test" task is run, first clean the "tmp" dir, then run this
// plugin's task(s), then test the result.
grunt.registerTask('test', ['clean', 'templates', 'nodeunit']);
// By default, lint and run all tests.
grunt.registerTask('default', ['jshint', 'test']);
};
|
import { setData } from '@progress/kendo-angular-intl';
setData({
name: "fr-SN",
likelySubtags: {
fr: "fr-Latn-FR"
},
identity: {
language: "fr",
territory: "SN"
},
territory: "SN",
calendar: {
patterns: {
d: "dd/MM/y",
D: "EEEE d MMMM y",
m: "d MMM",
M: "d MMMM",
y: "MMM y",
Y: "MMMM y",
F: "EEEE d MMMM y HH:mm:ss",
g: "dd/MM/y HH:mm",
G: "dd/MM/y HH:mm:ss",
t: "HH:mm",
T: "HH:mm:ss",
s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss",
u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'"
},
dateTimeFormats: {
full: "{1} 'à' {0}",
long: "{1} 'à' {0}",
medium: "{1} 'à' {0}",
short: "{1} {0}",
availableFormats: {
d: "d",
E: "E",
Ed: "E d",
Ehm: "E h:mm a",
EHm: "E HH:mm",
Ehms: "E h:mm:ss a",
EHms: "E HH:mm:ss",
Gy: "y G",
GyMMM: "MMM y G",
GyMMMd: "d MMM y G",
GyMMMEd: "E d MMM y G",
h: "h a",
H: "HH 'h'",
hm: "h:mm a",
Hm: "HH:mm",
hms: "h:mm:ss a",
Hms: "HH:mm:ss",
hmsv: "h:mm:ss a v",
Hmsv: "HH:mm:ss v",
hmv: "h:mm a v",
Hmv: "HH:mm v",
M: "L",
Md: "dd/MM",
MEd: "E dd/MM",
MMM: "LLL",
MMMd: "d MMM",
MMMEd: "E d MMM",
MMMMd: "d MMMM",
"MMMMW-count-one": "'semaine' W 'de' MMM",
"MMMMW-count-other": "'semaine' W 'de' MMM",
ms: "mm:ss",
y: "y",
yM: "MM/y",
yMd: "dd/MM/y",
yMEd: "E dd/MM/y",
yMMM: "MMM y",
yMMMd: "d MMM y",
yMMMEd: "E d MMM y",
yMMMM: "MMMM y",
yQQQ: "QQQ y",
yQQQQ: "QQQQ y",
"yw-count-one": "'semaine' w 'de' y",
"yw-count-other": "'semaine' w 'de' y"
}
},
timeFormats: {
full: "HH:mm:ss zzzz",
long: "HH:mm:ss z",
medium: "HH:mm:ss",
short: "HH:mm"
},
dateFormats: {
full: "EEEE d MMMM y",
long: "d MMMM y",
medium: "d MMM y",
short: "dd/MM/y"
},
days: {
format: {
abbreviated: [
"dim.",
"lun.",
"mar.",
"mer.",
"jeu.",
"ven.",
"sam."
],
narrow: [
"D",
"L",
"M",
"M",
"J",
"V",
"S"
],
short: [
"di",
"lu",
"ma",
"me",
"je",
"ve",
"sa"
],
wide: [
"dimanche",
"lundi",
"mardi",
"mercredi",
"jeudi",
"vendredi",
"samedi"
]
},
"stand-alone": {
abbreviated: [
"dim.",
"lun.",
"mar.",
"mer.",
"jeu.",
"ven.",
"sam."
],
narrow: [
"D",
"L",
"M",
"M",
"J",
"V",
"S"
],
short: [
"di",
"lu",
"ma",
"me",
"je",
"ve",
"sa"
],
wide: [
"dimanche",
"lundi",
"mardi",
"mercredi",
"jeudi",
"vendredi",
"samedi"
]
}
},
months: {
format: {
abbreviated: [
"janv.",
"févr.",
"mars",
"avr.",
"mai",
"juin",
"juil.",
"août",
"sept.",
"oct.",
"nov.",
"déc."
],
narrow: [
"J",
"F",
"M",
"A",
"M",
"J",
"J",
"A",
"S",
"O",
"N",
"D"
],
wide: [
"janvier",
"février",
"mars",
"avril",
"mai",
"juin",
"juillet",
"août",
"septembre",
"octobre",
"novembre",
"décembre"
]
},
"stand-alone": {
abbreviated: [
"janv.",
"févr.",
"mars",
"avr.",
"mai",
"juin",
"juil.",
"août",
"sept.",
"oct.",
"nov.",
"déc."
],
narrow: [
"J",
"F",
"M",
"A",
"M",
"J",
"J",
"A",
"S",
"O",
"N",
"D"
],
wide: [
"janvier",
"février",
"mars",
"avril",
"mai",
"juin",
"juillet",
"août",
"septembre",
"octobre",
"novembre",
"décembre"
]
}
},
quarters: {
format: {
abbreviated: [
"T1",
"T2",
"T3",
"T4"
],
narrow: [
"1",
"2",
"3",
"4"
],
wide: [
"1er trimestre",
"2e trimestre",
"3e trimestre",
"4e trimestre"
]
},
"stand-alone": {
abbreviated: [
"T1",
"T2",
"T3",
"T4"
],
narrow: [
"1",
"2",
"3",
"4"
],
wide: [
"1er trimestre",
"2e trimestre",
"3e trimestre",
"4e trimestre"
]
}
},
dayPeriods: {
format: {
abbreviated: {
midnight: "min.",
am: "AM",
noon: "midi",
pm: "PM",
morning1: "mat.",
afternoon1: "ap.m.",
evening1: "soir",
night1: "nuit"
},
narrow: {
midnight: "min.",
am: "AM",
noon: "midi",
pm: "PM",
morning1: "mat.",
afternoon1: "ap.m.",
evening1: "soir",
night1: "nuit"
},
wide: {
midnight: "minuit",
am: "AM",
noon: "midi",
pm: "PM",
morning1: "du matin",
afternoon1: "de l’après-midi",
evening1: "du soir",
night1: "de nuit"
}
},
"stand-alone": {
abbreviated: {
midnight: "min.",
am: "AM",
noon: "midi",
pm: "PM",
morning1: "mat.",
afternoon1: "ap.m.",
evening1: "soir",
night1: "nuit"
},
narrow: {
midnight: "min.",
am: "AM",
noon: "midi",
pm: "PM",
morning1: "mat.",
afternoon1: "ap.m.",
evening1: "soir",
night1: "nuit"
},
wide: {
midnight: "minuit",
am: "AM",
noon: "midi",
pm: "PM",
morning1: "matin",
afternoon1: "après-midi",
evening1: "soir",
night1: "nuit"
}
}
},
eras: {
format: {
wide: {
0: "avant Jésus-Christ",
1: "après Jésus-Christ",
"0-alt-variant": "avant l’ère commune",
"1-alt-variant": "de l’ère commune"
},
abbreviated: {
0: "av. J.-C.",
1: "ap. J.-C.",
"0-alt-variant": "AEC",
"1-alt-variant": "EC"
},
narrow: {
0: "av. J.-C.",
1: "ap. J.-C.",
"0-alt-variant": "AEC",
"1-alt-variant": "EC"
}
}
},
gmtFormat: "UTC{0}",
gmtZeroFormat: "UTC",
dateFields: {
era: {
wide: "ère",
short: "ère",
narrow: "ère"
},
year: {
wide: "année",
short: "an",
narrow: "a"
},
quarter: {
wide: "trimestre",
short: "trim.",
narrow: "trim."
},
month: {
wide: "mois",
short: "m.",
narrow: "m."
},
week: {
wide: "semaine",
short: "sem.",
narrow: "sem."
},
weekOfMonth: {
wide: "Week Of Month",
short: "Week Of Month",
narrow: "Week Of Month"
},
day: {
wide: "jour",
short: "j",
narrow: "j"
},
dayOfYear: {
wide: "Day Of Year",
short: "Day Of Year",
narrow: "Day Of Year"
},
weekday: {
wide: "jour de la semaine",
short: "jour de la semaine",
narrow: "jour de la semaine"
},
weekdayOfMonth: {
wide: "Weekday Of Month",
short: "Weekday Of Month",
narrow: "Weekday Of Month"
},
dayperiod: {
short: "cadran",
wide: "cadran",
narrow: "cadran"
},
hour: {
wide: "heure",
short: "h",
narrow: "h"
},
minute: {
wide: "minute",
short: "min",
narrow: "min"
},
second: {
wide: "seconde",
short: "s",
narrow: "s"
},
zone: {
wide: "fuseau horaire",
short: "fuseau horaire",
narrow: "fuseau horaire"
}
}
},
firstDay: 1
});
|
require('./navbar-list');
class ScrollSpy {
/**
* @param {NavBarList} navBarList
* @param {number} offset
*/
constructor (navBarList, offset) {
this.navBarList = navBarList;
this.offset = offset;
}
scrollEventListener () {
let activeLinkTarget = null;
let linkTargets = this.navBarList.getTargets();
let offset = this.offset;
let linkTargetsPastThreshold = [];
linkTargets.forEach(function (linkTarget) {
if (linkTarget) {
let offsetTop = linkTarget.getBoundingClientRect().top;
if (offsetTop < offset) {
linkTargetsPastThreshold.push(linkTarget);
}
}
});
if (linkTargetsPastThreshold.length === 0) {
activeLinkTarget = linkTargets[0];
} else if (linkTargetsPastThreshold.length === linkTargets.length) {
activeLinkTarget = linkTargets[linkTargets.length - 1];
} else {
activeLinkTarget = linkTargetsPastThreshold[linkTargetsPastThreshold.length - 1];
}
if (activeLinkTarget) {
this.navBarList.clearActive();
this.navBarList.setActive(activeLinkTarget.getAttribute('id'));
}
}
spy () {
window.addEventListener(
'scroll',
this.scrollEventListener.bind(this),
true
);
}
}
module.exports = ScrollSpy;
|
var d = require('../dtrace-provider');
var dtp = d.createDTraceProvider('test');
dtp.addProbe('probe1', 'int', 'int');
dtp.addProbe('probe2', 'int', 'int');
dtp.enable();
var dtp2 = d.createDTraceProvider('test');
dtp2.addProbe('probe3', 'int', 'int');
dtp2.addProbe('probe1', 'int', 'int');
dtp2.enable();
var dtp3 = d.createDTraceProvider('test', 'mymod1');
dtp3.addProbe('probe1', 'int', 'int');
dtp3.addProbe('probe2', 'int', 'int');
dtp3.enable();
var dtp4 = d.createDTraceProvider('test', 'mymod2');
dtp4.addProbe('probe1', 'int', 'int');
dtp4.addProbe('probe3', 'int', 'int');
dtp4.enable();
dtp.fire('probe1', function () {
return ([12, 3]);
});
dtp2.fire('probe1', function () {
return ([12, 73]);
});
dtp3.fire('probe1', function () {
return ([12, 3]);
});
dtp4.fire('probe1', function () {
return ([12, 73]);
});
|
'use strict';
// Given a bound list and the time steps,
// return the LB and UB at each timestep.
// List is in format of {LB:lb,UB:ub}
var months = ['JAN','FEB','MAR','APR','MAY','JUN','JUL','AUG','SEP','OCT','NOV','DEC'];
function getMonth(dateString) {
var m = parseInt(dateString.split('-')[1])-1;
return months[m];
}
module.exports = function(bounds, steps, callback) {
var steps_bound = [];
var month, month_cost = {};
var i,bound;
var bm = []; // Temporary bounds
// Start with no bounds
steps.forEach(function(step) {
// lb, ub, lb defined
steps_bound.push([0, null, false]);
});
var c = 0;
bounds.forEach(function(bound, index){
switch(bound.type) {
case 'NOB': // We are good
return;
case 'LBC':
for(i = 0; i < steps.length; i++) {
if( steps_bound[i][0] === null || steps_bound[i][0] < bound.bound ){
steps_bound[i][0] = bound.bound;
steps_bound[i][2] = true;
}
}
return;
case 'LBM':
case 'LBT':
var b;
bm = {};
bound.bound.forEach(function(b) {
bm[b[0]] = b[1];
});
for(i = 0; i < steps.length; i++) {
// Almost the same code for LBM and LBT
b = (bound.type === 'LBM') ? bm[getMonth(steps[i])] : bm[steps[i]];
if( (typeof b !== 'undefined' && b !== null) && (steps_bound[i][0] === null || steps_bound[i][0] < b) ){
steps_bound[i][0] = b;
steps_bound[i][2] = true;
}
}
return;
case 'UBC':
for( i = 0; i < steps.length; i++ ){
if( steps_bound[i][1] === null || steps_bound[i][1] > bound.bound) {
steps_bound[i][1] = bound.bound;
}
}
return;
case 'UBM':
case 'UBT':
bm = {};
bound.bound.forEach(function(b) {
bm[b[0]] = b[1];
});
for( i = 0; i < steps.length; i++ ){
// Almost the same code for BM and BT
b = (bound.type === 'UBM') ? bm[getMonth(steps[i])] : bm[steps[i]];
if( (typeof b !== 'undefined' && b !== null ) && (steps_bound[i][1] === null || steps_bound[i][1] > b) ) {
steps_bound[i][1] = b;
}
}
return;
case 'EQT':
var b;
bm = {};
bound.bound.forEach(function(b) {
bm[b[0]] = b[1];
});
for( i = 0; i < steps.length; i++ ){
b = bm[steps[i]];
if( typeof b !=='undefined' && b !== null) {
if( steps_bound[i][0] === null || steps_bound[i][0] < b ) {
steps_bound[i][0] = b;
steps_bound[i][2] = true;
}
if( steps_bound[i][1] === null || steps_bound[i][1] > b ) {
steps_bound[i][1] = b;
}
}
}
return;
default :
throw new Error('Bad Bound Type: '+bound.type);
}
});
return steps_bound.map((bound) => {
return {
LB : bound[0],
UB : bound[1],
LBDefined : bound[2]
}
});
};
|
/**
*
*/
define(['jquery', 'dropzone', 'pica', 'bootstrap'], function($, dropzone, pica, bootstrap) {
'use strict';
var Dropzone = window.Dropzone;
Dropzone.autoDiscover = false;
function dataURItoBlob(dataURI) {
// convert base64/URLEncoded data component to raw binary data held in a string
var byteString;
if (dataURI.split(',')[0].indexOf('base64') >= 0)
byteString = atob(dataURI.split(',')[1]);
else
byteString = unescape(dataURI.split(',')[1]);
// separate out the mime component
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
// write the bytes of the string to a typed array
var ia = new Uint8Array(byteString.length);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ia], {type:mimeString});
}
function base64ToArrayBuffer(dataURI) {
var byteString;
if (dataURI.split(',')[0].indexOf('base64') >= 0)
byteString = atob(dataURI.split(',')[1]);
else
byteString = unescape(dataURI.split(',')[1]);
// separate out the mime component
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
// write the bytes of the string to a typed array
var ia = new Uint8Array(byteString.length);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return ia.buffer;
}
function base64ToFile(dataURI, origFile) {
var byteString, mimestring;
if (dataURI.split(',')[0].indexOf('base64') !== -1) {
byteString = atob(dataURI.split(',')[1]);
} else {
byteString = decodeURI(dataURI.split(',')[1]);
}
mimestring = dataURI.split(',')[0].split(':')[1].split(';')[0];
var content = new Array();
for (var i = 0; i < byteString.length; i++) {
content[i] = byteString.charCodeAt(i);
}
var newFile = {};
try {
newFile = new File(
[new Uint8Array(content)], origFile.name, { 'type': mimestring }
);
} catch (error) {
// create Blob instead File because in IE constructor for File object doesn't exsist'
newFile = new Blob(
[new Uint8Array(content)], { 'type': mimestring }
);
newFile.name = origFile.name;
}
// Copy props set by the dropzone in the original file
var origProps = [
"upload", "status", "previewElement", "previewTemplate", "accepted"
];
$.each(origProps, function (i, p) {
newFile[p] = origFile[p];
});
return newFile;
}
// http://stackoverflow.com/questions/7584794/accessing-jpeg-exif-rotation-data-in-javascript-on-the-client-side
function getOrientation(buffer) {
var view = new DataView(buffer);
if (view.getUint16(0, false) != 0xFFD8) return -2;
var length = view.byteLength, offset = 2;
while (offset < length) {
var marker = view.getUint16(offset, false);
offset += 2;
if (marker == 0xFFE1) {
if (view.getUint32(offset += 2, false) != 0x45786966) return -1;
var little = view.getUint16(offset += 6, false) == 0x4949;
offset += view.getUint32(offset + 4, little);
var tags = view.getUint16(offset, little);
offset += 2;
for (var i = 0; i < tags; i++)
if (view.getUint16(offset + (i * 12), little) == 0x0112)
return view.getUint16(offset + (i * 12) + 8, little);
}
else if ((marker & 0xFF00) != 0xFF00) break;
else offset += view.getUint16(offset, false);
}
return -1;
}
function rotate(image, w, h, orientation) {
var canvas = document.createElement('canvas');
var ctx = canvas.getContext("2d");
var cw = image.width, ch = image.height, cx = 0, cy = 0, degree = 0;
switch (orientation) {
case -2: // not jpeg
case -1: // not defined
break;
case 1: // normal
break;
case 2: // flip
break;
case 3: // 180
degree = 180;
cx = image.width * (-1);
cy = image.height * (-1);
break;
case 4: // 180 flip
break;
case 5: // 270 flip
break;
case 6: // 270
degree = 90;
cw = image.height;
ch = image.width;
cy = image.height * (-1);
break;
case 7: // 90 flip
break;
case 8: // 90
degree = 270;
cw = image.height;
ch = image.width;
cx = image.width * (-1);
break;
}
canvas.setAttribute('width', cw);
canvas.setAttribute('height', ch);
ctx.rotate(degree * Math.PI / 180);
ctx.drawImage(image, cx, cy);
return canvas;
}
function initFileUpload() {
$('#js-completed-hint').hide();
var dropzone = new Dropzone('.dropzone', {
url: "/file/upload",
method: "post",
maxFilesize: 20,
addRemoveLinks: true,
autoQueue: false,
parallelUploads: 1
});
var uid = $('#js-content').data('uid');
$.each(window.checklist_files, function (index, value) {
var file = { name: value.filename, size: value.size };
var thumbnail = '//' + window.location.host + '/uploads/' + uid + '/' + value.filename;
dropzone.emit('addedfile', file);
if (value.filetype == 'image') {
dropzone.createThumbnailFromUrl(file, thumbnail);
} else if (value.filetype == 'document') {
dropzone.createThumbnailFromUrl(file, '/static/img/excelfile.png');
}
dropzone.emit('complete', file);
});
dropzone.on('queuecomplete', function (data) {
$('#js-completed-hint').hide();
$('#js-completed-btn').removeAttr('disabled');
});
dropzone.on('removedfile', function (origFile) {
$.post('/uploads/remove/' + uid + '/' + origFile.name);
});
dropzone.on("addedfile", function(origFile) {
var MAX_WIDTH = 800;
var MAX_HEIGHT = 800;
var reader = new FileReader();
var imageExts = ['jpg', 'jpeg', 'png', 'gif'];
$('#js-completed-btn').attr('disabled', 'disabled');
$('#js-completed-hint').show();
// Convert file to img
reader.addEventListener("load", function (event) {
var fileExt = origFile.name.split('.').pop().toLowerCase();
if ($.inArray(fileExt, imageExts) < 0) {
dropzone.enqueueFile(origFile);
return;
}
var orientation = getOrientation(base64ToArrayBuffer(event.target.result));
console.log(orientation);
var origImg = new Image();
origImg.src = event.target.result;
origImg.addEventListener("load", function (event) {
var width = event.target.width;
var height = event.target.height;
// Don't resize if it's small enough
if (width <= MAX_WIDTH && height <= MAX_HEIGHT) {
dropzone.enqueueFile(origFile);
return;
}
// Calc new dims otherwise
if (width > height) {
if (width > MAX_WIDTH) {
height *= MAX_WIDTH / width;
width = MAX_WIDTH;
}
} else {
if (height > MAX_HEIGHT) {
width *= MAX_HEIGHT / height;
height = MAX_HEIGHT;
}
}
// Resize
var canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
pica.resizeCanvas(origImg, canvas, 3, function () {
var rotatedCanvas = rotate(canvas, width, height, orientation);
var resizedFile = base64ToFile(rotatedCanvas.toDataURL(), origFile);
// Replace original with resized
var origFileIndex = dropzone.files.indexOf(origFile);
dropzone.files[origFileIndex] = resizedFile;
// Enqueue added file manually making it available for
// further processing by dropzone
dropzone.enqueueFile(resizedFile);
});
});
});
reader.readAsDataURL(origFile);
});
}
$(document).ready(function () {
initFileUpload();
var uid = $('#js-content').data('uid');
var noticeSent = $('#js-content').data('notice-sent');
$('#js-completed-btn').click(function (evt) {
if (noticeSent == 'False')
$('#myModal').modal('show');
else
$('#js-content').hide();
});
$('#js-modal-complete').click(function (evt) {
if (noticeSent == 'False') {
$.post('/checklist/complete/' + uid, { 'author_email': $('#js-author-email').val() }, function (data) {
$('#myModal').modal('hide');
$('#js-content').hide();
}).fail(function () {
$('#myModal').modal('hide');
$('#js-content').hide();
});
}
});
});
}); |
/* global sinon */
import React, { Component } from 'react';
import TestUtils from 'react-dom/test-utils';
import { expect } from 'chai';
import NotificationSystem from 'NotificationSystem';
import { positions, levels } from 'constants';
import merge from 'object-assign';
const defaultNotification = {
title: 'This is a title',
message: 'This is a message',
level: 'success'
};
const style = {
Containers: {
DefaultStyle: {
width: 600
},
tl: {
width: 800
}
}
};
describe('Notification Component', function() {
let node;
let instance;
let component;
let clock;
let notificationObj;
const ref = 'notificationSystem';
this.timeout(10000);
beforeEach(() => {
// We need to create this wrapper so we can use refs
class ElementWrapper extends Component {
render() {
return <NotificationSystem ref={ ref } style={ style } allowHTML={ true } noAnimation={ true } />;
}
}
node = window.document.createElement('div');
instance = TestUtils.renderIntoDocument(React.createElement(ElementWrapper), node);
component = instance.refs[ref];
notificationObj = merge({}, defaultNotification);
clock = sinon.useFakeTimers();
});
afterEach(() => {
clock.restore();
});
it('should be rendered', done => {
component = TestUtils.findRenderedDOMComponentWithClass(instance, 'notifications-wrapper');
expect(component).to.not.be.null;
done();
});
it('should hold the component ref', done => {
expect(component).to.not.be.null;
done();
});
it('should render a single notification', done => {
component.addNotification(defaultNotification);
let notification = TestUtils.scryRenderedDOMComponentsWithClass(instance, 'notification');
expect(notification.length).to.equal(1);
done();
});
it('should not set a notification visibility class when the notification is initially added', done => {
component.addNotification(defaultNotification);
let notification = TestUtils.findRenderedDOMComponentWithClass(instance, 'notification');
expect(notification.className).to.not.match(/notification-hidden/);
expect(notification.className).to.not.match(/notification-visible/);
done();
});
it('should set the notification class to visible after added', done => {
component.addNotification(defaultNotification);
let notification = TestUtils.findRenderedDOMComponentWithClass(instance, 'notification');
expect(notification.className).to.match(/notification/);
clock.tick(400);
expect(notification.className).to.match(/notification-visible/);
done();
});
it('should add additional classes to the notification if specified', done => {
component.addNotification(Object.assign({},defaultNotification, {className: 'FOO'}));
let notification = TestUtils.findRenderedDOMComponentWithClass(instance, 'notification');
expect(notification.className).to.contain(' FOO');
done();
});
it('should render notifications in all positions with all levels', done => {
let count = 0;
for (let position of Object.keys(positions)) {
for (let level of Object.keys(levels)) {
notificationObj.position = positions[position];
notificationObj.level = levels[level];
component.addNotification(notificationObj);
count++;
}
}
let containers = [];
for (let position of Object.keys(positions)) {
containers.push(TestUtils.findRenderedDOMComponentWithClass(instance, 'notifications-' + positions[position]));
}
containers.forEach(function(container) {
for (let level of Object.keys(levels)) {
let notification = container.getElementsByClassName('notification-' + levels[level]);
expect(notification).to.not.be.null;
}
});
let notifications = TestUtils.scryRenderedDOMComponentsWithClass(instance, 'notification');
expect(notifications.length).to.equal(count);
done();
});
it('should render multiple notifications', done => {
const randomNumber = Math.floor(Math.random(5, 10));
for (let i = 1; i <= randomNumber; i++) {
component.addNotification(defaultNotification);
}
let notifications = TestUtils.scryRenderedDOMComponentsWithClass(instance, 'notification');
expect(notifications.length).to.equal(randomNumber);
done();
});
it('should not render notifications with the same uid', done => {
notificationObj.uid = 500;
component.addNotification(notificationObj);
component.addNotification(notificationObj);
let notification = TestUtils.scryRenderedDOMComponentsWithClass(instance, 'notification');
expect(notification.length).to.equal(1);
done();
});
it('should remove a notification after autoDismiss', function(done) {
notificationObj.autoDismiss = 2;
component.addNotification(notificationObj);
clock.tick(3000);
let notification = TestUtils.scryRenderedDOMComponentsWithClass(instance, 'notification');
expect(notification.length).to.equal(0);
done();
});
it('should remove a notification using returned object', done => {
let notificationCreated = component.addNotification(defaultNotification);
let notification = TestUtils.scryRenderedDOMComponentsWithClass(instance, 'notification');
expect(notification.length).to.equal(1);
component.removeNotification(notificationCreated);
clock.tick(1000);
let notificationRemoved = TestUtils.scryRenderedDOMComponentsWithClass(instance, 'notification');
expect(notificationRemoved.length).to.equal(0);
done();
});
it('should remove a notification using uid', done => {
let notificationCreated = component.addNotification(defaultNotification);
let notification = TestUtils.scryRenderedDOMComponentsWithClass(instance, 'notification');
expect(notification.length).to.equal(1);
component.removeNotification(notificationCreated.uid);
clock.tick(200);
let notificationRemoved = TestUtils.scryRenderedDOMComponentsWithClass(instance, 'notification');
expect(notificationRemoved.length).to.equal(0);
done();
});
it('should edit an existing notification using returned object', (done) => {
const notificationCreated = component.addNotification(defaultNotification);
const notification = TestUtils.scryRenderedDOMComponentsWithClass(instance, 'notification');
expect(notification.length).to.equal(1);
const newTitle = 'foo';
const newContent = 'foobar';
component.editNotification(notificationCreated, { title: newTitle, message: newContent });
clock.tick(1000);
const notificationEdited = TestUtils.findRenderedDOMComponentWithClass(instance, 'notification');
expect(notificationEdited.getElementsByClassName('notification-title')[0].textContent).to.equal(newTitle);
expect(notificationEdited.getElementsByClassName('notification-message')[0].textContent).to.equal(newContent);
done();
});
it('should edit an existing notification using uid', (done) => {
const notificationCreated = component.addNotification(defaultNotification);
const notification = TestUtils.scryRenderedDOMComponentsWithClass(instance, 'notification');
expect(notification.length).to.equal(1);
const newTitle = 'foo';
const newContent = 'foobar';
component.editNotification(notificationCreated.uid, { title: newTitle, message: newContent });
clock.tick(1000);
const notificationEdited = TestUtils.findRenderedDOMComponentWithClass(instance, 'notification');
expect(notificationEdited.getElementsByClassName('notification-title')[0].textContent).to.equal(newTitle);
expect(notificationEdited.getElementsByClassName('notification-message')[0].textContent).to.equal(newContent);
done();
});
it('should remove all notifications', done => {
component.addNotification(defaultNotification);
component.addNotification(defaultNotification);
component.addNotification(defaultNotification);
let notification = TestUtils.scryRenderedDOMComponentsWithClass(instance, 'notification');
expect(notification.length).to.equal(3);
component.clearNotifications();
clock.tick(200);
let notificationRemoved = TestUtils.scryRenderedDOMComponentsWithClass(instance, 'notification');
expect(notificationRemoved.length).to.equal(0);
done();
});
it('should dismiss notification on click', done => {
component.addNotification(notificationObj);
let notification = TestUtils.findRenderedDOMComponentWithClass(instance, 'notification');
TestUtils.Simulate.click(notification);
clock.tick(1000);
let notificationRemoved = TestUtils.scryRenderedDOMComponentsWithClass(instance, 'notification');
expect(notificationRemoved.length).to.equal(0);
done();
});
it('should dismiss notification on click of dismiss button', done => {
component.addNotification(notificationObj);
let dismissButton = TestUtils.findRenderedDOMComponentWithClass(instance, 'notification-dismiss');
TestUtils.Simulate.click(dismissButton);
clock.tick(1000);
let notificationRemoved = TestUtils.scryRenderedDOMComponentsWithClass(instance, 'notification');
expect(notificationRemoved.length).to.equal(0);
done();
});
it('should not render title if not provided', done => {
delete notificationObj.title;
component.addNotification(notificationObj);
let notification = TestUtils.scryRenderedDOMComponentsWithClass(instance, 'notification-title');
expect(notification.length).to.equal(0);
done();
});
it('should not render message if not provided', done => {
delete notificationObj.message;
component.addNotification(notificationObj);
let notification = TestUtils.scryRenderedDOMComponentsWithClass(instance, 'notification-message');
expect(notification.length).to.equal(0);
done();
});
it('should not dismiss the notificaion on click if dismissible is false', done => {
notificationObj.dismissible = false;
component.addNotification(notificationObj);
let notification = TestUtils.findRenderedDOMComponentWithClass(instance, 'notification');
TestUtils.Simulate.click(notification);
let notificationAfterClicked = TestUtils.findRenderedDOMComponentWithClass(instance, 'notification');
expect(notificationAfterClicked).to.not.be.null;
done();
});
it('should not dismiss the notification on click if dismissible is none', done => {
notificationObj.dismissible = 'none';
component.addNotification(notificationObj);
let notification = TestUtils.findRenderedDOMComponentWithClass(instance, 'notification');
TestUtils.Simulate.click(notification);
let notificationAfterClicked = TestUtils.findRenderedDOMComponentWithClass(instance, 'notification');
expect(notificationAfterClicked).to.exist;
done();
});
it('should not dismiss the notification on click if dismissible is button', done => {
notificationObj.dismissible = 'button';
component.addNotification(notificationObj);
let notification = TestUtils.findRenderedDOMComponentWithClass(instance, 'notification');
TestUtils.Simulate.click(notification);
let notificationAfterClicked = TestUtils.findRenderedDOMComponentWithClass(instance, 'notification');
expect(notificationAfterClicked).to.exist;
done();
});
it('should render a button if action property is passed', done => {
defaultNotification.action = {
label: 'Click me',
callback: function() {}
};
component.addNotification(defaultNotification);
let button = TestUtils.findRenderedDOMComponentWithClass(instance, 'notification-action-button');
expect(button).to.not.be.null;
done();
});
it('should execute a callback function when notification button is clicked', done => {
let testThis = false;
notificationObj.action = {
label: 'Click me',
callback: function() {
testThis = true;
}
};
component.addNotification(notificationObj);
let button = TestUtils.findRenderedDOMComponentWithClass(instance, 'notification-action-button');
TestUtils.Simulate.click(button);
expect(testThis).to.equal(true);
done();
});
it('should accept an action without callback function defined', done => {
notificationObj.action = {
label: 'Click me'
};
component.addNotification(notificationObj);
let button = TestUtils.findRenderedDOMComponentWithClass(instance, 'notification-action-button');
TestUtils.Simulate.click(button);
let notification = TestUtils.scryRenderedDOMComponentsWithClass(instance, 'notification');
expect(notification.length).to.equal(0);
done();
});
it('should execute a callback function on add a notification', done => {
let testThis = false;
notificationObj.onAdd = function() {
testThis = true;
};
component.addNotification(notificationObj);
expect(testThis).to.equal(true);
done();
});
it('should execute a callback function on remove a notification', done => {
let testThis = false;
notificationObj.onRemove = function() {
testThis = true;
};
component.addNotification(notificationObj);
let notification = TestUtils.findRenderedDOMComponentWithClass(instance, 'notification');
TestUtils.Simulate.click(notification);
expect(testThis).to.equal(true);
done();
});
it('should render a children if passed', done => {
defaultNotification.children = (
<div className="custom-container"></div>
);
component.addNotification(defaultNotification);
let customContainer = TestUtils.findRenderedDOMComponentWithClass(instance, 'custom-container');
expect(customContainer).to.not.be.null;
done();
});
it('should pause the timer if a notification has a mouse enter', done => {
notificationObj.autoDismiss = 2;
component.addNotification(notificationObj);
let notification = TestUtils.findRenderedDOMComponentWithClass(instance, 'notification');
TestUtils.Simulate.mouseEnter(notification);
clock.tick(4000);
let _notification = TestUtils.findRenderedDOMComponentWithClass(instance, 'notification');
expect(_notification).to.not.be.null;
done();
});
it('should resume the timer if a notification has a mouse leave', done => {
notificationObj.autoDismiss = 2;
component.addNotification(notificationObj);
let notification = TestUtils.findRenderedDOMComponentWithClass(instance, 'notification');
TestUtils.Simulate.mouseEnter(notification);
clock.tick(800);
TestUtils.Simulate.mouseLeave(notification);
clock.tick(2000);
let _notification = TestUtils.scryRenderedDOMComponentsWithClass(instance, 'notification');
expect(_notification.length).to.equal(0);
done();
});
it('should allow HTML inside messages', done => {
defaultNotification.message = '<strong class="allow-html-strong">Strong</strong>';
component.addNotification(defaultNotification);
let notification = TestUtils.findRenderedDOMComponentWithClass(instance, 'notification-message');
let htmlElement = notification.getElementsByClassName('allow-html-strong');
expect(htmlElement.length).to.equal(1);
done();
});
it('should render containers with a overriden width', done => {
notificationObj.position = 'tc';
component.addNotification(notificationObj);
let notification = TestUtils.findRenderedDOMComponentWithClass(instance, 'notifications-tc');
let width = notification.style.width;
expect(width).to.equal('600px');
done();
});
it('should render a notification with specific style based on position', done => {
notificationObj.position = 'bc';
component.addNotification(notificationObj);
let notification = TestUtils.findRenderedDOMComponentWithClass(instance, 'notification');
let bottomPosition = notification.style.bottom;
expect(bottomPosition).to.equal('-100px');
done();
});
it('should render containers with a overriden width for a specific position', done => {
notificationObj.position = 'tl';
component.addNotification(notificationObj);
let notification = TestUtils.findRenderedDOMComponentWithClass(instance, 'notifications-tl');
let width = notification.style.width;
expect(width).to.equal('800px');
done();
});
it('should throw an error if no level is defined', done => {
delete notificationObj.level;
expect(() => component.addNotification(notificationObj)).to.throw(/notification level is required/);
done();
});
it('should throw an error if a invalid level is defined', done => {
notificationObj.level = 'invalid';
expect(() => component.addNotification(notificationObj)).to.throw(/is not a valid level/);
done();
});
it('should throw an error if a invalid position is defined', done => {
notificationObj.position = 'invalid';
expect(() => component.addNotification(notificationObj)).to.throw(/is not a valid position/);
done();
});
it('should throw an error if autoDismiss is not a number', done => {
notificationObj.autoDismiss = 'string';
expect(() => component.addNotification(notificationObj)).to.throw(/\'autoDismiss\' must be a number./);
done();
});
it('should render 2nd notification below 1st one', done => {
component.addNotification(merge({}, defaultNotification, {title: '1st'}));
component.addNotification(merge({}, defaultNotification, {title: '2nd'}));
const notifications = TestUtils.scryRenderedDOMComponentsWithClass(instance, 'notification');
expect(notifications[0].getElementsByClassName('notification-title')[0].textContent).to.equal('1st');
expect(notifications[1].getElementsByClassName('notification-title')[0].textContent).to.equal('2nd');
done();
});
});
describe('Notification Component with newOnTop=true', function() {
let node;
let instance;
let component;
let clock;
let notificationObj;
const ref = 'notificationSystem';
this.timeout(10000);
beforeEach(() => {
// We need to create this wrapper so we can use refs
class ElementWrapper extends Component {
render() {
return <NotificationSystem ref={ ref } style={ style } allowHTML={ true } noAnimation={ true } newOnTop={ true } />;
}
}
node = window.document.createElement("div");
instance = TestUtils.renderIntoDocument(React.createElement(ElementWrapper), node);
component = instance.refs[ref];
notificationObj = merge({}, defaultNotification);
clock = sinon.useFakeTimers();
});
afterEach(() => {
clock.restore();
});
it('should render 2nd notification above 1st one', done => {
component.addNotification(merge({}, defaultNotification, {title: '1st'}));
component.addNotification(merge({}, defaultNotification, {title: '2nd'}));
const notifications = TestUtils.scryRenderedDOMComponentsWithClass(instance, 'notification');
expect(notifications[0].getElementsByClassName('notification-title')[0].textContent).to.equal('2nd');
expect(notifications[1].getElementsByClassName('notification-title')[0].textContent).to.equal('1st');
done();
});
}); |
const AssignmentExpression = require('./AssignmentExpression');
const Class = require('./Class');
const DecoratorDescriptor = require('./DecoratorDescriptor');
const ExpressionStatement = require('./ExpressionStatement');
const Function = require('./Function');
const Identifier = require('./Identifier');
const MemberExpression = require('./MemberExpression');
const ModuleDeclarationInterface = require('./ModuleDeclarationInterface');
const VariableDeclaration = require('./VariableDeclaration');
/**
* @memberOf Jymfony.Component.Autoloader.Parser.AST
*/
class ExportNamedDeclaration extends implementationOf(ModuleDeclarationInterface) {
/**
* Constructor.
*
* @param {Jymfony.Component.Autoloader.Parser.AST.SourceLocation} location
* @param {Jymfony.Component.Autoloader.Parser.AST.VariableDeclaration} declarations
* @param {Jymfony.Component.Autoloader.Parser.AST.ExportSpecifier[]} specifiers
* @param {Jymfony.Component.Autoloader.Parser.AST.Literal} source
*/
__construct(location, declarations, specifiers, source) {
/**
* @type {Jymfony.Component.Autoloader.Parser.AST.SourceLocation}
*/
this.location = location;
/**
* @type {Jymfony.Component.Autoloader.Parser.AST.VariableDeclaration}
*
* @private
*/
this._declarations = declarations;
/**
* @type {Jymfony.Component.Autoloader.Parser.AST.ExportSpecifier[]}
*
* @private
*/
this._specifiers = specifiers;
/**
* @type {Jymfony.Component.Autoloader.Parser.AST.Literal}
*
* @private
*/
this._source = source;
/**
* @type {string}
*/
this.docblock = null;
/**
* @type {null|[string, Jymfony.Component.Autoloader.Parser.AST.ExpressionInterface][]}
*/
this.decorators = null;
}
/**
* @inheritdoc
*/
compile(compiler) {
if (null === this._declarations) {
for (const specifier of this._specifiers) {
compiler.compileNode(
new ExpressionStatement(null, new AssignmentExpression(
null,
'=',
new MemberExpression(null, new Identifier(null, 'exports'), specifier.exported),
specifier.local
))
);
compiler._emit(';\n');
}
return;
}
compiler.compileNode(this._declarations);
compiler._emit(';\n');
if (this._declarations instanceof VariableDeclaration) {
for (const declarator of this._declarations.declarators) {
ExportNamedDeclaration._exportDeclarator(compiler, declarator);
}
} else if (this._declarations instanceof DecoratorDescriptor) {
compiler.compileNode(
new ExpressionStatement(null, new AssignmentExpression(
null, '=',
new MemberExpression(null, new Identifier(null, 'exports'), new Identifier(null, this._declarations.mangledName)),
new Identifier(null, this._declarations.mangledName)
))
);
} else if (this._declarations instanceof Function || this._declarations instanceof Class) {
if (this.decorators) {
this._declarations.declarators = this.decorators;
}
compiler.compileNode(
new ExpressionStatement(null, new AssignmentExpression(
null,
'=',
new MemberExpression(null, new Identifier(null, 'exports'), this._declarations.id),
this._declarations.id
))
);
}
}
/**
* Compile a declarator export.
*
* @param {Jymfony.Component.Autoloader.Parser.Compiler} compiler
* @param {Jymfony.Component.Autoloader.Parser.AST.VariableDeclarator} declarator
*
* @private
*/
static _exportDeclarator(compiler, declarator) {
for (const exportedName of declarator.id.names) {
compiler.compileNode(
new ExpressionStatement(null, new AssignmentExpression(
null,
'=',
new MemberExpression(null, new Identifier(null, 'exports'), exportedName),
exportedName
))
);
}
}
}
module.exports = ExportNamedDeclaration;
|
export const APP_LAYOUT_INIT = 'APP_LAYOUT_INIT';
export const APP_LAYOUT_CHANGE = 'APP_LAYOUT_CHANGE';
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.