text stringlengths 2 1.04M | meta dict |
|---|---|
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __markAsModule = (target) => __defProp(target, "__esModule", { value: true });
var __require = typeof require !== "undefined" ? require : (x) => {
throw new Error('Dynamic require of "' + x + '" is not supported');
};
var __commonJS = (cb, mod) => function __require2() {
return mod || (0, cb[Object.keys(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __reExport = (target, module2, desc) => {
if (module2 && typeof module2 === "object" || typeof module2 === "function") {
for (let key of __getOwnPropNames(module2))
if (!__hasOwnProp.call(target, key) && key !== "default")
__defProp(target, key, { get: () => module2[key], enumerable: !(desc = __getOwnPropDesc(module2, key)) || desc.enumerable });
}
return target;
};
var __toModule = (module2) => {
return __reExport(__markAsModule(__defProp(module2 != null ? __create(__getProtoOf(module2)) : {}, "default", module2 && module2.__esModule && "default" in module2 ? { get: () => module2.default, enumerable: true } : { value: module2, enumerable: true })), module2);
};
// node_modules/object-assign/index.js
var require_object_assign = __commonJS({
"node_modules/object-assign/index.js"(exports2, module2) {
"use strict";
var getOwnPropertySymbols = Object.getOwnPropertySymbols;
var hasOwnProperty = Object.prototype.hasOwnProperty;
var propIsEnumerable = Object.prototype.propertyIsEnumerable;
function toObject(val) {
if (val === null || val === void 0) {
throw new TypeError("Object.assign cannot be called with null or undefined");
}
return Object(val);
}
function shouldUseNative() {
try {
if (!Object.assign) {
return false;
}
var test1 = new String("abc");
test1[5] = "de";
if (Object.getOwnPropertyNames(test1)[0] === "5") {
return false;
}
var test2 = {};
for (var i = 0; i < 10; i++) {
test2["_" + String.fromCharCode(i)] = i;
}
var order2 = Object.getOwnPropertyNames(test2).map(function(n) {
return test2[n];
});
if (order2.join("") !== "0123456789") {
return false;
}
var test3 = {};
"abcdefghijklmnopqrst".split("").forEach(function(letter) {
test3[letter] = letter;
});
if (Object.keys(Object.assign({}, test3)).join("") !== "abcdefghijklmnopqrst") {
return false;
}
return true;
} catch (err) {
return false;
}
}
module2.exports = shouldUseNative() ? Object.assign : function(target, source) {
var from;
var to = toObject(target);
var symbols;
for (var s = 1; s < arguments.length; s++) {
from = Object(arguments[s]);
for (var key in from) {
if (hasOwnProperty.call(from, key)) {
to[key] = from[key];
}
}
if (getOwnPropertySymbols) {
symbols = getOwnPropertySymbols(from);
for (var i = 0; i < symbols.length; i++) {
if (propIsEnumerable.call(from, symbols[i])) {
to[symbols[i]] = from[symbols[i]];
}
}
}
}
return to;
};
}
});
// node_modules/react/cjs/react.development.js
var require_react_development = __commonJS({
"node_modules/react/cjs/react.development.js"(exports2) {
"use strict";
if (true) {
(function() {
"use strict";
var _assign = require_object_assign();
var ReactVersion = "17.0.2";
var REACT_ELEMENT_TYPE = 60103;
var REACT_PORTAL_TYPE = 60106;
exports2.Fragment = 60107;
exports2.StrictMode = 60108;
exports2.Profiler = 60114;
var REACT_PROVIDER_TYPE = 60109;
var REACT_CONTEXT_TYPE = 60110;
var REACT_FORWARD_REF_TYPE = 60112;
exports2.Suspense = 60113;
var REACT_SUSPENSE_LIST_TYPE = 60120;
var REACT_MEMO_TYPE = 60115;
var REACT_LAZY_TYPE = 60116;
var REACT_BLOCK_TYPE = 60121;
var REACT_SERVER_BLOCK_TYPE = 60122;
var REACT_FUNDAMENTAL_TYPE = 60117;
var REACT_SCOPE_TYPE = 60119;
var REACT_OPAQUE_ID_TYPE = 60128;
var REACT_DEBUG_TRACING_MODE_TYPE = 60129;
var REACT_OFFSCREEN_TYPE = 60130;
var REACT_LEGACY_HIDDEN_TYPE = 60131;
if (typeof Symbol === "function" && Symbol.for) {
var symbolFor = Symbol.for;
REACT_ELEMENT_TYPE = symbolFor("react.element");
REACT_PORTAL_TYPE = symbolFor("react.portal");
exports2.Fragment = symbolFor("react.fragment");
exports2.StrictMode = symbolFor("react.strict_mode");
exports2.Profiler = symbolFor("react.profiler");
REACT_PROVIDER_TYPE = symbolFor("react.provider");
REACT_CONTEXT_TYPE = symbolFor("react.context");
REACT_FORWARD_REF_TYPE = symbolFor("react.forward_ref");
exports2.Suspense = symbolFor("react.suspense");
REACT_SUSPENSE_LIST_TYPE = symbolFor("react.suspense_list");
REACT_MEMO_TYPE = symbolFor("react.memo");
REACT_LAZY_TYPE = symbolFor("react.lazy");
REACT_BLOCK_TYPE = symbolFor("react.block");
REACT_SERVER_BLOCK_TYPE = symbolFor("react.server.block");
REACT_FUNDAMENTAL_TYPE = symbolFor("react.fundamental");
REACT_SCOPE_TYPE = symbolFor("react.scope");
REACT_OPAQUE_ID_TYPE = symbolFor("react.opaque.id");
REACT_DEBUG_TRACING_MODE_TYPE = symbolFor("react.debug_trace_mode");
REACT_OFFSCREEN_TYPE = symbolFor("react.offscreen");
REACT_LEGACY_HIDDEN_TYPE = symbolFor("react.legacy_hidden");
}
var MAYBE_ITERATOR_SYMBOL = typeof Symbol === "function" && Symbol.iterator;
var FAUX_ITERATOR_SYMBOL = "@@iterator";
function getIteratorFn(maybeIterable) {
if (maybeIterable === null || typeof maybeIterable !== "object") {
return null;
}
var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];
if (typeof maybeIterator === "function") {
return maybeIterator;
}
return null;
}
var ReactCurrentDispatcher = {
current: null
};
var ReactCurrentBatchConfig = {
transition: 0
};
var ReactCurrentOwner = {
current: null
};
var ReactDebugCurrentFrame = {};
var currentExtraStackFrame = null;
function setExtraStackFrame(stack) {
{
currentExtraStackFrame = stack;
}
}
{
ReactDebugCurrentFrame.setExtraStackFrame = function(stack) {
{
currentExtraStackFrame = stack;
}
};
ReactDebugCurrentFrame.getCurrentStack = null;
ReactDebugCurrentFrame.getStackAddendum = function() {
var stack = "";
if (currentExtraStackFrame) {
stack += currentExtraStackFrame;
}
var impl = ReactDebugCurrentFrame.getCurrentStack;
if (impl) {
stack += impl() || "";
}
return stack;
};
}
var IsSomeRendererActing = {
current: false
};
var ReactSharedInternals = {
ReactCurrentDispatcher,
ReactCurrentBatchConfig,
ReactCurrentOwner,
IsSomeRendererActing,
assign: _assign
};
{
ReactSharedInternals.ReactDebugCurrentFrame = ReactDebugCurrentFrame;
}
function warn(format) {
{
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
printWarning("warn", format, args);
}
}
function error(format) {
{
for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
args[_key2 - 1] = arguments[_key2];
}
printWarning("error", format, args);
}
}
function printWarning(level, format, args) {
{
var ReactDebugCurrentFrame2 = ReactSharedInternals.ReactDebugCurrentFrame;
var stack = ReactDebugCurrentFrame2.getStackAddendum();
if (stack !== "") {
format += "%s";
args = args.concat([stack]);
}
var argsWithFormat = args.map(function(item) {
return "" + item;
});
argsWithFormat.unshift("Warning: " + format);
Function.prototype.apply.call(console[level], console, argsWithFormat);
}
}
var didWarnStateUpdateForUnmountedComponent = {};
function warnNoop(publicInstance, callerName) {
{
var _constructor = publicInstance.constructor;
var componentName = _constructor && (_constructor.displayName || _constructor.name) || "ReactClass";
var warningKey = componentName + "." + callerName;
if (didWarnStateUpdateForUnmountedComponent[warningKey]) {
return;
}
error("Can't call %s on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to `this.state` directly or define a `state = {};` class property with the desired state in the %s component.", callerName, componentName);
didWarnStateUpdateForUnmountedComponent[warningKey] = true;
}
}
var ReactNoopUpdateQueue = {
isMounted: function(publicInstance) {
return false;
},
enqueueForceUpdate: function(publicInstance, callback, callerName) {
warnNoop(publicInstance, "forceUpdate");
},
enqueueReplaceState: function(publicInstance, completeState, callback, callerName) {
warnNoop(publicInstance, "replaceState");
},
enqueueSetState: function(publicInstance, partialState, callback, callerName) {
warnNoop(publicInstance, "setState");
}
};
var emptyObject = {};
{
Object.freeze(emptyObject);
}
function Component(props, context, updater) {
this.props = props;
this.context = context;
this.refs = emptyObject;
this.updater = updater || ReactNoopUpdateQueue;
}
Component.prototype.isReactComponent = {};
Component.prototype.setState = function(partialState, callback) {
if (!(typeof partialState === "object" || typeof partialState === "function" || partialState == null)) {
{
throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");
}
}
this.updater.enqueueSetState(this, partialState, callback, "setState");
};
Component.prototype.forceUpdate = function(callback) {
this.updater.enqueueForceUpdate(this, callback, "forceUpdate");
};
{
var deprecatedAPIs = {
isMounted: ["isMounted", "Instead, make sure to clean up subscriptions and pending requests in componentWillUnmount to prevent memory leaks."],
replaceState: ["replaceState", "Refactor your code to use setState instead (see https://github.com/facebook/react/issues/3236)."]
};
var defineDeprecationWarning = function(methodName, info) {
Object.defineProperty(Component.prototype, methodName, {
get: function() {
warn("%s(...) is deprecated in plain JavaScript React classes. %s", info[0], info[1]);
return void 0;
}
});
};
for (var fnName in deprecatedAPIs) {
if (deprecatedAPIs.hasOwnProperty(fnName)) {
defineDeprecationWarning(fnName, deprecatedAPIs[fnName]);
}
}
}
function ComponentDummy() {
}
ComponentDummy.prototype = Component.prototype;
function PureComponent(props, context, updater) {
this.props = props;
this.context = context;
this.refs = emptyObject;
this.updater = updater || ReactNoopUpdateQueue;
}
var pureComponentPrototype = PureComponent.prototype = new ComponentDummy();
pureComponentPrototype.constructor = PureComponent;
_assign(pureComponentPrototype, Component.prototype);
pureComponentPrototype.isPureReactComponent = true;
function createRef() {
var refObject = {
current: null
};
{
Object.seal(refObject);
}
return refObject;
}
function getWrappedName(outerType, innerType, wrapperName) {
var functionName = innerType.displayName || innerType.name || "";
return outerType.displayName || (functionName !== "" ? wrapperName + "(" + functionName + ")" : wrapperName);
}
function getContextName(type) {
return type.displayName || "Context";
}
function getComponentName(type) {
if (type == null) {
return null;
}
{
if (typeof type.tag === "number") {
error("Received an unexpected object in getComponentName(). This is likely a bug in React. Please file an issue.");
}
}
if (typeof type === "function") {
return type.displayName || type.name || null;
}
if (typeof type === "string") {
return type;
}
switch (type) {
case exports2.Fragment:
return "Fragment";
case REACT_PORTAL_TYPE:
return "Portal";
case exports2.Profiler:
return "Profiler";
case exports2.StrictMode:
return "StrictMode";
case exports2.Suspense:
return "Suspense";
case REACT_SUSPENSE_LIST_TYPE:
return "SuspenseList";
}
if (typeof type === "object") {
switch (type.$$typeof) {
case REACT_CONTEXT_TYPE:
var context = type;
return getContextName(context) + ".Consumer";
case REACT_PROVIDER_TYPE:
var provider = type;
return getContextName(provider._context) + ".Provider";
case REACT_FORWARD_REF_TYPE:
return getWrappedName(type, type.render, "ForwardRef");
case REACT_MEMO_TYPE:
return getComponentName(type.type);
case REACT_BLOCK_TYPE:
return getComponentName(type._render);
case REACT_LAZY_TYPE: {
var lazyComponent = type;
var payload = lazyComponent._payload;
var init = lazyComponent._init;
try {
return getComponentName(init(payload));
} catch (x) {
return null;
}
}
}
}
return null;
}
var hasOwnProperty = Object.prototype.hasOwnProperty;
var RESERVED_PROPS = {
key: true,
ref: true,
__self: true,
__source: true
};
var specialPropKeyWarningShown, specialPropRefWarningShown, didWarnAboutStringRefs;
{
didWarnAboutStringRefs = {};
}
function hasValidRef(config) {
{
if (hasOwnProperty.call(config, "ref")) {
var getter = Object.getOwnPropertyDescriptor(config, "ref").get;
if (getter && getter.isReactWarning) {
return false;
}
}
}
return config.ref !== void 0;
}
function hasValidKey(config) {
{
if (hasOwnProperty.call(config, "key")) {
var getter = Object.getOwnPropertyDescriptor(config, "key").get;
if (getter && getter.isReactWarning) {
return false;
}
}
}
return config.key !== void 0;
}
function defineKeyPropWarningGetter(props, displayName) {
var warnAboutAccessingKey = function() {
{
if (!specialPropKeyWarningShown) {
specialPropKeyWarningShown = true;
error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)", displayName);
}
}
};
warnAboutAccessingKey.isReactWarning = true;
Object.defineProperty(props, "key", {
get: warnAboutAccessingKey,
configurable: true
});
}
function defineRefPropWarningGetter(props, displayName) {
var warnAboutAccessingRef = function() {
{
if (!specialPropRefWarningShown) {
specialPropRefWarningShown = true;
error("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)", displayName);
}
}
};
warnAboutAccessingRef.isReactWarning = true;
Object.defineProperty(props, "ref", {
get: warnAboutAccessingRef,
configurable: true
});
}
function warnIfStringRefCannotBeAutoConverted(config) {
{
if (typeof config.ref === "string" && ReactCurrentOwner.current && config.__self && ReactCurrentOwner.current.stateNode !== config.__self) {
var componentName = getComponentName(ReactCurrentOwner.current.type);
if (!didWarnAboutStringRefs[componentName]) {
error('Component "%s" contains the string ref "%s". Support for string refs will be removed in a future major release. This case cannot be automatically converted to an arrow function. We ask you to manually fix this case by using useRef() or createRef() instead. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref', componentName, config.ref);
didWarnAboutStringRefs[componentName] = true;
}
}
}
}
var ReactElement = function(type, key, ref, self, source, owner, props) {
var element = {
$$typeof: REACT_ELEMENT_TYPE,
type,
key,
ref,
props,
_owner: owner
};
{
element._store = {};
Object.defineProperty(element._store, "validated", {
configurable: false,
enumerable: false,
writable: true,
value: false
});
Object.defineProperty(element, "_self", {
configurable: false,
enumerable: false,
writable: false,
value: self
});
Object.defineProperty(element, "_source", {
configurable: false,
enumerable: false,
writable: false,
value: source
});
if (Object.freeze) {
Object.freeze(element.props);
Object.freeze(element);
}
}
return element;
};
function createElement(type, config, children) {
var propName;
var props = {};
var key = null;
var ref = null;
var self = null;
var source = null;
if (config != null) {
if (hasValidRef(config)) {
ref = config.ref;
{
warnIfStringRefCannotBeAutoConverted(config);
}
}
if (hasValidKey(config)) {
key = "" + config.key;
}
self = config.__self === void 0 ? null : config.__self;
source = config.__source === void 0 ? null : config.__source;
for (propName in config) {
if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {
props[propName] = config[propName];
}
}
}
var childrenLength = arguments.length - 2;
if (childrenLength === 1) {
props.children = children;
} else if (childrenLength > 1) {
var childArray = Array(childrenLength);
for (var i = 0; i < childrenLength; i++) {
childArray[i] = arguments[i + 2];
}
{
if (Object.freeze) {
Object.freeze(childArray);
}
}
props.children = childArray;
}
if (type && type.defaultProps) {
var defaultProps = type.defaultProps;
for (propName in defaultProps) {
if (props[propName] === void 0) {
props[propName] = defaultProps[propName];
}
}
}
{
if (key || ref) {
var displayName = typeof type === "function" ? type.displayName || type.name || "Unknown" : type;
if (key) {
defineKeyPropWarningGetter(props, displayName);
}
if (ref) {
defineRefPropWarningGetter(props, displayName);
}
}
}
return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props);
}
function cloneAndReplaceKey(oldElement, newKey) {
var newElement = ReactElement(oldElement.type, newKey, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, oldElement.props);
return newElement;
}
function cloneElement(element, config, children) {
if (!!(element === null || element === void 0)) {
{
throw Error("React.cloneElement(...): The argument must be a React element, but you passed " + element + ".");
}
}
var propName;
var props = _assign({}, element.props);
var key = element.key;
var ref = element.ref;
var self = element._self;
var source = element._source;
var owner = element._owner;
if (config != null) {
if (hasValidRef(config)) {
ref = config.ref;
owner = ReactCurrentOwner.current;
}
if (hasValidKey(config)) {
key = "" + config.key;
}
var defaultProps;
if (element.type && element.type.defaultProps) {
defaultProps = element.type.defaultProps;
}
for (propName in config) {
if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {
if (config[propName] === void 0 && defaultProps !== void 0) {
props[propName] = defaultProps[propName];
} else {
props[propName] = config[propName];
}
}
}
}
var childrenLength = arguments.length - 2;
if (childrenLength === 1) {
props.children = children;
} else if (childrenLength > 1) {
var childArray = Array(childrenLength);
for (var i = 0; i < childrenLength; i++) {
childArray[i] = arguments[i + 2];
}
props.children = childArray;
}
return ReactElement(element.type, key, ref, self, source, owner, props);
}
function isValidElement(object) {
return typeof object === "object" && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
}
var SEPARATOR = ".";
var SUBSEPARATOR = ":";
function escape(key) {
var escapeRegex = /[=:]/g;
var escaperLookup = {
"=": "=0",
":": "=2"
};
var escapedString = key.replace(escapeRegex, function(match) {
return escaperLookup[match];
});
return "$" + escapedString;
}
var didWarnAboutMaps = false;
var userProvidedKeyEscapeRegex = /\/+/g;
function escapeUserProvidedKey(text) {
return text.replace(userProvidedKeyEscapeRegex, "$&/");
}
function getElementKey(element, index) {
if (typeof element === "object" && element !== null && element.key != null) {
return escape("" + element.key);
}
return index.toString(36);
}
function mapIntoArray(children, array, escapedPrefix, nameSoFar, callback) {
var type = typeof children;
if (type === "undefined" || type === "boolean") {
children = null;
}
var invokeCallback = false;
if (children === null) {
invokeCallback = true;
} else {
switch (type) {
case "string":
case "number":
invokeCallback = true;
break;
case "object":
switch (children.$$typeof) {
case REACT_ELEMENT_TYPE:
case REACT_PORTAL_TYPE:
invokeCallback = true;
}
}
}
if (invokeCallback) {
var _child = children;
var mappedChild = callback(_child);
var childKey = nameSoFar === "" ? SEPARATOR + getElementKey(_child, 0) : nameSoFar;
if (Array.isArray(mappedChild)) {
var escapedChildKey = "";
if (childKey != null) {
escapedChildKey = escapeUserProvidedKey(childKey) + "/";
}
mapIntoArray(mappedChild, array, escapedChildKey, "", function(c) {
return c;
});
} else if (mappedChild != null) {
if (isValidElement(mappedChild)) {
mappedChild = cloneAndReplaceKey(mappedChild, escapedPrefix + (mappedChild.key && (!_child || _child.key !== mappedChild.key) ? escapeUserProvidedKey("" + mappedChild.key) + "/" : "") + childKey);
}
array.push(mappedChild);
}
return 1;
}
var child;
var nextName;
var subtreeCount = 0;
var nextNamePrefix = nameSoFar === "" ? SEPARATOR : nameSoFar + SUBSEPARATOR;
if (Array.isArray(children)) {
for (var i = 0; i < children.length; i++) {
child = children[i];
nextName = nextNamePrefix + getElementKey(child, i);
subtreeCount += mapIntoArray(child, array, escapedPrefix, nextName, callback);
}
} else {
var iteratorFn = getIteratorFn(children);
if (typeof iteratorFn === "function") {
var iterableChildren = children;
{
if (iteratorFn === iterableChildren.entries) {
if (!didWarnAboutMaps) {
warn("Using Maps as children is not supported. Use an array of keyed ReactElements instead.");
}
didWarnAboutMaps = true;
}
}
var iterator = iteratorFn.call(iterableChildren);
var step;
var ii = 0;
while (!(step = iterator.next()).done) {
child = step.value;
nextName = nextNamePrefix + getElementKey(child, ii++);
subtreeCount += mapIntoArray(child, array, escapedPrefix, nextName, callback);
}
} else if (type === "object") {
var childrenString = "" + children;
{
{
throw Error("Objects are not valid as a React child (found: " + (childrenString === "[object Object]" ? "object with keys {" + Object.keys(children).join(", ") + "}" : childrenString) + "). If you meant to render a collection of children, use an array instead.");
}
}
}
}
return subtreeCount;
}
function mapChildren(children, func, context) {
if (children == null) {
return children;
}
var result = [];
var count = 0;
mapIntoArray(children, result, "", "", function(child) {
return func.call(context, child, count++);
});
return result;
}
function countChildren(children) {
var n = 0;
mapChildren(children, function() {
n++;
});
return n;
}
function forEachChildren(children, forEachFunc, forEachContext) {
mapChildren(children, function() {
forEachFunc.apply(this, arguments);
}, forEachContext);
}
function toArray(children) {
return mapChildren(children, function(child) {
return child;
}) || [];
}
function onlyChild(children) {
if (!isValidElement(children)) {
{
throw Error("React.Children.only expected to receive a single React element child.");
}
}
return children;
}
function createContext(defaultValue, calculateChangedBits) {
if (calculateChangedBits === void 0) {
calculateChangedBits = null;
} else {
{
if (calculateChangedBits !== null && typeof calculateChangedBits !== "function") {
error("createContext: Expected the optional second argument to be a function. Instead received: %s", calculateChangedBits);
}
}
}
var context = {
$$typeof: REACT_CONTEXT_TYPE,
_calculateChangedBits: calculateChangedBits,
_currentValue: defaultValue,
_currentValue2: defaultValue,
_threadCount: 0,
Provider: null,
Consumer: null
};
context.Provider = {
$$typeof: REACT_PROVIDER_TYPE,
_context: context
};
var hasWarnedAboutUsingNestedContextConsumers = false;
var hasWarnedAboutUsingConsumerProvider = false;
var hasWarnedAboutDisplayNameOnConsumer = false;
{
var Consumer = {
$$typeof: REACT_CONTEXT_TYPE,
_context: context,
_calculateChangedBits: context._calculateChangedBits
};
Object.defineProperties(Consumer, {
Provider: {
get: function() {
if (!hasWarnedAboutUsingConsumerProvider) {
hasWarnedAboutUsingConsumerProvider = true;
error("Rendering <Context.Consumer.Provider> is not supported and will be removed in a future major release. Did you mean to render <Context.Provider> instead?");
}
return context.Provider;
},
set: function(_Provider) {
context.Provider = _Provider;
}
},
_currentValue: {
get: function() {
return context._currentValue;
},
set: function(_currentValue) {
context._currentValue = _currentValue;
}
},
_currentValue2: {
get: function() {
return context._currentValue2;
},
set: function(_currentValue2) {
context._currentValue2 = _currentValue2;
}
},
_threadCount: {
get: function() {
return context._threadCount;
},
set: function(_threadCount) {
context._threadCount = _threadCount;
}
},
Consumer: {
get: function() {
if (!hasWarnedAboutUsingNestedContextConsumers) {
hasWarnedAboutUsingNestedContextConsumers = true;
error("Rendering <Context.Consumer.Consumer> is not supported and will be removed in a future major release. Did you mean to render <Context.Consumer> instead?");
}
return context.Consumer;
}
},
displayName: {
get: function() {
return context.displayName;
},
set: function(displayName) {
if (!hasWarnedAboutDisplayNameOnConsumer) {
warn("Setting `displayName` on Context.Consumer has no effect. You should set it directly on the context with Context.displayName = '%s'.", displayName);
hasWarnedAboutDisplayNameOnConsumer = true;
}
}
}
});
context.Consumer = Consumer;
}
{
context._currentRenderer = null;
context._currentRenderer2 = null;
}
return context;
}
var Uninitialized = -1;
var Pending = 0;
var Resolved = 1;
var Rejected = 2;
function lazyInitializer(payload) {
if (payload._status === Uninitialized) {
var ctor = payload._result;
var thenable = ctor();
var pending = payload;
pending._status = Pending;
pending._result = thenable;
thenable.then(function(moduleObject) {
if (payload._status === Pending) {
var defaultExport = moduleObject.default;
{
if (defaultExport === void 0) {
error("lazy: Expected the result of a dynamic import() call. Instead received: %s\n\nYour code should look like: \n const MyComponent = lazy(() => import('./MyComponent'))", moduleObject);
}
}
var resolved = payload;
resolved._status = Resolved;
resolved._result = defaultExport;
}
}, function(error2) {
if (payload._status === Pending) {
var rejected = payload;
rejected._status = Rejected;
rejected._result = error2;
}
});
}
if (payload._status === Resolved) {
return payload._result;
} else {
throw payload._result;
}
}
function lazy(ctor) {
var payload = {
_status: -1,
_result: ctor
};
var lazyType = {
$$typeof: REACT_LAZY_TYPE,
_payload: payload,
_init: lazyInitializer
};
{
var defaultProps;
var propTypes;
Object.defineProperties(lazyType, {
defaultProps: {
configurable: true,
get: function() {
return defaultProps;
},
set: function(newDefaultProps) {
error("React.lazy(...): It is not supported to assign `defaultProps` to a lazy component import. Either specify them where the component is defined, or create a wrapping component around it.");
defaultProps = newDefaultProps;
Object.defineProperty(lazyType, "defaultProps", {
enumerable: true
});
}
},
propTypes: {
configurable: true,
get: function() {
return propTypes;
},
set: function(newPropTypes) {
error("React.lazy(...): It is not supported to assign `propTypes` to a lazy component import. Either specify them where the component is defined, or create a wrapping component around it.");
propTypes = newPropTypes;
Object.defineProperty(lazyType, "propTypes", {
enumerable: true
});
}
}
});
}
return lazyType;
}
function forwardRef(render) {
{
if (render != null && render.$$typeof === REACT_MEMO_TYPE) {
error("forwardRef requires a render function but received a `memo` component. Instead of forwardRef(memo(...)), use memo(forwardRef(...)).");
} else if (typeof render !== "function") {
error("forwardRef requires a render function but was given %s.", render === null ? "null" : typeof render);
} else {
if (render.length !== 0 && render.length !== 2) {
error("forwardRef render functions accept exactly two parameters: props and ref. %s", render.length === 1 ? "Did you forget to use the ref parameter?" : "Any additional parameter will be undefined.");
}
}
if (render != null) {
if (render.defaultProps != null || render.propTypes != null) {
error("forwardRef render functions do not support propTypes or defaultProps. Did you accidentally pass a React component?");
}
}
}
var elementType = {
$$typeof: REACT_FORWARD_REF_TYPE,
render
};
{
var ownName;
Object.defineProperty(elementType, "displayName", {
enumerable: false,
configurable: true,
get: function() {
return ownName;
},
set: function(name) {
ownName = name;
if (render.displayName == null) {
render.displayName = name;
}
}
});
}
return elementType;
}
var enableScopeAPI = false;
function isValidElementType(type) {
if (typeof type === "string" || typeof type === "function") {
return true;
}
if (type === exports2.Fragment || type === exports2.Profiler || type === REACT_DEBUG_TRACING_MODE_TYPE || type === exports2.StrictMode || type === exports2.Suspense || type === REACT_SUSPENSE_LIST_TYPE || type === REACT_LEGACY_HIDDEN_TYPE || enableScopeAPI) {
return true;
}
if (typeof type === "object" && type !== null) {
if (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || type.$$typeof === REACT_FUNDAMENTAL_TYPE || type.$$typeof === REACT_BLOCK_TYPE || type[0] === REACT_SERVER_BLOCK_TYPE) {
return true;
}
}
return false;
}
function memo(type, compare) {
{
if (!isValidElementType(type)) {
error("memo: The first argument must be a component. Instead received: %s", type === null ? "null" : typeof type);
}
}
var elementType = {
$$typeof: REACT_MEMO_TYPE,
type,
compare: compare === void 0 ? null : compare
};
{
var ownName;
Object.defineProperty(elementType, "displayName", {
enumerable: false,
configurable: true,
get: function() {
return ownName;
},
set: function(name) {
ownName = name;
if (type.displayName == null) {
type.displayName = name;
}
}
});
}
return elementType;
}
function resolveDispatcher() {
var dispatcher = ReactCurrentDispatcher.current;
if (!(dispatcher !== null)) {
{
throw Error("Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.");
}
}
return dispatcher;
}
function useContext(Context, unstable_observedBits) {
var dispatcher = resolveDispatcher();
{
if (unstable_observedBits !== void 0) {
error("useContext() second argument is reserved for future use in React. Passing it is not supported. You passed: %s.%s", unstable_observedBits, typeof unstable_observedBits === "number" && Array.isArray(arguments[2]) ? "\n\nDid you call array.map(useContext)? Calling Hooks inside a loop is not supported. Learn more at https://reactjs.org/link/rules-of-hooks" : "");
}
if (Context._context !== void 0) {
var realContext = Context._context;
if (realContext.Consumer === Context) {
error("Calling useContext(Context.Consumer) is not supported, may cause bugs, and will be removed in a future major release. Did you mean to call useContext(Context) instead?");
} else if (realContext.Provider === Context) {
error("Calling useContext(Context.Provider) is not supported. Did you mean to call useContext(Context) instead?");
}
}
}
return dispatcher.useContext(Context, unstable_observedBits);
}
function useState(initialState) {
var dispatcher = resolveDispatcher();
return dispatcher.useState(initialState);
}
function useReducer(reducer, initialArg, init) {
var dispatcher = resolveDispatcher();
return dispatcher.useReducer(reducer, initialArg, init);
}
function useRef(initialValue) {
var dispatcher = resolveDispatcher();
return dispatcher.useRef(initialValue);
}
function useEffect(create, deps) {
var dispatcher = resolveDispatcher();
return dispatcher.useEffect(create, deps);
}
function useLayoutEffect(create, deps) {
var dispatcher = resolveDispatcher();
return dispatcher.useLayoutEffect(create, deps);
}
function useCallback(callback, deps) {
var dispatcher = resolveDispatcher();
return dispatcher.useCallback(callback, deps);
}
function useMemo(create, deps) {
var dispatcher = resolveDispatcher();
return dispatcher.useMemo(create, deps);
}
function useImperativeHandle(ref, create, deps) {
var dispatcher = resolveDispatcher();
return dispatcher.useImperativeHandle(ref, create, deps);
}
function useDebugValue(value, formatterFn) {
{
var dispatcher = resolveDispatcher();
return dispatcher.useDebugValue(value, formatterFn);
}
}
var disabledDepth = 0;
var prevLog;
var prevInfo;
var prevWarn;
var prevError;
var prevGroup;
var prevGroupCollapsed;
var prevGroupEnd;
function disabledLog() {
}
disabledLog.__reactDisabledLog = true;
function disableLogs() {
{
if (disabledDepth === 0) {
prevLog = console.log;
prevInfo = console.info;
prevWarn = console.warn;
prevError = console.error;
prevGroup = console.group;
prevGroupCollapsed = console.groupCollapsed;
prevGroupEnd = console.groupEnd;
var props = {
configurable: true,
enumerable: true,
value: disabledLog,
writable: true
};
Object.defineProperties(console, {
info: props,
log: props,
warn: props,
error: props,
group: props,
groupCollapsed: props,
groupEnd: props
});
}
disabledDepth++;
}
}
function reenableLogs() {
{
disabledDepth--;
if (disabledDepth === 0) {
var props = {
configurable: true,
enumerable: true,
writable: true
};
Object.defineProperties(console, {
log: _assign({}, props, {
value: prevLog
}),
info: _assign({}, props, {
value: prevInfo
}),
warn: _assign({}, props, {
value: prevWarn
}),
error: _assign({}, props, {
value: prevError
}),
group: _assign({}, props, {
value: prevGroup
}),
groupCollapsed: _assign({}, props, {
value: prevGroupCollapsed
}),
groupEnd: _assign({}, props, {
value: prevGroupEnd
})
});
}
if (disabledDepth < 0) {
error("disabledDepth fell below zero. This is a bug in React. Please file an issue.");
}
}
}
var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher;
var prefix;
function describeBuiltInComponentFrame(name, source, ownerFn) {
{
if (prefix === void 0) {
try {
throw Error();
} catch (x) {
var match = x.stack.trim().match(/\n( *(at )?)/);
prefix = match && match[1] || "";
}
}
return "\n" + prefix + name;
}
}
var reentry = false;
var componentFrameCache;
{
var PossiblyWeakMap = typeof WeakMap === "function" ? WeakMap : Map;
componentFrameCache = new PossiblyWeakMap();
}
function describeNativeComponentFrame(fn, construct) {
if (!fn || reentry) {
return "";
}
{
var frame = componentFrameCache.get(fn);
if (frame !== void 0) {
return frame;
}
}
var control;
reentry = true;
var previousPrepareStackTrace = Error.prepareStackTrace;
Error.prepareStackTrace = void 0;
var previousDispatcher;
{
previousDispatcher = ReactCurrentDispatcher$1.current;
ReactCurrentDispatcher$1.current = null;
disableLogs();
}
try {
if (construct) {
var Fake = function() {
throw Error();
};
Object.defineProperty(Fake.prototype, "props", {
set: function() {
throw Error();
}
});
if (typeof Reflect === "object" && Reflect.construct) {
try {
Reflect.construct(Fake, []);
} catch (x) {
control = x;
}
Reflect.construct(fn, [], Fake);
} else {
try {
Fake.call();
} catch (x) {
control = x;
}
fn.call(Fake.prototype);
}
} else {
try {
throw Error();
} catch (x) {
control = x;
}
fn();
}
} catch (sample) {
if (sample && control && typeof sample.stack === "string") {
var sampleLines = sample.stack.split("\n");
var controlLines = control.stack.split("\n");
var s = sampleLines.length - 1;
var c = controlLines.length - 1;
while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) {
c--;
}
for (; s >= 1 && c >= 0; s--, c--) {
if (sampleLines[s] !== controlLines[c]) {
if (s !== 1 || c !== 1) {
do {
s--;
c--;
if (c < 0 || sampleLines[s] !== controlLines[c]) {
var _frame = "\n" + sampleLines[s].replace(" at new ", " at ");
{
if (typeof fn === "function") {
componentFrameCache.set(fn, _frame);
}
}
return _frame;
}
} while (s >= 1 && c >= 0);
}
break;
}
}
}
} finally {
reentry = false;
{
ReactCurrentDispatcher$1.current = previousDispatcher;
reenableLogs();
}
Error.prepareStackTrace = previousPrepareStackTrace;
}
var name = fn ? fn.displayName || fn.name : "";
var syntheticFrame = name ? describeBuiltInComponentFrame(name) : "";
{
if (typeof fn === "function") {
componentFrameCache.set(fn, syntheticFrame);
}
}
return syntheticFrame;
}
function describeFunctionComponentFrame(fn, source, ownerFn) {
{
return describeNativeComponentFrame(fn, false);
}
}
function shouldConstruct(Component2) {
var prototype = Component2.prototype;
return !!(prototype && prototype.isReactComponent);
}
function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) {
if (type == null) {
return "";
}
if (typeof type === "function") {
{
return describeNativeComponentFrame(type, shouldConstruct(type));
}
}
if (typeof type === "string") {
return describeBuiltInComponentFrame(type);
}
switch (type) {
case exports2.Suspense:
return describeBuiltInComponentFrame("Suspense");
case REACT_SUSPENSE_LIST_TYPE:
return describeBuiltInComponentFrame("SuspenseList");
}
if (typeof type === "object") {
switch (type.$$typeof) {
case REACT_FORWARD_REF_TYPE:
return describeFunctionComponentFrame(type.render);
case REACT_MEMO_TYPE:
return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn);
case REACT_BLOCK_TYPE:
return describeFunctionComponentFrame(type._render);
case REACT_LAZY_TYPE: {
var lazyComponent = type;
var payload = lazyComponent._payload;
var init = lazyComponent._init;
try {
return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn);
} catch (x) {
}
}
}
}
return "";
}
var loggedTypeFailures = {};
var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame;
function setCurrentlyValidatingElement(element) {
{
if (element) {
var owner = element._owner;
var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
ReactDebugCurrentFrame$1.setExtraStackFrame(stack);
} else {
ReactDebugCurrentFrame$1.setExtraStackFrame(null);
}
}
}
function checkPropTypes(typeSpecs, values, location, componentName, element) {
{
var has = Function.call.bind(Object.prototype.hasOwnProperty);
for (var typeSpecName in typeSpecs) {
if (has(typeSpecs, typeSpecName)) {
var error$1 = void 0;
try {
if (typeof typeSpecs[typeSpecName] !== "function") {
var err = Error((componentName || "React class") + ": " + location + " type `" + typeSpecName + "` is invalid; it must be a function, usually from the `prop-types` package, but received `" + typeof typeSpecs[typeSpecName] + "`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");
err.name = "Invariant Violation";
throw err;
}
error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, "SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED");
} catch (ex) {
error$1 = ex;
}
if (error$1 && !(error$1 instanceof Error)) {
setCurrentlyValidatingElement(element);
error("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).", componentName || "React class", location, typeSpecName, typeof error$1);
setCurrentlyValidatingElement(null);
}
if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) {
loggedTypeFailures[error$1.message] = true;
setCurrentlyValidatingElement(element);
error("Failed %s type: %s", location, error$1.message);
setCurrentlyValidatingElement(null);
}
}
}
}
}
function setCurrentlyValidatingElement$1(element) {
{
if (element) {
var owner = element._owner;
var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
setExtraStackFrame(stack);
} else {
setExtraStackFrame(null);
}
}
}
var propTypesMisspellWarningShown;
{
propTypesMisspellWarningShown = false;
}
function getDeclarationErrorAddendum() {
if (ReactCurrentOwner.current) {
var name = getComponentName(ReactCurrentOwner.current.type);
if (name) {
return "\n\nCheck the render method of `" + name + "`.";
}
}
return "";
}
function getSourceInfoErrorAddendum(source) {
if (source !== void 0) {
var fileName = source.fileName.replace(/^.*[\\\/]/, "");
var lineNumber = source.lineNumber;
return "\n\nCheck your code at " + fileName + ":" + lineNumber + ".";
}
return "";
}
function getSourceInfoErrorAddendumForProps(elementProps) {
if (elementProps !== null && elementProps !== void 0) {
return getSourceInfoErrorAddendum(elementProps.__source);
}
return "";
}
var ownerHasKeyUseWarning = {};
function getCurrentComponentErrorInfo(parentType) {
var info = getDeclarationErrorAddendum();
if (!info) {
var parentName = typeof parentType === "string" ? parentType : parentType.displayName || parentType.name;
if (parentName) {
info = "\n\nCheck the top-level render call using <" + parentName + ">.";
}
}
return info;
}
function validateExplicitKey(element, parentType) {
if (!element._store || element._store.validated || element.key != null) {
return;
}
element._store.validated = true;
var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType);
if (ownerHasKeyUseWarning[currentComponentErrorInfo]) {
return;
}
ownerHasKeyUseWarning[currentComponentErrorInfo] = true;
var childOwner = "";
if (element && element._owner && element._owner !== ReactCurrentOwner.current) {
childOwner = " It was passed a child from " + getComponentName(element._owner.type) + ".";
}
{
setCurrentlyValidatingElement$1(element);
error('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.', currentComponentErrorInfo, childOwner);
setCurrentlyValidatingElement$1(null);
}
}
function validateChildKeys(node, parentType) {
if (typeof node !== "object") {
return;
}
if (Array.isArray(node)) {
for (var i = 0; i < node.length; i++) {
var child = node[i];
if (isValidElement(child)) {
validateExplicitKey(child, parentType);
}
}
} else if (isValidElement(node)) {
if (node._store) {
node._store.validated = true;
}
} else if (node) {
var iteratorFn = getIteratorFn(node);
if (typeof iteratorFn === "function") {
if (iteratorFn !== node.entries) {
var iterator = iteratorFn.call(node);
var step;
while (!(step = iterator.next()).done) {
if (isValidElement(step.value)) {
validateExplicitKey(step.value, parentType);
}
}
}
}
}
}
function validatePropTypes(element) {
{
var type = element.type;
if (type === null || type === void 0 || typeof type === "string") {
return;
}
var propTypes;
if (typeof type === "function") {
propTypes = type.propTypes;
} else if (typeof type === "object" && (type.$$typeof === REACT_FORWARD_REF_TYPE || type.$$typeof === REACT_MEMO_TYPE)) {
propTypes = type.propTypes;
} else {
return;
}
if (propTypes) {
var name = getComponentName(type);
checkPropTypes(propTypes, element.props, "prop", name, element);
} else if (type.PropTypes !== void 0 && !propTypesMisspellWarningShown) {
propTypesMisspellWarningShown = true;
var _name = getComponentName(type);
error("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?", _name || "Unknown");
}
if (typeof type.getDefaultProps === "function" && !type.getDefaultProps.isReactClassApproved) {
error("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.");
}
}
}
function validateFragmentProps(fragment) {
{
var keys = Object.keys(fragment.props);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if (key !== "children" && key !== "key") {
setCurrentlyValidatingElement$1(fragment);
error("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.", key);
setCurrentlyValidatingElement$1(null);
break;
}
}
if (fragment.ref !== null) {
setCurrentlyValidatingElement$1(fragment);
error("Invalid attribute `ref` supplied to `React.Fragment`.");
setCurrentlyValidatingElement$1(null);
}
}
}
function createElementWithValidation(type, props, children) {
var validType = isValidElementType(type);
if (!validType) {
var info = "";
if (type === void 0 || typeof type === "object" && type !== null && Object.keys(type).length === 0) {
info += " You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.";
}
var sourceInfo = getSourceInfoErrorAddendumForProps(props);
if (sourceInfo) {
info += sourceInfo;
} else {
info += getDeclarationErrorAddendum();
}
var typeString;
if (type === null) {
typeString = "null";
} else if (Array.isArray(type)) {
typeString = "array";
} else if (type !== void 0 && type.$$typeof === REACT_ELEMENT_TYPE) {
typeString = "<" + (getComponentName(type.type) || "Unknown") + " />";
info = " Did you accidentally export a JSX literal instead of a component?";
} else {
typeString = typeof type;
}
{
error("React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s", typeString, info);
}
}
var element = createElement.apply(this, arguments);
if (element == null) {
return element;
}
if (validType) {
for (var i = 2; i < arguments.length; i++) {
validateChildKeys(arguments[i], type);
}
}
if (type === exports2.Fragment) {
validateFragmentProps(element);
} else {
validatePropTypes(element);
}
return element;
}
var didWarnAboutDeprecatedCreateFactory = false;
function createFactoryWithValidation(type) {
var validatedFactory = createElementWithValidation.bind(null, type);
validatedFactory.type = type;
{
if (!didWarnAboutDeprecatedCreateFactory) {
didWarnAboutDeprecatedCreateFactory = true;
warn("React.createFactory() is deprecated and will be removed in a future major release. Consider using JSX or use React.createElement() directly instead.");
}
Object.defineProperty(validatedFactory, "type", {
enumerable: false,
get: function() {
warn("Factory.type is deprecated. Access the class directly before passing it to createFactory.");
Object.defineProperty(this, "type", {
value: type
});
return type;
}
});
}
return validatedFactory;
}
function cloneElementWithValidation(element, props, children) {
var newElement = cloneElement.apply(this, arguments);
for (var i = 2; i < arguments.length; i++) {
validateChildKeys(arguments[i], newElement.type);
}
validatePropTypes(newElement);
return newElement;
}
{
try {
var frozenObject = Object.freeze({});
new Map([[frozenObject, null]]);
new Set([frozenObject]);
} catch (e) {
}
}
var createElement$1 = createElementWithValidation;
var cloneElement$1 = cloneElementWithValidation;
var createFactory = createFactoryWithValidation;
var Children = {
map: mapChildren,
forEach: forEachChildren,
count: countChildren,
toArray,
only: onlyChild
};
exports2.Children = Children;
exports2.Component = Component;
exports2.PureComponent = PureComponent;
exports2.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = ReactSharedInternals;
exports2.cloneElement = cloneElement$1;
exports2.createContext = createContext;
exports2.createElement = createElement$1;
exports2.createFactory = createFactory;
exports2.createRef = createRef;
exports2.forwardRef = forwardRef;
exports2.isValidElement = isValidElement;
exports2.lazy = lazy;
exports2.memo = memo;
exports2.useCallback = useCallback;
exports2.useContext = useContext;
exports2.useDebugValue = useDebugValue;
exports2.useEffect = useEffect;
exports2.useImperativeHandle = useImperativeHandle;
exports2.useLayoutEffect = useLayoutEffect;
exports2.useMemo = useMemo;
exports2.useReducer = useReducer;
exports2.useRef = useRef;
exports2.useState = useState;
exports2.version = ReactVersion;
})();
}
}
});
// node_modules/react/index.js
var require_react = __commonJS({
"node_modules/react/index.js"(exports2, module2) {
"use strict";
if (false) {
module2.exports = null;
} else {
module2.exports = require_react_development();
}
}
});
// node_modules/scheduler/cjs/scheduler.development.js
var require_scheduler_development = __commonJS({
"node_modules/scheduler/cjs/scheduler.development.js"(exports2) {
"use strict";
if (true) {
(function() {
"use strict";
var enableSchedulerDebugging = false;
var enableProfiling = false;
var requestHostCallback;
var requestHostTimeout;
var cancelHostTimeout;
var requestPaint;
var hasPerformanceNow = typeof performance === "object" && typeof performance.now === "function";
if (hasPerformanceNow) {
var localPerformance = performance;
exports2.unstable_now = function() {
return localPerformance.now();
};
} else {
var localDate = Date;
var initialTime = localDate.now();
exports2.unstable_now = function() {
return localDate.now() - initialTime;
};
}
if (typeof window === "undefined" || typeof MessageChannel !== "function") {
var _callback = null;
var _timeoutID = null;
var _flushCallback = function() {
if (_callback !== null) {
try {
var currentTime = exports2.unstable_now();
var hasRemainingTime = true;
_callback(hasRemainingTime, currentTime);
_callback = null;
} catch (e) {
setTimeout(_flushCallback, 0);
throw e;
}
}
};
requestHostCallback = function(cb) {
if (_callback !== null) {
setTimeout(requestHostCallback, 0, cb);
} else {
_callback = cb;
setTimeout(_flushCallback, 0);
}
};
requestHostTimeout = function(cb, ms) {
_timeoutID = setTimeout(cb, ms);
};
cancelHostTimeout = function() {
clearTimeout(_timeoutID);
};
exports2.unstable_shouldYield = function() {
return false;
};
requestPaint = exports2.unstable_forceFrameRate = function() {
};
} else {
var _setTimeout = window.setTimeout;
var _clearTimeout = window.clearTimeout;
if (typeof console !== "undefined") {
var requestAnimationFrame = window.requestAnimationFrame;
var cancelAnimationFrame = window.cancelAnimationFrame;
if (typeof requestAnimationFrame !== "function") {
console["error"]("This browser doesn't support requestAnimationFrame. Make sure that you load a polyfill in older browsers. https://reactjs.org/link/react-polyfills");
}
if (typeof cancelAnimationFrame !== "function") {
console["error"]("This browser doesn't support cancelAnimationFrame. Make sure that you load a polyfill in older browsers. https://reactjs.org/link/react-polyfills");
}
}
var isMessageLoopRunning = false;
var scheduledHostCallback = null;
var taskTimeoutID = -1;
var yieldInterval = 5;
var deadline = 0;
{
exports2.unstable_shouldYield = function() {
return exports2.unstable_now() >= deadline;
};
requestPaint = function() {
};
}
exports2.unstable_forceFrameRate = function(fps) {
if (fps < 0 || fps > 125) {
console["error"]("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported");
return;
}
if (fps > 0) {
yieldInterval = Math.floor(1e3 / fps);
} else {
yieldInterval = 5;
}
};
var performWorkUntilDeadline = function() {
if (scheduledHostCallback !== null) {
var currentTime = exports2.unstable_now();
deadline = currentTime + yieldInterval;
var hasTimeRemaining = true;
try {
var hasMoreWork = scheduledHostCallback(hasTimeRemaining, currentTime);
if (!hasMoreWork) {
isMessageLoopRunning = false;
scheduledHostCallback = null;
} else {
port.postMessage(null);
}
} catch (error) {
port.postMessage(null);
throw error;
}
} else {
isMessageLoopRunning = false;
}
};
var channel = new MessageChannel();
var port = channel.port2;
channel.port1.onmessage = performWorkUntilDeadline;
requestHostCallback = function(callback) {
scheduledHostCallback = callback;
if (!isMessageLoopRunning) {
isMessageLoopRunning = true;
port.postMessage(null);
}
};
requestHostTimeout = function(callback, ms) {
taskTimeoutID = _setTimeout(function() {
callback(exports2.unstable_now());
}, ms);
};
cancelHostTimeout = function() {
_clearTimeout(taskTimeoutID);
taskTimeoutID = -1;
};
}
function push(heap, node) {
var index = heap.length;
heap.push(node);
siftUp(heap, node, index);
}
function peek(heap) {
var first = heap[0];
return first === void 0 ? null : first;
}
function pop(heap) {
var first = heap[0];
if (first !== void 0) {
var last = heap.pop();
if (last !== first) {
heap[0] = last;
siftDown(heap, last, 0);
}
return first;
} else {
return null;
}
}
function siftUp(heap, node, i) {
var index = i;
while (true) {
var parentIndex = index - 1 >>> 1;
var parent = heap[parentIndex];
if (parent !== void 0 && compare(parent, node) > 0) {
heap[parentIndex] = node;
heap[index] = parent;
index = parentIndex;
} else {
return;
}
}
}
function siftDown(heap, node, i) {
var index = i;
var length = heap.length;
while (index < length) {
var leftIndex = (index + 1) * 2 - 1;
var left = heap[leftIndex];
var rightIndex = leftIndex + 1;
var right = heap[rightIndex];
if (left !== void 0 && compare(left, node) < 0) {
if (right !== void 0 && compare(right, left) < 0) {
heap[index] = right;
heap[rightIndex] = node;
index = rightIndex;
} else {
heap[index] = left;
heap[leftIndex] = node;
index = leftIndex;
}
} else if (right !== void 0 && compare(right, node) < 0) {
heap[index] = right;
heap[rightIndex] = node;
index = rightIndex;
} else {
return;
}
}
}
function compare(a, b) {
var diff = a.sortIndex - b.sortIndex;
return diff !== 0 ? diff : a.id - b.id;
}
var ImmediatePriority = 1;
var UserBlockingPriority = 2;
var NormalPriority = 3;
var LowPriority = 4;
var IdlePriority = 5;
function markTaskErrored(task, ms) {
}
var maxSigned31BitInt = 1073741823;
var IMMEDIATE_PRIORITY_TIMEOUT = -1;
var USER_BLOCKING_PRIORITY_TIMEOUT = 250;
var NORMAL_PRIORITY_TIMEOUT = 5e3;
var LOW_PRIORITY_TIMEOUT = 1e4;
var IDLE_PRIORITY_TIMEOUT = maxSigned31BitInt;
var taskQueue = [];
var timerQueue = [];
var taskIdCounter = 1;
var currentTask = null;
var currentPriorityLevel = NormalPriority;
var isPerformingWork = false;
var isHostCallbackScheduled = false;
var isHostTimeoutScheduled = false;
function advanceTimers(currentTime) {
var timer = peek(timerQueue);
while (timer !== null) {
if (timer.callback === null) {
pop(timerQueue);
} else if (timer.startTime <= currentTime) {
pop(timerQueue);
timer.sortIndex = timer.expirationTime;
push(taskQueue, timer);
} else {
return;
}
timer = peek(timerQueue);
}
}
function handleTimeout(currentTime) {
isHostTimeoutScheduled = false;
advanceTimers(currentTime);
if (!isHostCallbackScheduled) {
if (peek(taskQueue) !== null) {
isHostCallbackScheduled = true;
requestHostCallback(flushWork);
} else {
var firstTimer = peek(timerQueue);
if (firstTimer !== null) {
requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime);
}
}
}
}
function flushWork(hasTimeRemaining, initialTime2) {
isHostCallbackScheduled = false;
if (isHostTimeoutScheduled) {
isHostTimeoutScheduled = false;
cancelHostTimeout();
}
isPerformingWork = true;
var previousPriorityLevel = currentPriorityLevel;
try {
if (enableProfiling) {
try {
return workLoop(hasTimeRemaining, initialTime2);
} catch (error) {
if (currentTask !== null) {
var currentTime = exports2.unstable_now();
markTaskErrored(currentTask, currentTime);
currentTask.isQueued = false;
}
throw error;
}
} else {
return workLoop(hasTimeRemaining, initialTime2);
}
} finally {
currentTask = null;
currentPriorityLevel = previousPriorityLevel;
isPerformingWork = false;
}
}
function workLoop(hasTimeRemaining, initialTime2) {
var currentTime = initialTime2;
advanceTimers(currentTime);
currentTask = peek(taskQueue);
while (currentTask !== null && !enableSchedulerDebugging) {
if (currentTask.expirationTime > currentTime && (!hasTimeRemaining || exports2.unstable_shouldYield())) {
break;
}
var callback = currentTask.callback;
if (typeof callback === "function") {
currentTask.callback = null;
currentPriorityLevel = currentTask.priorityLevel;
var didUserCallbackTimeout = currentTask.expirationTime <= currentTime;
var continuationCallback = callback(didUserCallbackTimeout);
currentTime = exports2.unstable_now();
if (typeof continuationCallback === "function") {
currentTask.callback = continuationCallback;
} else {
if (currentTask === peek(taskQueue)) {
pop(taskQueue);
}
}
advanceTimers(currentTime);
} else {
pop(taskQueue);
}
currentTask = peek(taskQueue);
}
if (currentTask !== null) {
return true;
} else {
var firstTimer = peek(timerQueue);
if (firstTimer !== null) {
requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime);
}
return false;
}
}
function unstable_runWithPriority(priorityLevel, eventHandler) {
switch (priorityLevel) {
case ImmediatePriority:
case UserBlockingPriority:
case NormalPriority:
case LowPriority:
case IdlePriority:
break;
default:
priorityLevel = NormalPriority;
}
var previousPriorityLevel = currentPriorityLevel;
currentPriorityLevel = priorityLevel;
try {
return eventHandler();
} finally {
currentPriorityLevel = previousPriorityLevel;
}
}
function unstable_next(eventHandler) {
var priorityLevel;
switch (currentPriorityLevel) {
case ImmediatePriority:
case UserBlockingPriority:
case NormalPriority:
priorityLevel = NormalPriority;
break;
default:
priorityLevel = currentPriorityLevel;
break;
}
var previousPriorityLevel = currentPriorityLevel;
currentPriorityLevel = priorityLevel;
try {
return eventHandler();
} finally {
currentPriorityLevel = previousPriorityLevel;
}
}
function unstable_wrapCallback(callback) {
var parentPriorityLevel = currentPriorityLevel;
return function() {
var previousPriorityLevel = currentPriorityLevel;
currentPriorityLevel = parentPriorityLevel;
try {
return callback.apply(this, arguments);
} finally {
currentPriorityLevel = previousPriorityLevel;
}
};
}
function unstable_scheduleCallback(priorityLevel, callback, options) {
var currentTime = exports2.unstable_now();
var startTime;
if (typeof options === "object" && options !== null) {
var delay = options.delay;
if (typeof delay === "number" && delay > 0) {
startTime = currentTime + delay;
} else {
startTime = currentTime;
}
} else {
startTime = currentTime;
}
var timeout;
switch (priorityLevel) {
case ImmediatePriority:
timeout = IMMEDIATE_PRIORITY_TIMEOUT;
break;
case UserBlockingPriority:
timeout = USER_BLOCKING_PRIORITY_TIMEOUT;
break;
case IdlePriority:
timeout = IDLE_PRIORITY_TIMEOUT;
break;
case LowPriority:
timeout = LOW_PRIORITY_TIMEOUT;
break;
case NormalPriority:
default:
timeout = NORMAL_PRIORITY_TIMEOUT;
break;
}
var expirationTime = startTime + timeout;
var newTask = {
id: taskIdCounter++,
callback,
priorityLevel,
startTime,
expirationTime,
sortIndex: -1
};
if (startTime > currentTime) {
newTask.sortIndex = startTime;
push(timerQueue, newTask);
if (peek(taskQueue) === null && newTask === peek(timerQueue)) {
if (isHostTimeoutScheduled) {
cancelHostTimeout();
} else {
isHostTimeoutScheduled = true;
}
requestHostTimeout(handleTimeout, startTime - currentTime);
}
} else {
newTask.sortIndex = expirationTime;
push(taskQueue, newTask);
if (!isHostCallbackScheduled && !isPerformingWork) {
isHostCallbackScheduled = true;
requestHostCallback(flushWork);
}
}
return newTask;
}
function unstable_pauseExecution() {
}
function unstable_continueExecution() {
if (!isHostCallbackScheduled && !isPerformingWork) {
isHostCallbackScheduled = true;
requestHostCallback(flushWork);
}
}
function unstable_getFirstCallbackNode() {
return peek(taskQueue);
}
function unstable_cancelCallback(task) {
task.callback = null;
}
function unstable_getCurrentPriorityLevel() {
return currentPriorityLevel;
}
var unstable_requestPaint = requestPaint;
var unstable_Profiling = null;
exports2.unstable_IdlePriority = IdlePriority;
exports2.unstable_ImmediatePriority = ImmediatePriority;
exports2.unstable_LowPriority = LowPriority;
exports2.unstable_NormalPriority = NormalPriority;
exports2.unstable_Profiling = unstable_Profiling;
exports2.unstable_UserBlockingPriority = UserBlockingPriority;
exports2.unstable_cancelCallback = unstable_cancelCallback;
exports2.unstable_continueExecution = unstable_continueExecution;
exports2.unstable_getCurrentPriorityLevel = unstable_getCurrentPriorityLevel;
exports2.unstable_getFirstCallbackNode = unstable_getFirstCallbackNode;
exports2.unstable_next = unstable_next;
exports2.unstable_pauseExecution = unstable_pauseExecution;
exports2.unstable_requestPaint = unstable_requestPaint;
exports2.unstable_runWithPriority = unstable_runWithPriority;
exports2.unstable_scheduleCallback = unstable_scheduleCallback;
exports2.unstable_wrapCallback = unstable_wrapCallback;
})();
}
}
});
// node_modules/scheduler/index.js
var require_scheduler = __commonJS({
"node_modules/scheduler/index.js"(exports2, module2) {
"use strict";
if (false) {
module2.exports = null;
} else {
module2.exports = require_scheduler_development();
}
}
});
// node_modules/scheduler/cjs/scheduler-tracing.development.js
var require_scheduler_tracing_development = __commonJS({
"node_modules/scheduler/cjs/scheduler-tracing.development.js"(exports2) {
"use strict";
if (true) {
(function() {
"use strict";
var DEFAULT_THREAD_ID = 0;
var interactionIDCounter = 0;
var threadIDCounter = 0;
exports2.__interactionsRef = null;
exports2.__subscriberRef = null;
{
exports2.__interactionsRef = {
current: new Set()
};
exports2.__subscriberRef = {
current: null
};
}
function unstable_clear(callback) {
var prevInteractions = exports2.__interactionsRef.current;
exports2.__interactionsRef.current = new Set();
try {
return callback();
} finally {
exports2.__interactionsRef.current = prevInteractions;
}
}
function unstable_getCurrent() {
{
return exports2.__interactionsRef.current;
}
}
function unstable_getThreadID() {
return ++threadIDCounter;
}
function unstable_trace(name, timestamp, callback) {
var threadID = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : DEFAULT_THREAD_ID;
var interaction = {
__count: 1,
id: interactionIDCounter++,
name,
timestamp
};
var prevInteractions = exports2.__interactionsRef.current;
var interactions = new Set(prevInteractions);
interactions.add(interaction);
exports2.__interactionsRef.current = interactions;
var subscriber = exports2.__subscriberRef.current;
var returnValue;
try {
if (subscriber !== null) {
subscriber.onInteractionTraced(interaction);
}
} finally {
try {
if (subscriber !== null) {
subscriber.onWorkStarted(interactions, threadID);
}
} finally {
try {
returnValue = callback();
} finally {
exports2.__interactionsRef.current = prevInteractions;
try {
if (subscriber !== null) {
subscriber.onWorkStopped(interactions, threadID);
}
} finally {
interaction.__count--;
if (subscriber !== null && interaction.__count === 0) {
subscriber.onInteractionScheduledWorkCompleted(interaction);
}
}
}
}
}
return returnValue;
}
function unstable_wrap(callback) {
var threadID = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : DEFAULT_THREAD_ID;
var wrappedInteractions = exports2.__interactionsRef.current;
var subscriber = exports2.__subscriberRef.current;
if (subscriber !== null) {
subscriber.onWorkScheduled(wrappedInteractions, threadID);
}
wrappedInteractions.forEach(function(interaction) {
interaction.__count++;
});
var hasRun = false;
function wrapped() {
var prevInteractions = exports2.__interactionsRef.current;
exports2.__interactionsRef.current = wrappedInteractions;
subscriber = exports2.__subscriberRef.current;
try {
var returnValue;
try {
if (subscriber !== null) {
subscriber.onWorkStarted(wrappedInteractions, threadID);
}
} finally {
try {
returnValue = callback.apply(void 0, arguments);
} finally {
exports2.__interactionsRef.current = prevInteractions;
if (subscriber !== null) {
subscriber.onWorkStopped(wrappedInteractions, threadID);
}
}
}
return returnValue;
} finally {
if (!hasRun) {
hasRun = true;
wrappedInteractions.forEach(function(interaction) {
interaction.__count--;
if (subscriber !== null && interaction.__count === 0) {
subscriber.onInteractionScheduledWorkCompleted(interaction);
}
});
}
}
}
wrapped.cancel = function cancel() {
subscriber = exports2.__subscriberRef.current;
try {
if (subscriber !== null) {
subscriber.onWorkCanceled(wrappedInteractions, threadID);
}
} finally {
wrappedInteractions.forEach(function(interaction) {
interaction.__count--;
if (subscriber && interaction.__count === 0) {
subscriber.onInteractionScheduledWorkCompleted(interaction);
}
});
}
};
return wrapped;
}
var subscribers = null;
{
subscribers = new Set();
}
function unstable_subscribe(subscriber) {
{
subscribers.add(subscriber);
if (subscribers.size === 1) {
exports2.__subscriberRef.current = {
onInteractionScheduledWorkCompleted,
onInteractionTraced,
onWorkCanceled,
onWorkScheduled,
onWorkStarted,
onWorkStopped
};
}
}
}
function unstable_unsubscribe(subscriber) {
{
subscribers.delete(subscriber);
if (subscribers.size === 0) {
exports2.__subscriberRef.current = null;
}
}
}
function onInteractionTraced(interaction) {
var didCatchError = false;
var caughtError = null;
subscribers.forEach(function(subscriber) {
try {
subscriber.onInteractionTraced(interaction);
} catch (error) {
if (!didCatchError) {
didCatchError = true;
caughtError = error;
}
}
});
if (didCatchError) {
throw caughtError;
}
}
function onInteractionScheduledWorkCompleted(interaction) {
var didCatchError = false;
var caughtError = null;
subscribers.forEach(function(subscriber) {
try {
subscriber.onInteractionScheduledWorkCompleted(interaction);
} catch (error) {
if (!didCatchError) {
didCatchError = true;
caughtError = error;
}
}
});
if (didCatchError) {
throw caughtError;
}
}
function onWorkScheduled(interactions, threadID) {
var didCatchError = false;
var caughtError = null;
subscribers.forEach(function(subscriber) {
try {
subscriber.onWorkScheduled(interactions, threadID);
} catch (error) {
if (!didCatchError) {
didCatchError = true;
caughtError = error;
}
}
});
if (didCatchError) {
throw caughtError;
}
}
function onWorkStarted(interactions, threadID) {
var didCatchError = false;
var caughtError = null;
subscribers.forEach(function(subscriber) {
try {
subscriber.onWorkStarted(interactions, threadID);
} catch (error) {
if (!didCatchError) {
didCatchError = true;
caughtError = error;
}
}
});
if (didCatchError) {
throw caughtError;
}
}
function onWorkStopped(interactions, threadID) {
var didCatchError = false;
var caughtError = null;
subscribers.forEach(function(subscriber) {
try {
subscriber.onWorkStopped(interactions, threadID);
} catch (error) {
if (!didCatchError) {
didCatchError = true;
caughtError = error;
}
}
});
if (didCatchError) {
throw caughtError;
}
}
function onWorkCanceled(interactions, threadID) {
var didCatchError = false;
var caughtError = null;
subscribers.forEach(function(subscriber) {
try {
subscriber.onWorkCanceled(interactions, threadID);
} catch (error) {
if (!didCatchError) {
didCatchError = true;
caughtError = error;
}
}
});
if (didCatchError) {
throw caughtError;
}
}
exports2.unstable_clear = unstable_clear;
exports2.unstable_getCurrent = unstable_getCurrent;
exports2.unstable_getThreadID = unstable_getThreadID;
exports2.unstable_subscribe = unstable_subscribe;
exports2.unstable_trace = unstable_trace;
exports2.unstable_unsubscribe = unstable_unsubscribe;
exports2.unstable_wrap = unstable_wrap;
})();
}
}
});
// node_modules/scheduler/tracing.js
var require_tracing = __commonJS({
"node_modules/scheduler/tracing.js"(exports2, module2) {
"use strict";
if (false) {
module2.exports = null;
} else {
module2.exports = require_scheduler_tracing_development();
}
}
});
// node_modules/react-dom/cjs/react-dom.development.js
var require_react_dom_development = __commonJS({
"node_modules/react-dom/cjs/react-dom.development.js"(exports2) {
"use strict";
if (true) {
(function() {
"use strict";
var React3 = require_react();
var _assign = require_object_assign();
var Scheduler = require_scheduler();
var tracing = require_tracing();
var ReactSharedInternals = React3.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
function warn(format) {
{
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
printWarning("warn", format, args);
}
}
function error(format) {
{
for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
args[_key2 - 1] = arguments[_key2];
}
printWarning("error", format, args);
}
}
function printWarning(level, format, args) {
{
var ReactDebugCurrentFrame2 = ReactSharedInternals.ReactDebugCurrentFrame;
var stack = ReactDebugCurrentFrame2.getStackAddendum();
if (stack !== "") {
format += "%s";
args = args.concat([stack]);
}
var argsWithFormat = args.map(function(item) {
return "" + item;
});
argsWithFormat.unshift("Warning: " + format);
Function.prototype.apply.call(console[level], console, argsWithFormat);
}
}
if (!React3) {
{
throw Error("ReactDOM was loaded before React. Make sure you load the React package before loading ReactDOM.");
}
}
var FunctionComponent = 0;
var ClassComponent = 1;
var IndeterminateComponent = 2;
var HostRoot = 3;
var HostPortal = 4;
var HostComponent = 5;
var HostText = 6;
var Fragment = 7;
var Mode = 8;
var ContextConsumer = 9;
var ContextProvider = 10;
var ForwardRef = 11;
var Profiler = 12;
var SuspenseComponent = 13;
var MemoComponent = 14;
var SimpleMemoComponent = 15;
var LazyComponent = 16;
var IncompleteClassComponent = 17;
var DehydratedFragment = 18;
var SuspenseListComponent = 19;
var FundamentalComponent = 20;
var ScopeComponent = 21;
var Block = 22;
var OffscreenComponent = 23;
var LegacyHiddenComponent = 24;
var enableProfilerTimer = true;
var enableFundamentalAPI = false;
var enableNewReconciler = false;
var warnAboutStringRefs = false;
var allNativeEvents = new Set();
var registrationNameDependencies = {};
var possibleRegistrationNames = {};
function registerTwoPhaseEvent(registrationName, dependencies) {
registerDirectEvent(registrationName, dependencies);
registerDirectEvent(registrationName + "Capture", dependencies);
}
function registerDirectEvent(registrationName, dependencies) {
{
if (registrationNameDependencies[registrationName]) {
error("EventRegistry: More than one plugin attempted to publish the same registration name, `%s`.", registrationName);
}
}
registrationNameDependencies[registrationName] = dependencies;
{
var lowerCasedName = registrationName.toLowerCase();
possibleRegistrationNames[lowerCasedName] = registrationName;
if (registrationName === "onDoubleClick") {
possibleRegistrationNames.ondblclick = registrationName;
}
}
for (var i = 0; i < dependencies.length; i++) {
allNativeEvents.add(dependencies[i]);
}
}
var canUseDOM = !!(typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined");
var RESERVED = 0;
var STRING = 1;
var BOOLEANISH_STRING = 2;
var BOOLEAN = 3;
var OVERLOADED_BOOLEAN = 4;
var NUMERIC = 5;
var POSITIVE_NUMERIC = 6;
var ATTRIBUTE_NAME_START_CHAR = ":A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD";
var ATTRIBUTE_NAME_CHAR = ATTRIBUTE_NAME_START_CHAR + "\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040";
var ROOT_ATTRIBUTE_NAME = "data-reactroot";
var VALID_ATTRIBUTE_NAME_REGEX = new RegExp("^[" + ATTRIBUTE_NAME_START_CHAR + "][" + ATTRIBUTE_NAME_CHAR + "]*$");
var hasOwnProperty = Object.prototype.hasOwnProperty;
var illegalAttributeNameCache = {};
var validatedAttributeNameCache = {};
function isAttributeNameSafe(attributeName) {
if (hasOwnProperty.call(validatedAttributeNameCache, attributeName)) {
return true;
}
if (hasOwnProperty.call(illegalAttributeNameCache, attributeName)) {
return false;
}
if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName)) {
validatedAttributeNameCache[attributeName] = true;
return true;
}
illegalAttributeNameCache[attributeName] = true;
{
error("Invalid attribute name: `%s`", attributeName);
}
return false;
}
function shouldIgnoreAttribute(name, propertyInfo, isCustomComponentTag) {
if (propertyInfo !== null) {
return propertyInfo.type === RESERVED;
}
if (isCustomComponentTag) {
return false;
}
if (name.length > 2 && (name[0] === "o" || name[0] === "O") && (name[1] === "n" || name[1] === "N")) {
return true;
}
return false;
}
function shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag) {
if (propertyInfo !== null && propertyInfo.type === RESERVED) {
return false;
}
switch (typeof value) {
case "function":
case "symbol":
return true;
case "boolean": {
if (isCustomComponentTag) {
return false;
}
if (propertyInfo !== null) {
return !propertyInfo.acceptsBooleans;
} else {
var prefix2 = name.toLowerCase().slice(0, 5);
return prefix2 !== "data-" && prefix2 !== "aria-";
}
}
default:
return false;
}
}
function shouldRemoveAttribute(name, value, propertyInfo, isCustomComponentTag) {
if (value === null || typeof value === "undefined") {
return true;
}
if (shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag)) {
return true;
}
if (isCustomComponentTag) {
return false;
}
if (propertyInfo !== null) {
switch (propertyInfo.type) {
case BOOLEAN:
return !value;
case OVERLOADED_BOOLEAN:
return value === false;
case NUMERIC:
return isNaN(value);
case POSITIVE_NUMERIC:
return isNaN(value) || value < 1;
}
}
return false;
}
function getPropertyInfo(name) {
return properties.hasOwnProperty(name) ? properties[name] : null;
}
function PropertyInfoRecord(name, type, mustUseProperty, attributeName, attributeNamespace, sanitizeURL2, removeEmptyString) {
this.acceptsBooleans = type === BOOLEANISH_STRING || type === BOOLEAN || type === OVERLOADED_BOOLEAN;
this.attributeName = attributeName;
this.attributeNamespace = attributeNamespace;
this.mustUseProperty = mustUseProperty;
this.propertyName = name;
this.type = type;
this.sanitizeURL = sanitizeURL2;
this.removeEmptyString = removeEmptyString;
}
var properties = {};
var reservedProps = [
"children",
"dangerouslySetInnerHTML",
"defaultValue",
"defaultChecked",
"innerHTML",
"suppressContentEditableWarning",
"suppressHydrationWarning",
"style"
];
reservedProps.forEach(function(name) {
properties[name] = new PropertyInfoRecord(name, RESERVED, false, name, null, false, false);
});
[["acceptCharset", "accept-charset"], ["className", "class"], ["htmlFor", "for"], ["httpEquiv", "http-equiv"]].forEach(function(_ref) {
var name = _ref[0], attributeName = _ref[1];
properties[name] = new PropertyInfoRecord(name, STRING, false, attributeName, null, false, false);
});
["contentEditable", "draggable", "spellCheck", "value"].forEach(function(name) {
properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, name.toLowerCase(), null, false, false);
});
["autoReverse", "externalResourcesRequired", "focusable", "preserveAlpha"].forEach(function(name) {
properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, name, null, false, false);
});
[
"allowFullScreen",
"async",
"autoFocus",
"autoPlay",
"controls",
"default",
"defer",
"disabled",
"disablePictureInPicture",
"disableRemotePlayback",
"formNoValidate",
"hidden",
"loop",
"noModule",
"noValidate",
"open",
"playsInline",
"readOnly",
"required",
"reversed",
"scoped",
"seamless",
"itemScope"
].forEach(function(name) {
properties[name] = new PropertyInfoRecord(name, BOOLEAN, false, name.toLowerCase(), null, false, false);
});
[
"checked",
"multiple",
"muted",
"selected"
].forEach(function(name) {
properties[name] = new PropertyInfoRecord(name, BOOLEAN, true, name, null, false, false);
});
[
"capture",
"download"
].forEach(function(name) {
properties[name] = new PropertyInfoRecord(name, OVERLOADED_BOOLEAN, false, name, null, false, false);
});
[
"cols",
"rows",
"size",
"span"
].forEach(function(name) {
properties[name] = new PropertyInfoRecord(name, POSITIVE_NUMERIC, false, name, null, false, false);
});
["rowSpan", "start"].forEach(function(name) {
properties[name] = new PropertyInfoRecord(name, NUMERIC, false, name.toLowerCase(), null, false, false);
});
var CAMELIZE = /[\-\:]([a-z])/g;
var capitalize = function(token) {
return token[1].toUpperCase();
};
[
"accent-height",
"alignment-baseline",
"arabic-form",
"baseline-shift",
"cap-height",
"clip-path",
"clip-rule",
"color-interpolation",
"color-interpolation-filters",
"color-profile",
"color-rendering",
"dominant-baseline",
"enable-background",
"fill-opacity",
"fill-rule",
"flood-color",
"flood-opacity",
"font-family",
"font-size",
"font-size-adjust",
"font-stretch",
"font-style",
"font-variant",
"font-weight",
"glyph-name",
"glyph-orientation-horizontal",
"glyph-orientation-vertical",
"horiz-adv-x",
"horiz-origin-x",
"image-rendering",
"letter-spacing",
"lighting-color",
"marker-end",
"marker-mid",
"marker-start",
"overline-position",
"overline-thickness",
"paint-order",
"panose-1",
"pointer-events",
"rendering-intent",
"shape-rendering",
"stop-color",
"stop-opacity",
"strikethrough-position",
"strikethrough-thickness",
"stroke-dasharray",
"stroke-dashoffset",
"stroke-linecap",
"stroke-linejoin",
"stroke-miterlimit",
"stroke-opacity",
"stroke-width",
"text-anchor",
"text-decoration",
"text-rendering",
"underline-position",
"underline-thickness",
"unicode-bidi",
"unicode-range",
"units-per-em",
"v-alphabetic",
"v-hanging",
"v-ideographic",
"v-mathematical",
"vector-effect",
"vert-adv-y",
"vert-origin-x",
"vert-origin-y",
"word-spacing",
"writing-mode",
"xmlns:xlink",
"x-height"
].forEach(function(attributeName) {
var name = attributeName.replace(CAMELIZE, capitalize);
properties[name] = new PropertyInfoRecord(name, STRING, false, attributeName, null, false, false);
});
[
"xlink:actuate",
"xlink:arcrole",
"xlink:role",
"xlink:show",
"xlink:title",
"xlink:type"
].forEach(function(attributeName) {
var name = attributeName.replace(CAMELIZE, capitalize);
properties[name] = new PropertyInfoRecord(name, STRING, false, attributeName, "http://www.w3.org/1999/xlink", false, false);
});
[
"xml:base",
"xml:lang",
"xml:space"
].forEach(function(attributeName) {
var name = attributeName.replace(CAMELIZE, capitalize);
properties[name] = new PropertyInfoRecord(name, STRING, false, attributeName, "http://www.w3.org/XML/1998/namespace", false, false);
});
["tabIndex", "crossOrigin"].forEach(function(attributeName) {
properties[attributeName] = new PropertyInfoRecord(attributeName, STRING, false, attributeName.toLowerCase(), null, false, false);
});
var xlinkHref = "xlinkHref";
properties[xlinkHref] = new PropertyInfoRecord("xlinkHref", STRING, false, "xlink:href", "http://www.w3.org/1999/xlink", true, false);
["src", "href", "action", "formAction"].forEach(function(attributeName) {
properties[attributeName] = new PropertyInfoRecord(attributeName, STRING, false, attributeName.toLowerCase(), null, true, true);
});
var isJavaScriptProtocol = /^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*\:/i;
var didWarn = false;
function sanitizeURL(url) {
{
if (!didWarn && isJavaScriptProtocol.test(url)) {
didWarn = true;
error("A future version of React will block javascript: URLs as a security precaution. Use event handlers instead if you can. If you need to generate unsafe HTML try using dangerouslySetInnerHTML instead. React was passed %s.", JSON.stringify(url));
}
}
}
function getValueForProperty(node, name, expected, propertyInfo) {
{
if (propertyInfo.mustUseProperty) {
var propertyName = propertyInfo.propertyName;
return node[propertyName];
} else {
if (propertyInfo.sanitizeURL) {
sanitizeURL("" + expected);
}
var attributeName = propertyInfo.attributeName;
var stringValue = null;
if (propertyInfo.type === OVERLOADED_BOOLEAN) {
if (node.hasAttribute(attributeName)) {
var value = node.getAttribute(attributeName);
if (value === "") {
return true;
}
if (shouldRemoveAttribute(name, expected, propertyInfo, false)) {
return value;
}
if (value === "" + expected) {
return expected;
}
return value;
}
} else if (node.hasAttribute(attributeName)) {
if (shouldRemoveAttribute(name, expected, propertyInfo, false)) {
return node.getAttribute(attributeName);
}
if (propertyInfo.type === BOOLEAN) {
return expected;
}
stringValue = node.getAttribute(attributeName);
}
if (shouldRemoveAttribute(name, expected, propertyInfo, false)) {
return stringValue === null ? expected : stringValue;
} else if (stringValue === "" + expected) {
return expected;
} else {
return stringValue;
}
}
}
}
function getValueForAttribute(node, name, expected) {
{
if (!isAttributeNameSafe(name)) {
return;
}
if (isOpaqueHydratingObject(expected)) {
return expected;
}
if (!node.hasAttribute(name)) {
return expected === void 0 ? void 0 : null;
}
var value = node.getAttribute(name);
if (value === "" + expected) {
return expected;
}
return value;
}
}
function setValueForProperty(node, name, value, isCustomComponentTag) {
var propertyInfo = getPropertyInfo(name);
if (shouldIgnoreAttribute(name, propertyInfo, isCustomComponentTag)) {
return;
}
if (shouldRemoveAttribute(name, value, propertyInfo, isCustomComponentTag)) {
value = null;
}
if (isCustomComponentTag || propertyInfo === null) {
if (isAttributeNameSafe(name)) {
var _attributeName = name;
if (value === null) {
node.removeAttribute(_attributeName);
} else {
node.setAttribute(_attributeName, "" + value);
}
}
return;
}
var mustUseProperty = propertyInfo.mustUseProperty;
if (mustUseProperty) {
var propertyName = propertyInfo.propertyName;
if (value === null) {
var type = propertyInfo.type;
node[propertyName] = type === BOOLEAN ? false : "";
} else {
node[propertyName] = value;
}
return;
}
var attributeName = propertyInfo.attributeName, attributeNamespace = propertyInfo.attributeNamespace;
if (value === null) {
node.removeAttribute(attributeName);
} else {
var _type = propertyInfo.type;
var attributeValue;
if (_type === BOOLEAN || _type === OVERLOADED_BOOLEAN && value === true) {
attributeValue = "";
} else {
{
attributeValue = "" + value;
}
if (propertyInfo.sanitizeURL) {
sanitizeURL(attributeValue.toString());
}
}
if (attributeNamespace) {
node.setAttributeNS(attributeNamespace, attributeName, attributeValue);
} else {
node.setAttribute(attributeName, attributeValue);
}
}
}
var REACT_ELEMENT_TYPE = 60103;
var REACT_PORTAL_TYPE = 60106;
var REACT_FRAGMENT_TYPE = 60107;
var REACT_STRICT_MODE_TYPE = 60108;
var REACT_PROFILER_TYPE = 60114;
var REACT_PROVIDER_TYPE = 60109;
var REACT_CONTEXT_TYPE = 60110;
var REACT_FORWARD_REF_TYPE = 60112;
var REACT_SUSPENSE_TYPE = 60113;
var REACT_SUSPENSE_LIST_TYPE = 60120;
var REACT_MEMO_TYPE = 60115;
var REACT_LAZY_TYPE = 60116;
var REACT_BLOCK_TYPE = 60121;
var REACT_SERVER_BLOCK_TYPE = 60122;
var REACT_FUNDAMENTAL_TYPE = 60117;
var REACT_SCOPE_TYPE = 60119;
var REACT_OPAQUE_ID_TYPE = 60128;
var REACT_DEBUG_TRACING_MODE_TYPE = 60129;
var REACT_OFFSCREEN_TYPE = 60130;
var REACT_LEGACY_HIDDEN_TYPE = 60131;
if (typeof Symbol === "function" && Symbol.for) {
var symbolFor = Symbol.for;
REACT_ELEMENT_TYPE = symbolFor("react.element");
REACT_PORTAL_TYPE = symbolFor("react.portal");
REACT_FRAGMENT_TYPE = symbolFor("react.fragment");
REACT_STRICT_MODE_TYPE = symbolFor("react.strict_mode");
REACT_PROFILER_TYPE = symbolFor("react.profiler");
REACT_PROVIDER_TYPE = symbolFor("react.provider");
REACT_CONTEXT_TYPE = symbolFor("react.context");
REACT_FORWARD_REF_TYPE = symbolFor("react.forward_ref");
REACT_SUSPENSE_TYPE = symbolFor("react.suspense");
REACT_SUSPENSE_LIST_TYPE = symbolFor("react.suspense_list");
REACT_MEMO_TYPE = symbolFor("react.memo");
REACT_LAZY_TYPE = symbolFor("react.lazy");
REACT_BLOCK_TYPE = symbolFor("react.block");
REACT_SERVER_BLOCK_TYPE = symbolFor("react.server.block");
REACT_FUNDAMENTAL_TYPE = symbolFor("react.fundamental");
REACT_SCOPE_TYPE = symbolFor("react.scope");
REACT_OPAQUE_ID_TYPE = symbolFor("react.opaque.id");
REACT_DEBUG_TRACING_MODE_TYPE = symbolFor("react.debug_trace_mode");
REACT_OFFSCREEN_TYPE = symbolFor("react.offscreen");
REACT_LEGACY_HIDDEN_TYPE = symbolFor("react.legacy_hidden");
}
var MAYBE_ITERATOR_SYMBOL = typeof Symbol === "function" && Symbol.iterator;
var FAUX_ITERATOR_SYMBOL = "@@iterator";
function getIteratorFn(maybeIterable) {
if (maybeIterable === null || typeof maybeIterable !== "object") {
return null;
}
var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];
if (typeof maybeIterator === "function") {
return maybeIterator;
}
return null;
}
var disabledDepth = 0;
var prevLog;
var prevInfo;
var prevWarn;
var prevError;
var prevGroup;
var prevGroupCollapsed;
var prevGroupEnd;
function disabledLog() {
}
disabledLog.__reactDisabledLog = true;
function disableLogs() {
{
if (disabledDepth === 0) {
prevLog = console.log;
prevInfo = console.info;
prevWarn = console.warn;
prevError = console.error;
prevGroup = console.group;
prevGroupCollapsed = console.groupCollapsed;
prevGroupEnd = console.groupEnd;
var props = {
configurable: true,
enumerable: true,
value: disabledLog,
writable: true
};
Object.defineProperties(console, {
info: props,
log: props,
warn: props,
error: props,
group: props,
groupCollapsed: props,
groupEnd: props
});
}
disabledDepth++;
}
}
function reenableLogs() {
{
disabledDepth--;
if (disabledDepth === 0) {
var props = {
configurable: true,
enumerable: true,
writable: true
};
Object.defineProperties(console, {
log: _assign({}, props, {
value: prevLog
}),
info: _assign({}, props, {
value: prevInfo
}),
warn: _assign({}, props, {
value: prevWarn
}),
error: _assign({}, props, {
value: prevError
}),
group: _assign({}, props, {
value: prevGroup
}),
groupCollapsed: _assign({}, props, {
value: prevGroupCollapsed
}),
groupEnd: _assign({}, props, {
value: prevGroupEnd
})
});
}
if (disabledDepth < 0) {
error("disabledDepth fell below zero. This is a bug in React. Please file an issue.");
}
}
}
var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
var prefix;
function describeBuiltInComponentFrame(name, source, ownerFn) {
{
if (prefix === void 0) {
try {
throw Error();
} catch (x) {
var match = x.stack.trim().match(/\n( *(at )?)/);
prefix = match && match[1] || "";
}
}
return "\n" + prefix + name;
}
}
var reentry = false;
var componentFrameCache;
{
var PossiblyWeakMap = typeof WeakMap === "function" ? WeakMap : Map;
componentFrameCache = new PossiblyWeakMap();
}
function describeNativeComponentFrame(fn, construct) {
if (!fn || reentry) {
return "";
}
{
var frame = componentFrameCache.get(fn);
if (frame !== void 0) {
return frame;
}
}
var control;
reentry = true;
var previousPrepareStackTrace = Error.prepareStackTrace;
Error.prepareStackTrace = void 0;
var previousDispatcher;
{
previousDispatcher = ReactCurrentDispatcher.current;
ReactCurrentDispatcher.current = null;
disableLogs();
}
try {
if (construct) {
var Fake = function() {
throw Error();
};
Object.defineProperty(Fake.prototype, "props", {
set: function() {
throw Error();
}
});
if (typeof Reflect === "object" && Reflect.construct) {
try {
Reflect.construct(Fake, []);
} catch (x) {
control = x;
}
Reflect.construct(fn, [], Fake);
} else {
try {
Fake.call();
} catch (x) {
control = x;
}
fn.call(Fake.prototype);
}
} else {
try {
throw Error();
} catch (x) {
control = x;
}
fn();
}
} catch (sample) {
if (sample && control && typeof sample.stack === "string") {
var sampleLines = sample.stack.split("\n");
var controlLines = control.stack.split("\n");
var s = sampleLines.length - 1;
var c = controlLines.length - 1;
while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) {
c--;
}
for (; s >= 1 && c >= 0; s--, c--) {
if (sampleLines[s] !== controlLines[c]) {
if (s !== 1 || c !== 1) {
do {
s--;
c--;
if (c < 0 || sampleLines[s] !== controlLines[c]) {
var _frame = "\n" + sampleLines[s].replace(" at new ", " at ");
{
if (typeof fn === "function") {
componentFrameCache.set(fn, _frame);
}
}
return _frame;
}
} while (s >= 1 && c >= 0);
}
break;
}
}
}
} finally {
reentry = false;
{
ReactCurrentDispatcher.current = previousDispatcher;
reenableLogs();
}
Error.prepareStackTrace = previousPrepareStackTrace;
}
var name = fn ? fn.displayName || fn.name : "";
var syntheticFrame = name ? describeBuiltInComponentFrame(name) : "";
{
if (typeof fn === "function") {
componentFrameCache.set(fn, syntheticFrame);
}
}
return syntheticFrame;
}
function describeClassComponentFrame(ctor, source, ownerFn) {
{
return describeNativeComponentFrame(ctor, true);
}
}
function describeFunctionComponentFrame(fn, source, ownerFn) {
{
return describeNativeComponentFrame(fn, false);
}
}
function shouldConstruct(Component) {
var prototype = Component.prototype;
return !!(prototype && prototype.isReactComponent);
}
function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) {
if (type == null) {
return "";
}
if (typeof type === "function") {
{
return describeNativeComponentFrame(type, shouldConstruct(type));
}
}
if (typeof type === "string") {
return describeBuiltInComponentFrame(type);
}
switch (type) {
case REACT_SUSPENSE_TYPE:
return describeBuiltInComponentFrame("Suspense");
case REACT_SUSPENSE_LIST_TYPE:
return describeBuiltInComponentFrame("SuspenseList");
}
if (typeof type === "object") {
switch (type.$$typeof) {
case REACT_FORWARD_REF_TYPE:
return describeFunctionComponentFrame(type.render);
case REACT_MEMO_TYPE:
return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn);
case REACT_BLOCK_TYPE:
return describeFunctionComponentFrame(type._render);
case REACT_LAZY_TYPE: {
var lazyComponent = type;
var payload = lazyComponent._payload;
var init = lazyComponent._init;
try {
return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn);
} catch (x) {
}
}
}
}
return "";
}
function describeFiber(fiber) {
var owner = fiber._debugOwner ? fiber._debugOwner.type : null;
var source = fiber._debugSource;
switch (fiber.tag) {
case HostComponent:
return describeBuiltInComponentFrame(fiber.type);
case LazyComponent:
return describeBuiltInComponentFrame("Lazy");
case SuspenseComponent:
return describeBuiltInComponentFrame("Suspense");
case SuspenseListComponent:
return describeBuiltInComponentFrame("SuspenseList");
case FunctionComponent:
case IndeterminateComponent:
case SimpleMemoComponent:
return describeFunctionComponentFrame(fiber.type);
case ForwardRef:
return describeFunctionComponentFrame(fiber.type.render);
case Block:
return describeFunctionComponentFrame(fiber.type._render);
case ClassComponent:
return describeClassComponentFrame(fiber.type);
default:
return "";
}
}
function getStackByFiberInDevAndProd(workInProgress2) {
try {
var info = "";
var node = workInProgress2;
do {
info += describeFiber(node);
node = node.return;
} while (node);
return info;
} catch (x) {
return "\nError generating stack: " + x.message + "\n" + x.stack;
}
}
function getWrappedName(outerType, innerType, wrapperName) {
var functionName = innerType.displayName || innerType.name || "";
return outerType.displayName || (functionName !== "" ? wrapperName + "(" + functionName + ")" : wrapperName);
}
function getContextName(type) {
return type.displayName || "Context";
}
function getComponentName(type) {
if (type == null) {
return null;
}
{
if (typeof type.tag === "number") {
error("Received an unexpected object in getComponentName(). This is likely a bug in React. Please file an issue.");
}
}
if (typeof type === "function") {
return type.displayName || type.name || null;
}
if (typeof type === "string") {
return type;
}
switch (type) {
case REACT_FRAGMENT_TYPE:
return "Fragment";
case REACT_PORTAL_TYPE:
return "Portal";
case REACT_PROFILER_TYPE:
return "Profiler";
case REACT_STRICT_MODE_TYPE:
return "StrictMode";
case REACT_SUSPENSE_TYPE:
return "Suspense";
case REACT_SUSPENSE_LIST_TYPE:
return "SuspenseList";
}
if (typeof type === "object") {
switch (type.$$typeof) {
case REACT_CONTEXT_TYPE:
var context = type;
return getContextName(context) + ".Consumer";
case REACT_PROVIDER_TYPE:
var provider = type;
return getContextName(provider._context) + ".Provider";
case REACT_FORWARD_REF_TYPE:
return getWrappedName(type, type.render, "ForwardRef");
case REACT_MEMO_TYPE:
return getComponentName(type.type);
case REACT_BLOCK_TYPE:
return getComponentName(type._render);
case REACT_LAZY_TYPE: {
var lazyComponent = type;
var payload = lazyComponent._payload;
var init = lazyComponent._init;
try {
return getComponentName(init(payload));
} catch (x) {
return null;
}
}
}
}
return null;
}
var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
var current = null;
var isRendering = false;
function getCurrentFiberOwnerNameInDevOrNull() {
{
if (current === null) {
return null;
}
var owner = current._debugOwner;
if (owner !== null && typeof owner !== "undefined") {
return getComponentName(owner.type);
}
}
return null;
}
function getCurrentFiberStackInDev() {
{
if (current === null) {
return "";
}
return getStackByFiberInDevAndProd(current);
}
}
function resetCurrentFiber() {
{
ReactDebugCurrentFrame.getCurrentStack = null;
current = null;
isRendering = false;
}
}
function setCurrentFiber(fiber) {
{
ReactDebugCurrentFrame.getCurrentStack = getCurrentFiberStackInDev;
current = fiber;
isRendering = false;
}
}
function setIsRendering(rendering) {
{
isRendering = rendering;
}
}
function getIsRendering() {
{
return isRendering;
}
}
function toString(value) {
return "" + value;
}
function getToStringValue(value) {
switch (typeof value) {
case "boolean":
case "number":
case "object":
case "string":
case "undefined":
return value;
default:
return "";
}
}
var hasReadOnlyValue = {
button: true,
checkbox: true,
image: true,
hidden: true,
radio: true,
reset: true,
submit: true
};
function checkControlledValueProps(tagName, props) {
{
if (!(hasReadOnlyValue[props.type] || props.onChange || props.onInput || props.readOnly || props.disabled || props.value == null)) {
error("You provided a `value` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultValue`. Otherwise, set either `onChange` or `readOnly`.");
}
if (!(props.onChange || props.readOnly || props.disabled || props.checked == null)) {
error("You provided a `checked` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultChecked`. Otherwise, set either `onChange` or `readOnly`.");
}
}
}
function isCheckable(elem) {
var type = elem.type;
var nodeName = elem.nodeName;
return nodeName && nodeName.toLowerCase() === "input" && (type === "checkbox" || type === "radio");
}
function getTracker(node) {
return node._valueTracker;
}
function detachTracker(node) {
node._valueTracker = null;
}
function getValueFromNode(node) {
var value = "";
if (!node) {
return value;
}
if (isCheckable(node)) {
value = node.checked ? "true" : "false";
} else {
value = node.value;
}
return value;
}
function trackValueOnNode(node) {
var valueField = isCheckable(node) ? "checked" : "value";
var descriptor = Object.getOwnPropertyDescriptor(node.constructor.prototype, valueField);
var currentValue = "" + node[valueField];
if (node.hasOwnProperty(valueField) || typeof descriptor === "undefined" || typeof descriptor.get !== "function" || typeof descriptor.set !== "function") {
return;
}
var get2 = descriptor.get, set2 = descriptor.set;
Object.defineProperty(node, valueField, {
configurable: true,
get: function() {
return get2.call(this);
},
set: function(value) {
currentValue = "" + value;
set2.call(this, value);
}
});
Object.defineProperty(node, valueField, {
enumerable: descriptor.enumerable
});
var tracker = {
getValue: function() {
return currentValue;
},
setValue: function(value) {
currentValue = "" + value;
},
stopTracking: function() {
detachTracker(node);
delete node[valueField];
}
};
return tracker;
}
function track(node) {
if (getTracker(node)) {
return;
}
node._valueTracker = trackValueOnNode(node);
}
function updateValueIfChanged(node) {
if (!node) {
return false;
}
var tracker = getTracker(node);
if (!tracker) {
return true;
}
var lastValue = tracker.getValue();
var nextValue = getValueFromNode(node);
if (nextValue !== lastValue) {
tracker.setValue(nextValue);
return true;
}
return false;
}
function getActiveElement(doc) {
doc = doc || (typeof document !== "undefined" ? document : void 0);
if (typeof doc === "undefined") {
return null;
}
try {
return doc.activeElement || doc.body;
} catch (e) {
return doc.body;
}
}
var didWarnValueDefaultValue = false;
var didWarnCheckedDefaultChecked = false;
var didWarnControlledToUncontrolled = false;
var didWarnUncontrolledToControlled = false;
function isControlled(props) {
var usesChecked = props.type === "checkbox" || props.type === "radio";
return usesChecked ? props.checked != null : props.value != null;
}
function getHostProps(element, props) {
var node = element;
var checked = props.checked;
var hostProps = _assign({}, props, {
defaultChecked: void 0,
defaultValue: void 0,
value: void 0,
checked: checked != null ? checked : node._wrapperState.initialChecked
});
return hostProps;
}
function initWrapperState(element, props) {
{
checkControlledValueProps("input", props);
if (props.checked !== void 0 && props.defaultChecked !== void 0 && !didWarnCheckedDefaultChecked) {
error("%s contains an input of type %s with both checked and defaultChecked props. Input elements must be either controlled or uncontrolled (specify either the checked prop, or the defaultChecked prop, but not both). Decide between using a controlled or uncontrolled input element and remove one of these props. More info: https://reactjs.org/link/controlled-components", getCurrentFiberOwnerNameInDevOrNull() || "A component", props.type);
didWarnCheckedDefaultChecked = true;
}
if (props.value !== void 0 && props.defaultValue !== void 0 && !didWarnValueDefaultValue) {
error("%s contains an input of type %s with both value and defaultValue props. Input elements must be either controlled or uncontrolled (specify either the value prop, or the defaultValue prop, but not both). Decide between using a controlled or uncontrolled input element and remove one of these props. More info: https://reactjs.org/link/controlled-components", getCurrentFiberOwnerNameInDevOrNull() || "A component", props.type);
didWarnValueDefaultValue = true;
}
}
var node = element;
var defaultValue = props.defaultValue == null ? "" : props.defaultValue;
node._wrapperState = {
initialChecked: props.checked != null ? props.checked : props.defaultChecked,
initialValue: getToStringValue(props.value != null ? props.value : defaultValue),
controlled: isControlled(props)
};
}
function updateChecked(element, props) {
var node = element;
var checked = props.checked;
if (checked != null) {
setValueForProperty(node, "checked", checked, false);
}
}
function updateWrapper(element, props) {
var node = element;
{
var controlled = isControlled(props);
if (!node._wrapperState.controlled && controlled && !didWarnUncontrolledToControlled) {
error("A component is changing an uncontrolled input to be controlled. This is likely caused by the value changing from undefined to a defined value, which should not happen. Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: https://reactjs.org/link/controlled-components");
didWarnUncontrolledToControlled = true;
}
if (node._wrapperState.controlled && !controlled && !didWarnControlledToUncontrolled) {
error("A component is changing a controlled input to be uncontrolled. This is likely caused by the value changing from a defined to undefined, which should not happen. Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: https://reactjs.org/link/controlled-components");
didWarnControlledToUncontrolled = true;
}
}
updateChecked(element, props);
var value = getToStringValue(props.value);
var type = props.type;
if (value != null) {
if (type === "number") {
if (value === 0 && node.value === "" || node.value != value) {
node.value = toString(value);
}
} else if (node.value !== toString(value)) {
node.value = toString(value);
}
} else if (type === "submit" || type === "reset") {
node.removeAttribute("value");
return;
}
{
if (props.hasOwnProperty("value")) {
setDefaultValue(node, props.type, value);
} else if (props.hasOwnProperty("defaultValue")) {
setDefaultValue(node, props.type, getToStringValue(props.defaultValue));
}
}
{
if (props.checked == null && props.defaultChecked != null) {
node.defaultChecked = !!props.defaultChecked;
}
}
}
function postMountWrapper(element, props, isHydrating2) {
var node = element;
if (props.hasOwnProperty("value") || props.hasOwnProperty("defaultValue")) {
var type = props.type;
var isButton = type === "submit" || type === "reset";
if (isButton && (props.value === void 0 || props.value === null)) {
return;
}
var initialValue = toString(node._wrapperState.initialValue);
if (!isHydrating2) {
{
if (initialValue !== node.value) {
node.value = initialValue;
}
}
}
{
node.defaultValue = initialValue;
}
}
var name = node.name;
if (name !== "") {
node.name = "";
}
{
node.defaultChecked = !node.defaultChecked;
node.defaultChecked = !!node._wrapperState.initialChecked;
}
if (name !== "") {
node.name = name;
}
}
function restoreControlledState(element, props) {
var node = element;
updateWrapper(node, props);
updateNamedCousins(node, props);
}
function updateNamedCousins(rootNode, props) {
var name = props.name;
if (props.type === "radio" && name != null) {
var queryRoot = rootNode;
while (queryRoot.parentNode) {
queryRoot = queryRoot.parentNode;
}
var group = queryRoot.querySelectorAll("input[name=" + JSON.stringify("" + name) + '][type="radio"]');
for (var i = 0; i < group.length; i++) {
var otherNode = group[i];
if (otherNode === rootNode || otherNode.form !== rootNode.form) {
continue;
}
var otherProps = getFiberCurrentPropsFromNode(otherNode);
if (!otherProps) {
{
throw Error("ReactDOMInput: Mixing React and non-React radio inputs with the same `name` is not supported.");
}
}
updateValueIfChanged(otherNode);
updateWrapper(otherNode, otherProps);
}
}
}
function setDefaultValue(node, type, value) {
if (type !== "number" || getActiveElement(node.ownerDocument) !== node) {
if (value == null) {
node.defaultValue = toString(node._wrapperState.initialValue);
} else if (node.defaultValue !== toString(value)) {
node.defaultValue = toString(value);
}
}
}
var didWarnSelectedSetOnOption = false;
var didWarnInvalidChild = false;
function flattenChildren(children) {
var content = "";
React3.Children.forEach(children, function(child) {
if (child == null) {
return;
}
content += child;
});
return content;
}
function validateProps(element, props) {
{
if (typeof props.children === "object" && props.children !== null) {
React3.Children.forEach(props.children, function(child) {
if (child == null) {
return;
}
if (typeof child === "string" || typeof child === "number") {
return;
}
if (typeof child.type !== "string") {
return;
}
if (!didWarnInvalidChild) {
didWarnInvalidChild = true;
error("Only strings and numbers are supported as <option> children.");
}
});
}
if (props.selected != null && !didWarnSelectedSetOnOption) {
error("Use the `defaultValue` or `value` props on <select> instead of setting `selected` on <option>.");
didWarnSelectedSetOnOption = true;
}
}
}
function postMountWrapper$1(element, props) {
if (props.value != null) {
element.setAttribute("value", toString(getToStringValue(props.value)));
}
}
function getHostProps$1(element, props) {
var hostProps = _assign({
children: void 0
}, props);
var content = flattenChildren(props.children);
if (content) {
hostProps.children = content;
}
return hostProps;
}
var didWarnValueDefaultValue$1;
{
didWarnValueDefaultValue$1 = false;
}
function getDeclarationErrorAddendum() {
var ownerName = getCurrentFiberOwnerNameInDevOrNull();
if (ownerName) {
return "\n\nCheck the render method of `" + ownerName + "`.";
}
return "";
}
var valuePropNames = ["value", "defaultValue"];
function checkSelectPropTypes(props) {
{
checkControlledValueProps("select", props);
for (var i = 0; i < valuePropNames.length; i++) {
var propName = valuePropNames[i];
if (props[propName] == null) {
continue;
}
var isArray2 = Array.isArray(props[propName]);
if (props.multiple && !isArray2) {
error("The `%s` prop supplied to <select> must be an array if `multiple` is true.%s", propName, getDeclarationErrorAddendum());
} else if (!props.multiple && isArray2) {
error("The `%s` prop supplied to <select> must be a scalar value if `multiple` is false.%s", propName, getDeclarationErrorAddendum());
}
}
}
}
function updateOptions(node, multiple, propValue, setDefaultSelected) {
var options2 = node.options;
if (multiple) {
var selectedValues = propValue;
var selectedValue = {};
for (var i = 0; i < selectedValues.length; i++) {
selectedValue["$" + selectedValues[i]] = true;
}
for (var _i = 0; _i < options2.length; _i++) {
var selected = selectedValue.hasOwnProperty("$" + options2[_i].value);
if (options2[_i].selected !== selected) {
options2[_i].selected = selected;
}
if (selected && setDefaultSelected) {
options2[_i].defaultSelected = true;
}
}
} else {
var _selectedValue = toString(getToStringValue(propValue));
var defaultSelected = null;
for (var _i2 = 0; _i2 < options2.length; _i2++) {
if (options2[_i2].value === _selectedValue) {
options2[_i2].selected = true;
if (setDefaultSelected) {
options2[_i2].defaultSelected = true;
}
return;
}
if (defaultSelected === null && !options2[_i2].disabled) {
defaultSelected = options2[_i2];
}
}
if (defaultSelected !== null) {
defaultSelected.selected = true;
}
}
}
function getHostProps$2(element, props) {
return _assign({}, props, {
value: void 0
});
}
function initWrapperState$1(element, props) {
var node = element;
{
checkSelectPropTypes(props);
}
node._wrapperState = {
wasMultiple: !!props.multiple
};
{
if (props.value !== void 0 && props.defaultValue !== void 0 && !didWarnValueDefaultValue$1) {
error("Select elements must be either controlled or uncontrolled (specify either the value prop, or the defaultValue prop, but not both). Decide between using a controlled or uncontrolled select element and remove one of these props. More info: https://reactjs.org/link/controlled-components");
didWarnValueDefaultValue$1 = true;
}
}
}
function postMountWrapper$2(element, props) {
var node = element;
node.multiple = !!props.multiple;
var value = props.value;
if (value != null) {
updateOptions(node, !!props.multiple, value, false);
} else if (props.defaultValue != null) {
updateOptions(node, !!props.multiple, props.defaultValue, true);
}
}
function postUpdateWrapper(element, props) {
var node = element;
var wasMultiple = node._wrapperState.wasMultiple;
node._wrapperState.wasMultiple = !!props.multiple;
var value = props.value;
if (value != null) {
updateOptions(node, !!props.multiple, value, false);
} else if (wasMultiple !== !!props.multiple) {
if (props.defaultValue != null) {
updateOptions(node, !!props.multiple, props.defaultValue, true);
} else {
updateOptions(node, !!props.multiple, props.multiple ? [] : "", false);
}
}
}
function restoreControlledState$1(element, props) {
var node = element;
var value = props.value;
if (value != null) {
updateOptions(node, !!props.multiple, value, false);
}
}
var didWarnValDefaultVal = false;
function getHostProps$3(element, props) {
var node = element;
if (!(props.dangerouslySetInnerHTML == null)) {
{
throw Error("`dangerouslySetInnerHTML` does not make sense on <textarea>.");
}
}
var hostProps = _assign({}, props, {
value: void 0,
defaultValue: void 0,
children: toString(node._wrapperState.initialValue)
});
return hostProps;
}
function initWrapperState$2(element, props) {
var node = element;
{
checkControlledValueProps("textarea", props);
if (props.value !== void 0 && props.defaultValue !== void 0 && !didWarnValDefaultVal) {
error("%s contains a textarea with both value and defaultValue props. Textarea elements must be either controlled or uncontrolled (specify either the value prop, or the defaultValue prop, but not both). Decide between using a controlled or uncontrolled textarea and remove one of these props. More info: https://reactjs.org/link/controlled-components", getCurrentFiberOwnerNameInDevOrNull() || "A component");
didWarnValDefaultVal = true;
}
}
var initialValue = props.value;
if (initialValue == null) {
var children = props.children, defaultValue = props.defaultValue;
if (children != null) {
{
error("Use the `defaultValue` or `value` props instead of setting children on <textarea>.");
}
{
if (!(defaultValue == null)) {
{
throw Error("If you supply `defaultValue` on a <textarea>, do not pass children.");
}
}
if (Array.isArray(children)) {
if (!(children.length <= 1)) {
{
throw Error("<textarea> can only have at most one child.");
}
}
children = children[0];
}
defaultValue = children;
}
}
if (defaultValue == null) {
defaultValue = "";
}
initialValue = defaultValue;
}
node._wrapperState = {
initialValue: getToStringValue(initialValue)
};
}
function updateWrapper$1(element, props) {
var node = element;
var value = getToStringValue(props.value);
var defaultValue = getToStringValue(props.defaultValue);
if (value != null) {
var newValue = toString(value);
if (newValue !== node.value) {
node.value = newValue;
}
if (props.defaultValue == null && node.defaultValue !== newValue) {
node.defaultValue = newValue;
}
}
if (defaultValue != null) {
node.defaultValue = toString(defaultValue);
}
}
function postMountWrapper$3(element, props) {
var node = element;
var textContent = node.textContent;
if (textContent === node._wrapperState.initialValue) {
if (textContent !== "" && textContent !== null) {
node.value = textContent;
}
}
}
function restoreControlledState$2(element, props) {
updateWrapper$1(element, props);
}
var HTML_NAMESPACE = "http://www.w3.org/1999/xhtml";
var MATH_NAMESPACE = "http://www.w3.org/1998/Math/MathML";
var SVG_NAMESPACE = "http://www.w3.org/2000/svg";
var Namespaces = {
html: HTML_NAMESPACE,
mathml: MATH_NAMESPACE,
svg: SVG_NAMESPACE
};
function getIntrinsicNamespace(type) {
switch (type) {
case "svg":
return SVG_NAMESPACE;
case "math":
return MATH_NAMESPACE;
default:
return HTML_NAMESPACE;
}
}
function getChildNamespace(parentNamespace, type) {
if (parentNamespace == null || parentNamespace === HTML_NAMESPACE) {
return getIntrinsicNamespace(type);
}
if (parentNamespace === SVG_NAMESPACE && type === "foreignObject") {
return HTML_NAMESPACE;
}
return parentNamespace;
}
var createMicrosoftUnsafeLocalFunction = function(func) {
if (typeof MSApp !== "undefined" && MSApp.execUnsafeLocalFunction) {
return function(arg0, arg1, arg2, arg3) {
MSApp.execUnsafeLocalFunction(function() {
return func(arg0, arg1, arg2, arg3);
});
};
} else {
return func;
}
};
var reusableSVGContainer;
var setInnerHTML = createMicrosoftUnsafeLocalFunction(function(node, html) {
if (node.namespaceURI === Namespaces.svg) {
if (!("innerHTML" in node)) {
reusableSVGContainer = reusableSVGContainer || document.createElement("div");
reusableSVGContainer.innerHTML = "<svg>" + html.valueOf().toString() + "</svg>";
var svgNode = reusableSVGContainer.firstChild;
while (node.firstChild) {
node.removeChild(node.firstChild);
}
while (svgNode.firstChild) {
node.appendChild(svgNode.firstChild);
}
return;
}
}
node.innerHTML = html;
});
var ELEMENT_NODE = 1;
var TEXT_NODE = 3;
var COMMENT_NODE = 8;
var DOCUMENT_NODE = 9;
var DOCUMENT_FRAGMENT_NODE = 11;
var setTextContent = function(node, text) {
if (text) {
var firstChild = node.firstChild;
if (firstChild && firstChild === node.lastChild && firstChild.nodeType === TEXT_NODE) {
firstChild.nodeValue = text;
return;
}
}
node.textContent = text;
};
var shorthandToLonghand = {
animation: ["animationDelay", "animationDirection", "animationDuration", "animationFillMode", "animationIterationCount", "animationName", "animationPlayState", "animationTimingFunction"],
background: ["backgroundAttachment", "backgroundClip", "backgroundColor", "backgroundImage", "backgroundOrigin", "backgroundPositionX", "backgroundPositionY", "backgroundRepeat", "backgroundSize"],
backgroundPosition: ["backgroundPositionX", "backgroundPositionY"],
border: ["borderBottomColor", "borderBottomStyle", "borderBottomWidth", "borderImageOutset", "borderImageRepeat", "borderImageSlice", "borderImageSource", "borderImageWidth", "borderLeftColor", "borderLeftStyle", "borderLeftWidth", "borderRightColor", "borderRightStyle", "borderRightWidth", "borderTopColor", "borderTopStyle", "borderTopWidth"],
borderBlockEnd: ["borderBlockEndColor", "borderBlockEndStyle", "borderBlockEndWidth"],
borderBlockStart: ["borderBlockStartColor", "borderBlockStartStyle", "borderBlockStartWidth"],
borderBottom: ["borderBottomColor", "borderBottomStyle", "borderBottomWidth"],
borderColor: ["borderBottomColor", "borderLeftColor", "borderRightColor", "borderTopColor"],
borderImage: ["borderImageOutset", "borderImageRepeat", "borderImageSlice", "borderImageSource", "borderImageWidth"],
borderInlineEnd: ["borderInlineEndColor", "borderInlineEndStyle", "borderInlineEndWidth"],
borderInlineStart: ["borderInlineStartColor", "borderInlineStartStyle", "borderInlineStartWidth"],
borderLeft: ["borderLeftColor", "borderLeftStyle", "borderLeftWidth"],
borderRadius: ["borderBottomLeftRadius", "borderBottomRightRadius", "borderTopLeftRadius", "borderTopRightRadius"],
borderRight: ["borderRightColor", "borderRightStyle", "borderRightWidth"],
borderStyle: ["borderBottomStyle", "borderLeftStyle", "borderRightStyle", "borderTopStyle"],
borderTop: ["borderTopColor", "borderTopStyle", "borderTopWidth"],
borderWidth: ["borderBottomWidth", "borderLeftWidth", "borderRightWidth", "borderTopWidth"],
columnRule: ["columnRuleColor", "columnRuleStyle", "columnRuleWidth"],
columns: ["columnCount", "columnWidth"],
flex: ["flexBasis", "flexGrow", "flexShrink"],
flexFlow: ["flexDirection", "flexWrap"],
font: ["fontFamily", "fontFeatureSettings", "fontKerning", "fontLanguageOverride", "fontSize", "fontSizeAdjust", "fontStretch", "fontStyle", "fontVariant", "fontVariantAlternates", "fontVariantCaps", "fontVariantEastAsian", "fontVariantLigatures", "fontVariantNumeric", "fontVariantPosition", "fontWeight", "lineHeight"],
fontVariant: ["fontVariantAlternates", "fontVariantCaps", "fontVariantEastAsian", "fontVariantLigatures", "fontVariantNumeric", "fontVariantPosition"],
gap: ["columnGap", "rowGap"],
grid: ["gridAutoColumns", "gridAutoFlow", "gridAutoRows", "gridTemplateAreas", "gridTemplateColumns", "gridTemplateRows"],
gridArea: ["gridColumnEnd", "gridColumnStart", "gridRowEnd", "gridRowStart"],
gridColumn: ["gridColumnEnd", "gridColumnStart"],
gridColumnGap: ["columnGap"],
gridGap: ["columnGap", "rowGap"],
gridRow: ["gridRowEnd", "gridRowStart"],
gridRowGap: ["rowGap"],
gridTemplate: ["gridTemplateAreas", "gridTemplateColumns", "gridTemplateRows"],
listStyle: ["listStyleImage", "listStylePosition", "listStyleType"],
margin: ["marginBottom", "marginLeft", "marginRight", "marginTop"],
marker: ["markerEnd", "markerMid", "markerStart"],
mask: ["maskClip", "maskComposite", "maskImage", "maskMode", "maskOrigin", "maskPositionX", "maskPositionY", "maskRepeat", "maskSize"],
maskPosition: ["maskPositionX", "maskPositionY"],
outline: ["outlineColor", "outlineStyle", "outlineWidth"],
overflow: ["overflowX", "overflowY"],
padding: ["paddingBottom", "paddingLeft", "paddingRight", "paddingTop"],
placeContent: ["alignContent", "justifyContent"],
placeItems: ["alignItems", "justifyItems"],
placeSelf: ["alignSelf", "justifySelf"],
textDecoration: ["textDecorationColor", "textDecorationLine", "textDecorationStyle"],
textEmphasis: ["textEmphasisColor", "textEmphasisStyle"],
transition: ["transitionDelay", "transitionDuration", "transitionProperty", "transitionTimingFunction"],
wordWrap: ["overflowWrap"]
};
var isUnitlessNumber = {
animationIterationCount: true,
borderImageOutset: true,
borderImageSlice: true,
borderImageWidth: true,
boxFlex: true,
boxFlexGroup: true,
boxOrdinalGroup: true,
columnCount: true,
columns: true,
flex: true,
flexGrow: true,
flexPositive: true,
flexShrink: true,
flexNegative: true,
flexOrder: true,
gridArea: true,
gridRow: true,
gridRowEnd: true,
gridRowSpan: true,
gridRowStart: true,
gridColumn: true,
gridColumnEnd: true,
gridColumnSpan: true,
gridColumnStart: true,
fontWeight: true,
lineClamp: true,
lineHeight: true,
opacity: true,
order: true,
orphans: true,
tabSize: true,
widows: true,
zIndex: true,
zoom: true,
fillOpacity: true,
floodOpacity: true,
stopOpacity: true,
strokeDasharray: true,
strokeDashoffset: true,
strokeMiterlimit: true,
strokeOpacity: true,
strokeWidth: true
};
function prefixKey(prefix2, key) {
return prefix2 + key.charAt(0).toUpperCase() + key.substring(1);
}
var prefixes = ["Webkit", "ms", "Moz", "O"];
Object.keys(isUnitlessNumber).forEach(function(prop) {
prefixes.forEach(function(prefix2) {
isUnitlessNumber[prefixKey(prefix2, prop)] = isUnitlessNumber[prop];
});
});
function dangerousStyleValue(name, value, isCustomProperty) {
var isEmpty = value == null || typeof value === "boolean" || value === "";
if (isEmpty) {
return "";
}
if (!isCustomProperty && typeof value === "number" && value !== 0 && !(isUnitlessNumber.hasOwnProperty(name) && isUnitlessNumber[name])) {
return value + "px";
}
return ("" + value).trim();
}
var uppercasePattern = /([A-Z])/g;
var msPattern = /^ms-/;
function hyphenateStyleName(name) {
return name.replace(uppercasePattern, "-$1").toLowerCase().replace(msPattern, "-ms-");
}
var warnValidStyle = function() {
};
{
var badVendoredStyleNamePattern = /^(?:webkit|moz|o)[A-Z]/;
var msPattern$1 = /^-ms-/;
var hyphenPattern = /-(.)/g;
var badStyleValueWithSemicolonPattern = /;\s*$/;
var warnedStyleNames = {};
var warnedStyleValues = {};
var warnedForNaNValue = false;
var warnedForInfinityValue = false;
var camelize = function(string) {
return string.replace(hyphenPattern, function(_, character) {
return character.toUpperCase();
});
};
var warnHyphenatedStyleName = function(name) {
if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) {
return;
}
warnedStyleNames[name] = true;
error("Unsupported style property %s. Did you mean %s?", name, camelize(name.replace(msPattern$1, "ms-")));
};
var warnBadVendoredStyleName = function(name) {
if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) {
return;
}
warnedStyleNames[name] = true;
error("Unsupported vendor-prefixed style property %s. Did you mean %s?", name, name.charAt(0).toUpperCase() + name.slice(1));
};
var warnStyleValueWithSemicolon = function(name, value) {
if (warnedStyleValues.hasOwnProperty(value) && warnedStyleValues[value]) {
return;
}
warnedStyleValues[value] = true;
error(`Style property values shouldn't contain a semicolon. Try "%s: %s" instead.`, name, value.replace(badStyleValueWithSemicolonPattern, ""));
};
var warnStyleValueIsNaN = function(name, value) {
if (warnedForNaNValue) {
return;
}
warnedForNaNValue = true;
error("`NaN` is an invalid value for the `%s` css style property.", name);
};
var warnStyleValueIsInfinity = function(name, value) {
if (warnedForInfinityValue) {
return;
}
warnedForInfinityValue = true;
error("`Infinity` is an invalid value for the `%s` css style property.", name);
};
warnValidStyle = function(name, value) {
if (name.indexOf("-") > -1) {
warnHyphenatedStyleName(name);
} else if (badVendoredStyleNamePattern.test(name)) {
warnBadVendoredStyleName(name);
} else if (badStyleValueWithSemicolonPattern.test(value)) {
warnStyleValueWithSemicolon(name, value);
}
if (typeof value === "number") {
if (isNaN(value)) {
warnStyleValueIsNaN(name, value);
} else if (!isFinite(value)) {
warnStyleValueIsInfinity(name, value);
}
}
};
}
var warnValidStyle$1 = warnValidStyle;
function createDangerousStringForStyles(styles) {
{
var serialized = "";
var delimiter = "";
for (var styleName in styles) {
if (!styles.hasOwnProperty(styleName)) {
continue;
}
var styleValue = styles[styleName];
if (styleValue != null) {
var isCustomProperty = styleName.indexOf("--") === 0;
serialized += delimiter + (isCustomProperty ? styleName : hyphenateStyleName(styleName)) + ":";
serialized += dangerousStyleValue(styleName, styleValue, isCustomProperty);
delimiter = ";";
}
}
return serialized || null;
}
}
function setValueForStyles(node, styles) {
var style2 = node.style;
for (var styleName in styles) {
if (!styles.hasOwnProperty(styleName)) {
continue;
}
var isCustomProperty = styleName.indexOf("--") === 0;
{
if (!isCustomProperty) {
warnValidStyle$1(styleName, styles[styleName]);
}
}
var styleValue = dangerousStyleValue(styleName, styles[styleName], isCustomProperty);
if (styleName === "float") {
styleName = "cssFloat";
}
if (isCustomProperty) {
style2.setProperty(styleName, styleValue);
} else {
style2[styleName] = styleValue;
}
}
}
function isValueEmpty(value) {
return value == null || typeof value === "boolean" || value === "";
}
function expandShorthandMap(styles) {
var expanded = {};
for (var key in styles) {
var longhands = shorthandToLonghand[key] || [key];
for (var i = 0; i < longhands.length; i++) {
expanded[longhands[i]] = key;
}
}
return expanded;
}
function validateShorthandPropertyCollisionInDev(styleUpdates, nextStyles) {
{
if (!nextStyles) {
return;
}
var expandedUpdates = expandShorthandMap(styleUpdates);
var expandedStyles = expandShorthandMap(nextStyles);
var warnedAbout = {};
for (var key in expandedUpdates) {
var originalKey = expandedUpdates[key];
var correctOriginalKey = expandedStyles[key];
if (correctOriginalKey && originalKey !== correctOriginalKey) {
var warningKey = originalKey + "," + correctOriginalKey;
if (warnedAbout[warningKey]) {
continue;
}
warnedAbout[warningKey] = true;
error("%s a style property during rerender (%s) when a conflicting property is set (%s) can lead to styling bugs. To avoid this, don't mix shorthand and non-shorthand properties for the same value; instead, replace the shorthand with separate values.", isValueEmpty(styleUpdates[originalKey]) ? "Removing" : "Updating", originalKey, correctOriginalKey);
}
}
}
}
var omittedCloseTags = {
area: true,
base: true,
br: true,
col: true,
embed: true,
hr: true,
img: true,
input: true,
keygen: true,
link: true,
meta: true,
param: true,
source: true,
track: true,
wbr: true
};
var voidElementTags = _assign({
menuitem: true
}, omittedCloseTags);
var HTML = "__html";
function assertValidProps(tag, props) {
if (!props) {
return;
}
if (voidElementTags[tag]) {
if (!(props.children == null && props.dangerouslySetInnerHTML == null)) {
{
throw Error(tag + " is a void element tag and must neither have `children` nor use `dangerouslySetInnerHTML`.");
}
}
}
if (props.dangerouslySetInnerHTML != null) {
if (!(props.children == null)) {
{
throw Error("Can only set one of `children` or `props.dangerouslySetInnerHTML`.");
}
}
if (!(typeof props.dangerouslySetInnerHTML === "object" && HTML in props.dangerouslySetInnerHTML)) {
{
throw Error("`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. Please visit https://reactjs.org/link/dangerously-set-inner-html for more information.");
}
}
}
{
if (!props.suppressContentEditableWarning && props.contentEditable && props.children != null) {
error("A component is `contentEditable` and contains `children` managed by React. It is now your responsibility to guarantee that none of those nodes are unexpectedly modified or duplicated. This is probably not intentional.");
}
}
if (!(props.style == null || typeof props.style === "object")) {
{
throw Error("The `style` prop expects a mapping from style properties to values, not a string. For example, style={{marginRight: spacing + 'em'}} when using JSX.");
}
}
}
function isCustomComponent(tagName, props) {
if (tagName.indexOf("-") === -1) {
return typeof props.is === "string";
}
switch (tagName) {
case "annotation-xml":
case "color-profile":
case "font-face":
case "font-face-src":
case "font-face-uri":
case "font-face-format":
case "font-face-name":
case "missing-glyph":
return false;
default:
return true;
}
}
var possibleStandardNames = {
accept: "accept",
acceptcharset: "acceptCharset",
"accept-charset": "acceptCharset",
accesskey: "accessKey",
action: "action",
allowfullscreen: "allowFullScreen",
alt: "alt",
as: "as",
async: "async",
autocapitalize: "autoCapitalize",
autocomplete: "autoComplete",
autocorrect: "autoCorrect",
autofocus: "autoFocus",
autoplay: "autoPlay",
autosave: "autoSave",
capture: "capture",
cellpadding: "cellPadding",
cellspacing: "cellSpacing",
challenge: "challenge",
charset: "charSet",
checked: "checked",
children: "children",
cite: "cite",
class: "className",
classid: "classID",
classname: "className",
cols: "cols",
colspan: "colSpan",
content: "content",
contenteditable: "contentEditable",
contextmenu: "contextMenu",
controls: "controls",
controlslist: "controlsList",
coords: "coords",
crossorigin: "crossOrigin",
dangerouslysetinnerhtml: "dangerouslySetInnerHTML",
data: "data",
datetime: "dateTime",
default: "default",
defaultchecked: "defaultChecked",
defaultvalue: "defaultValue",
defer: "defer",
dir: "dir",
disabled: "disabled",
disablepictureinpicture: "disablePictureInPicture",
disableremoteplayback: "disableRemotePlayback",
download: "download",
draggable: "draggable",
enctype: "encType",
enterkeyhint: "enterKeyHint",
for: "htmlFor",
form: "form",
formmethod: "formMethod",
formaction: "formAction",
formenctype: "formEncType",
formnovalidate: "formNoValidate",
formtarget: "formTarget",
frameborder: "frameBorder",
headers: "headers",
height: "height",
hidden: "hidden",
high: "high",
href: "href",
hreflang: "hrefLang",
htmlfor: "htmlFor",
httpequiv: "httpEquiv",
"http-equiv": "httpEquiv",
icon: "icon",
id: "id",
innerhtml: "innerHTML",
inputmode: "inputMode",
integrity: "integrity",
is: "is",
itemid: "itemID",
itemprop: "itemProp",
itemref: "itemRef",
itemscope: "itemScope",
itemtype: "itemType",
keyparams: "keyParams",
keytype: "keyType",
kind: "kind",
label: "label",
lang: "lang",
list: "list",
loop: "loop",
low: "low",
manifest: "manifest",
marginwidth: "marginWidth",
marginheight: "marginHeight",
max: "max",
maxlength: "maxLength",
media: "media",
mediagroup: "mediaGroup",
method: "method",
min: "min",
minlength: "minLength",
multiple: "multiple",
muted: "muted",
name: "name",
nomodule: "noModule",
nonce: "nonce",
novalidate: "noValidate",
open: "open",
optimum: "optimum",
pattern: "pattern",
placeholder: "placeholder",
playsinline: "playsInline",
poster: "poster",
preload: "preload",
profile: "profile",
radiogroup: "radioGroup",
readonly: "readOnly",
referrerpolicy: "referrerPolicy",
rel: "rel",
required: "required",
reversed: "reversed",
role: "role",
rows: "rows",
rowspan: "rowSpan",
sandbox: "sandbox",
scope: "scope",
scoped: "scoped",
scrolling: "scrolling",
seamless: "seamless",
selected: "selected",
shape: "shape",
size: "size",
sizes: "sizes",
span: "span",
spellcheck: "spellCheck",
src: "src",
srcdoc: "srcDoc",
srclang: "srcLang",
srcset: "srcSet",
start: "start",
step: "step",
style: "style",
summary: "summary",
tabindex: "tabIndex",
target: "target",
title: "title",
type: "type",
usemap: "useMap",
value: "value",
width: "width",
wmode: "wmode",
wrap: "wrap",
about: "about",
accentheight: "accentHeight",
"accent-height": "accentHeight",
accumulate: "accumulate",
additive: "additive",
alignmentbaseline: "alignmentBaseline",
"alignment-baseline": "alignmentBaseline",
allowreorder: "allowReorder",
alphabetic: "alphabetic",
amplitude: "amplitude",
arabicform: "arabicForm",
"arabic-form": "arabicForm",
ascent: "ascent",
attributename: "attributeName",
attributetype: "attributeType",
autoreverse: "autoReverse",
azimuth: "azimuth",
basefrequency: "baseFrequency",
baselineshift: "baselineShift",
"baseline-shift": "baselineShift",
baseprofile: "baseProfile",
bbox: "bbox",
begin: "begin",
bias: "bias",
by: "by",
calcmode: "calcMode",
capheight: "capHeight",
"cap-height": "capHeight",
clip: "clip",
clippath: "clipPath",
"clip-path": "clipPath",
clippathunits: "clipPathUnits",
cliprule: "clipRule",
"clip-rule": "clipRule",
color: "color",
colorinterpolation: "colorInterpolation",
"color-interpolation": "colorInterpolation",
colorinterpolationfilters: "colorInterpolationFilters",
"color-interpolation-filters": "colorInterpolationFilters",
colorprofile: "colorProfile",
"color-profile": "colorProfile",
colorrendering: "colorRendering",
"color-rendering": "colorRendering",
contentscripttype: "contentScriptType",
contentstyletype: "contentStyleType",
cursor: "cursor",
cx: "cx",
cy: "cy",
d: "d",
datatype: "datatype",
decelerate: "decelerate",
descent: "descent",
diffuseconstant: "diffuseConstant",
direction: "direction",
display: "display",
divisor: "divisor",
dominantbaseline: "dominantBaseline",
"dominant-baseline": "dominantBaseline",
dur: "dur",
dx: "dx",
dy: "dy",
edgemode: "edgeMode",
elevation: "elevation",
enablebackground: "enableBackground",
"enable-background": "enableBackground",
end: "end",
exponent: "exponent",
externalresourcesrequired: "externalResourcesRequired",
fill: "fill",
fillopacity: "fillOpacity",
"fill-opacity": "fillOpacity",
fillrule: "fillRule",
"fill-rule": "fillRule",
filter: "filter",
filterres: "filterRes",
filterunits: "filterUnits",
floodopacity: "floodOpacity",
"flood-opacity": "floodOpacity",
floodcolor: "floodColor",
"flood-color": "floodColor",
focusable: "focusable",
fontfamily: "fontFamily",
"font-family": "fontFamily",
fontsize: "fontSize",
"font-size": "fontSize",
fontsizeadjust: "fontSizeAdjust",
"font-size-adjust": "fontSizeAdjust",
fontstretch: "fontStretch",
"font-stretch": "fontStretch",
fontstyle: "fontStyle",
"font-style": "fontStyle",
fontvariant: "fontVariant",
"font-variant": "fontVariant",
fontweight: "fontWeight",
"font-weight": "fontWeight",
format: "format",
from: "from",
fx: "fx",
fy: "fy",
g1: "g1",
g2: "g2",
glyphname: "glyphName",
"glyph-name": "glyphName",
glyphorientationhorizontal: "glyphOrientationHorizontal",
"glyph-orientation-horizontal": "glyphOrientationHorizontal",
glyphorientationvertical: "glyphOrientationVertical",
"glyph-orientation-vertical": "glyphOrientationVertical",
glyphref: "glyphRef",
gradienttransform: "gradientTransform",
gradientunits: "gradientUnits",
hanging: "hanging",
horizadvx: "horizAdvX",
"horiz-adv-x": "horizAdvX",
horizoriginx: "horizOriginX",
"horiz-origin-x": "horizOriginX",
ideographic: "ideographic",
imagerendering: "imageRendering",
"image-rendering": "imageRendering",
in2: "in2",
in: "in",
inlist: "inlist",
intercept: "intercept",
k1: "k1",
k2: "k2",
k3: "k3",
k4: "k4",
k: "k",
kernelmatrix: "kernelMatrix",
kernelunitlength: "kernelUnitLength",
kerning: "kerning",
keypoints: "keyPoints",
keysplines: "keySplines",
keytimes: "keyTimes",
lengthadjust: "lengthAdjust",
letterspacing: "letterSpacing",
"letter-spacing": "letterSpacing",
lightingcolor: "lightingColor",
"lighting-color": "lightingColor",
limitingconeangle: "limitingConeAngle",
local: "local",
markerend: "markerEnd",
"marker-end": "markerEnd",
markerheight: "markerHeight",
markermid: "markerMid",
"marker-mid": "markerMid",
markerstart: "markerStart",
"marker-start": "markerStart",
markerunits: "markerUnits",
markerwidth: "markerWidth",
mask: "mask",
maskcontentunits: "maskContentUnits",
maskunits: "maskUnits",
mathematical: "mathematical",
mode: "mode",
numoctaves: "numOctaves",
offset: "offset",
opacity: "opacity",
operator: "operator",
order: "order",
orient: "orient",
orientation: "orientation",
origin: "origin",
overflow: "overflow",
overlineposition: "overlinePosition",
"overline-position": "overlinePosition",
overlinethickness: "overlineThickness",
"overline-thickness": "overlineThickness",
paintorder: "paintOrder",
"paint-order": "paintOrder",
panose1: "panose1",
"panose-1": "panose1",
pathlength: "pathLength",
patterncontentunits: "patternContentUnits",
patterntransform: "patternTransform",
patternunits: "patternUnits",
pointerevents: "pointerEvents",
"pointer-events": "pointerEvents",
points: "points",
pointsatx: "pointsAtX",
pointsaty: "pointsAtY",
pointsatz: "pointsAtZ",
prefix: "prefix",
preservealpha: "preserveAlpha",
preserveaspectratio: "preserveAspectRatio",
primitiveunits: "primitiveUnits",
property: "property",
r: "r",
radius: "radius",
refx: "refX",
refy: "refY",
renderingintent: "renderingIntent",
"rendering-intent": "renderingIntent",
repeatcount: "repeatCount",
repeatdur: "repeatDur",
requiredextensions: "requiredExtensions",
requiredfeatures: "requiredFeatures",
resource: "resource",
restart: "restart",
result: "result",
results: "results",
rotate: "rotate",
rx: "rx",
ry: "ry",
scale: "scale",
security: "security",
seed: "seed",
shaperendering: "shapeRendering",
"shape-rendering": "shapeRendering",
slope: "slope",
spacing: "spacing",
specularconstant: "specularConstant",
specularexponent: "specularExponent",
speed: "speed",
spreadmethod: "spreadMethod",
startoffset: "startOffset",
stddeviation: "stdDeviation",
stemh: "stemh",
stemv: "stemv",
stitchtiles: "stitchTiles",
stopcolor: "stopColor",
"stop-color": "stopColor",
stopopacity: "stopOpacity",
"stop-opacity": "stopOpacity",
strikethroughposition: "strikethroughPosition",
"strikethrough-position": "strikethroughPosition",
strikethroughthickness: "strikethroughThickness",
"strikethrough-thickness": "strikethroughThickness",
string: "string",
stroke: "stroke",
strokedasharray: "strokeDasharray",
"stroke-dasharray": "strokeDasharray",
strokedashoffset: "strokeDashoffset",
"stroke-dashoffset": "strokeDashoffset",
strokelinecap: "strokeLinecap",
"stroke-linecap": "strokeLinecap",
strokelinejoin: "strokeLinejoin",
"stroke-linejoin": "strokeLinejoin",
strokemiterlimit: "strokeMiterlimit",
"stroke-miterlimit": "strokeMiterlimit",
strokewidth: "strokeWidth",
"stroke-width": "strokeWidth",
strokeopacity: "strokeOpacity",
"stroke-opacity": "strokeOpacity",
suppresscontenteditablewarning: "suppressContentEditableWarning",
suppresshydrationwarning: "suppressHydrationWarning",
surfacescale: "surfaceScale",
systemlanguage: "systemLanguage",
tablevalues: "tableValues",
targetx: "targetX",
targety: "targetY",
textanchor: "textAnchor",
"text-anchor": "textAnchor",
textdecoration: "textDecoration",
"text-decoration": "textDecoration",
textlength: "textLength",
textrendering: "textRendering",
"text-rendering": "textRendering",
to: "to",
transform: "transform",
typeof: "typeof",
u1: "u1",
u2: "u2",
underlineposition: "underlinePosition",
"underline-position": "underlinePosition",
underlinethickness: "underlineThickness",
"underline-thickness": "underlineThickness",
unicode: "unicode",
unicodebidi: "unicodeBidi",
"unicode-bidi": "unicodeBidi",
unicoderange: "unicodeRange",
"unicode-range": "unicodeRange",
unitsperem: "unitsPerEm",
"units-per-em": "unitsPerEm",
unselectable: "unselectable",
valphabetic: "vAlphabetic",
"v-alphabetic": "vAlphabetic",
values: "values",
vectoreffect: "vectorEffect",
"vector-effect": "vectorEffect",
version: "version",
vertadvy: "vertAdvY",
"vert-adv-y": "vertAdvY",
vertoriginx: "vertOriginX",
"vert-origin-x": "vertOriginX",
vertoriginy: "vertOriginY",
"vert-origin-y": "vertOriginY",
vhanging: "vHanging",
"v-hanging": "vHanging",
videographic: "vIdeographic",
"v-ideographic": "vIdeographic",
viewbox: "viewBox",
viewtarget: "viewTarget",
visibility: "visibility",
vmathematical: "vMathematical",
"v-mathematical": "vMathematical",
vocab: "vocab",
widths: "widths",
wordspacing: "wordSpacing",
"word-spacing": "wordSpacing",
writingmode: "writingMode",
"writing-mode": "writingMode",
x1: "x1",
x2: "x2",
x: "x",
xchannelselector: "xChannelSelector",
xheight: "xHeight",
"x-height": "xHeight",
xlinkactuate: "xlinkActuate",
"xlink:actuate": "xlinkActuate",
xlinkarcrole: "xlinkArcrole",
"xlink:arcrole": "xlinkArcrole",
xlinkhref: "xlinkHref",
"xlink:href": "xlinkHref",
xlinkrole: "xlinkRole",
"xlink:role": "xlinkRole",
xlinkshow: "xlinkShow",
"xlink:show": "xlinkShow",
xlinktitle: "xlinkTitle",
"xlink:title": "xlinkTitle",
xlinktype: "xlinkType",
"xlink:type": "xlinkType",
xmlbase: "xmlBase",
"xml:base": "xmlBase",
xmllang: "xmlLang",
"xml:lang": "xmlLang",
xmlns: "xmlns",
"xml:space": "xmlSpace",
xmlnsxlink: "xmlnsXlink",
"xmlns:xlink": "xmlnsXlink",
xmlspace: "xmlSpace",
y1: "y1",
y2: "y2",
y: "y",
ychannelselector: "yChannelSelector",
z: "z",
zoomandpan: "zoomAndPan"
};
var ariaProperties = {
"aria-current": 0,
"aria-details": 0,
"aria-disabled": 0,
"aria-hidden": 0,
"aria-invalid": 0,
"aria-keyshortcuts": 0,
"aria-label": 0,
"aria-roledescription": 0,
"aria-autocomplete": 0,
"aria-checked": 0,
"aria-expanded": 0,
"aria-haspopup": 0,
"aria-level": 0,
"aria-modal": 0,
"aria-multiline": 0,
"aria-multiselectable": 0,
"aria-orientation": 0,
"aria-placeholder": 0,
"aria-pressed": 0,
"aria-readonly": 0,
"aria-required": 0,
"aria-selected": 0,
"aria-sort": 0,
"aria-valuemax": 0,
"aria-valuemin": 0,
"aria-valuenow": 0,
"aria-valuetext": 0,
"aria-atomic": 0,
"aria-busy": 0,
"aria-live": 0,
"aria-relevant": 0,
"aria-dropeffect": 0,
"aria-grabbed": 0,
"aria-activedescendant": 0,
"aria-colcount": 0,
"aria-colindex": 0,
"aria-colspan": 0,
"aria-controls": 0,
"aria-describedby": 0,
"aria-errormessage": 0,
"aria-flowto": 0,
"aria-labelledby": 0,
"aria-owns": 0,
"aria-posinset": 0,
"aria-rowcount": 0,
"aria-rowindex": 0,
"aria-rowspan": 0,
"aria-setsize": 0
};
var warnedProperties = {};
var rARIA = new RegExp("^(aria)-[" + ATTRIBUTE_NAME_CHAR + "]*$");
var rARIACamel = new RegExp("^(aria)[A-Z][" + ATTRIBUTE_NAME_CHAR + "]*$");
var hasOwnProperty$1 = Object.prototype.hasOwnProperty;
function validateProperty(tagName, name) {
{
if (hasOwnProperty$1.call(warnedProperties, name) && warnedProperties[name]) {
return true;
}
if (rARIACamel.test(name)) {
var ariaName = "aria-" + name.slice(4).toLowerCase();
var correctName = ariaProperties.hasOwnProperty(ariaName) ? ariaName : null;
if (correctName == null) {
error("Invalid ARIA attribute `%s`. ARIA attributes follow the pattern aria-* and must be lowercase.", name);
warnedProperties[name] = true;
return true;
}
if (name !== correctName) {
error("Invalid ARIA attribute `%s`. Did you mean `%s`?", name, correctName);
warnedProperties[name] = true;
return true;
}
}
if (rARIA.test(name)) {
var lowerCasedName = name.toLowerCase();
var standardName = ariaProperties.hasOwnProperty(lowerCasedName) ? lowerCasedName : null;
if (standardName == null) {
warnedProperties[name] = true;
return false;
}
if (name !== standardName) {
error("Unknown ARIA attribute `%s`. Did you mean `%s`?", name, standardName);
warnedProperties[name] = true;
return true;
}
}
}
return true;
}
function warnInvalidARIAProps(type, props) {
{
var invalidProps = [];
for (var key in props) {
var isValid = validateProperty(type, key);
if (!isValid) {
invalidProps.push(key);
}
}
var unknownPropString = invalidProps.map(function(prop) {
return "`" + prop + "`";
}).join(", ");
if (invalidProps.length === 1) {
error("Invalid aria prop %s on <%s> tag. For details, see https://reactjs.org/link/invalid-aria-props", unknownPropString, type);
} else if (invalidProps.length > 1) {
error("Invalid aria props %s on <%s> tag. For details, see https://reactjs.org/link/invalid-aria-props", unknownPropString, type);
}
}
}
function validateProperties(type, props) {
if (isCustomComponent(type, props)) {
return;
}
warnInvalidARIAProps(type, props);
}
var didWarnValueNull = false;
function validateProperties$1(type, props) {
{
if (type !== "input" && type !== "textarea" && type !== "select") {
return;
}
if (props != null && props.value === null && !didWarnValueNull) {
didWarnValueNull = true;
if (type === "select" && props.multiple) {
error("`value` prop on `%s` should not be null. Consider using an empty array when `multiple` is set to `true` to clear the component or `undefined` for uncontrolled components.", type);
} else {
error("`value` prop on `%s` should not be null. Consider using an empty string to clear the component or `undefined` for uncontrolled components.", type);
}
}
}
}
var validateProperty$1 = function() {
};
{
var warnedProperties$1 = {};
var _hasOwnProperty = Object.prototype.hasOwnProperty;
var EVENT_NAME_REGEX = /^on./;
var INVALID_EVENT_NAME_REGEX = /^on[^A-Z]/;
var rARIA$1 = new RegExp("^(aria)-[" + ATTRIBUTE_NAME_CHAR + "]*$");
var rARIACamel$1 = new RegExp("^(aria)[A-Z][" + ATTRIBUTE_NAME_CHAR + "]*$");
validateProperty$1 = function(tagName, name, value, eventRegistry) {
if (_hasOwnProperty.call(warnedProperties$1, name) && warnedProperties$1[name]) {
return true;
}
var lowerCasedName = name.toLowerCase();
if (lowerCasedName === "onfocusin" || lowerCasedName === "onfocusout") {
error("React uses onFocus and onBlur instead of onFocusIn and onFocusOut. All React events are normalized to bubble, so onFocusIn and onFocusOut are not needed/supported by React.");
warnedProperties$1[name] = true;
return true;
}
if (eventRegistry != null) {
var registrationNameDependencies2 = eventRegistry.registrationNameDependencies, possibleRegistrationNames2 = eventRegistry.possibleRegistrationNames;
if (registrationNameDependencies2.hasOwnProperty(name)) {
return true;
}
var registrationName = possibleRegistrationNames2.hasOwnProperty(lowerCasedName) ? possibleRegistrationNames2[lowerCasedName] : null;
if (registrationName != null) {
error("Invalid event handler property `%s`. Did you mean `%s`?", name, registrationName);
warnedProperties$1[name] = true;
return true;
}
if (EVENT_NAME_REGEX.test(name)) {
error("Unknown event handler property `%s`. It will be ignored.", name);
warnedProperties$1[name] = true;
return true;
}
} else if (EVENT_NAME_REGEX.test(name)) {
if (INVALID_EVENT_NAME_REGEX.test(name)) {
error("Invalid event handler property `%s`. React events use the camelCase naming convention, for example `onClick`.", name);
}
warnedProperties$1[name] = true;
return true;
}
if (rARIA$1.test(name) || rARIACamel$1.test(name)) {
return true;
}
if (lowerCasedName === "innerhtml") {
error("Directly setting property `innerHTML` is not permitted. For more information, lookup documentation on `dangerouslySetInnerHTML`.");
warnedProperties$1[name] = true;
return true;
}
if (lowerCasedName === "aria") {
error("The `aria` attribute is reserved for future use in React. Pass individual `aria-` attributes instead.");
warnedProperties$1[name] = true;
return true;
}
if (lowerCasedName === "is" && value !== null && value !== void 0 && typeof value !== "string") {
error("Received a `%s` for a string attribute `is`. If this is expected, cast the value to a string.", typeof value);
warnedProperties$1[name] = true;
return true;
}
if (typeof value === "number" && isNaN(value)) {
error("Received NaN for the `%s` attribute. If this is expected, cast the value to a string.", name);
warnedProperties$1[name] = true;
return true;
}
var propertyInfo = getPropertyInfo(name);
var isReserved = propertyInfo !== null && propertyInfo.type === RESERVED;
if (possibleStandardNames.hasOwnProperty(lowerCasedName)) {
var standardName = possibleStandardNames[lowerCasedName];
if (standardName !== name) {
error("Invalid DOM property `%s`. Did you mean `%s`?", name, standardName);
warnedProperties$1[name] = true;
return true;
}
} else if (!isReserved && name !== lowerCasedName) {
error("React does not recognize the `%s` prop on a DOM element. If you intentionally want it to appear in the DOM as a custom attribute, spell it as lowercase `%s` instead. If you accidentally passed it from a parent component, remove it from the DOM element.", name, lowerCasedName);
warnedProperties$1[name] = true;
return true;
}
if (typeof value === "boolean" && shouldRemoveAttributeWithWarning(name, value, propertyInfo, false)) {
if (value) {
error('Received `%s` for a non-boolean attribute `%s`.\n\nIf you want to write it to the DOM, pass a string instead: %s="%s" or %s={value.toString()}.', value, name, name, value, name);
} else {
error('Received `%s` for a non-boolean attribute `%s`.\n\nIf you want to write it to the DOM, pass a string instead: %s="%s" or %s={value.toString()}.\n\nIf you used to conditionally omit it with %s={condition && value}, pass %s={condition ? value : undefined} instead.', value, name, name, value, name, name, name);
}
warnedProperties$1[name] = true;
return true;
}
if (isReserved) {
return true;
}
if (shouldRemoveAttributeWithWarning(name, value, propertyInfo, false)) {
warnedProperties$1[name] = true;
return false;
}
if ((value === "false" || value === "true") && propertyInfo !== null && propertyInfo.type === BOOLEAN) {
error("Received the string `%s` for the boolean attribute `%s`. %s Did you mean %s={%s}?", value, name, value === "false" ? "The browser will interpret it as a truthy value." : 'Although this works, it will not work as expected if you pass the string "false".', name, value);
warnedProperties$1[name] = true;
return true;
}
return true;
};
}
var warnUnknownProperties = function(type, props, eventRegistry) {
{
var unknownProps = [];
for (var key in props) {
var isValid = validateProperty$1(type, key, props[key], eventRegistry);
if (!isValid) {
unknownProps.push(key);
}
}
var unknownPropString = unknownProps.map(function(prop) {
return "`" + prop + "`";
}).join(", ");
if (unknownProps.length === 1) {
error("Invalid value for prop %s on <%s> tag. Either remove it from the element, or pass a string or number value to keep it in the DOM. For details, see https://reactjs.org/link/attribute-behavior ", unknownPropString, type);
} else if (unknownProps.length > 1) {
error("Invalid values for props %s on <%s> tag. Either remove them from the element, or pass a string or number value to keep them in the DOM. For details, see https://reactjs.org/link/attribute-behavior ", unknownPropString, type);
}
}
};
function validateProperties$2(type, props, eventRegistry) {
if (isCustomComponent(type, props)) {
return;
}
warnUnknownProperties(type, props, eventRegistry);
}
var IS_EVENT_HANDLE_NON_MANAGED_NODE = 1;
var IS_NON_DELEGATED = 1 << 1;
var IS_CAPTURE_PHASE = 1 << 2;
var IS_REPLAYED = 1 << 4;
var SHOULD_NOT_PROCESS_POLYFILL_EVENT_PLUGINS = IS_EVENT_HANDLE_NON_MANAGED_NODE | IS_NON_DELEGATED | IS_CAPTURE_PHASE;
function getEventTarget(nativeEvent) {
var target = nativeEvent.target || nativeEvent.srcElement || window;
if (target.correspondingUseElement) {
target = target.correspondingUseElement;
}
return target.nodeType === TEXT_NODE ? target.parentNode : target;
}
var restoreImpl = null;
var restoreTarget = null;
var restoreQueue = null;
function restoreStateOfTarget(target) {
var internalInstance = getInstanceFromNode(target);
if (!internalInstance) {
return;
}
if (!(typeof restoreImpl === "function")) {
{
throw Error("setRestoreImplementation() needs to be called to handle a target for controlled events. This error is likely caused by a bug in React. Please file an issue.");
}
}
var stateNode = internalInstance.stateNode;
if (stateNode) {
var _props = getFiberCurrentPropsFromNode(stateNode);
restoreImpl(internalInstance.stateNode, internalInstance.type, _props);
}
}
function setRestoreImplementation(impl) {
restoreImpl = impl;
}
function enqueueStateRestore(target) {
if (restoreTarget) {
if (restoreQueue) {
restoreQueue.push(target);
} else {
restoreQueue = [target];
}
} else {
restoreTarget = target;
}
}
function needsStateRestore() {
return restoreTarget !== null || restoreQueue !== null;
}
function restoreStateIfNeeded() {
if (!restoreTarget) {
return;
}
var target = restoreTarget;
var queuedTargets = restoreQueue;
restoreTarget = null;
restoreQueue = null;
restoreStateOfTarget(target);
if (queuedTargets) {
for (var i = 0; i < queuedTargets.length; i++) {
restoreStateOfTarget(queuedTargets[i]);
}
}
}
var batchedUpdatesImpl = function(fn, bookkeeping) {
return fn(bookkeeping);
};
var discreteUpdatesImpl = function(fn, a, b, c, d) {
return fn(a, b, c, d);
};
var flushDiscreteUpdatesImpl = function() {
};
var batchedEventUpdatesImpl = batchedUpdatesImpl;
var isInsideEventHandler = false;
var isBatchingEventUpdates = false;
function finishEventHandler() {
var controlledComponentsHavePendingUpdates = needsStateRestore();
if (controlledComponentsHavePendingUpdates) {
flushDiscreteUpdatesImpl();
restoreStateIfNeeded();
}
}
function batchedUpdates(fn, bookkeeping) {
if (isInsideEventHandler) {
return fn(bookkeeping);
}
isInsideEventHandler = true;
try {
return batchedUpdatesImpl(fn, bookkeeping);
} finally {
isInsideEventHandler = false;
finishEventHandler();
}
}
function batchedEventUpdates(fn, a, b) {
if (isBatchingEventUpdates) {
return fn(a, b);
}
isBatchingEventUpdates = true;
try {
return batchedEventUpdatesImpl(fn, a, b);
} finally {
isBatchingEventUpdates = false;
finishEventHandler();
}
}
function discreteUpdates(fn, a, b, c, d) {
var prevIsInsideEventHandler = isInsideEventHandler;
isInsideEventHandler = true;
try {
return discreteUpdatesImpl(fn, a, b, c, d);
} finally {
isInsideEventHandler = prevIsInsideEventHandler;
if (!isInsideEventHandler) {
finishEventHandler();
}
}
}
function flushDiscreteUpdatesIfNeeded(timeStamp) {
{
if (!isInsideEventHandler) {
flushDiscreteUpdatesImpl();
}
}
}
function setBatchingImplementation(_batchedUpdatesImpl, _discreteUpdatesImpl, _flushDiscreteUpdatesImpl, _batchedEventUpdatesImpl) {
batchedUpdatesImpl = _batchedUpdatesImpl;
discreteUpdatesImpl = _discreteUpdatesImpl;
flushDiscreteUpdatesImpl = _flushDiscreteUpdatesImpl;
batchedEventUpdatesImpl = _batchedEventUpdatesImpl;
}
function isInteractive(tag) {
return tag === "button" || tag === "input" || tag === "select" || tag === "textarea";
}
function shouldPreventMouseEvent(name, type, props) {
switch (name) {
case "onClick":
case "onClickCapture":
case "onDoubleClick":
case "onDoubleClickCapture":
case "onMouseDown":
case "onMouseDownCapture":
case "onMouseMove":
case "onMouseMoveCapture":
case "onMouseUp":
case "onMouseUpCapture":
case "onMouseEnter":
return !!(props.disabled && isInteractive(type));
default:
return false;
}
}
function getListener(inst, registrationName) {
var stateNode = inst.stateNode;
if (stateNode === null) {
return null;
}
var props = getFiberCurrentPropsFromNode(stateNode);
if (props === null) {
return null;
}
var listener = props[registrationName];
if (shouldPreventMouseEvent(registrationName, inst.type, props)) {
return null;
}
if (!(!listener || typeof listener === "function")) {
{
throw Error("Expected `" + registrationName + "` listener to be a function, instead got a value of `" + typeof listener + "` type.");
}
}
return listener;
}
var passiveBrowserEventsSupported = false;
if (canUseDOM) {
try {
var options = {};
Object.defineProperty(options, "passive", {
get: function() {
passiveBrowserEventsSupported = true;
}
});
window.addEventListener("test", options, options);
window.removeEventListener("test", options, options);
} catch (e) {
passiveBrowserEventsSupported = false;
}
}
function invokeGuardedCallbackProd(name, func, context, a, b, c, d, e, f) {
var funcArgs = Array.prototype.slice.call(arguments, 3);
try {
func.apply(context, funcArgs);
} catch (error2) {
this.onError(error2);
}
}
var invokeGuardedCallbackImpl = invokeGuardedCallbackProd;
{
if (typeof window !== "undefined" && typeof window.dispatchEvent === "function" && typeof document !== "undefined" && typeof document.createEvent === "function") {
var fakeNode = document.createElement("react");
invokeGuardedCallbackImpl = function invokeGuardedCallbackDev(name, func, context, a, b, c, d, e, f) {
if (!(typeof document !== "undefined")) {
{
throw Error("The `document` global was defined when React was initialized, but is not defined anymore. This can happen in a test environment if a component schedules an update from an asynchronous callback, but the test has already finished running. To solve this, you can either unmount the component at the end of your test (and ensure that any asynchronous operations get canceled in `componentWillUnmount`), or you can change the test itself to be asynchronous.");
}
}
var evt = document.createEvent("Event");
var didCall = false;
var didError = true;
var windowEvent = window.event;
var windowEventDescriptor = Object.getOwnPropertyDescriptor(window, "event");
function restoreAfterDispatch() {
fakeNode.removeEventListener(evtType, callCallback2, false);
if (typeof window.event !== "undefined" && window.hasOwnProperty("event")) {
window.event = windowEvent;
}
}
var funcArgs = Array.prototype.slice.call(arguments, 3);
function callCallback2() {
didCall = true;
restoreAfterDispatch();
func.apply(context, funcArgs);
didError = false;
}
var error2;
var didSetError = false;
var isCrossOriginError = false;
function handleWindowError(event) {
error2 = event.error;
didSetError = true;
if (error2 === null && event.colno === 0 && event.lineno === 0) {
isCrossOriginError = true;
}
if (event.defaultPrevented) {
if (error2 != null && typeof error2 === "object") {
try {
error2._suppressLogging = true;
} catch (inner) {
}
}
}
}
var evtType = "react-" + (name ? name : "invokeguardedcallback");
window.addEventListener("error", handleWindowError);
fakeNode.addEventListener(evtType, callCallback2, false);
evt.initEvent(evtType, false, false);
fakeNode.dispatchEvent(evt);
if (windowEventDescriptor) {
Object.defineProperty(window, "event", windowEventDescriptor);
}
if (didCall && didError) {
if (!didSetError) {
error2 = new Error(`An error was thrown inside one of your components, but React doesn't know what it was. This is likely due to browser flakiness. React does its best to preserve the "Pause on exceptions" behavior of the DevTools, which requires some DEV-mode only tricks. It's possible that these don't work in your browser. Try triggering the error in production mode, or switching to a modern browser. If you suspect that this is actually an issue with React, please file an issue.`);
} else if (isCrossOriginError) {
error2 = new Error("A cross-origin error was thrown. React doesn't have access to the actual error object in development. See https://reactjs.org/link/crossorigin-error for more information.");
}
this.onError(error2);
}
window.removeEventListener("error", handleWindowError);
if (!didCall) {
restoreAfterDispatch();
return invokeGuardedCallbackProd.apply(this, arguments);
}
};
}
}
var invokeGuardedCallbackImpl$1 = invokeGuardedCallbackImpl;
var hasError = false;
var caughtError = null;
var hasRethrowError = false;
var rethrowError = null;
var reporter = {
onError: function(error2) {
hasError = true;
caughtError = error2;
}
};
function invokeGuardedCallback(name, func, context, a, b, c, d, e, f) {
hasError = false;
caughtError = null;
invokeGuardedCallbackImpl$1.apply(reporter, arguments);
}
function invokeGuardedCallbackAndCatchFirstError(name, func, context, a, b, c, d, e, f) {
invokeGuardedCallback.apply(this, arguments);
if (hasError) {
var error2 = clearCaughtError();
if (!hasRethrowError) {
hasRethrowError = true;
rethrowError = error2;
}
}
}
function rethrowCaughtError() {
if (hasRethrowError) {
var error2 = rethrowError;
hasRethrowError = false;
rethrowError = null;
throw error2;
}
}
function hasCaughtError() {
return hasError;
}
function clearCaughtError() {
if (hasError) {
var error2 = caughtError;
hasError = false;
caughtError = null;
return error2;
} else {
{
{
throw Error("clearCaughtError was called but no error was captured. This error is likely caused by a bug in React. Please file an issue.");
}
}
}
}
function get(key) {
return key._reactInternals;
}
function has(key) {
return key._reactInternals !== void 0;
}
function set(key, value) {
key._reactInternals = value;
}
var NoFlags = 0;
var PerformedWork = 1;
var Placement = 2;
var Update = 4;
var PlacementAndUpdate = 6;
var Deletion = 8;
var ContentReset = 16;
var Callback = 32;
var DidCapture = 64;
var Ref = 128;
var Snapshot = 256;
var Passive = 512;
var PassiveUnmountPendingDev = 8192;
var Hydrating = 1024;
var HydratingAndUpdate = 1028;
var LifecycleEffectMask = 932;
var HostEffectMask = 2047;
var Incomplete = 2048;
var ShouldCapture = 4096;
var ForceUpdateForLegacySuspense = 16384;
var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner;
function getNearestMountedFiber(fiber) {
var node = fiber;
var nearestMounted = fiber;
if (!fiber.alternate) {
var nextNode = node;
do {
node = nextNode;
if ((node.flags & (Placement | Hydrating)) !== NoFlags) {
nearestMounted = node.return;
}
nextNode = node.return;
} while (nextNode);
} else {
while (node.return) {
node = node.return;
}
}
if (node.tag === HostRoot) {
return nearestMounted;
}
return null;
}
function getSuspenseInstanceFromFiber(fiber) {
if (fiber.tag === SuspenseComponent) {
var suspenseState = fiber.memoizedState;
if (suspenseState === null) {
var current2 = fiber.alternate;
if (current2 !== null) {
suspenseState = current2.memoizedState;
}
}
if (suspenseState !== null) {
return suspenseState.dehydrated;
}
}
return null;
}
function getContainerFromFiber(fiber) {
return fiber.tag === HostRoot ? fiber.stateNode.containerInfo : null;
}
function isFiberMounted(fiber) {
return getNearestMountedFiber(fiber) === fiber;
}
function isMounted(component) {
{
var owner = ReactCurrentOwner.current;
if (owner !== null && owner.tag === ClassComponent) {
var ownerFiber = owner;
var instance = ownerFiber.stateNode;
if (!instance._warnedAboutRefsInRender) {
error("%s is accessing isMounted inside its render() function. render() should be a pure function of props and state. It should never access something that requires stale data from the previous render, such as refs. Move this logic to componentDidMount and componentDidUpdate instead.", getComponentName(ownerFiber.type) || "A component");
}
instance._warnedAboutRefsInRender = true;
}
}
var fiber = get(component);
if (!fiber) {
return false;
}
return getNearestMountedFiber(fiber) === fiber;
}
function assertIsMounted(fiber) {
if (!(getNearestMountedFiber(fiber) === fiber)) {
{
throw Error("Unable to find node on an unmounted component.");
}
}
}
function findCurrentFiberUsingSlowPath(fiber) {
var alternate = fiber.alternate;
if (!alternate) {
var nearestMounted = getNearestMountedFiber(fiber);
if (!(nearestMounted !== null)) {
{
throw Error("Unable to find node on an unmounted component.");
}
}
if (nearestMounted !== fiber) {
return null;
}
return fiber;
}
var a = fiber;
var b = alternate;
while (true) {
var parentA = a.return;
if (parentA === null) {
break;
}
var parentB = parentA.alternate;
if (parentB === null) {
var nextParent = parentA.return;
if (nextParent !== null) {
a = b = nextParent;
continue;
}
break;
}
if (parentA.child === parentB.child) {
var child = parentA.child;
while (child) {
if (child === a) {
assertIsMounted(parentA);
return fiber;
}
if (child === b) {
assertIsMounted(parentA);
return alternate;
}
child = child.sibling;
}
{
{
throw Error("Unable to find node on an unmounted component.");
}
}
}
if (a.return !== b.return) {
a = parentA;
b = parentB;
} else {
var didFindChild = false;
var _child = parentA.child;
while (_child) {
if (_child === a) {
didFindChild = true;
a = parentA;
b = parentB;
break;
}
if (_child === b) {
didFindChild = true;
b = parentA;
a = parentB;
break;
}
_child = _child.sibling;
}
if (!didFindChild) {
_child = parentB.child;
while (_child) {
if (_child === a) {
didFindChild = true;
a = parentB;
b = parentA;
break;
}
if (_child === b) {
didFindChild = true;
b = parentB;
a = parentA;
break;
}
_child = _child.sibling;
}
if (!didFindChild) {
{
throw Error("Child was not found in either parent set. This indicates a bug in React related to the return pointer. Please file an issue.");
}
}
}
}
if (!(a.alternate === b)) {
{
throw Error("Return fibers should always be each others' alternates. This error is likely caused by a bug in React. Please file an issue.");
}
}
}
if (!(a.tag === HostRoot)) {
{
throw Error("Unable to find node on an unmounted component.");
}
}
if (a.stateNode.current === a) {
return fiber;
}
return alternate;
}
function findCurrentHostFiber(parent) {
var currentParent = findCurrentFiberUsingSlowPath(parent);
if (!currentParent) {
return null;
}
var node = currentParent;
while (true) {
if (node.tag === HostComponent || node.tag === HostText) {
return node;
} else if (node.child) {
node.child.return = node;
node = node.child;
continue;
}
if (node === currentParent) {
return null;
}
while (!node.sibling) {
if (!node.return || node.return === currentParent) {
return null;
}
node = node.return;
}
node.sibling.return = node.return;
node = node.sibling;
}
return null;
}
function findCurrentHostFiberWithNoPortals(parent) {
var currentParent = findCurrentFiberUsingSlowPath(parent);
if (!currentParent) {
return null;
}
var node = currentParent;
while (true) {
if (node.tag === HostComponent || node.tag === HostText || enableFundamentalAPI) {
return node;
} else if (node.child && node.tag !== HostPortal) {
node.child.return = node;
node = node.child;
continue;
}
if (node === currentParent) {
return null;
}
while (!node.sibling) {
if (!node.return || node.return === currentParent) {
return null;
}
node = node.return;
}
node.sibling.return = node.return;
node = node.sibling;
}
return null;
}
function doesFiberContain(parentFiber, childFiber) {
var node = childFiber;
var parentFiberAlternate = parentFiber.alternate;
while (node !== null) {
if (node === parentFiber || node === parentFiberAlternate) {
return true;
}
node = node.return;
}
return false;
}
var attemptUserBlockingHydration;
function setAttemptUserBlockingHydration(fn) {
attemptUserBlockingHydration = fn;
}
var attemptContinuousHydration;
function setAttemptContinuousHydration(fn) {
attemptContinuousHydration = fn;
}
var attemptHydrationAtCurrentPriority;
function setAttemptHydrationAtCurrentPriority(fn) {
attemptHydrationAtCurrentPriority = fn;
}
var attemptHydrationAtPriority;
function setAttemptHydrationAtPriority(fn) {
attemptHydrationAtPriority = fn;
}
var hasScheduledReplayAttempt = false;
var queuedDiscreteEvents = [];
var queuedFocus = null;
var queuedDrag = null;
var queuedMouse = null;
var queuedPointers = new Map();
var queuedPointerCaptures = new Map();
var queuedExplicitHydrationTargets = [];
function hasQueuedDiscreteEvents() {
return queuedDiscreteEvents.length > 0;
}
var discreteReplayableEvents = [
"mousedown",
"mouseup",
"touchcancel",
"touchend",
"touchstart",
"auxclick",
"dblclick",
"pointercancel",
"pointerdown",
"pointerup",
"dragend",
"dragstart",
"drop",
"compositionend",
"compositionstart",
"keydown",
"keypress",
"keyup",
"input",
"textInput",
"copy",
"cut",
"paste",
"click",
"change",
"contextmenu",
"reset",
"submit"
];
function isReplayableDiscreteEvent(eventType) {
return discreteReplayableEvents.indexOf(eventType) > -1;
}
function createQueuedReplayableEvent(blockedOn, domEventName, eventSystemFlags, targetContainer, nativeEvent) {
return {
blockedOn,
domEventName,
eventSystemFlags: eventSystemFlags | IS_REPLAYED,
nativeEvent,
targetContainers: [targetContainer]
};
}
function queueDiscreteEvent(blockedOn, domEventName, eventSystemFlags, targetContainer, nativeEvent) {
var queuedEvent = createQueuedReplayableEvent(blockedOn, domEventName, eventSystemFlags, targetContainer, nativeEvent);
queuedDiscreteEvents.push(queuedEvent);
}
function clearIfContinuousEvent(domEventName, nativeEvent) {
switch (domEventName) {
case "focusin":
case "focusout":
queuedFocus = null;
break;
case "dragenter":
case "dragleave":
queuedDrag = null;
break;
case "mouseover":
case "mouseout":
queuedMouse = null;
break;
case "pointerover":
case "pointerout": {
var pointerId = nativeEvent.pointerId;
queuedPointers.delete(pointerId);
break;
}
case "gotpointercapture":
case "lostpointercapture": {
var _pointerId = nativeEvent.pointerId;
queuedPointerCaptures.delete(_pointerId);
break;
}
}
}
function accumulateOrCreateContinuousQueuedReplayableEvent(existingQueuedEvent, blockedOn, domEventName, eventSystemFlags, targetContainer, nativeEvent) {
if (existingQueuedEvent === null || existingQueuedEvent.nativeEvent !== nativeEvent) {
var queuedEvent = createQueuedReplayableEvent(blockedOn, domEventName, eventSystemFlags, targetContainer, nativeEvent);
if (blockedOn !== null) {
var _fiber2 = getInstanceFromNode(blockedOn);
if (_fiber2 !== null) {
attemptContinuousHydration(_fiber2);
}
}
return queuedEvent;
}
existingQueuedEvent.eventSystemFlags |= eventSystemFlags;
var targetContainers = existingQueuedEvent.targetContainers;
if (targetContainer !== null && targetContainers.indexOf(targetContainer) === -1) {
targetContainers.push(targetContainer);
}
return existingQueuedEvent;
}
function queueIfContinuousEvent(blockedOn, domEventName, eventSystemFlags, targetContainer, nativeEvent) {
switch (domEventName) {
case "focusin": {
var focusEvent = nativeEvent;
queuedFocus = accumulateOrCreateContinuousQueuedReplayableEvent(queuedFocus, blockedOn, domEventName, eventSystemFlags, targetContainer, focusEvent);
return true;
}
case "dragenter": {
var dragEvent = nativeEvent;
queuedDrag = accumulateOrCreateContinuousQueuedReplayableEvent(queuedDrag, blockedOn, domEventName, eventSystemFlags, targetContainer, dragEvent);
return true;
}
case "mouseover": {
var mouseEvent = nativeEvent;
queuedMouse = accumulateOrCreateContinuousQueuedReplayableEvent(queuedMouse, blockedOn, domEventName, eventSystemFlags, targetContainer, mouseEvent);
return true;
}
case "pointerover": {
var pointerEvent = nativeEvent;
var pointerId = pointerEvent.pointerId;
queuedPointers.set(pointerId, accumulateOrCreateContinuousQueuedReplayableEvent(queuedPointers.get(pointerId) || null, blockedOn, domEventName, eventSystemFlags, targetContainer, pointerEvent));
return true;
}
case "gotpointercapture": {
var _pointerEvent = nativeEvent;
var _pointerId2 = _pointerEvent.pointerId;
queuedPointerCaptures.set(_pointerId2, accumulateOrCreateContinuousQueuedReplayableEvent(queuedPointerCaptures.get(_pointerId2) || null, blockedOn, domEventName, eventSystemFlags, targetContainer, _pointerEvent));
return true;
}
}
return false;
}
function attemptExplicitHydrationTarget(queuedTarget) {
var targetInst = getClosestInstanceFromNode(queuedTarget.target);
if (targetInst !== null) {
var nearestMounted = getNearestMountedFiber(targetInst);
if (nearestMounted !== null) {
var tag = nearestMounted.tag;
if (tag === SuspenseComponent) {
var instance = getSuspenseInstanceFromFiber(nearestMounted);
if (instance !== null) {
queuedTarget.blockedOn = instance;
attemptHydrationAtPriority(queuedTarget.lanePriority, function() {
Scheduler.unstable_runWithPriority(queuedTarget.priority, function() {
attemptHydrationAtCurrentPriority(nearestMounted);
});
});
return;
}
} else if (tag === HostRoot) {
var root2 = nearestMounted.stateNode;
if (root2.hydrate) {
queuedTarget.blockedOn = getContainerFromFiber(nearestMounted);
return;
}
}
}
}
queuedTarget.blockedOn = null;
}
function attemptReplayContinuousQueuedEvent(queuedEvent) {
if (queuedEvent.blockedOn !== null) {
return false;
}
var targetContainers = queuedEvent.targetContainers;
while (targetContainers.length > 0) {
var targetContainer = targetContainers[0];
var nextBlockedOn = attemptToDispatchEvent(queuedEvent.domEventName, queuedEvent.eventSystemFlags, targetContainer, queuedEvent.nativeEvent);
if (nextBlockedOn !== null) {
var _fiber3 = getInstanceFromNode(nextBlockedOn);
if (_fiber3 !== null) {
attemptContinuousHydration(_fiber3);
}
queuedEvent.blockedOn = nextBlockedOn;
return false;
}
targetContainers.shift();
}
return true;
}
function attemptReplayContinuousQueuedEventInMap(queuedEvent, key, map) {
if (attemptReplayContinuousQueuedEvent(queuedEvent)) {
map.delete(key);
}
}
function replayUnblockedEvents() {
hasScheduledReplayAttempt = false;
while (queuedDiscreteEvents.length > 0) {
var nextDiscreteEvent = queuedDiscreteEvents[0];
if (nextDiscreteEvent.blockedOn !== null) {
var _fiber4 = getInstanceFromNode(nextDiscreteEvent.blockedOn);
if (_fiber4 !== null) {
attemptUserBlockingHydration(_fiber4);
}
break;
}
var targetContainers = nextDiscreteEvent.targetContainers;
while (targetContainers.length > 0) {
var targetContainer = targetContainers[0];
var nextBlockedOn = attemptToDispatchEvent(nextDiscreteEvent.domEventName, nextDiscreteEvent.eventSystemFlags, targetContainer, nextDiscreteEvent.nativeEvent);
if (nextBlockedOn !== null) {
nextDiscreteEvent.blockedOn = nextBlockedOn;
break;
}
targetContainers.shift();
}
if (nextDiscreteEvent.blockedOn === null) {
queuedDiscreteEvents.shift();
}
}
if (queuedFocus !== null && attemptReplayContinuousQueuedEvent(queuedFocus)) {
queuedFocus = null;
}
if (queuedDrag !== null && attemptReplayContinuousQueuedEvent(queuedDrag)) {
queuedDrag = null;
}
if (queuedMouse !== null && attemptReplayContinuousQueuedEvent(queuedMouse)) {
queuedMouse = null;
}
queuedPointers.forEach(attemptReplayContinuousQueuedEventInMap);
queuedPointerCaptures.forEach(attemptReplayContinuousQueuedEventInMap);
}
function scheduleCallbackIfUnblocked(queuedEvent, unblocked) {
if (queuedEvent.blockedOn === unblocked) {
queuedEvent.blockedOn = null;
if (!hasScheduledReplayAttempt) {
hasScheduledReplayAttempt = true;
Scheduler.unstable_scheduleCallback(Scheduler.unstable_NormalPriority, replayUnblockedEvents);
}
}
}
function retryIfBlockedOn(unblocked) {
if (queuedDiscreteEvents.length > 0) {
scheduleCallbackIfUnblocked(queuedDiscreteEvents[0], unblocked);
for (var i = 1; i < queuedDiscreteEvents.length; i++) {
var queuedEvent = queuedDiscreteEvents[i];
if (queuedEvent.blockedOn === unblocked) {
queuedEvent.blockedOn = null;
}
}
}
if (queuedFocus !== null) {
scheduleCallbackIfUnblocked(queuedFocus, unblocked);
}
if (queuedDrag !== null) {
scheduleCallbackIfUnblocked(queuedDrag, unblocked);
}
if (queuedMouse !== null) {
scheduleCallbackIfUnblocked(queuedMouse, unblocked);
}
var unblock = function(queuedEvent2) {
return scheduleCallbackIfUnblocked(queuedEvent2, unblocked);
};
queuedPointers.forEach(unblock);
queuedPointerCaptures.forEach(unblock);
for (var _i = 0; _i < queuedExplicitHydrationTargets.length; _i++) {
var queuedTarget = queuedExplicitHydrationTargets[_i];
if (queuedTarget.blockedOn === unblocked) {
queuedTarget.blockedOn = null;
}
}
while (queuedExplicitHydrationTargets.length > 0) {
var nextExplicitTarget = queuedExplicitHydrationTargets[0];
if (nextExplicitTarget.blockedOn !== null) {
break;
} else {
attemptExplicitHydrationTarget(nextExplicitTarget);
if (nextExplicitTarget.blockedOn === null) {
queuedExplicitHydrationTargets.shift();
}
}
}
}
var DiscreteEvent = 0;
var UserBlockingEvent = 1;
var ContinuousEvent = 2;
function makePrefixMap(styleProp, eventName) {
var prefixes2 = {};
prefixes2[styleProp.toLowerCase()] = eventName.toLowerCase();
prefixes2["Webkit" + styleProp] = "webkit" + eventName;
prefixes2["Moz" + styleProp] = "moz" + eventName;
return prefixes2;
}
var vendorPrefixes = {
animationend: makePrefixMap("Animation", "AnimationEnd"),
animationiteration: makePrefixMap("Animation", "AnimationIteration"),
animationstart: makePrefixMap("Animation", "AnimationStart"),
transitionend: makePrefixMap("Transition", "TransitionEnd")
};
var prefixedEventNames = {};
var style = {};
if (canUseDOM) {
style = document.createElement("div").style;
if (!("AnimationEvent" in window)) {
delete vendorPrefixes.animationend.animation;
delete vendorPrefixes.animationiteration.animation;
delete vendorPrefixes.animationstart.animation;
}
if (!("TransitionEvent" in window)) {
delete vendorPrefixes.transitionend.transition;
}
}
function getVendorPrefixedEventName(eventName) {
if (prefixedEventNames[eventName]) {
return prefixedEventNames[eventName];
} else if (!vendorPrefixes[eventName]) {
return eventName;
}
var prefixMap = vendorPrefixes[eventName];
for (var styleProp in prefixMap) {
if (prefixMap.hasOwnProperty(styleProp) && styleProp in style) {
return prefixedEventNames[eventName] = prefixMap[styleProp];
}
}
return eventName;
}
var ANIMATION_END = getVendorPrefixedEventName("animationend");
var ANIMATION_ITERATION = getVendorPrefixedEventName("animationiteration");
var ANIMATION_START = getVendorPrefixedEventName("animationstart");
var TRANSITION_END = getVendorPrefixedEventName("transitionend");
var topLevelEventsToReactNames = new Map();
var eventPriorities = new Map();
var discreteEventPairsForSimpleEventPlugin = [
"cancel",
"cancel",
"click",
"click",
"close",
"close",
"contextmenu",
"contextMenu",
"copy",
"copy",
"cut",
"cut",
"auxclick",
"auxClick",
"dblclick",
"doubleClick",
"dragend",
"dragEnd",
"dragstart",
"dragStart",
"drop",
"drop",
"focusin",
"focus",
"focusout",
"blur",
"input",
"input",
"invalid",
"invalid",
"keydown",
"keyDown",
"keypress",
"keyPress",
"keyup",
"keyUp",
"mousedown",
"mouseDown",
"mouseup",
"mouseUp",
"paste",
"paste",
"pause",
"pause",
"play",
"play",
"pointercancel",
"pointerCancel",
"pointerdown",
"pointerDown",
"pointerup",
"pointerUp",
"ratechange",
"rateChange",
"reset",
"reset",
"seeked",
"seeked",
"submit",
"submit",
"touchcancel",
"touchCancel",
"touchend",
"touchEnd",
"touchstart",
"touchStart",
"volumechange",
"volumeChange"
];
var otherDiscreteEvents = ["change", "selectionchange", "textInput", "compositionstart", "compositionend", "compositionupdate"];
var userBlockingPairsForSimpleEventPlugin = ["drag", "drag", "dragenter", "dragEnter", "dragexit", "dragExit", "dragleave", "dragLeave", "dragover", "dragOver", "mousemove", "mouseMove", "mouseout", "mouseOut", "mouseover", "mouseOver", "pointermove", "pointerMove", "pointerout", "pointerOut", "pointerover", "pointerOver", "scroll", "scroll", "toggle", "toggle", "touchmove", "touchMove", "wheel", "wheel"];
var continuousPairsForSimpleEventPlugin = ["abort", "abort", ANIMATION_END, "animationEnd", ANIMATION_ITERATION, "animationIteration", ANIMATION_START, "animationStart", "canplay", "canPlay", "canplaythrough", "canPlayThrough", "durationchange", "durationChange", "emptied", "emptied", "encrypted", "encrypted", "ended", "ended", "error", "error", "gotpointercapture", "gotPointerCapture", "load", "load", "loadeddata", "loadedData", "loadedmetadata", "loadedMetadata", "loadstart", "loadStart", "lostpointercapture", "lostPointerCapture", "playing", "playing", "progress", "progress", "seeking", "seeking", "stalled", "stalled", "suspend", "suspend", "timeupdate", "timeUpdate", TRANSITION_END, "transitionEnd", "waiting", "waiting"];
function registerSimplePluginEventsAndSetTheirPriorities(eventTypes, priority) {
for (var i = 0; i < eventTypes.length; i += 2) {
var topEvent = eventTypes[i];
var event = eventTypes[i + 1];
var capitalizedEvent = event[0].toUpperCase() + event.slice(1);
var reactName = "on" + capitalizedEvent;
eventPriorities.set(topEvent, priority);
topLevelEventsToReactNames.set(topEvent, reactName);
registerTwoPhaseEvent(reactName, [topEvent]);
}
}
function setEventPriorities(eventTypes, priority) {
for (var i = 0; i < eventTypes.length; i++) {
eventPriorities.set(eventTypes[i], priority);
}
}
function getEventPriorityForPluginSystem(domEventName) {
var priority = eventPriorities.get(domEventName);
return priority === void 0 ? ContinuousEvent : priority;
}
function registerSimpleEvents() {
registerSimplePluginEventsAndSetTheirPriorities(discreteEventPairsForSimpleEventPlugin, DiscreteEvent);
registerSimplePluginEventsAndSetTheirPriorities(userBlockingPairsForSimpleEventPlugin, UserBlockingEvent);
registerSimplePluginEventsAndSetTheirPriorities(continuousPairsForSimpleEventPlugin, ContinuousEvent);
setEventPriorities(otherDiscreteEvents, DiscreteEvent);
}
var Scheduler_now = Scheduler.unstable_now;
{
if (!(tracing.__interactionsRef != null && tracing.__interactionsRef.current != null)) {
{
throw Error("It is not supported to run the profiling version of a renderer (for example, `react-dom/profiling`) without also replacing the `scheduler/tracing` module with `scheduler/tracing-profiling`. Your bundler might have a setting for aliasing both modules. Learn more at https://reactjs.org/link/profiling");
}
}
}
var ImmediatePriority = 99;
var UserBlockingPriority = 98;
var NormalPriority = 97;
var LowPriority = 96;
var IdlePriority = 95;
var NoPriority = 90;
var initialTimeMs = Scheduler_now();
var SyncLanePriority = 15;
var SyncBatchedLanePriority = 14;
var InputDiscreteHydrationLanePriority = 13;
var InputDiscreteLanePriority = 12;
var InputContinuousHydrationLanePriority = 11;
var InputContinuousLanePriority = 10;
var DefaultHydrationLanePriority = 9;
var DefaultLanePriority = 8;
var TransitionHydrationPriority = 7;
var TransitionPriority = 6;
var RetryLanePriority = 5;
var SelectiveHydrationLanePriority = 4;
var IdleHydrationLanePriority = 3;
var IdleLanePriority = 2;
var OffscreenLanePriority = 1;
var NoLanePriority = 0;
var TotalLanes = 31;
var NoLanes = 0;
var NoLane = 0;
var SyncLane = 1;
var SyncBatchedLane = 2;
var InputDiscreteHydrationLane = 4;
var InputDiscreteLanes = 24;
var InputContinuousHydrationLane = 32;
var InputContinuousLanes = 192;
var DefaultHydrationLane = 256;
var DefaultLanes = 3584;
var TransitionHydrationLane = 4096;
var TransitionLanes = 4186112;
var RetryLanes = 62914560;
var SomeRetryLane = 33554432;
var SelectiveHydrationLane = 67108864;
var NonIdleLanes = 134217727;
var IdleHydrationLane = 134217728;
var IdleLanes = 805306368;
var OffscreenLane = 1073741824;
var NoTimestamp = -1;
function setCurrentUpdateLanePriority(newLanePriority) {
}
var return_highestLanePriority = DefaultLanePriority;
function getHighestPriorityLanes(lanes) {
if ((SyncLane & lanes) !== NoLanes) {
return_highestLanePriority = SyncLanePriority;
return SyncLane;
}
if ((SyncBatchedLane & lanes) !== NoLanes) {
return_highestLanePriority = SyncBatchedLanePriority;
return SyncBatchedLane;
}
if ((InputDiscreteHydrationLane & lanes) !== NoLanes) {
return_highestLanePriority = InputDiscreteHydrationLanePriority;
return InputDiscreteHydrationLane;
}
var inputDiscreteLanes = InputDiscreteLanes & lanes;
if (inputDiscreteLanes !== NoLanes) {
return_highestLanePriority = InputDiscreteLanePriority;
return inputDiscreteLanes;
}
if ((lanes & InputContinuousHydrationLane) !== NoLanes) {
return_highestLanePriority = InputContinuousHydrationLanePriority;
return InputContinuousHydrationLane;
}
var inputContinuousLanes = InputContinuousLanes & lanes;
if (inputContinuousLanes !== NoLanes) {
return_highestLanePriority = InputContinuousLanePriority;
return inputContinuousLanes;
}
if ((lanes & DefaultHydrationLane) !== NoLanes) {
return_highestLanePriority = DefaultHydrationLanePriority;
return DefaultHydrationLane;
}
var defaultLanes = DefaultLanes & lanes;
if (defaultLanes !== NoLanes) {
return_highestLanePriority = DefaultLanePriority;
return defaultLanes;
}
if ((lanes & TransitionHydrationLane) !== NoLanes) {
return_highestLanePriority = TransitionHydrationPriority;
return TransitionHydrationLane;
}
var transitionLanes = TransitionLanes & lanes;
if (transitionLanes !== NoLanes) {
return_highestLanePriority = TransitionPriority;
return transitionLanes;
}
var retryLanes = RetryLanes & lanes;
if (retryLanes !== NoLanes) {
return_highestLanePriority = RetryLanePriority;
return retryLanes;
}
if (lanes & SelectiveHydrationLane) {
return_highestLanePriority = SelectiveHydrationLanePriority;
return SelectiveHydrationLane;
}
if ((lanes & IdleHydrationLane) !== NoLanes) {
return_highestLanePriority = IdleHydrationLanePriority;
return IdleHydrationLane;
}
var idleLanes = IdleLanes & lanes;
if (idleLanes !== NoLanes) {
return_highestLanePriority = IdleLanePriority;
return idleLanes;
}
if ((OffscreenLane & lanes) !== NoLanes) {
return_highestLanePriority = OffscreenLanePriority;
return OffscreenLane;
}
{
error("Should have found matching lanes. This is a bug in React.");
}
return_highestLanePriority = DefaultLanePriority;
return lanes;
}
function schedulerPriorityToLanePriority(schedulerPriorityLevel) {
switch (schedulerPriorityLevel) {
case ImmediatePriority:
return SyncLanePriority;
case UserBlockingPriority:
return InputContinuousLanePriority;
case NormalPriority:
case LowPriority:
return DefaultLanePriority;
case IdlePriority:
return IdleLanePriority;
default:
return NoLanePriority;
}
}
function lanePriorityToSchedulerPriority(lanePriority) {
switch (lanePriority) {
case SyncLanePriority:
case SyncBatchedLanePriority:
return ImmediatePriority;
case InputDiscreteHydrationLanePriority:
case InputDiscreteLanePriority:
case InputContinuousHydrationLanePriority:
case InputContinuousLanePriority:
return UserBlockingPriority;
case DefaultHydrationLanePriority:
case DefaultLanePriority:
case TransitionHydrationPriority:
case TransitionPriority:
case SelectiveHydrationLanePriority:
case RetryLanePriority:
return NormalPriority;
case IdleHydrationLanePriority:
case IdleLanePriority:
case OffscreenLanePriority:
return IdlePriority;
case NoLanePriority:
return NoPriority;
default: {
{
throw Error("Invalid update priority: " + lanePriority + ". This is a bug in React.");
}
}
}
}
function getNextLanes(root2, wipLanes) {
var pendingLanes = root2.pendingLanes;
if (pendingLanes === NoLanes) {
return_highestLanePriority = NoLanePriority;
return NoLanes;
}
var nextLanes = NoLanes;
var nextLanePriority = NoLanePriority;
var expiredLanes = root2.expiredLanes;
var suspendedLanes = root2.suspendedLanes;
var pingedLanes = root2.pingedLanes;
if (expiredLanes !== NoLanes) {
nextLanes = expiredLanes;
nextLanePriority = return_highestLanePriority = SyncLanePriority;
} else {
var nonIdlePendingLanes = pendingLanes & NonIdleLanes;
if (nonIdlePendingLanes !== NoLanes) {
var nonIdleUnblockedLanes = nonIdlePendingLanes & ~suspendedLanes;
if (nonIdleUnblockedLanes !== NoLanes) {
nextLanes = getHighestPriorityLanes(nonIdleUnblockedLanes);
nextLanePriority = return_highestLanePriority;
} else {
var nonIdlePingedLanes = nonIdlePendingLanes & pingedLanes;
if (nonIdlePingedLanes !== NoLanes) {
nextLanes = getHighestPriorityLanes(nonIdlePingedLanes);
nextLanePriority = return_highestLanePriority;
}
}
} else {
var unblockedLanes = pendingLanes & ~suspendedLanes;
if (unblockedLanes !== NoLanes) {
nextLanes = getHighestPriorityLanes(unblockedLanes);
nextLanePriority = return_highestLanePriority;
} else {
if (pingedLanes !== NoLanes) {
nextLanes = getHighestPriorityLanes(pingedLanes);
nextLanePriority = return_highestLanePriority;
}
}
}
}
if (nextLanes === NoLanes) {
return NoLanes;
}
nextLanes = pendingLanes & getEqualOrHigherPriorityLanes(nextLanes);
if (wipLanes !== NoLanes && wipLanes !== nextLanes && (wipLanes & suspendedLanes) === NoLanes) {
getHighestPriorityLanes(wipLanes);
var wipLanePriority = return_highestLanePriority;
if (nextLanePriority <= wipLanePriority) {
return wipLanes;
} else {
return_highestLanePriority = nextLanePriority;
}
}
var entangledLanes = root2.entangledLanes;
if (entangledLanes !== NoLanes) {
var entanglements = root2.entanglements;
var lanes = nextLanes & entangledLanes;
while (lanes > 0) {
var index2 = pickArbitraryLaneIndex(lanes);
var lane = 1 << index2;
nextLanes |= entanglements[index2];
lanes &= ~lane;
}
}
return nextLanes;
}
function getMostRecentEventTime(root2, lanes) {
var eventTimes = root2.eventTimes;
var mostRecentEventTime = NoTimestamp;
while (lanes > 0) {
var index2 = pickArbitraryLaneIndex(lanes);
var lane = 1 << index2;
var eventTime = eventTimes[index2];
if (eventTime > mostRecentEventTime) {
mostRecentEventTime = eventTime;
}
lanes &= ~lane;
}
return mostRecentEventTime;
}
function computeExpirationTime(lane, currentTime) {
getHighestPriorityLanes(lane);
var priority = return_highestLanePriority;
if (priority >= InputContinuousLanePriority) {
return currentTime + 250;
} else if (priority >= TransitionPriority) {
return currentTime + 5e3;
} else {
return NoTimestamp;
}
}
function markStarvedLanesAsExpired(root2, currentTime) {
var pendingLanes = root2.pendingLanes;
var suspendedLanes = root2.suspendedLanes;
var pingedLanes = root2.pingedLanes;
var expirationTimes = root2.expirationTimes;
var lanes = pendingLanes;
while (lanes > 0) {
var index2 = pickArbitraryLaneIndex(lanes);
var lane = 1 << index2;
var expirationTime = expirationTimes[index2];
if (expirationTime === NoTimestamp) {
if ((lane & suspendedLanes) === NoLanes || (lane & pingedLanes) !== NoLanes) {
expirationTimes[index2] = computeExpirationTime(lane, currentTime);
}
} else if (expirationTime <= currentTime) {
root2.expiredLanes |= lane;
}
lanes &= ~lane;
}
}
function getLanesToRetrySynchronouslyOnError(root2) {
var everythingButOffscreen = root2.pendingLanes & ~OffscreenLane;
if (everythingButOffscreen !== NoLanes) {
return everythingButOffscreen;
}
if (everythingButOffscreen & OffscreenLane) {
return OffscreenLane;
}
return NoLanes;
}
function returnNextLanesPriority() {
return return_highestLanePriority;
}
function includesNonIdleWork(lanes) {
return (lanes & NonIdleLanes) !== NoLanes;
}
function includesOnlyRetries(lanes) {
return (lanes & RetryLanes) === lanes;
}
function includesOnlyTransitions(lanes) {
return (lanes & TransitionLanes) === lanes;
}
function findUpdateLane(lanePriority, wipLanes) {
switch (lanePriority) {
case NoLanePriority:
break;
case SyncLanePriority:
return SyncLane;
case SyncBatchedLanePriority:
return SyncBatchedLane;
case InputDiscreteLanePriority: {
var _lane = pickArbitraryLane(InputDiscreteLanes & ~wipLanes);
if (_lane === NoLane) {
return findUpdateLane(InputContinuousLanePriority, wipLanes);
}
return _lane;
}
case InputContinuousLanePriority: {
var _lane2 = pickArbitraryLane(InputContinuousLanes & ~wipLanes);
if (_lane2 === NoLane) {
return findUpdateLane(DefaultLanePriority, wipLanes);
}
return _lane2;
}
case DefaultLanePriority: {
var _lane3 = pickArbitraryLane(DefaultLanes & ~wipLanes);
if (_lane3 === NoLane) {
_lane3 = pickArbitraryLane(TransitionLanes & ~wipLanes);
if (_lane3 === NoLane) {
_lane3 = pickArbitraryLane(DefaultLanes);
}
}
return _lane3;
}
case TransitionPriority:
case RetryLanePriority:
break;
case IdleLanePriority:
var lane = pickArbitraryLane(IdleLanes & ~wipLanes);
if (lane === NoLane) {
lane = pickArbitraryLane(IdleLanes);
}
return lane;
}
{
{
throw Error("Invalid update priority: " + lanePriority + ". This is a bug in React.");
}
}
}
function findTransitionLane(wipLanes, pendingLanes) {
var lane = pickArbitraryLane(TransitionLanes & ~pendingLanes);
if (lane === NoLane) {
lane = pickArbitraryLane(TransitionLanes & ~wipLanes);
if (lane === NoLane) {
lane = pickArbitraryLane(TransitionLanes);
}
}
return lane;
}
function findRetryLane(wipLanes) {
var lane = pickArbitraryLane(RetryLanes & ~wipLanes);
if (lane === NoLane) {
lane = pickArbitraryLane(RetryLanes);
}
return lane;
}
function getHighestPriorityLane(lanes) {
return lanes & -lanes;
}
function getLowestPriorityLane(lanes) {
var index2 = 31 - clz32(lanes);
return index2 < 0 ? NoLanes : 1 << index2;
}
function getEqualOrHigherPriorityLanes(lanes) {
return (getLowestPriorityLane(lanes) << 1) - 1;
}
function pickArbitraryLane(lanes) {
return getHighestPriorityLane(lanes);
}
function pickArbitraryLaneIndex(lanes) {
return 31 - clz32(lanes);
}
function laneToIndex(lane) {
return pickArbitraryLaneIndex(lane);
}
function includesSomeLane(a, b) {
return (a & b) !== NoLanes;
}
function isSubsetOfLanes(set2, subset) {
return (set2 & subset) === subset;
}
function mergeLanes(a, b) {
return a | b;
}
function removeLanes(set2, subset) {
return set2 & ~subset;
}
function laneToLanes(lane) {
return lane;
}
function higherPriorityLane(a, b) {
return a !== NoLane && a < b ? a : b;
}
function createLaneMap(initial) {
var laneMap = [];
for (var i = 0; i < TotalLanes; i++) {
laneMap.push(initial);
}
return laneMap;
}
function markRootUpdated(root2, updateLane, eventTime) {
root2.pendingLanes |= updateLane;
var higherPriorityLanes = updateLane - 1;
root2.suspendedLanes &= higherPriorityLanes;
root2.pingedLanes &= higherPriorityLanes;
var eventTimes = root2.eventTimes;
var index2 = laneToIndex(updateLane);
eventTimes[index2] = eventTime;
}
function markRootSuspended(root2, suspendedLanes) {
root2.suspendedLanes |= suspendedLanes;
root2.pingedLanes &= ~suspendedLanes;
var expirationTimes = root2.expirationTimes;
var lanes = suspendedLanes;
while (lanes > 0) {
var index2 = pickArbitraryLaneIndex(lanes);
var lane = 1 << index2;
expirationTimes[index2] = NoTimestamp;
lanes &= ~lane;
}
}
function markRootPinged(root2, pingedLanes, eventTime) {
root2.pingedLanes |= root2.suspendedLanes & pingedLanes;
}
function markDiscreteUpdatesExpired(root2) {
root2.expiredLanes |= InputDiscreteLanes & root2.pendingLanes;
}
function hasDiscreteLanes(lanes) {
return (lanes & InputDiscreteLanes) !== NoLanes;
}
function markRootMutableRead(root2, updateLane) {
root2.mutableReadLanes |= updateLane & root2.pendingLanes;
}
function markRootFinished(root2, remainingLanes) {
var noLongerPendingLanes = root2.pendingLanes & ~remainingLanes;
root2.pendingLanes = remainingLanes;
root2.suspendedLanes = 0;
root2.pingedLanes = 0;
root2.expiredLanes &= remainingLanes;
root2.mutableReadLanes &= remainingLanes;
root2.entangledLanes &= remainingLanes;
var entanglements = root2.entanglements;
var eventTimes = root2.eventTimes;
var expirationTimes = root2.expirationTimes;
var lanes = noLongerPendingLanes;
while (lanes > 0) {
var index2 = pickArbitraryLaneIndex(lanes);
var lane = 1 << index2;
entanglements[index2] = NoLanes;
eventTimes[index2] = NoTimestamp;
expirationTimes[index2] = NoTimestamp;
lanes &= ~lane;
}
}
function markRootEntangled(root2, entangledLanes) {
root2.entangledLanes |= entangledLanes;
var entanglements = root2.entanglements;
var lanes = entangledLanes;
while (lanes > 0) {
var index2 = pickArbitraryLaneIndex(lanes);
var lane = 1 << index2;
entanglements[index2] |= entangledLanes;
lanes &= ~lane;
}
}
var clz32 = Math.clz32 ? Math.clz32 : clz32Fallback;
var log = Math.log;
var LN2 = Math.LN2;
function clz32Fallback(lanes) {
if (lanes === 0) {
return 32;
}
return 31 - (log(lanes) / LN2 | 0) | 0;
}
var UserBlockingPriority$1 = Scheduler.unstable_UserBlockingPriority, runWithPriority = Scheduler.unstable_runWithPriority;
var _enabled = true;
function setEnabled(enabled) {
_enabled = !!enabled;
}
function isEnabled() {
return _enabled;
}
function createEventListenerWrapperWithPriority(targetContainer, domEventName, eventSystemFlags) {
var eventPriority = getEventPriorityForPluginSystem(domEventName);
var listenerWrapper;
switch (eventPriority) {
case DiscreteEvent:
listenerWrapper = dispatchDiscreteEvent;
break;
case UserBlockingEvent:
listenerWrapper = dispatchUserBlockingUpdate;
break;
case ContinuousEvent:
default:
listenerWrapper = dispatchEvent;
break;
}
return listenerWrapper.bind(null, domEventName, eventSystemFlags, targetContainer);
}
function dispatchDiscreteEvent(domEventName, eventSystemFlags, container, nativeEvent) {
{
flushDiscreteUpdatesIfNeeded(nativeEvent.timeStamp);
}
discreteUpdates(dispatchEvent, domEventName, eventSystemFlags, container, nativeEvent);
}
function dispatchUserBlockingUpdate(domEventName, eventSystemFlags, container, nativeEvent) {
{
runWithPriority(UserBlockingPriority$1, dispatchEvent.bind(null, domEventName, eventSystemFlags, container, nativeEvent));
}
}
function dispatchEvent(domEventName, eventSystemFlags, targetContainer, nativeEvent) {
if (!_enabled) {
return;
}
var allowReplay = true;
{
allowReplay = (eventSystemFlags & IS_CAPTURE_PHASE) === 0;
}
if (allowReplay && hasQueuedDiscreteEvents() && isReplayableDiscreteEvent(domEventName)) {
queueDiscreteEvent(null, domEventName, eventSystemFlags, targetContainer, nativeEvent);
return;
}
var blockedOn = attemptToDispatchEvent(domEventName, eventSystemFlags, targetContainer, nativeEvent);
if (blockedOn === null) {
if (allowReplay) {
clearIfContinuousEvent(domEventName, nativeEvent);
}
return;
}
if (allowReplay) {
if (isReplayableDiscreteEvent(domEventName)) {
queueDiscreteEvent(blockedOn, domEventName, eventSystemFlags, targetContainer, nativeEvent);
return;
}
if (queueIfContinuousEvent(blockedOn, domEventName, eventSystemFlags, targetContainer, nativeEvent)) {
return;
}
clearIfContinuousEvent(domEventName, nativeEvent);
}
dispatchEventForPluginEventSystem(domEventName, eventSystemFlags, nativeEvent, null, targetContainer);
}
function attemptToDispatchEvent(domEventName, eventSystemFlags, targetContainer, nativeEvent) {
var nativeEventTarget = getEventTarget(nativeEvent);
var targetInst = getClosestInstanceFromNode(nativeEventTarget);
if (targetInst !== null) {
var nearestMounted = getNearestMountedFiber(targetInst);
if (nearestMounted === null) {
targetInst = null;
} else {
var tag = nearestMounted.tag;
if (tag === SuspenseComponent) {
var instance = getSuspenseInstanceFromFiber(nearestMounted);
if (instance !== null) {
return instance;
}
targetInst = null;
} else if (tag === HostRoot) {
var root2 = nearestMounted.stateNode;
if (root2.hydrate) {
return getContainerFromFiber(nearestMounted);
}
targetInst = null;
} else if (nearestMounted !== targetInst) {
targetInst = null;
}
}
}
dispatchEventForPluginEventSystem(domEventName, eventSystemFlags, nativeEvent, targetInst, targetContainer);
return null;
}
function addEventBubbleListener(target, eventType, listener) {
target.addEventListener(eventType, listener, false);
return listener;
}
function addEventCaptureListener(target, eventType, listener) {
target.addEventListener(eventType, listener, true);
return listener;
}
function addEventCaptureListenerWithPassiveFlag(target, eventType, listener, passive) {
target.addEventListener(eventType, listener, {
capture: true,
passive
});
return listener;
}
function addEventBubbleListenerWithPassiveFlag(target, eventType, listener, passive) {
target.addEventListener(eventType, listener, {
passive
});
return listener;
}
var root = null;
var startText = null;
var fallbackText = null;
function initialize(nativeEventTarget) {
root = nativeEventTarget;
startText = getText();
return true;
}
function reset() {
root = null;
startText = null;
fallbackText = null;
}
function getData() {
if (fallbackText) {
return fallbackText;
}
var start;
var startValue = startText;
var startLength = startValue.length;
var end;
var endValue = getText();
var endLength = endValue.length;
for (start = 0; start < startLength; start++) {
if (startValue[start] !== endValue[start]) {
break;
}
}
var minEnd = startLength - start;
for (end = 1; end <= minEnd; end++) {
if (startValue[startLength - end] !== endValue[endLength - end]) {
break;
}
}
var sliceTail = end > 1 ? 1 - end : void 0;
fallbackText = endValue.slice(start, sliceTail);
return fallbackText;
}
function getText() {
if ("value" in root) {
return root.value;
}
return root.textContent;
}
function getEventCharCode(nativeEvent) {
var charCode;
var keyCode = nativeEvent.keyCode;
if ("charCode" in nativeEvent) {
charCode = nativeEvent.charCode;
if (charCode === 0 && keyCode === 13) {
charCode = 13;
}
} else {
charCode = keyCode;
}
if (charCode === 10) {
charCode = 13;
}
if (charCode >= 32 || charCode === 13) {
return charCode;
}
return 0;
}
function functionThatReturnsTrue() {
return true;
}
function functionThatReturnsFalse() {
return false;
}
function createSyntheticEvent(Interface) {
function SyntheticBaseEvent(reactName, reactEventType, targetInst, nativeEvent, nativeEventTarget) {
this._reactName = reactName;
this._targetInst = targetInst;
this.type = reactEventType;
this.nativeEvent = nativeEvent;
this.target = nativeEventTarget;
this.currentTarget = null;
for (var _propName in Interface) {
if (!Interface.hasOwnProperty(_propName)) {
continue;
}
var normalize = Interface[_propName];
if (normalize) {
this[_propName] = normalize(nativeEvent);
} else {
this[_propName] = nativeEvent[_propName];
}
}
var defaultPrevented = nativeEvent.defaultPrevented != null ? nativeEvent.defaultPrevented : nativeEvent.returnValue === false;
if (defaultPrevented) {
this.isDefaultPrevented = functionThatReturnsTrue;
} else {
this.isDefaultPrevented = functionThatReturnsFalse;
}
this.isPropagationStopped = functionThatReturnsFalse;
return this;
}
_assign(SyntheticBaseEvent.prototype, {
preventDefault: function() {
this.defaultPrevented = true;
var event = this.nativeEvent;
if (!event) {
return;
}
if (event.preventDefault) {
event.preventDefault();
} else if (typeof event.returnValue !== "unknown") {
event.returnValue = false;
}
this.isDefaultPrevented = functionThatReturnsTrue;
},
stopPropagation: function() {
var event = this.nativeEvent;
if (!event) {
return;
}
if (event.stopPropagation) {
event.stopPropagation();
} else if (typeof event.cancelBubble !== "unknown") {
event.cancelBubble = true;
}
this.isPropagationStopped = functionThatReturnsTrue;
},
persist: function() {
},
isPersistent: functionThatReturnsTrue
});
return SyntheticBaseEvent;
}
var EventInterface = {
eventPhase: 0,
bubbles: 0,
cancelable: 0,
timeStamp: function(event) {
return event.timeStamp || Date.now();
},
defaultPrevented: 0,
isTrusted: 0
};
var SyntheticEvent = createSyntheticEvent(EventInterface);
var UIEventInterface = _assign({}, EventInterface, {
view: 0,
detail: 0
});
var SyntheticUIEvent = createSyntheticEvent(UIEventInterface);
var lastMovementX;
var lastMovementY;
var lastMouseEvent;
function updateMouseMovementPolyfillState(event) {
if (event !== lastMouseEvent) {
if (lastMouseEvent && event.type === "mousemove") {
lastMovementX = event.screenX - lastMouseEvent.screenX;
lastMovementY = event.screenY - lastMouseEvent.screenY;
} else {
lastMovementX = 0;
lastMovementY = 0;
}
lastMouseEvent = event;
}
}
var MouseEventInterface = _assign({}, UIEventInterface, {
screenX: 0,
screenY: 0,
clientX: 0,
clientY: 0,
pageX: 0,
pageY: 0,
ctrlKey: 0,
shiftKey: 0,
altKey: 0,
metaKey: 0,
getModifierState: getEventModifierState,
button: 0,
buttons: 0,
relatedTarget: function(event) {
if (event.relatedTarget === void 0)
return event.fromElement === event.srcElement ? event.toElement : event.fromElement;
return event.relatedTarget;
},
movementX: function(event) {
if ("movementX" in event) {
return event.movementX;
}
updateMouseMovementPolyfillState(event);
return lastMovementX;
},
movementY: function(event) {
if ("movementY" in event) {
return event.movementY;
}
return lastMovementY;
}
});
var SyntheticMouseEvent = createSyntheticEvent(MouseEventInterface);
var DragEventInterface = _assign({}, MouseEventInterface, {
dataTransfer: 0
});
var SyntheticDragEvent = createSyntheticEvent(DragEventInterface);
var FocusEventInterface = _assign({}, UIEventInterface, {
relatedTarget: 0
});
var SyntheticFocusEvent = createSyntheticEvent(FocusEventInterface);
var AnimationEventInterface = _assign({}, EventInterface, {
animationName: 0,
elapsedTime: 0,
pseudoElement: 0
});
var SyntheticAnimationEvent = createSyntheticEvent(AnimationEventInterface);
var ClipboardEventInterface = _assign({}, EventInterface, {
clipboardData: function(event) {
return "clipboardData" in event ? event.clipboardData : window.clipboardData;
}
});
var SyntheticClipboardEvent = createSyntheticEvent(ClipboardEventInterface);
var CompositionEventInterface = _assign({}, EventInterface, {
data: 0
});
var SyntheticCompositionEvent = createSyntheticEvent(CompositionEventInterface);
var SyntheticInputEvent = SyntheticCompositionEvent;
var normalizeKey = {
Esc: "Escape",
Spacebar: " ",
Left: "ArrowLeft",
Up: "ArrowUp",
Right: "ArrowRight",
Down: "ArrowDown",
Del: "Delete",
Win: "OS",
Menu: "ContextMenu",
Apps: "ContextMenu",
Scroll: "ScrollLock",
MozPrintableKey: "Unidentified"
};
var translateToKey = {
"8": "Backspace",
"9": "Tab",
"12": "Clear",
"13": "Enter",
"16": "Shift",
"17": "Control",
"18": "Alt",
"19": "Pause",
"20": "CapsLock",
"27": "Escape",
"32": " ",
"33": "PageUp",
"34": "PageDown",
"35": "End",
"36": "Home",
"37": "ArrowLeft",
"38": "ArrowUp",
"39": "ArrowRight",
"40": "ArrowDown",
"45": "Insert",
"46": "Delete",
"112": "F1",
"113": "F2",
"114": "F3",
"115": "F4",
"116": "F5",
"117": "F6",
"118": "F7",
"119": "F8",
"120": "F9",
"121": "F10",
"122": "F11",
"123": "F12",
"144": "NumLock",
"145": "ScrollLock",
"224": "Meta"
};
function getEventKey(nativeEvent) {
if (nativeEvent.key) {
var key = normalizeKey[nativeEvent.key] || nativeEvent.key;
if (key !== "Unidentified") {
return key;
}
}
if (nativeEvent.type === "keypress") {
var charCode = getEventCharCode(nativeEvent);
return charCode === 13 ? "Enter" : String.fromCharCode(charCode);
}
if (nativeEvent.type === "keydown" || nativeEvent.type === "keyup") {
return translateToKey[nativeEvent.keyCode] || "Unidentified";
}
return "";
}
var modifierKeyToProp = {
Alt: "altKey",
Control: "ctrlKey",
Meta: "metaKey",
Shift: "shiftKey"
};
function modifierStateGetter(keyArg) {
var syntheticEvent = this;
var nativeEvent = syntheticEvent.nativeEvent;
if (nativeEvent.getModifierState) {
return nativeEvent.getModifierState(keyArg);
}
var keyProp = modifierKeyToProp[keyArg];
return keyProp ? !!nativeEvent[keyProp] : false;
}
function getEventModifierState(nativeEvent) {
return modifierStateGetter;
}
var KeyboardEventInterface = _assign({}, UIEventInterface, {
key: getEventKey,
code: 0,
location: 0,
ctrlKey: 0,
shiftKey: 0,
altKey: 0,
metaKey: 0,
repeat: 0,
locale: 0,
getModifierState: getEventModifierState,
charCode: function(event) {
if (event.type === "keypress") {
return getEventCharCode(event);
}
return 0;
},
keyCode: function(event) {
if (event.type === "keydown" || event.type === "keyup") {
return event.keyCode;
}
return 0;
},
which: function(event) {
if (event.type === "keypress") {
return getEventCharCode(event);
}
if (event.type === "keydown" || event.type === "keyup") {
return event.keyCode;
}
return 0;
}
});
var SyntheticKeyboardEvent = createSyntheticEvent(KeyboardEventInterface);
var PointerEventInterface = _assign({}, MouseEventInterface, {
pointerId: 0,
width: 0,
height: 0,
pressure: 0,
tangentialPressure: 0,
tiltX: 0,
tiltY: 0,
twist: 0,
pointerType: 0,
isPrimary: 0
});
var SyntheticPointerEvent = createSyntheticEvent(PointerEventInterface);
var TouchEventInterface = _assign({}, UIEventInterface, {
touches: 0,
targetTouches: 0,
changedTouches: 0,
altKey: 0,
metaKey: 0,
ctrlKey: 0,
shiftKey: 0,
getModifierState: getEventModifierState
});
var SyntheticTouchEvent = createSyntheticEvent(TouchEventInterface);
var TransitionEventInterface = _assign({}, EventInterface, {
propertyName: 0,
elapsedTime: 0,
pseudoElement: 0
});
var SyntheticTransitionEvent = createSyntheticEvent(TransitionEventInterface);
var WheelEventInterface = _assign({}, MouseEventInterface, {
deltaX: function(event) {
return "deltaX" in event ? event.deltaX : "wheelDeltaX" in event ? -event.wheelDeltaX : 0;
},
deltaY: function(event) {
return "deltaY" in event ? event.deltaY : "wheelDeltaY" in event ? -event.wheelDeltaY : "wheelDelta" in event ? -event.wheelDelta : 0;
},
deltaZ: 0,
deltaMode: 0
});
var SyntheticWheelEvent = createSyntheticEvent(WheelEventInterface);
var END_KEYCODES = [9, 13, 27, 32];
var START_KEYCODE = 229;
var canUseCompositionEvent = canUseDOM && "CompositionEvent" in window;
var documentMode = null;
if (canUseDOM && "documentMode" in document) {
documentMode = document.documentMode;
}
var canUseTextInputEvent = canUseDOM && "TextEvent" in window && !documentMode;
var useFallbackCompositionData = canUseDOM && (!canUseCompositionEvent || documentMode && documentMode > 8 && documentMode <= 11);
var SPACEBAR_CODE = 32;
var SPACEBAR_CHAR = String.fromCharCode(SPACEBAR_CODE);
function registerEvents() {
registerTwoPhaseEvent("onBeforeInput", ["compositionend", "keypress", "textInput", "paste"]);
registerTwoPhaseEvent("onCompositionEnd", ["compositionend", "focusout", "keydown", "keypress", "keyup", "mousedown"]);
registerTwoPhaseEvent("onCompositionStart", ["compositionstart", "focusout", "keydown", "keypress", "keyup", "mousedown"]);
registerTwoPhaseEvent("onCompositionUpdate", ["compositionupdate", "focusout", "keydown", "keypress", "keyup", "mousedown"]);
}
var hasSpaceKeypress = false;
function isKeypressCommand(nativeEvent) {
return (nativeEvent.ctrlKey || nativeEvent.altKey || nativeEvent.metaKey) && !(nativeEvent.ctrlKey && nativeEvent.altKey);
}
function getCompositionEventType(domEventName) {
switch (domEventName) {
case "compositionstart":
return "onCompositionStart";
case "compositionend":
return "onCompositionEnd";
case "compositionupdate":
return "onCompositionUpdate";
}
}
function isFallbackCompositionStart(domEventName, nativeEvent) {
return domEventName === "keydown" && nativeEvent.keyCode === START_KEYCODE;
}
function isFallbackCompositionEnd(domEventName, nativeEvent) {
switch (domEventName) {
case "keyup":
return END_KEYCODES.indexOf(nativeEvent.keyCode) !== -1;
case "keydown":
return nativeEvent.keyCode !== START_KEYCODE;
case "keypress":
case "mousedown":
case "focusout":
return true;
default:
return false;
}
}
function getDataFromCustomEvent(nativeEvent) {
var detail = nativeEvent.detail;
if (typeof detail === "object" && "data" in detail) {
return detail.data;
}
return null;
}
function isUsingKoreanIME(nativeEvent) {
return nativeEvent.locale === "ko";
}
var isComposing = false;
function extractCompositionEvent(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget) {
var eventType;
var fallbackData;
if (canUseCompositionEvent) {
eventType = getCompositionEventType(domEventName);
} else if (!isComposing) {
if (isFallbackCompositionStart(domEventName, nativeEvent)) {
eventType = "onCompositionStart";
}
} else if (isFallbackCompositionEnd(domEventName, nativeEvent)) {
eventType = "onCompositionEnd";
}
if (!eventType) {
return null;
}
if (useFallbackCompositionData && !isUsingKoreanIME(nativeEvent)) {
if (!isComposing && eventType === "onCompositionStart") {
isComposing = initialize(nativeEventTarget);
} else if (eventType === "onCompositionEnd") {
if (isComposing) {
fallbackData = getData();
}
}
}
var listeners = accumulateTwoPhaseListeners(targetInst, eventType);
if (listeners.length > 0) {
var event = new SyntheticCompositionEvent(eventType, domEventName, null, nativeEvent, nativeEventTarget);
dispatchQueue.push({
event,
listeners
});
if (fallbackData) {
event.data = fallbackData;
} else {
var customData = getDataFromCustomEvent(nativeEvent);
if (customData !== null) {
event.data = customData;
}
}
}
}
function getNativeBeforeInputChars(domEventName, nativeEvent) {
switch (domEventName) {
case "compositionend":
return getDataFromCustomEvent(nativeEvent);
case "keypress":
var which = nativeEvent.which;
if (which !== SPACEBAR_CODE) {
return null;
}
hasSpaceKeypress = true;
return SPACEBAR_CHAR;
case "textInput":
var chars = nativeEvent.data;
if (chars === SPACEBAR_CHAR && hasSpaceKeypress) {
return null;
}
return chars;
default:
return null;
}
}
function getFallbackBeforeInputChars(domEventName, nativeEvent) {
if (isComposing) {
if (domEventName === "compositionend" || !canUseCompositionEvent && isFallbackCompositionEnd(domEventName, nativeEvent)) {
var chars = getData();
reset();
isComposing = false;
return chars;
}
return null;
}
switch (domEventName) {
case "paste":
return null;
case "keypress":
if (!isKeypressCommand(nativeEvent)) {
if (nativeEvent.char && nativeEvent.char.length > 1) {
return nativeEvent.char;
} else if (nativeEvent.which) {
return String.fromCharCode(nativeEvent.which);
}
}
return null;
case "compositionend":
return useFallbackCompositionData && !isUsingKoreanIME(nativeEvent) ? null : nativeEvent.data;
default:
return null;
}
}
function extractBeforeInputEvent(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget) {
var chars;
if (canUseTextInputEvent) {
chars = getNativeBeforeInputChars(domEventName, nativeEvent);
} else {
chars = getFallbackBeforeInputChars(domEventName, nativeEvent);
}
if (!chars) {
return null;
}
var listeners = accumulateTwoPhaseListeners(targetInst, "onBeforeInput");
if (listeners.length > 0) {
var event = new SyntheticInputEvent("onBeforeInput", "beforeinput", null, nativeEvent, nativeEventTarget);
dispatchQueue.push({
event,
listeners
});
event.data = chars;
}
}
function extractEvents(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags, targetContainer) {
extractCompositionEvent(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget);
extractBeforeInputEvent(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget);
}
var supportedInputTypes = {
color: true,
date: true,
datetime: true,
"datetime-local": true,
email: true,
month: true,
number: true,
password: true,
range: true,
search: true,
tel: true,
text: true,
time: true,
url: true,
week: true
};
function isTextInputElement(elem) {
var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase();
if (nodeName === "input") {
return !!supportedInputTypes[elem.type];
}
if (nodeName === "textarea") {
return true;
}
return false;
}
function isEventSupported(eventNameSuffix) {
if (!canUseDOM) {
return false;
}
var eventName = "on" + eventNameSuffix;
var isSupported = eventName in document;
if (!isSupported) {
var element = document.createElement("div");
element.setAttribute(eventName, "return;");
isSupported = typeof element[eventName] === "function";
}
return isSupported;
}
function registerEvents$1() {
registerTwoPhaseEvent("onChange", ["change", "click", "focusin", "focusout", "input", "keydown", "keyup", "selectionchange"]);
}
function createAndAccumulateChangeEvent(dispatchQueue, inst, nativeEvent, target) {
enqueueStateRestore(target);
var listeners = accumulateTwoPhaseListeners(inst, "onChange");
if (listeners.length > 0) {
var event = new SyntheticEvent("onChange", "change", null, nativeEvent, target);
dispatchQueue.push({
event,
listeners
});
}
}
var activeElement = null;
var activeElementInst = null;
function shouldUseChangeEvent(elem) {
var nodeName = elem.nodeName && elem.nodeName.toLowerCase();
return nodeName === "select" || nodeName === "input" && elem.type === "file";
}
function manualDispatchChangeEvent(nativeEvent) {
var dispatchQueue = [];
createAndAccumulateChangeEvent(dispatchQueue, activeElementInst, nativeEvent, getEventTarget(nativeEvent));
batchedUpdates(runEventInBatch, dispatchQueue);
}
function runEventInBatch(dispatchQueue) {
processDispatchQueue(dispatchQueue, 0);
}
function getInstIfValueChanged(targetInst) {
var targetNode = getNodeFromInstance(targetInst);
if (updateValueIfChanged(targetNode)) {
return targetInst;
}
}
function getTargetInstForChangeEvent(domEventName, targetInst) {
if (domEventName === "change") {
return targetInst;
}
}
var isInputEventSupported = false;
if (canUseDOM) {
isInputEventSupported = isEventSupported("input") && (!document.documentMode || document.documentMode > 9);
}
function startWatchingForValueChange(target, targetInst) {
activeElement = target;
activeElementInst = targetInst;
activeElement.attachEvent("onpropertychange", handlePropertyChange);
}
function stopWatchingForValueChange() {
if (!activeElement) {
return;
}
activeElement.detachEvent("onpropertychange", handlePropertyChange);
activeElement = null;
activeElementInst = null;
}
function handlePropertyChange(nativeEvent) {
if (nativeEvent.propertyName !== "value") {
return;
}
if (getInstIfValueChanged(activeElementInst)) {
manualDispatchChangeEvent(nativeEvent);
}
}
function handleEventsForInputEventPolyfill(domEventName, target, targetInst) {
if (domEventName === "focusin") {
stopWatchingForValueChange();
startWatchingForValueChange(target, targetInst);
} else if (domEventName === "focusout") {
stopWatchingForValueChange();
}
}
function getTargetInstForInputEventPolyfill(domEventName, targetInst) {
if (domEventName === "selectionchange" || domEventName === "keyup" || domEventName === "keydown") {
return getInstIfValueChanged(activeElementInst);
}
}
function shouldUseClickEvent(elem) {
var nodeName = elem.nodeName;
return nodeName && nodeName.toLowerCase() === "input" && (elem.type === "checkbox" || elem.type === "radio");
}
function getTargetInstForClickEvent(domEventName, targetInst) {
if (domEventName === "click") {
return getInstIfValueChanged(targetInst);
}
}
function getTargetInstForInputOrChangeEvent(domEventName, targetInst) {
if (domEventName === "input" || domEventName === "change") {
return getInstIfValueChanged(targetInst);
}
}
function handleControlledInputBlur(node) {
var state = node._wrapperState;
if (!state || !state.controlled || node.type !== "number") {
return;
}
{
setDefaultValue(node, "number", node.value);
}
}
function extractEvents$1(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags, targetContainer) {
var targetNode = targetInst ? getNodeFromInstance(targetInst) : window;
var getTargetInstFunc, handleEventFunc;
if (shouldUseChangeEvent(targetNode)) {
getTargetInstFunc = getTargetInstForChangeEvent;
} else if (isTextInputElement(targetNode)) {
if (isInputEventSupported) {
getTargetInstFunc = getTargetInstForInputOrChangeEvent;
} else {
getTargetInstFunc = getTargetInstForInputEventPolyfill;
handleEventFunc = handleEventsForInputEventPolyfill;
}
} else if (shouldUseClickEvent(targetNode)) {
getTargetInstFunc = getTargetInstForClickEvent;
}
if (getTargetInstFunc) {
var inst = getTargetInstFunc(domEventName, targetInst);
if (inst) {
createAndAccumulateChangeEvent(dispatchQueue, inst, nativeEvent, nativeEventTarget);
return;
}
}
if (handleEventFunc) {
handleEventFunc(domEventName, targetNode, targetInst);
}
if (domEventName === "focusout") {
handleControlledInputBlur(targetNode);
}
}
function registerEvents$2() {
registerDirectEvent("onMouseEnter", ["mouseout", "mouseover"]);
registerDirectEvent("onMouseLeave", ["mouseout", "mouseover"]);
registerDirectEvent("onPointerEnter", ["pointerout", "pointerover"]);
registerDirectEvent("onPointerLeave", ["pointerout", "pointerover"]);
}
function extractEvents$2(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags, targetContainer) {
var isOverEvent = domEventName === "mouseover" || domEventName === "pointerover";
var isOutEvent = domEventName === "mouseout" || domEventName === "pointerout";
if (isOverEvent && (eventSystemFlags & IS_REPLAYED) === 0) {
var related = nativeEvent.relatedTarget || nativeEvent.fromElement;
if (related) {
if (getClosestInstanceFromNode(related) || isContainerMarkedAsRoot(related)) {
return;
}
}
}
if (!isOutEvent && !isOverEvent) {
return;
}
var win;
if (nativeEventTarget.window === nativeEventTarget) {
win = nativeEventTarget;
} else {
var doc = nativeEventTarget.ownerDocument;
if (doc) {
win = doc.defaultView || doc.parentWindow;
} else {
win = window;
}
}
var from;
var to;
if (isOutEvent) {
var _related = nativeEvent.relatedTarget || nativeEvent.toElement;
from = targetInst;
to = _related ? getClosestInstanceFromNode(_related) : null;
if (to !== null) {
var nearestMounted = getNearestMountedFiber(to);
if (to !== nearestMounted || to.tag !== HostComponent && to.tag !== HostText) {
to = null;
}
}
} else {
from = null;
to = targetInst;
}
if (from === to) {
return;
}
var SyntheticEventCtor = SyntheticMouseEvent;
var leaveEventType = "onMouseLeave";
var enterEventType = "onMouseEnter";
var eventTypePrefix = "mouse";
if (domEventName === "pointerout" || domEventName === "pointerover") {
SyntheticEventCtor = SyntheticPointerEvent;
leaveEventType = "onPointerLeave";
enterEventType = "onPointerEnter";
eventTypePrefix = "pointer";
}
var fromNode = from == null ? win : getNodeFromInstance(from);
var toNode = to == null ? win : getNodeFromInstance(to);
var leave = new SyntheticEventCtor(leaveEventType, eventTypePrefix + "leave", from, nativeEvent, nativeEventTarget);
leave.target = fromNode;
leave.relatedTarget = toNode;
var enter = null;
var nativeTargetInst = getClosestInstanceFromNode(nativeEventTarget);
if (nativeTargetInst === targetInst) {
var enterEvent = new SyntheticEventCtor(enterEventType, eventTypePrefix + "enter", to, nativeEvent, nativeEventTarget);
enterEvent.target = toNode;
enterEvent.relatedTarget = fromNode;
enter = enterEvent;
}
accumulateEnterLeaveTwoPhaseListeners(dispatchQueue, leave, enter, from, to);
}
function is(x, y) {
return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y;
}
var objectIs = typeof Object.is === "function" ? Object.is : is;
var hasOwnProperty$2 = Object.prototype.hasOwnProperty;
function shallowEqual(objA, objB) {
if (objectIs(objA, objB)) {
return true;
}
if (typeof objA !== "object" || objA === null || typeof objB !== "object" || objB === null) {
return false;
}
var keysA = Object.keys(objA);
var keysB = Object.keys(objB);
if (keysA.length !== keysB.length) {
return false;
}
for (var i = 0; i < keysA.length; i++) {
if (!hasOwnProperty$2.call(objB, keysA[i]) || !objectIs(objA[keysA[i]], objB[keysA[i]])) {
return false;
}
}
return true;
}
function getLeafNode(node) {
while (node && node.firstChild) {
node = node.firstChild;
}
return node;
}
function getSiblingNode(node) {
while (node) {
if (node.nextSibling) {
return node.nextSibling;
}
node = node.parentNode;
}
}
function getNodeForCharacterOffset(root2, offset) {
var node = getLeafNode(root2);
var nodeStart = 0;
var nodeEnd = 0;
while (node) {
if (node.nodeType === TEXT_NODE) {
nodeEnd = nodeStart + node.textContent.length;
if (nodeStart <= offset && nodeEnd >= offset) {
return {
node,
offset: offset - nodeStart
};
}
nodeStart = nodeEnd;
}
node = getLeafNode(getSiblingNode(node));
}
}
function getOffsets(outerNode) {
var ownerDocument = outerNode.ownerDocument;
var win = ownerDocument && ownerDocument.defaultView || window;
var selection = win.getSelection && win.getSelection();
if (!selection || selection.rangeCount === 0) {
return null;
}
var anchorNode = selection.anchorNode, anchorOffset = selection.anchorOffset, focusNode = selection.focusNode, focusOffset = selection.focusOffset;
try {
anchorNode.nodeType;
focusNode.nodeType;
} catch (e) {
return null;
}
return getModernOffsetsFromPoints(outerNode, anchorNode, anchorOffset, focusNode, focusOffset);
}
function getModernOffsetsFromPoints(outerNode, anchorNode, anchorOffset, focusNode, focusOffset) {
var length = 0;
var start = -1;
var end = -1;
var indexWithinAnchor = 0;
var indexWithinFocus = 0;
var node = outerNode;
var parentNode = null;
outer:
while (true) {
var next = null;
while (true) {
if (node === anchorNode && (anchorOffset === 0 || node.nodeType === TEXT_NODE)) {
start = length + anchorOffset;
}
if (node === focusNode && (focusOffset === 0 || node.nodeType === TEXT_NODE)) {
end = length + focusOffset;
}
if (node.nodeType === TEXT_NODE) {
length += node.nodeValue.length;
}
if ((next = node.firstChild) === null) {
break;
}
parentNode = node;
node = next;
}
while (true) {
if (node === outerNode) {
break outer;
}
if (parentNode === anchorNode && ++indexWithinAnchor === anchorOffset) {
start = length;
}
if (parentNode === focusNode && ++indexWithinFocus === focusOffset) {
end = length;
}
if ((next = node.nextSibling) !== null) {
break;
}
node = parentNode;
parentNode = node.parentNode;
}
node = next;
}
if (start === -1 || end === -1) {
return null;
}
return {
start,
end
};
}
function setOffsets(node, offsets) {
var doc = node.ownerDocument || document;
var win = doc && doc.defaultView || window;
if (!win.getSelection) {
return;
}
var selection = win.getSelection();
var length = node.textContent.length;
var start = Math.min(offsets.start, length);
var end = offsets.end === void 0 ? start : Math.min(offsets.end, length);
if (!selection.extend && start > end) {
var temp = end;
end = start;
start = temp;
}
var startMarker = getNodeForCharacterOffset(node, start);
var endMarker = getNodeForCharacterOffset(node, end);
if (startMarker && endMarker) {
if (selection.rangeCount === 1 && selection.anchorNode === startMarker.node && selection.anchorOffset === startMarker.offset && selection.focusNode === endMarker.node && selection.focusOffset === endMarker.offset) {
return;
}
var range = doc.createRange();
range.setStart(startMarker.node, startMarker.offset);
selection.removeAllRanges();
if (start > end) {
selection.addRange(range);
selection.extend(endMarker.node, endMarker.offset);
} else {
range.setEnd(endMarker.node, endMarker.offset);
selection.addRange(range);
}
}
}
function isTextNode(node) {
return node && node.nodeType === TEXT_NODE;
}
function containsNode(outerNode, innerNode) {
if (!outerNode || !innerNode) {
return false;
} else if (outerNode === innerNode) {
return true;
} else if (isTextNode(outerNode)) {
return false;
} else if (isTextNode(innerNode)) {
return containsNode(outerNode, innerNode.parentNode);
} else if ("contains" in outerNode) {
return outerNode.contains(innerNode);
} else if (outerNode.compareDocumentPosition) {
return !!(outerNode.compareDocumentPosition(innerNode) & 16);
} else {
return false;
}
}
function isInDocument(node) {
return node && node.ownerDocument && containsNode(node.ownerDocument.documentElement, node);
}
function isSameOriginFrame(iframe) {
try {
return typeof iframe.contentWindow.location.href === "string";
} catch (err) {
return false;
}
}
function getActiveElementDeep() {
var win = window;
var element = getActiveElement();
while (element instanceof win.HTMLIFrameElement) {
if (isSameOriginFrame(element)) {
win = element.contentWindow;
} else {
return element;
}
element = getActiveElement(win.document);
}
return element;
}
function hasSelectionCapabilities(elem) {
var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase();
return nodeName && (nodeName === "input" && (elem.type === "text" || elem.type === "search" || elem.type === "tel" || elem.type === "url" || elem.type === "password") || nodeName === "textarea" || elem.contentEditable === "true");
}
function getSelectionInformation() {
var focusedElem = getActiveElementDeep();
return {
focusedElem,
selectionRange: hasSelectionCapabilities(focusedElem) ? getSelection(focusedElem) : null
};
}
function restoreSelection(priorSelectionInformation) {
var curFocusedElem = getActiveElementDeep();
var priorFocusedElem = priorSelectionInformation.focusedElem;
var priorSelectionRange = priorSelectionInformation.selectionRange;
if (curFocusedElem !== priorFocusedElem && isInDocument(priorFocusedElem)) {
if (priorSelectionRange !== null && hasSelectionCapabilities(priorFocusedElem)) {
setSelection(priorFocusedElem, priorSelectionRange);
}
var ancestors = [];
var ancestor = priorFocusedElem;
while (ancestor = ancestor.parentNode) {
if (ancestor.nodeType === ELEMENT_NODE) {
ancestors.push({
element: ancestor,
left: ancestor.scrollLeft,
top: ancestor.scrollTop
});
}
}
if (typeof priorFocusedElem.focus === "function") {
priorFocusedElem.focus();
}
for (var i = 0; i < ancestors.length; i++) {
var info = ancestors[i];
info.element.scrollLeft = info.left;
info.element.scrollTop = info.top;
}
}
}
function getSelection(input) {
var selection;
if ("selectionStart" in input) {
selection = {
start: input.selectionStart,
end: input.selectionEnd
};
} else {
selection = getOffsets(input);
}
return selection || {
start: 0,
end: 0
};
}
function setSelection(input, offsets) {
var start = offsets.start;
var end = offsets.end;
if (end === void 0) {
end = start;
}
if ("selectionStart" in input) {
input.selectionStart = start;
input.selectionEnd = Math.min(end, input.value.length);
} else {
setOffsets(input, offsets);
}
}
var skipSelectionChangeEvent = canUseDOM && "documentMode" in document && document.documentMode <= 11;
function registerEvents$3() {
registerTwoPhaseEvent("onSelect", ["focusout", "contextmenu", "dragend", "focusin", "keydown", "keyup", "mousedown", "mouseup", "selectionchange"]);
}
var activeElement$1 = null;
var activeElementInst$1 = null;
var lastSelection = null;
var mouseDown = false;
function getSelection$1(node) {
if ("selectionStart" in node && hasSelectionCapabilities(node)) {
return {
start: node.selectionStart,
end: node.selectionEnd
};
} else {
var win = node.ownerDocument && node.ownerDocument.defaultView || window;
var selection = win.getSelection();
return {
anchorNode: selection.anchorNode,
anchorOffset: selection.anchorOffset,
focusNode: selection.focusNode,
focusOffset: selection.focusOffset
};
}
}
function getEventTargetDocument(eventTarget) {
return eventTarget.window === eventTarget ? eventTarget.document : eventTarget.nodeType === DOCUMENT_NODE ? eventTarget : eventTarget.ownerDocument;
}
function constructSelectEvent(dispatchQueue, nativeEvent, nativeEventTarget) {
var doc = getEventTargetDocument(nativeEventTarget);
if (mouseDown || activeElement$1 == null || activeElement$1 !== getActiveElement(doc)) {
return;
}
var currentSelection = getSelection$1(activeElement$1);
if (!lastSelection || !shallowEqual(lastSelection, currentSelection)) {
lastSelection = currentSelection;
var listeners = accumulateTwoPhaseListeners(activeElementInst$1, "onSelect");
if (listeners.length > 0) {
var event = new SyntheticEvent("onSelect", "select", null, nativeEvent, nativeEventTarget);
dispatchQueue.push({
event,
listeners
});
event.target = activeElement$1;
}
}
}
function extractEvents$3(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags, targetContainer) {
var targetNode = targetInst ? getNodeFromInstance(targetInst) : window;
switch (domEventName) {
case "focusin":
if (isTextInputElement(targetNode) || targetNode.contentEditable === "true") {
activeElement$1 = targetNode;
activeElementInst$1 = targetInst;
lastSelection = null;
}
break;
case "focusout":
activeElement$1 = null;
activeElementInst$1 = null;
lastSelection = null;
break;
case "mousedown":
mouseDown = true;
break;
case "contextmenu":
case "mouseup":
case "dragend":
mouseDown = false;
constructSelectEvent(dispatchQueue, nativeEvent, nativeEventTarget);
break;
case "selectionchange":
if (skipSelectionChangeEvent) {
break;
}
case "keydown":
case "keyup":
constructSelectEvent(dispatchQueue, nativeEvent, nativeEventTarget);
}
}
function extractEvents$4(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags, targetContainer) {
var reactName = topLevelEventsToReactNames.get(domEventName);
if (reactName === void 0) {
return;
}
var SyntheticEventCtor = SyntheticEvent;
var reactEventType = domEventName;
switch (domEventName) {
case "keypress":
if (getEventCharCode(nativeEvent) === 0) {
return;
}
case "keydown":
case "keyup":
SyntheticEventCtor = SyntheticKeyboardEvent;
break;
case "focusin":
reactEventType = "focus";
SyntheticEventCtor = SyntheticFocusEvent;
break;
case "focusout":
reactEventType = "blur";
SyntheticEventCtor = SyntheticFocusEvent;
break;
case "beforeblur":
case "afterblur":
SyntheticEventCtor = SyntheticFocusEvent;
break;
case "click":
if (nativeEvent.button === 2) {
return;
}
case "auxclick":
case "dblclick":
case "mousedown":
case "mousemove":
case "mouseup":
case "mouseout":
case "mouseover":
case "contextmenu":
SyntheticEventCtor = SyntheticMouseEvent;
break;
case "drag":
case "dragend":
case "dragenter":
case "dragexit":
case "dragleave":
case "dragover":
case "dragstart":
case "drop":
SyntheticEventCtor = SyntheticDragEvent;
break;
case "touchcancel":
case "touchend":
case "touchmove":
case "touchstart":
SyntheticEventCtor = SyntheticTouchEvent;
break;
case ANIMATION_END:
case ANIMATION_ITERATION:
case ANIMATION_START:
SyntheticEventCtor = SyntheticAnimationEvent;
break;
case TRANSITION_END:
SyntheticEventCtor = SyntheticTransitionEvent;
break;
case "scroll":
SyntheticEventCtor = SyntheticUIEvent;
break;
case "wheel":
SyntheticEventCtor = SyntheticWheelEvent;
break;
case "copy":
case "cut":
case "paste":
SyntheticEventCtor = SyntheticClipboardEvent;
break;
case "gotpointercapture":
case "lostpointercapture":
case "pointercancel":
case "pointerdown":
case "pointermove":
case "pointerout":
case "pointerover":
case "pointerup":
SyntheticEventCtor = SyntheticPointerEvent;
break;
}
var inCapturePhase = (eventSystemFlags & IS_CAPTURE_PHASE) !== 0;
{
var accumulateTargetOnly = !inCapturePhase && domEventName === "scroll";
var _listeners = accumulateSinglePhaseListeners(targetInst, reactName, nativeEvent.type, inCapturePhase, accumulateTargetOnly);
if (_listeners.length > 0) {
var _event = new SyntheticEventCtor(reactName, reactEventType, null, nativeEvent, nativeEventTarget);
dispatchQueue.push({
event: _event,
listeners: _listeners
});
}
}
}
registerSimpleEvents();
registerEvents$2();
registerEvents$1();
registerEvents$3();
registerEvents();
function extractEvents$5(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags, targetContainer) {
extractEvents$4(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags);
var shouldProcessPolyfillPlugins = (eventSystemFlags & SHOULD_NOT_PROCESS_POLYFILL_EVENT_PLUGINS) === 0;
if (shouldProcessPolyfillPlugins) {
extractEvents$2(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags);
extractEvents$1(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget);
extractEvents$3(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget);
extractEvents(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget);
}
}
var mediaEventTypes = ["abort", "canplay", "canplaythrough", "durationchange", "emptied", "encrypted", "ended", "error", "loadeddata", "loadedmetadata", "loadstart", "pause", "play", "playing", "progress", "ratechange", "seeked", "seeking", "stalled", "suspend", "timeupdate", "volumechange", "waiting"];
var nonDelegatedEvents = new Set(["cancel", "close", "invalid", "load", "scroll", "toggle"].concat(mediaEventTypes));
function executeDispatch(event, listener, currentTarget) {
var type = event.type || "unknown-event";
event.currentTarget = currentTarget;
invokeGuardedCallbackAndCatchFirstError(type, listener, void 0, event);
event.currentTarget = null;
}
function processDispatchQueueItemsInOrder(event, dispatchListeners, inCapturePhase) {
var previousInstance;
if (inCapturePhase) {
for (var i = dispatchListeners.length - 1; i >= 0; i--) {
var _dispatchListeners$i = dispatchListeners[i], instance = _dispatchListeners$i.instance, currentTarget = _dispatchListeners$i.currentTarget, listener = _dispatchListeners$i.listener;
if (instance !== previousInstance && event.isPropagationStopped()) {
return;
}
executeDispatch(event, listener, currentTarget);
previousInstance = instance;
}
} else {
for (var _i = 0; _i < dispatchListeners.length; _i++) {
var _dispatchListeners$_i = dispatchListeners[_i], _instance = _dispatchListeners$_i.instance, _currentTarget = _dispatchListeners$_i.currentTarget, _listener = _dispatchListeners$_i.listener;
if (_instance !== previousInstance && event.isPropagationStopped()) {
return;
}
executeDispatch(event, _listener, _currentTarget);
previousInstance = _instance;
}
}
}
function processDispatchQueue(dispatchQueue, eventSystemFlags) {
var inCapturePhase = (eventSystemFlags & IS_CAPTURE_PHASE) !== 0;
for (var i = 0; i < dispatchQueue.length; i++) {
var _dispatchQueue$i = dispatchQueue[i], event = _dispatchQueue$i.event, listeners = _dispatchQueue$i.listeners;
processDispatchQueueItemsInOrder(event, listeners, inCapturePhase);
}
rethrowCaughtError();
}
function dispatchEventsForPlugins(domEventName, eventSystemFlags, nativeEvent, targetInst, targetContainer) {
var nativeEventTarget = getEventTarget(nativeEvent);
var dispatchQueue = [];
extractEvents$5(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags);
processDispatchQueue(dispatchQueue, eventSystemFlags);
}
function listenToNonDelegatedEvent(domEventName, targetElement) {
var isCapturePhaseListener = false;
var listenerSet = getEventListenerSet(targetElement);
var listenerSetKey = getListenerSetKey(domEventName, isCapturePhaseListener);
if (!listenerSet.has(listenerSetKey)) {
addTrappedEventListener(targetElement, domEventName, IS_NON_DELEGATED, isCapturePhaseListener);
listenerSet.add(listenerSetKey);
}
}
var listeningMarker = "_reactListening" + Math.random().toString(36).slice(2);
function listenToAllSupportedEvents(rootContainerElement) {
{
if (rootContainerElement[listeningMarker]) {
return;
}
rootContainerElement[listeningMarker] = true;
allNativeEvents.forEach(function(domEventName) {
if (!nonDelegatedEvents.has(domEventName)) {
listenToNativeEvent(domEventName, false, rootContainerElement, null);
}
listenToNativeEvent(domEventName, true, rootContainerElement, null);
});
}
}
function listenToNativeEvent(domEventName, isCapturePhaseListener, rootContainerElement, targetElement) {
var eventSystemFlags = arguments.length > 4 && arguments[4] !== void 0 ? arguments[4] : 0;
var target = rootContainerElement;
if (domEventName === "selectionchange" && rootContainerElement.nodeType !== DOCUMENT_NODE) {
target = rootContainerElement.ownerDocument;
}
if (targetElement !== null && !isCapturePhaseListener && nonDelegatedEvents.has(domEventName)) {
if (domEventName !== "scroll") {
return;
}
eventSystemFlags |= IS_NON_DELEGATED;
target = targetElement;
}
var listenerSet = getEventListenerSet(target);
var listenerSetKey = getListenerSetKey(domEventName, isCapturePhaseListener);
if (!listenerSet.has(listenerSetKey)) {
if (isCapturePhaseListener) {
eventSystemFlags |= IS_CAPTURE_PHASE;
}
addTrappedEventListener(target, domEventName, eventSystemFlags, isCapturePhaseListener);
listenerSet.add(listenerSetKey);
}
}
function addTrappedEventListener(targetContainer, domEventName, eventSystemFlags, isCapturePhaseListener, isDeferredListenerForLegacyFBSupport) {
var listener = createEventListenerWrapperWithPriority(targetContainer, domEventName, eventSystemFlags);
var isPassiveListener = void 0;
if (passiveBrowserEventsSupported) {
if (domEventName === "touchstart" || domEventName === "touchmove" || domEventName === "wheel") {
isPassiveListener = true;
}
}
targetContainer = targetContainer;
var unsubscribeListener;
if (isCapturePhaseListener) {
if (isPassiveListener !== void 0) {
unsubscribeListener = addEventCaptureListenerWithPassiveFlag(targetContainer, domEventName, listener, isPassiveListener);
} else {
unsubscribeListener = addEventCaptureListener(targetContainer, domEventName, listener);
}
} else {
if (isPassiveListener !== void 0) {
unsubscribeListener = addEventBubbleListenerWithPassiveFlag(targetContainer, domEventName, listener, isPassiveListener);
} else {
unsubscribeListener = addEventBubbleListener(targetContainer, domEventName, listener);
}
}
}
function isMatchingRootContainer(grandContainer, targetContainer) {
return grandContainer === targetContainer || grandContainer.nodeType === COMMENT_NODE && grandContainer.parentNode === targetContainer;
}
function dispatchEventForPluginEventSystem(domEventName, eventSystemFlags, nativeEvent, targetInst, targetContainer) {
var ancestorInst = targetInst;
if ((eventSystemFlags & IS_EVENT_HANDLE_NON_MANAGED_NODE) === 0 && (eventSystemFlags & IS_NON_DELEGATED) === 0) {
var targetContainerNode = targetContainer;
if (targetInst !== null) {
var node = targetInst;
mainLoop:
while (true) {
if (node === null) {
return;
}
var nodeTag = node.tag;
if (nodeTag === HostRoot || nodeTag === HostPortal) {
var container = node.stateNode.containerInfo;
if (isMatchingRootContainer(container, targetContainerNode)) {
break;
}
if (nodeTag === HostPortal) {
var grandNode = node.return;
while (grandNode !== null) {
var grandTag = grandNode.tag;
if (grandTag === HostRoot || grandTag === HostPortal) {
var grandContainer = grandNode.stateNode.containerInfo;
if (isMatchingRootContainer(grandContainer, targetContainerNode)) {
return;
}
}
grandNode = grandNode.return;
}
}
while (container !== null) {
var parentNode = getClosestInstanceFromNode(container);
if (parentNode === null) {
return;
}
var parentTag = parentNode.tag;
if (parentTag === HostComponent || parentTag === HostText) {
node = ancestorInst = parentNode;
continue mainLoop;
}
container = container.parentNode;
}
}
node = node.return;
}
}
}
batchedEventUpdates(function() {
return dispatchEventsForPlugins(domEventName, eventSystemFlags, nativeEvent, ancestorInst);
});
}
function createDispatchListener(instance, listener, currentTarget) {
return {
instance,
listener,
currentTarget
};
}
function accumulateSinglePhaseListeners(targetFiber, reactName, nativeEventType, inCapturePhase, accumulateTargetOnly) {
var captureName = reactName !== null ? reactName + "Capture" : null;
var reactEventName = inCapturePhase ? captureName : reactName;
var listeners = [];
var instance = targetFiber;
var lastHostComponent = null;
while (instance !== null) {
var _instance2 = instance, stateNode = _instance2.stateNode, tag = _instance2.tag;
if (tag === HostComponent && stateNode !== null) {
lastHostComponent = stateNode;
if (reactEventName !== null) {
var listener = getListener(instance, reactEventName);
if (listener != null) {
listeners.push(createDispatchListener(instance, listener, lastHostComponent));
}
}
}
if (accumulateTargetOnly) {
break;
}
instance = instance.return;
}
return listeners;
}
function accumulateTwoPhaseListeners(targetFiber, reactName) {
var captureName = reactName + "Capture";
var listeners = [];
var instance = targetFiber;
while (instance !== null) {
var _instance3 = instance, stateNode = _instance3.stateNode, tag = _instance3.tag;
if (tag === HostComponent && stateNode !== null) {
var currentTarget = stateNode;
var captureListener = getListener(instance, captureName);
if (captureListener != null) {
listeners.unshift(createDispatchListener(instance, captureListener, currentTarget));
}
var bubbleListener = getListener(instance, reactName);
if (bubbleListener != null) {
listeners.push(createDispatchListener(instance, bubbleListener, currentTarget));
}
}
instance = instance.return;
}
return listeners;
}
function getParent(inst) {
if (inst === null) {
return null;
}
do {
inst = inst.return;
} while (inst && inst.tag !== HostComponent);
if (inst) {
return inst;
}
return null;
}
function getLowestCommonAncestor(instA, instB) {
var nodeA = instA;
var nodeB = instB;
var depthA = 0;
for (var tempA = nodeA; tempA; tempA = getParent(tempA)) {
depthA++;
}
var depthB = 0;
for (var tempB = nodeB; tempB; tempB = getParent(tempB)) {
depthB++;
}
while (depthA - depthB > 0) {
nodeA = getParent(nodeA);
depthA--;
}
while (depthB - depthA > 0) {
nodeB = getParent(nodeB);
depthB--;
}
var depth = depthA;
while (depth--) {
if (nodeA === nodeB || nodeB !== null && nodeA === nodeB.alternate) {
return nodeA;
}
nodeA = getParent(nodeA);
nodeB = getParent(nodeB);
}
return null;
}
function accumulateEnterLeaveListenersForEvent(dispatchQueue, event, target, common, inCapturePhase) {
var registrationName = event._reactName;
var listeners = [];
var instance = target;
while (instance !== null) {
if (instance === common) {
break;
}
var _instance4 = instance, alternate = _instance4.alternate, stateNode = _instance4.stateNode, tag = _instance4.tag;
if (alternate !== null && alternate === common) {
break;
}
if (tag === HostComponent && stateNode !== null) {
var currentTarget = stateNode;
if (inCapturePhase) {
var captureListener = getListener(instance, registrationName);
if (captureListener != null) {
listeners.unshift(createDispatchListener(instance, captureListener, currentTarget));
}
} else if (!inCapturePhase) {
var bubbleListener = getListener(instance, registrationName);
if (bubbleListener != null) {
listeners.push(createDispatchListener(instance, bubbleListener, currentTarget));
}
}
}
instance = instance.return;
}
if (listeners.length !== 0) {
dispatchQueue.push({
event,
listeners
});
}
}
function accumulateEnterLeaveTwoPhaseListeners(dispatchQueue, leaveEvent, enterEvent, from, to) {
var common = from && to ? getLowestCommonAncestor(from, to) : null;
if (from !== null) {
accumulateEnterLeaveListenersForEvent(dispatchQueue, leaveEvent, from, common, false);
}
if (to !== null && enterEvent !== null) {
accumulateEnterLeaveListenersForEvent(dispatchQueue, enterEvent, to, common, true);
}
}
function getListenerSetKey(domEventName, capture) {
return domEventName + "__" + (capture ? "capture" : "bubble");
}
var didWarnInvalidHydration = false;
var DANGEROUSLY_SET_INNER_HTML = "dangerouslySetInnerHTML";
var SUPPRESS_CONTENT_EDITABLE_WARNING = "suppressContentEditableWarning";
var SUPPRESS_HYDRATION_WARNING = "suppressHydrationWarning";
var AUTOFOCUS = "autoFocus";
var CHILDREN = "children";
var STYLE = "style";
var HTML$1 = "__html";
var HTML_NAMESPACE$1 = Namespaces.html;
var warnedUnknownTags;
var suppressHydrationWarning;
var validatePropertiesInDevelopment;
var warnForTextDifference;
var warnForPropDifference;
var warnForExtraAttributes;
var warnForInvalidEventListener;
var canDiffStyleForHydrationWarning;
var normalizeMarkupForTextOrAttribute;
var normalizeHTML;
{
warnedUnknownTags = {
dialog: true,
webview: true
};
validatePropertiesInDevelopment = function(type, props) {
validateProperties(type, props);
validateProperties$1(type, props);
validateProperties$2(type, props, {
registrationNameDependencies,
possibleRegistrationNames
});
};
canDiffStyleForHydrationWarning = canUseDOM && !document.documentMode;
var NORMALIZE_NEWLINES_REGEX = /\r\n?/g;
var NORMALIZE_NULL_AND_REPLACEMENT_REGEX = /\u0000|\uFFFD/g;
normalizeMarkupForTextOrAttribute = function(markup) {
var markupString = typeof markup === "string" ? markup : "" + markup;
return markupString.replace(NORMALIZE_NEWLINES_REGEX, "\n").replace(NORMALIZE_NULL_AND_REPLACEMENT_REGEX, "");
};
warnForTextDifference = function(serverText, clientText) {
if (didWarnInvalidHydration) {
return;
}
var normalizedClientText = normalizeMarkupForTextOrAttribute(clientText);
var normalizedServerText = normalizeMarkupForTextOrAttribute(serverText);
if (normalizedServerText === normalizedClientText) {
return;
}
didWarnInvalidHydration = true;
error('Text content did not match. Server: "%s" Client: "%s"', normalizedServerText, normalizedClientText);
};
warnForPropDifference = function(propName, serverValue, clientValue) {
if (didWarnInvalidHydration) {
return;
}
var normalizedClientValue = normalizeMarkupForTextOrAttribute(clientValue);
var normalizedServerValue = normalizeMarkupForTextOrAttribute(serverValue);
if (normalizedServerValue === normalizedClientValue) {
return;
}
didWarnInvalidHydration = true;
error("Prop `%s` did not match. Server: %s Client: %s", propName, JSON.stringify(normalizedServerValue), JSON.stringify(normalizedClientValue));
};
warnForExtraAttributes = function(attributeNames) {
if (didWarnInvalidHydration) {
return;
}
didWarnInvalidHydration = true;
var names = [];
attributeNames.forEach(function(name) {
names.push(name);
});
error("Extra attributes from the server: %s", names);
};
warnForInvalidEventListener = function(registrationName, listener) {
if (listener === false) {
error("Expected `%s` listener to be a function, instead got `false`.\n\nIf you used to conditionally omit it with %s={condition && value}, pass %s={condition ? value : undefined} instead.", registrationName, registrationName, registrationName);
} else {
error("Expected `%s` listener to be a function, instead got a value of `%s` type.", registrationName, typeof listener);
}
};
normalizeHTML = function(parent, html) {
var testElement = parent.namespaceURI === HTML_NAMESPACE$1 ? parent.ownerDocument.createElement(parent.tagName) : parent.ownerDocument.createElementNS(parent.namespaceURI, parent.tagName);
testElement.innerHTML = html;
return testElement.innerHTML;
};
}
function getOwnerDocumentFromRootContainer(rootContainerElement) {
return rootContainerElement.nodeType === DOCUMENT_NODE ? rootContainerElement : rootContainerElement.ownerDocument;
}
function noop() {
}
function trapClickOnNonInteractiveElement(node) {
node.onclick = noop;
}
function setInitialDOMProperties(tag, domElement, rootContainerElement, nextProps, isCustomComponentTag) {
for (var propKey in nextProps) {
if (!nextProps.hasOwnProperty(propKey)) {
continue;
}
var nextProp = nextProps[propKey];
if (propKey === STYLE) {
{
if (nextProp) {
Object.freeze(nextProp);
}
}
setValueForStyles(domElement, nextProp);
} else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
var nextHtml = nextProp ? nextProp[HTML$1] : void 0;
if (nextHtml != null) {
setInnerHTML(domElement, nextHtml);
}
} else if (propKey === CHILDREN) {
if (typeof nextProp === "string") {
var canSetTextContent = tag !== "textarea" || nextProp !== "";
if (canSetTextContent) {
setTextContent(domElement, nextProp);
}
} else if (typeof nextProp === "number") {
setTextContent(domElement, "" + nextProp);
}
} else if (propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING)
;
else if (propKey === AUTOFOCUS)
;
else if (registrationNameDependencies.hasOwnProperty(propKey)) {
if (nextProp != null) {
if (typeof nextProp !== "function") {
warnForInvalidEventListener(propKey, nextProp);
}
if (propKey === "onScroll") {
listenToNonDelegatedEvent("scroll", domElement);
}
}
} else if (nextProp != null) {
setValueForProperty(domElement, propKey, nextProp, isCustomComponentTag);
}
}
}
function updateDOMProperties(domElement, updatePayload, wasCustomComponentTag, isCustomComponentTag) {
for (var i = 0; i < updatePayload.length; i += 2) {
var propKey = updatePayload[i];
var propValue = updatePayload[i + 1];
if (propKey === STYLE) {
setValueForStyles(domElement, propValue);
} else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
setInnerHTML(domElement, propValue);
} else if (propKey === CHILDREN) {
setTextContent(domElement, propValue);
} else {
setValueForProperty(domElement, propKey, propValue, isCustomComponentTag);
}
}
}
function createElement(type, props, rootContainerElement, parentNamespace) {
var isCustomComponentTag;
var ownerDocument = getOwnerDocumentFromRootContainer(rootContainerElement);
var domElement;
var namespaceURI = parentNamespace;
if (namespaceURI === HTML_NAMESPACE$1) {
namespaceURI = getIntrinsicNamespace(type);
}
if (namespaceURI === HTML_NAMESPACE$1) {
{
isCustomComponentTag = isCustomComponent(type, props);
if (!isCustomComponentTag && type !== type.toLowerCase()) {
error("<%s /> is using incorrect casing. Use PascalCase for React components, or lowercase for HTML elements.", type);
}
}
if (type === "script") {
var div = ownerDocument.createElement("div");
div.innerHTML = "<script><\/script>";
var firstChild = div.firstChild;
domElement = div.removeChild(firstChild);
} else if (typeof props.is === "string") {
domElement = ownerDocument.createElement(type, {
is: props.is
});
} else {
domElement = ownerDocument.createElement(type);
if (type === "select") {
var node = domElement;
if (props.multiple) {
node.multiple = true;
} else if (props.size) {
node.size = props.size;
}
}
}
} else {
domElement = ownerDocument.createElementNS(namespaceURI, type);
}
{
if (namespaceURI === HTML_NAMESPACE$1) {
if (!isCustomComponentTag && Object.prototype.toString.call(domElement) === "[object HTMLUnknownElement]" && !Object.prototype.hasOwnProperty.call(warnedUnknownTags, type)) {
warnedUnknownTags[type] = true;
error("The tag <%s> is unrecognized in this browser. If you meant to render a React component, start its name with an uppercase letter.", type);
}
}
}
return domElement;
}
function createTextNode(text, rootContainerElement) {
return getOwnerDocumentFromRootContainer(rootContainerElement).createTextNode(text);
}
function setInitialProperties(domElement, tag, rawProps, rootContainerElement) {
var isCustomComponentTag = isCustomComponent(tag, rawProps);
{
validatePropertiesInDevelopment(tag, rawProps);
}
var props;
switch (tag) {
case "dialog":
listenToNonDelegatedEvent("cancel", domElement);
listenToNonDelegatedEvent("close", domElement);
props = rawProps;
break;
case "iframe":
case "object":
case "embed":
listenToNonDelegatedEvent("load", domElement);
props = rawProps;
break;
case "video":
case "audio":
for (var i = 0; i < mediaEventTypes.length; i++) {
listenToNonDelegatedEvent(mediaEventTypes[i], domElement);
}
props = rawProps;
break;
case "source":
listenToNonDelegatedEvent("error", domElement);
props = rawProps;
break;
case "img":
case "image":
case "link":
listenToNonDelegatedEvent("error", domElement);
listenToNonDelegatedEvent("load", domElement);
props = rawProps;
break;
case "details":
listenToNonDelegatedEvent("toggle", domElement);
props = rawProps;
break;
case "input":
initWrapperState(domElement, rawProps);
props = getHostProps(domElement, rawProps);
listenToNonDelegatedEvent("invalid", domElement);
break;
case "option":
validateProps(domElement, rawProps);
props = getHostProps$1(domElement, rawProps);
break;
case "select":
initWrapperState$1(domElement, rawProps);
props = getHostProps$2(domElement, rawProps);
listenToNonDelegatedEvent("invalid", domElement);
break;
case "textarea":
initWrapperState$2(domElement, rawProps);
props = getHostProps$3(domElement, rawProps);
listenToNonDelegatedEvent("invalid", domElement);
break;
default:
props = rawProps;
}
assertValidProps(tag, props);
setInitialDOMProperties(tag, domElement, rootContainerElement, props, isCustomComponentTag);
switch (tag) {
case "input":
track(domElement);
postMountWrapper(domElement, rawProps, false);
break;
case "textarea":
track(domElement);
postMountWrapper$3(domElement);
break;
case "option":
postMountWrapper$1(domElement, rawProps);
break;
case "select":
postMountWrapper$2(domElement, rawProps);
break;
default:
if (typeof props.onClick === "function") {
trapClickOnNonInteractiveElement(domElement);
}
break;
}
}
function diffProperties(domElement, tag, lastRawProps, nextRawProps, rootContainerElement) {
{
validatePropertiesInDevelopment(tag, nextRawProps);
}
var updatePayload = null;
var lastProps;
var nextProps;
switch (tag) {
case "input":
lastProps = getHostProps(domElement, lastRawProps);
nextProps = getHostProps(domElement, nextRawProps);
updatePayload = [];
break;
case "option":
lastProps = getHostProps$1(domElement, lastRawProps);
nextProps = getHostProps$1(domElement, nextRawProps);
updatePayload = [];
break;
case "select":
lastProps = getHostProps$2(domElement, lastRawProps);
nextProps = getHostProps$2(domElement, nextRawProps);
updatePayload = [];
break;
case "textarea":
lastProps = getHostProps$3(domElement, lastRawProps);
nextProps = getHostProps$3(domElement, nextRawProps);
updatePayload = [];
break;
default:
lastProps = lastRawProps;
nextProps = nextRawProps;
if (typeof lastProps.onClick !== "function" && typeof nextProps.onClick === "function") {
trapClickOnNonInteractiveElement(domElement);
}
break;
}
assertValidProps(tag, nextProps);
var propKey;
var styleName;
var styleUpdates = null;
for (propKey in lastProps) {
if (nextProps.hasOwnProperty(propKey) || !lastProps.hasOwnProperty(propKey) || lastProps[propKey] == null) {
continue;
}
if (propKey === STYLE) {
var lastStyle = lastProps[propKey];
for (styleName in lastStyle) {
if (lastStyle.hasOwnProperty(styleName)) {
if (!styleUpdates) {
styleUpdates = {};
}
styleUpdates[styleName] = "";
}
}
} else if (propKey === DANGEROUSLY_SET_INNER_HTML || propKey === CHILDREN)
;
else if (propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING)
;
else if (propKey === AUTOFOCUS)
;
else if (registrationNameDependencies.hasOwnProperty(propKey)) {
if (!updatePayload) {
updatePayload = [];
}
} else {
(updatePayload = updatePayload || []).push(propKey, null);
}
}
for (propKey in nextProps) {
var nextProp = nextProps[propKey];
var lastProp = lastProps != null ? lastProps[propKey] : void 0;
if (!nextProps.hasOwnProperty(propKey) || nextProp === lastProp || nextProp == null && lastProp == null) {
continue;
}
if (propKey === STYLE) {
{
if (nextProp) {
Object.freeze(nextProp);
}
}
if (lastProp) {
for (styleName in lastProp) {
if (lastProp.hasOwnProperty(styleName) && (!nextProp || !nextProp.hasOwnProperty(styleName))) {
if (!styleUpdates) {
styleUpdates = {};
}
styleUpdates[styleName] = "";
}
}
for (styleName in nextProp) {
if (nextProp.hasOwnProperty(styleName) && lastProp[styleName] !== nextProp[styleName]) {
if (!styleUpdates) {
styleUpdates = {};
}
styleUpdates[styleName] = nextProp[styleName];
}
}
} else {
if (!styleUpdates) {
if (!updatePayload) {
updatePayload = [];
}
updatePayload.push(propKey, styleUpdates);
}
styleUpdates = nextProp;
}
} else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
var nextHtml = nextProp ? nextProp[HTML$1] : void 0;
var lastHtml = lastProp ? lastProp[HTML$1] : void 0;
if (nextHtml != null) {
if (lastHtml !== nextHtml) {
(updatePayload = updatePayload || []).push(propKey, nextHtml);
}
}
} else if (propKey === CHILDREN) {
if (typeof nextProp === "string" || typeof nextProp === "number") {
(updatePayload = updatePayload || []).push(propKey, "" + nextProp);
}
} else if (propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING)
;
else if (registrationNameDependencies.hasOwnProperty(propKey)) {
if (nextProp != null) {
if (typeof nextProp !== "function") {
warnForInvalidEventListener(propKey, nextProp);
}
if (propKey === "onScroll") {
listenToNonDelegatedEvent("scroll", domElement);
}
}
if (!updatePayload && lastProp !== nextProp) {
updatePayload = [];
}
} else if (typeof nextProp === "object" && nextProp !== null && nextProp.$$typeof === REACT_OPAQUE_ID_TYPE) {
nextProp.toString();
} else {
(updatePayload = updatePayload || []).push(propKey, nextProp);
}
}
if (styleUpdates) {
{
validateShorthandPropertyCollisionInDev(styleUpdates, nextProps[STYLE]);
}
(updatePayload = updatePayload || []).push(STYLE, styleUpdates);
}
return updatePayload;
}
function updateProperties(domElement, updatePayload, tag, lastRawProps, nextRawProps) {
if (tag === "input" && nextRawProps.type === "radio" && nextRawProps.name != null) {
updateChecked(domElement, nextRawProps);
}
var wasCustomComponentTag = isCustomComponent(tag, lastRawProps);
var isCustomComponentTag = isCustomComponent(tag, nextRawProps);
updateDOMProperties(domElement, updatePayload, wasCustomComponentTag, isCustomComponentTag);
switch (tag) {
case "input":
updateWrapper(domElement, nextRawProps);
break;
case "textarea":
updateWrapper$1(domElement, nextRawProps);
break;
case "select":
postUpdateWrapper(domElement, nextRawProps);
break;
}
}
function getPossibleStandardName(propName) {
{
var lowerCasedName = propName.toLowerCase();
if (!possibleStandardNames.hasOwnProperty(lowerCasedName)) {
return null;
}
return possibleStandardNames[lowerCasedName] || null;
}
}
function diffHydratedProperties(domElement, tag, rawProps, parentNamespace, rootContainerElement) {
var isCustomComponentTag;
var extraAttributeNames;
{
suppressHydrationWarning = rawProps[SUPPRESS_HYDRATION_WARNING] === true;
isCustomComponentTag = isCustomComponent(tag, rawProps);
validatePropertiesInDevelopment(tag, rawProps);
}
switch (tag) {
case "dialog":
listenToNonDelegatedEvent("cancel", domElement);
listenToNonDelegatedEvent("close", domElement);
break;
case "iframe":
case "object":
case "embed":
listenToNonDelegatedEvent("load", domElement);
break;
case "video":
case "audio":
for (var i = 0; i < mediaEventTypes.length; i++) {
listenToNonDelegatedEvent(mediaEventTypes[i], domElement);
}
break;
case "source":
listenToNonDelegatedEvent("error", domElement);
break;
case "img":
case "image":
case "link":
listenToNonDelegatedEvent("error", domElement);
listenToNonDelegatedEvent("load", domElement);
break;
case "details":
listenToNonDelegatedEvent("toggle", domElement);
break;
case "input":
initWrapperState(domElement, rawProps);
listenToNonDelegatedEvent("invalid", domElement);
break;
case "option":
validateProps(domElement, rawProps);
break;
case "select":
initWrapperState$1(domElement, rawProps);
listenToNonDelegatedEvent("invalid", domElement);
break;
case "textarea":
initWrapperState$2(domElement, rawProps);
listenToNonDelegatedEvent("invalid", domElement);
break;
}
assertValidProps(tag, rawProps);
{
extraAttributeNames = new Set();
var attributes = domElement.attributes;
for (var _i = 0; _i < attributes.length; _i++) {
var name = attributes[_i].name.toLowerCase();
switch (name) {
case "data-reactroot":
break;
case "value":
break;
case "checked":
break;
case "selected":
break;
default:
extraAttributeNames.add(attributes[_i].name);
}
}
}
var updatePayload = null;
for (var propKey in rawProps) {
if (!rawProps.hasOwnProperty(propKey)) {
continue;
}
var nextProp = rawProps[propKey];
if (propKey === CHILDREN) {
if (typeof nextProp === "string") {
if (domElement.textContent !== nextProp) {
if (!suppressHydrationWarning) {
warnForTextDifference(domElement.textContent, nextProp);
}
updatePayload = [CHILDREN, nextProp];
}
} else if (typeof nextProp === "number") {
if (domElement.textContent !== "" + nextProp) {
if (!suppressHydrationWarning) {
warnForTextDifference(domElement.textContent, nextProp);
}
updatePayload = [CHILDREN, "" + nextProp];
}
}
} else if (registrationNameDependencies.hasOwnProperty(propKey)) {
if (nextProp != null) {
if (typeof nextProp !== "function") {
warnForInvalidEventListener(propKey, nextProp);
}
if (propKey === "onScroll") {
listenToNonDelegatedEvent("scroll", domElement);
}
}
} else if (typeof isCustomComponentTag === "boolean") {
var serverValue = void 0;
var propertyInfo = getPropertyInfo(propKey);
if (suppressHydrationWarning)
;
else if (propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING || propKey === "value" || propKey === "checked" || propKey === "selected")
;
else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
var serverHTML = domElement.innerHTML;
var nextHtml = nextProp ? nextProp[HTML$1] : void 0;
if (nextHtml != null) {
var expectedHTML = normalizeHTML(domElement, nextHtml);
if (expectedHTML !== serverHTML) {
warnForPropDifference(propKey, serverHTML, expectedHTML);
}
}
} else if (propKey === STYLE) {
extraAttributeNames.delete(propKey);
if (canDiffStyleForHydrationWarning) {
var expectedStyle = createDangerousStringForStyles(nextProp);
serverValue = domElement.getAttribute("style");
if (expectedStyle !== serverValue) {
warnForPropDifference(propKey, serverValue, expectedStyle);
}
}
} else if (isCustomComponentTag) {
extraAttributeNames.delete(propKey.toLowerCase());
serverValue = getValueForAttribute(domElement, propKey, nextProp);
if (nextProp !== serverValue) {
warnForPropDifference(propKey, serverValue, nextProp);
}
} else if (!shouldIgnoreAttribute(propKey, propertyInfo, isCustomComponentTag) && !shouldRemoveAttribute(propKey, nextProp, propertyInfo, isCustomComponentTag)) {
var isMismatchDueToBadCasing = false;
if (propertyInfo !== null) {
extraAttributeNames.delete(propertyInfo.attributeName);
serverValue = getValueForProperty(domElement, propKey, nextProp, propertyInfo);
} else {
var ownNamespace = parentNamespace;
if (ownNamespace === HTML_NAMESPACE$1) {
ownNamespace = getIntrinsicNamespace(tag);
}
if (ownNamespace === HTML_NAMESPACE$1) {
extraAttributeNames.delete(propKey.toLowerCase());
} else {
var standardName = getPossibleStandardName(propKey);
if (standardName !== null && standardName !== propKey) {
isMismatchDueToBadCasing = true;
extraAttributeNames.delete(standardName);
}
extraAttributeNames.delete(propKey);
}
serverValue = getValueForAttribute(domElement, propKey, nextProp);
}
if (nextProp !== serverValue && !isMismatchDueToBadCasing) {
warnForPropDifference(propKey, serverValue, nextProp);
}
}
}
}
{
if (extraAttributeNames.size > 0 && !suppressHydrationWarning) {
warnForExtraAttributes(extraAttributeNames);
}
}
switch (tag) {
case "input":
track(domElement);
postMountWrapper(domElement, rawProps, true);
break;
case "textarea":
track(domElement);
postMountWrapper$3(domElement);
break;
case "select":
case "option":
break;
default:
if (typeof rawProps.onClick === "function") {
trapClickOnNonInteractiveElement(domElement);
}
break;
}
return updatePayload;
}
function diffHydratedText(textNode, text) {
var isDifferent = textNode.nodeValue !== text;
return isDifferent;
}
function warnForUnmatchedText(textNode, text) {
{
warnForTextDifference(textNode.nodeValue, text);
}
}
function warnForDeletedHydratableElement(parentNode, child) {
{
if (didWarnInvalidHydration) {
return;
}
didWarnInvalidHydration = true;
error("Did not expect server HTML to contain a <%s> in <%s>.", child.nodeName.toLowerCase(), parentNode.nodeName.toLowerCase());
}
}
function warnForDeletedHydratableText(parentNode, child) {
{
if (didWarnInvalidHydration) {
return;
}
didWarnInvalidHydration = true;
error('Did not expect server HTML to contain the text node "%s" in <%s>.', child.nodeValue, parentNode.nodeName.toLowerCase());
}
}
function warnForInsertedHydratedElement(parentNode, tag, props) {
{
if (didWarnInvalidHydration) {
return;
}
didWarnInvalidHydration = true;
error("Expected server HTML to contain a matching <%s> in <%s>.", tag, parentNode.nodeName.toLowerCase());
}
}
function warnForInsertedHydratedText(parentNode, text) {
{
if (text === "") {
return;
}
if (didWarnInvalidHydration) {
return;
}
didWarnInvalidHydration = true;
error('Expected server HTML to contain a matching text node for "%s" in <%s>.', text, parentNode.nodeName.toLowerCase());
}
}
function restoreControlledState$3(domElement, tag, props) {
switch (tag) {
case "input":
restoreControlledState(domElement, props);
return;
case "textarea":
restoreControlledState$2(domElement, props);
return;
case "select":
restoreControlledState$1(domElement, props);
return;
}
}
var validateDOMNesting = function() {
};
var updatedAncestorInfo = function() {
};
{
var specialTags = ["address", "applet", "area", "article", "aside", "base", "basefont", "bgsound", "blockquote", "body", "br", "button", "caption", "center", "col", "colgroup", "dd", "details", "dir", "div", "dl", "dt", "embed", "fieldset", "figcaption", "figure", "footer", "form", "frame", "frameset", "h1", "h2", "h3", "h4", "h5", "h6", "head", "header", "hgroup", "hr", "html", "iframe", "img", "input", "isindex", "li", "link", "listing", "main", "marquee", "menu", "menuitem", "meta", "nav", "noembed", "noframes", "noscript", "object", "ol", "p", "param", "plaintext", "pre", "script", "section", "select", "source", "style", "summary", "table", "tbody", "td", "template", "textarea", "tfoot", "th", "thead", "title", "tr", "track", "ul", "wbr", "xmp"];
var inScopeTags = [
"applet",
"caption",
"html",
"table",
"td",
"th",
"marquee",
"object",
"template",
"foreignObject",
"desc",
"title"
];
var buttonScopeTags = inScopeTags.concat(["button"]);
var impliedEndTags = ["dd", "dt", "li", "option", "optgroup", "p", "rp", "rt"];
var emptyAncestorInfo = {
current: null,
formTag: null,
aTagInScope: null,
buttonTagInScope: null,
nobrTagInScope: null,
pTagInButtonScope: null,
listItemTagAutoclosing: null,
dlItemTagAutoclosing: null
};
updatedAncestorInfo = function(oldInfo, tag) {
var ancestorInfo = _assign({}, oldInfo || emptyAncestorInfo);
var info = {
tag
};
if (inScopeTags.indexOf(tag) !== -1) {
ancestorInfo.aTagInScope = null;
ancestorInfo.buttonTagInScope = null;
ancestorInfo.nobrTagInScope = null;
}
if (buttonScopeTags.indexOf(tag) !== -1) {
ancestorInfo.pTagInButtonScope = null;
}
if (specialTags.indexOf(tag) !== -1 && tag !== "address" && tag !== "div" && tag !== "p") {
ancestorInfo.listItemTagAutoclosing = null;
ancestorInfo.dlItemTagAutoclosing = null;
}
ancestorInfo.current = info;
if (tag === "form") {
ancestorInfo.formTag = info;
}
if (tag === "a") {
ancestorInfo.aTagInScope = info;
}
if (tag === "button") {
ancestorInfo.buttonTagInScope = info;
}
if (tag === "nobr") {
ancestorInfo.nobrTagInScope = info;
}
if (tag === "p") {
ancestorInfo.pTagInButtonScope = info;
}
if (tag === "li") {
ancestorInfo.listItemTagAutoclosing = info;
}
if (tag === "dd" || tag === "dt") {
ancestorInfo.dlItemTagAutoclosing = info;
}
return ancestorInfo;
};
var isTagValidWithParent = function(tag, parentTag) {
switch (parentTag) {
case "select":
return tag === "option" || tag === "optgroup" || tag === "#text";
case "optgroup":
return tag === "option" || tag === "#text";
case "option":
return tag === "#text";
case "tr":
return tag === "th" || tag === "td" || tag === "style" || tag === "script" || tag === "template";
case "tbody":
case "thead":
case "tfoot":
return tag === "tr" || tag === "style" || tag === "script" || tag === "template";
case "colgroup":
return tag === "col" || tag === "template";
case "table":
return tag === "caption" || tag === "colgroup" || tag === "tbody" || tag === "tfoot" || tag === "thead" || tag === "style" || tag === "script" || tag === "template";
case "head":
return tag === "base" || tag === "basefont" || tag === "bgsound" || tag === "link" || tag === "meta" || tag === "title" || tag === "noscript" || tag === "noframes" || tag === "style" || tag === "script" || tag === "template";
case "html":
return tag === "head" || tag === "body" || tag === "frameset";
case "frameset":
return tag === "frame";
case "#document":
return tag === "html";
}
switch (tag) {
case "h1":
case "h2":
case "h3":
case "h4":
case "h5":
case "h6":
return parentTag !== "h1" && parentTag !== "h2" && parentTag !== "h3" && parentTag !== "h4" && parentTag !== "h5" && parentTag !== "h6";
case "rp":
case "rt":
return impliedEndTags.indexOf(parentTag) === -1;
case "body":
case "caption":
case "col":
case "colgroup":
case "frameset":
case "frame":
case "head":
case "html":
case "tbody":
case "td":
case "tfoot":
case "th":
case "thead":
case "tr":
return parentTag == null;
}
return true;
};
var findInvalidAncestorForTag = function(tag, ancestorInfo) {
switch (tag) {
case "address":
case "article":
case "aside":
case "blockquote":
case "center":
case "details":
case "dialog":
case "dir":
case "div":
case "dl":
case "fieldset":
case "figcaption":
case "figure":
case "footer":
case "header":
case "hgroup":
case "main":
case "menu":
case "nav":
case "ol":
case "p":
case "section":
case "summary":
case "ul":
case "pre":
case "listing":
case "table":
case "hr":
case "xmp":
case "h1":
case "h2":
case "h3":
case "h4":
case "h5":
case "h6":
return ancestorInfo.pTagInButtonScope;
case "form":
return ancestorInfo.formTag || ancestorInfo.pTagInButtonScope;
case "li":
return ancestorInfo.listItemTagAutoclosing;
case "dd":
case "dt":
return ancestorInfo.dlItemTagAutoclosing;
case "button":
return ancestorInfo.buttonTagInScope;
case "a":
return ancestorInfo.aTagInScope;
case "nobr":
return ancestorInfo.nobrTagInScope;
}
return null;
};
var didWarn$1 = {};
validateDOMNesting = function(childTag, childText, ancestorInfo) {
ancestorInfo = ancestorInfo || emptyAncestorInfo;
var parentInfo = ancestorInfo.current;
var parentTag = parentInfo && parentInfo.tag;
if (childText != null) {
if (childTag != null) {
error("validateDOMNesting: when childText is passed, childTag should be null");
}
childTag = "#text";
}
var invalidParent = isTagValidWithParent(childTag, parentTag) ? null : parentInfo;
var invalidAncestor = invalidParent ? null : findInvalidAncestorForTag(childTag, ancestorInfo);
var invalidParentOrAncestor = invalidParent || invalidAncestor;
if (!invalidParentOrAncestor) {
return;
}
var ancestorTag = invalidParentOrAncestor.tag;
var warnKey = !!invalidParent + "|" + childTag + "|" + ancestorTag;
if (didWarn$1[warnKey]) {
return;
}
didWarn$1[warnKey] = true;
var tagDisplayName = childTag;
var whitespaceInfo = "";
if (childTag === "#text") {
if (/\S/.test(childText)) {
tagDisplayName = "Text nodes";
} else {
tagDisplayName = "Whitespace text nodes";
whitespaceInfo = " Make sure you don't have any extra whitespace between tags on each line of your source code.";
}
} else {
tagDisplayName = "<" + childTag + ">";
}
if (invalidParent) {
var info = "";
if (ancestorTag === "table" && childTag === "tr") {
info += " Add a <tbody>, <thead> or <tfoot> to your code to match the DOM tree generated by the browser.";
}
error("validateDOMNesting(...): %s cannot appear as a child of <%s>.%s%s", tagDisplayName, ancestorTag, whitespaceInfo, info);
} else {
error("validateDOMNesting(...): %s cannot appear as a descendant of <%s>.", tagDisplayName, ancestorTag);
}
};
}
var SUPPRESS_HYDRATION_WARNING$1;
{
SUPPRESS_HYDRATION_WARNING$1 = "suppressHydrationWarning";
}
var SUSPENSE_START_DATA = "$";
var SUSPENSE_END_DATA = "/$";
var SUSPENSE_PENDING_START_DATA = "$?";
var SUSPENSE_FALLBACK_START_DATA = "$!";
var STYLE$1 = "style";
var eventsEnabled = null;
var selectionInformation = null;
function shouldAutoFocusHostComponent(type, props) {
switch (type) {
case "button":
case "input":
case "select":
case "textarea":
return !!props.autoFocus;
}
return false;
}
function getRootHostContext(rootContainerInstance) {
var type;
var namespace;
var nodeType = rootContainerInstance.nodeType;
switch (nodeType) {
case DOCUMENT_NODE:
case DOCUMENT_FRAGMENT_NODE: {
type = nodeType === DOCUMENT_NODE ? "#document" : "#fragment";
var root2 = rootContainerInstance.documentElement;
namespace = root2 ? root2.namespaceURI : getChildNamespace(null, "");
break;
}
default: {
var container = nodeType === COMMENT_NODE ? rootContainerInstance.parentNode : rootContainerInstance;
var ownNamespace = container.namespaceURI || null;
type = container.tagName;
namespace = getChildNamespace(ownNamespace, type);
break;
}
}
{
var validatedTag = type.toLowerCase();
var ancestorInfo = updatedAncestorInfo(null, validatedTag);
return {
namespace,
ancestorInfo
};
}
}
function getChildHostContext(parentHostContext, type, rootContainerInstance) {
{
var parentHostContextDev = parentHostContext;
var namespace = getChildNamespace(parentHostContextDev.namespace, type);
var ancestorInfo = updatedAncestorInfo(parentHostContextDev.ancestorInfo, type);
return {
namespace,
ancestorInfo
};
}
}
function getPublicInstance(instance) {
return instance;
}
function prepareForCommit(containerInfo) {
eventsEnabled = isEnabled();
selectionInformation = getSelectionInformation();
var activeInstance = null;
setEnabled(false);
return activeInstance;
}
function resetAfterCommit(containerInfo) {
restoreSelection(selectionInformation);
setEnabled(eventsEnabled);
eventsEnabled = null;
selectionInformation = null;
}
function createInstance(type, props, rootContainerInstance, hostContext, internalInstanceHandle) {
var parentNamespace;
{
var hostContextDev = hostContext;
validateDOMNesting(type, null, hostContextDev.ancestorInfo);
if (typeof props.children === "string" || typeof props.children === "number") {
var string = "" + props.children;
var ownAncestorInfo = updatedAncestorInfo(hostContextDev.ancestorInfo, type);
validateDOMNesting(null, string, ownAncestorInfo);
}
parentNamespace = hostContextDev.namespace;
}
var domElement = createElement(type, props, rootContainerInstance, parentNamespace);
precacheFiberNode(internalInstanceHandle, domElement);
updateFiberProps(domElement, props);
return domElement;
}
function appendInitialChild(parentInstance, child) {
parentInstance.appendChild(child);
}
function finalizeInitialChildren(domElement, type, props, rootContainerInstance, hostContext) {
setInitialProperties(domElement, type, props, rootContainerInstance);
return shouldAutoFocusHostComponent(type, props);
}
function prepareUpdate(domElement, type, oldProps, newProps, rootContainerInstance, hostContext) {
{
var hostContextDev = hostContext;
if (typeof newProps.children !== typeof oldProps.children && (typeof newProps.children === "string" || typeof newProps.children === "number")) {
var string = "" + newProps.children;
var ownAncestorInfo = updatedAncestorInfo(hostContextDev.ancestorInfo, type);
validateDOMNesting(null, string, ownAncestorInfo);
}
}
return diffProperties(domElement, type, oldProps, newProps);
}
function shouldSetTextContent(type, props) {
return type === "textarea" || type === "option" || type === "noscript" || typeof props.children === "string" || typeof props.children === "number" || typeof props.dangerouslySetInnerHTML === "object" && props.dangerouslySetInnerHTML !== null && props.dangerouslySetInnerHTML.__html != null;
}
function createTextInstance(text, rootContainerInstance, hostContext, internalInstanceHandle) {
{
var hostContextDev = hostContext;
validateDOMNesting(null, text, hostContextDev.ancestorInfo);
}
var textNode = createTextNode(text, rootContainerInstance);
precacheFiberNode(internalInstanceHandle, textNode);
return textNode;
}
var scheduleTimeout = typeof setTimeout === "function" ? setTimeout : void 0;
var cancelTimeout = typeof clearTimeout === "function" ? clearTimeout : void 0;
var noTimeout = -1;
function commitMount(domElement, type, newProps, internalInstanceHandle) {
if (shouldAutoFocusHostComponent(type, newProps)) {
domElement.focus();
}
}
function commitUpdate(domElement, updatePayload, type, oldProps, newProps, internalInstanceHandle) {
updateFiberProps(domElement, newProps);
updateProperties(domElement, updatePayload, type, oldProps, newProps);
}
function resetTextContent(domElement) {
setTextContent(domElement, "");
}
function commitTextUpdate(textInstance, oldText, newText) {
textInstance.nodeValue = newText;
}
function appendChild(parentInstance, child) {
parentInstance.appendChild(child);
}
function appendChildToContainer(container, child) {
var parentNode;
if (container.nodeType === COMMENT_NODE) {
parentNode = container.parentNode;
parentNode.insertBefore(child, container);
} else {
parentNode = container;
parentNode.appendChild(child);
}
var reactRootContainer = container._reactRootContainer;
if ((reactRootContainer === null || reactRootContainer === void 0) && parentNode.onclick === null) {
trapClickOnNonInteractiveElement(parentNode);
}
}
function insertBefore(parentInstance, child, beforeChild) {
parentInstance.insertBefore(child, beforeChild);
}
function insertInContainerBefore(container, child, beforeChild) {
if (container.nodeType === COMMENT_NODE) {
container.parentNode.insertBefore(child, beforeChild);
} else {
container.insertBefore(child, beforeChild);
}
}
function removeChild(parentInstance, child) {
parentInstance.removeChild(child);
}
function removeChildFromContainer(container, child) {
if (container.nodeType === COMMENT_NODE) {
container.parentNode.removeChild(child);
} else {
container.removeChild(child);
}
}
function hideInstance(instance) {
instance = instance;
var style2 = instance.style;
if (typeof style2.setProperty === "function") {
style2.setProperty("display", "none", "important");
} else {
style2.display = "none";
}
}
function hideTextInstance(textInstance) {
textInstance.nodeValue = "";
}
function unhideInstance(instance, props) {
instance = instance;
var styleProp = props[STYLE$1];
var display = styleProp !== void 0 && styleProp !== null && styleProp.hasOwnProperty("display") ? styleProp.display : null;
instance.style.display = dangerousStyleValue("display", display);
}
function unhideTextInstance(textInstance, text) {
textInstance.nodeValue = text;
}
function clearContainer(container) {
if (container.nodeType === ELEMENT_NODE) {
container.textContent = "";
} else if (container.nodeType === DOCUMENT_NODE) {
var body = container.body;
if (body != null) {
body.textContent = "";
}
}
}
function canHydrateInstance(instance, type, props) {
if (instance.nodeType !== ELEMENT_NODE || type.toLowerCase() !== instance.nodeName.toLowerCase()) {
return null;
}
return instance;
}
function canHydrateTextInstance(instance, text) {
if (text === "" || instance.nodeType !== TEXT_NODE) {
return null;
}
return instance;
}
function isSuspenseInstancePending(instance) {
return instance.data === SUSPENSE_PENDING_START_DATA;
}
function isSuspenseInstanceFallback(instance) {
return instance.data === SUSPENSE_FALLBACK_START_DATA;
}
function getNextHydratable(node) {
for (; node != null; node = node.nextSibling) {
var nodeType = node.nodeType;
if (nodeType === ELEMENT_NODE || nodeType === TEXT_NODE) {
break;
}
}
return node;
}
function getNextHydratableSibling(instance) {
return getNextHydratable(instance.nextSibling);
}
function getFirstHydratableChild(parentInstance) {
return getNextHydratable(parentInstance.firstChild);
}
function hydrateInstance(instance, type, props, rootContainerInstance, hostContext, internalInstanceHandle) {
precacheFiberNode(internalInstanceHandle, instance);
updateFiberProps(instance, props);
var parentNamespace;
{
var hostContextDev = hostContext;
parentNamespace = hostContextDev.namespace;
}
return diffHydratedProperties(instance, type, props, parentNamespace);
}
function hydrateTextInstance(textInstance, text, internalInstanceHandle) {
precacheFiberNode(internalInstanceHandle, textInstance);
return diffHydratedText(textInstance, text);
}
function getNextHydratableInstanceAfterSuspenseInstance(suspenseInstance) {
var node = suspenseInstance.nextSibling;
var depth = 0;
while (node) {
if (node.nodeType === COMMENT_NODE) {
var data = node.data;
if (data === SUSPENSE_END_DATA) {
if (depth === 0) {
return getNextHydratableSibling(node);
} else {
depth--;
}
} else if (data === SUSPENSE_START_DATA || data === SUSPENSE_FALLBACK_START_DATA || data === SUSPENSE_PENDING_START_DATA) {
depth++;
}
}
node = node.nextSibling;
}
return null;
}
function getParentSuspenseInstance(targetInstance) {
var node = targetInstance.previousSibling;
var depth = 0;
while (node) {
if (node.nodeType === COMMENT_NODE) {
var data = node.data;
if (data === SUSPENSE_START_DATA || data === SUSPENSE_FALLBACK_START_DATA || data === SUSPENSE_PENDING_START_DATA) {
if (depth === 0) {
return node;
} else {
depth--;
}
} else if (data === SUSPENSE_END_DATA) {
depth++;
}
}
node = node.previousSibling;
}
return null;
}
function commitHydratedContainer(container) {
retryIfBlockedOn(container);
}
function commitHydratedSuspenseInstance(suspenseInstance) {
retryIfBlockedOn(suspenseInstance);
}
function didNotMatchHydratedContainerTextInstance(parentContainer, textInstance, text) {
{
warnForUnmatchedText(textInstance, text);
}
}
function didNotMatchHydratedTextInstance(parentType, parentProps, parentInstance, textInstance, text) {
if (parentProps[SUPPRESS_HYDRATION_WARNING$1] !== true) {
warnForUnmatchedText(textInstance, text);
}
}
function didNotHydrateContainerInstance(parentContainer, instance) {
{
if (instance.nodeType === ELEMENT_NODE) {
warnForDeletedHydratableElement(parentContainer, instance);
} else if (instance.nodeType === COMMENT_NODE)
;
else {
warnForDeletedHydratableText(parentContainer, instance);
}
}
}
function didNotHydrateInstance(parentType, parentProps, parentInstance, instance) {
if (parentProps[SUPPRESS_HYDRATION_WARNING$1] !== true) {
if (instance.nodeType === ELEMENT_NODE) {
warnForDeletedHydratableElement(parentInstance, instance);
} else if (instance.nodeType === COMMENT_NODE)
;
else {
warnForDeletedHydratableText(parentInstance, instance);
}
}
}
function didNotFindHydratableContainerInstance(parentContainer, type, props) {
{
warnForInsertedHydratedElement(parentContainer, type);
}
}
function didNotFindHydratableContainerTextInstance(parentContainer, text) {
{
warnForInsertedHydratedText(parentContainer, text);
}
}
function didNotFindHydratableInstance(parentType, parentProps, parentInstance, type, props) {
if (parentProps[SUPPRESS_HYDRATION_WARNING$1] !== true) {
warnForInsertedHydratedElement(parentInstance, type);
}
}
function didNotFindHydratableTextInstance(parentType, parentProps, parentInstance, text) {
if (parentProps[SUPPRESS_HYDRATION_WARNING$1] !== true) {
warnForInsertedHydratedText(parentInstance, text);
}
}
function didNotFindHydratableSuspenseInstance(parentType, parentProps, parentInstance) {
if (parentProps[SUPPRESS_HYDRATION_WARNING$1] !== true)
;
}
var clientId = 0;
function makeClientIdInDEV(warnOnAccessInDEV) {
var id = "r:" + (clientId++).toString(36);
return {
toString: function() {
warnOnAccessInDEV();
return id;
},
valueOf: function() {
warnOnAccessInDEV();
return id;
}
};
}
function isOpaqueHydratingObject(value) {
return value !== null && typeof value === "object" && value.$$typeof === REACT_OPAQUE_ID_TYPE;
}
function makeOpaqueHydratingObject(attemptToReadValue) {
return {
$$typeof: REACT_OPAQUE_ID_TYPE,
toString: attemptToReadValue,
valueOf: attemptToReadValue
};
}
function preparePortalMount(portalInstance) {
{
listenToAllSupportedEvents(portalInstance);
}
}
var randomKey = Math.random().toString(36).slice(2);
var internalInstanceKey = "__reactFiber$" + randomKey;
var internalPropsKey = "__reactProps$" + randomKey;
var internalContainerInstanceKey = "__reactContainer$" + randomKey;
var internalEventHandlersKey = "__reactEvents$" + randomKey;
function precacheFiberNode(hostInst, node) {
node[internalInstanceKey] = hostInst;
}
function markContainerAsRoot(hostRoot, node) {
node[internalContainerInstanceKey] = hostRoot;
}
function unmarkContainerAsRoot(node) {
node[internalContainerInstanceKey] = null;
}
function isContainerMarkedAsRoot(node) {
return !!node[internalContainerInstanceKey];
}
function getClosestInstanceFromNode(targetNode) {
var targetInst = targetNode[internalInstanceKey];
if (targetInst) {
return targetInst;
}
var parentNode = targetNode.parentNode;
while (parentNode) {
targetInst = parentNode[internalContainerInstanceKey] || parentNode[internalInstanceKey];
if (targetInst) {
var alternate = targetInst.alternate;
if (targetInst.child !== null || alternate !== null && alternate.child !== null) {
var suspenseInstance = getParentSuspenseInstance(targetNode);
while (suspenseInstance !== null) {
var targetSuspenseInst = suspenseInstance[internalInstanceKey];
if (targetSuspenseInst) {
return targetSuspenseInst;
}
suspenseInstance = getParentSuspenseInstance(suspenseInstance);
}
}
return targetInst;
}
targetNode = parentNode;
parentNode = targetNode.parentNode;
}
return null;
}
function getInstanceFromNode(node) {
var inst = node[internalInstanceKey] || node[internalContainerInstanceKey];
if (inst) {
if (inst.tag === HostComponent || inst.tag === HostText || inst.tag === SuspenseComponent || inst.tag === HostRoot) {
return inst;
} else {
return null;
}
}
return null;
}
function getNodeFromInstance(inst) {
if (inst.tag === HostComponent || inst.tag === HostText) {
return inst.stateNode;
}
{
{
throw Error("getNodeFromInstance: Invalid argument.");
}
}
}
function getFiberCurrentPropsFromNode(node) {
return node[internalPropsKey] || null;
}
function updateFiberProps(node, props) {
node[internalPropsKey] = props;
}
function getEventListenerSet(node) {
var elementListenerSet = node[internalEventHandlersKey];
if (elementListenerSet === void 0) {
elementListenerSet = node[internalEventHandlersKey] = new Set();
}
return elementListenerSet;
}
var loggedTypeFailures = {};
var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame;
function setCurrentlyValidatingElement(element) {
{
if (element) {
var owner = element._owner;
var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
ReactDebugCurrentFrame$1.setExtraStackFrame(stack);
} else {
ReactDebugCurrentFrame$1.setExtraStackFrame(null);
}
}
}
function checkPropTypes(typeSpecs, values, location, componentName, element) {
{
var has2 = Function.call.bind(Object.prototype.hasOwnProperty);
for (var typeSpecName in typeSpecs) {
if (has2(typeSpecs, typeSpecName)) {
var error$1 = void 0;
try {
if (typeof typeSpecs[typeSpecName] !== "function") {
var err = Error((componentName || "React class") + ": " + location + " type `" + typeSpecName + "` is invalid; it must be a function, usually from the `prop-types` package, but received `" + typeof typeSpecs[typeSpecName] + "`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");
err.name = "Invariant Violation";
throw err;
}
error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, "SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED");
} catch (ex) {
error$1 = ex;
}
if (error$1 && !(error$1 instanceof Error)) {
setCurrentlyValidatingElement(element);
error("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).", componentName || "React class", location, typeSpecName, typeof error$1);
setCurrentlyValidatingElement(null);
}
if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) {
loggedTypeFailures[error$1.message] = true;
setCurrentlyValidatingElement(element);
error("Failed %s type: %s", location, error$1.message);
setCurrentlyValidatingElement(null);
}
}
}
}
}
var valueStack = [];
var fiberStack;
{
fiberStack = [];
}
var index = -1;
function createCursor(defaultValue) {
return {
current: defaultValue
};
}
function pop(cursor, fiber) {
if (index < 0) {
{
error("Unexpected pop.");
}
return;
}
{
if (fiber !== fiberStack[index]) {
error("Unexpected Fiber popped.");
}
}
cursor.current = valueStack[index];
valueStack[index] = null;
{
fiberStack[index] = null;
}
index--;
}
function push(cursor, value, fiber) {
index++;
valueStack[index] = cursor.current;
{
fiberStack[index] = fiber;
}
cursor.current = value;
}
var warnedAboutMissingGetChildContext;
{
warnedAboutMissingGetChildContext = {};
}
var emptyContextObject = {};
{
Object.freeze(emptyContextObject);
}
var contextStackCursor = createCursor(emptyContextObject);
var didPerformWorkStackCursor = createCursor(false);
var previousContext = emptyContextObject;
function getUnmaskedContext(workInProgress2, Component, didPushOwnContextIfProvider) {
{
if (didPushOwnContextIfProvider && isContextProvider(Component)) {
return previousContext;
}
return contextStackCursor.current;
}
}
function cacheContext(workInProgress2, unmaskedContext, maskedContext) {
{
var instance = workInProgress2.stateNode;
instance.__reactInternalMemoizedUnmaskedChildContext = unmaskedContext;
instance.__reactInternalMemoizedMaskedChildContext = maskedContext;
}
}
function getMaskedContext(workInProgress2, unmaskedContext) {
{
var type = workInProgress2.type;
var contextTypes = type.contextTypes;
if (!contextTypes) {
return emptyContextObject;
}
var instance = workInProgress2.stateNode;
if (instance && instance.__reactInternalMemoizedUnmaskedChildContext === unmaskedContext) {
return instance.__reactInternalMemoizedMaskedChildContext;
}
var context = {};
for (var key in contextTypes) {
context[key] = unmaskedContext[key];
}
{
var name = getComponentName(type) || "Unknown";
checkPropTypes(contextTypes, context, "context", name);
}
if (instance) {
cacheContext(workInProgress2, unmaskedContext, context);
}
return context;
}
}
function hasContextChanged() {
{
return didPerformWorkStackCursor.current;
}
}
function isContextProvider(type) {
{
var childContextTypes = type.childContextTypes;
return childContextTypes !== null && childContextTypes !== void 0;
}
}
function popContext(fiber) {
{
pop(didPerformWorkStackCursor, fiber);
pop(contextStackCursor, fiber);
}
}
function popTopLevelContextObject(fiber) {
{
pop(didPerformWorkStackCursor, fiber);
pop(contextStackCursor, fiber);
}
}
function pushTopLevelContextObject(fiber, context, didChange) {
{
if (!(contextStackCursor.current === emptyContextObject)) {
{
throw Error("Unexpected context found on stack. This error is likely caused by a bug in React. Please file an issue.");
}
}
push(contextStackCursor, context, fiber);
push(didPerformWorkStackCursor, didChange, fiber);
}
}
function processChildContext(fiber, type, parentContext) {
{
var instance = fiber.stateNode;
var childContextTypes = type.childContextTypes;
if (typeof instance.getChildContext !== "function") {
{
var componentName = getComponentName(type) || "Unknown";
if (!warnedAboutMissingGetChildContext[componentName]) {
warnedAboutMissingGetChildContext[componentName] = true;
error("%s.childContextTypes is specified but there is no getChildContext() method on the instance. You can either define getChildContext() on %s or remove childContextTypes from it.", componentName, componentName);
}
}
return parentContext;
}
var childContext = instance.getChildContext();
for (var contextKey in childContext) {
if (!(contextKey in childContextTypes)) {
{
throw Error((getComponentName(type) || "Unknown") + '.getChildContext(): key "' + contextKey + '" is not defined in childContextTypes.');
}
}
}
{
var name = getComponentName(type) || "Unknown";
checkPropTypes(childContextTypes, childContext, "child context", name);
}
return _assign({}, parentContext, childContext);
}
}
function pushContextProvider(workInProgress2) {
{
var instance = workInProgress2.stateNode;
var memoizedMergedChildContext = instance && instance.__reactInternalMemoizedMergedChildContext || emptyContextObject;
previousContext = contextStackCursor.current;
push(contextStackCursor, memoizedMergedChildContext, workInProgress2);
push(didPerformWorkStackCursor, didPerformWorkStackCursor.current, workInProgress2);
return true;
}
}
function invalidateContextProvider(workInProgress2, type, didChange) {
{
var instance = workInProgress2.stateNode;
if (!instance) {
{
throw Error("Expected to have an instance by this point. This error is likely caused by a bug in React. Please file an issue.");
}
}
if (didChange) {
var mergedContext = processChildContext(workInProgress2, type, previousContext);
instance.__reactInternalMemoizedMergedChildContext = mergedContext;
pop(didPerformWorkStackCursor, workInProgress2);
pop(contextStackCursor, workInProgress2);
push(contextStackCursor, mergedContext, workInProgress2);
push(didPerformWorkStackCursor, didChange, workInProgress2);
} else {
pop(didPerformWorkStackCursor, workInProgress2);
push(didPerformWorkStackCursor, didChange, workInProgress2);
}
}
}
function findCurrentUnmaskedContext(fiber) {
{
if (!(isFiberMounted(fiber) && fiber.tag === ClassComponent)) {
{
throw Error("Expected subtree parent to be a mounted class component. This error is likely caused by a bug in React. Please file an issue.");
}
}
var node = fiber;
do {
switch (node.tag) {
case HostRoot:
return node.stateNode.context;
case ClassComponent: {
var Component = node.type;
if (isContextProvider(Component)) {
return node.stateNode.__reactInternalMemoizedMergedChildContext;
}
break;
}
}
node = node.return;
} while (node !== null);
{
{
throw Error("Found unexpected detached subtree parent. This error is likely caused by a bug in React. Please file an issue.");
}
}
}
}
var LegacyRoot = 0;
var BlockingRoot = 1;
var ConcurrentRoot = 2;
var rendererID = null;
var injectedHook = null;
var hasLoggedError = false;
var isDevToolsPresent = typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined";
function injectInternals(internals) {
if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === "undefined") {
return false;
}
var hook = __REACT_DEVTOOLS_GLOBAL_HOOK__;
if (hook.isDisabled) {
return true;
}
if (!hook.supportsFiber) {
{
error("The installed version of React DevTools is too old and will not work with the current version of React. Please update React DevTools. https://reactjs.org/link/react-devtools");
}
return true;
}
try {
rendererID = hook.inject(internals);
injectedHook = hook;
} catch (err) {
{
error("React instrumentation encountered an error: %s.", err);
}
}
return true;
}
function onScheduleRoot(root2, children) {
{
if (injectedHook && typeof injectedHook.onScheduleFiberRoot === "function") {
try {
injectedHook.onScheduleFiberRoot(rendererID, root2, children);
} catch (err) {
if (!hasLoggedError) {
hasLoggedError = true;
error("React instrumentation encountered an error: %s", err);
}
}
}
}
}
function onCommitRoot(root2, priorityLevel) {
if (injectedHook && typeof injectedHook.onCommitFiberRoot === "function") {
try {
var didError = (root2.current.flags & DidCapture) === DidCapture;
if (enableProfilerTimer) {
injectedHook.onCommitFiberRoot(rendererID, root2, priorityLevel, didError);
} else {
injectedHook.onCommitFiberRoot(rendererID, root2, void 0, didError);
}
} catch (err) {
{
if (!hasLoggedError) {
hasLoggedError = true;
error("React instrumentation encountered an error: %s", err);
}
}
}
}
}
function onCommitUnmount(fiber) {
if (injectedHook && typeof injectedHook.onCommitFiberUnmount === "function") {
try {
injectedHook.onCommitFiberUnmount(rendererID, fiber);
} catch (err) {
{
if (!hasLoggedError) {
hasLoggedError = true;
error("React instrumentation encountered an error: %s", err);
}
}
}
}
}
var Scheduler_runWithPriority = Scheduler.unstable_runWithPriority, Scheduler_scheduleCallback = Scheduler.unstable_scheduleCallback, Scheduler_cancelCallback = Scheduler.unstable_cancelCallback, Scheduler_shouldYield = Scheduler.unstable_shouldYield, Scheduler_requestPaint = Scheduler.unstable_requestPaint, Scheduler_now$1 = Scheduler.unstable_now, Scheduler_getCurrentPriorityLevel = Scheduler.unstable_getCurrentPriorityLevel, Scheduler_ImmediatePriority = Scheduler.unstable_ImmediatePriority, Scheduler_UserBlockingPriority = Scheduler.unstable_UserBlockingPriority, Scheduler_NormalPriority = Scheduler.unstable_NormalPriority, Scheduler_LowPriority = Scheduler.unstable_LowPriority, Scheduler_IdlePriority = Scheduler.unstable_IdlePriority;
{
if (!(tracing.__interactionsRef != null && tracing.__interactionsRef.current != null)) {
{
throw Error("It is not supported to run the profiling version of a renderer (for example, `react-dom/profiling`) without also replacing the `scheduler/tracing` module with `scheduler/tracing-profiling`. Your bundler might have a setting for aliasing both modules. Learn more at https://reactjs.org/link/profiling");
}
}
}
var fakeCallbackNode = {};
var ImmediatePriority$1 = 99;
var UserBlockingPriority$2 = 98;
var NormalPriority$1 = 97;
var LowPriority$1 = 96;
var IdlePriority$1 = 95;
var NoPriority$1 = 90;
var shouldYield = Scheduler_shouldYield;
var requestPaint = Scheduler_requestPaint !== void 0 ? Scheduler_requestPaint : function() {
};
var syncQueue = null;
var immediateQueueCallbackNode = null;
var isFlushingSyncQueue = false;
var initialTimeMs$1 = Scheduler_now$1();
var now = initialTimeMs$1 < 1e4 ? Scheduler_now$1 : function() {
return Scheduler_now$1() - initialTimeMs$1;
};
function getCurrentPriorityLevel() {
switch (Scheduler_getCurrentPriorityLevel()) {
case Scheduler_ImmediatePriority:
return ImmediatePriority$1;
case Scheduler_UserBlockingPriority:
return UserBlockingPriority$2;
case Scheduler_NormalPriority:
return NormalPriority$1;
case Scheduler_LowPriority:
return LowPriority$1;
case Scheduler_IdlePriority:
return IdlePriority$1;
default: {
{
throw Error("Unknown priority level.");
}
}
}
}
function reactPriorityToSchedulerPriority(reactPriorityLevel) {
switch (reactPriorityLevel) {
case ImmediatePriority$1:
return Scheduler_ImmediatePriority;
case UserBlockingPriority$2:
return Scheduler_UserBlockingPriority;
case NormalPriority$1:
return Scheduler_NormalPriority;
case LowPriority$1:
return Scheduler_LowPriority;
case IdlePriority$1:
return Scheduler_IdlePriority;
default: {
{
throw Error("Unknown priority level.");
}
}
}
}
function runWithPriority$1(reactPriorityLevel, fn) {
var priorityLevel = reactPriorityToSchedulerPriority(reactPriorityLevel);
return Scheduler_runWithPriority(priorityLevel, fn);
}
function scheduleCallback(reactPriorityLevel, callback, options2) {
var priorityLevel = reactPriorityToSchedulerPriority(reactPriorityLevel);
return Scheduler_scheduleCallback(priorityLevel, callback, options2);
}
function scheduleSyncCallback(callback) {
if (syncQueue === null) {
syncQueue = [callback];
immediateQueueCallbackNode = Scheduler_scheduleCallback(Scheduler_ImmediatePriority, flushSyncCallbackQueueImpl);
} else {
syncQueue.push(callback);
}
return fakeCallbackNode;
}
function cancelCallback(callbackNode) {
if (callbackNode !== fakeCallbackNode) {
Scheduler_cancelCallback(callbackNode);
}
}
function flushSyncCallbackQueue() {
if (immediateQueueCallbackNode !== null) {
var node = immediateQueueCallbackNode;
immediateQueueCallbackNode = null;
Scheduler_cancelCallback(node);
}
flushSyncCallbackQueueImpl();
}
function flushSyncCallbackQueueImpl() {
if (!isFlushingSyncQueue && syncQueue !== null) {
isFlushingSyncQueue = true;
var i = 0;
{
try {
var _isSync2 = true;
var _queue = syncQueue;
runWithPriority$1(ImmediatePriority$1, function() {
for (; i < _queue.length; i++) {
var callback = _queue[i];
do {
callback = callback(_isSync2);
} while (callback !== null);
}
});
syncQueue = null;
} catch (error2) {
if (syncQueue !== null) {
syncQueue = syncQueue.slice(i + 1);
}
Scheduler_scheduleCallback(Scheduler_ImmediatePriority, flushSyncCallbackQueue);
throw error2;
} finally {
isFlushingSyncQueue = false;
}
}
}
}
var ReactVersion = "17.0.2";
var NoMode = 0;
var StrictMode = 1;
var BlockingMode = 2;
var ConcurrentMode = 4;
var ProfileMode = 8;
var DebugTracingMode = 16;
var ReactCurrentBatchConfig = ReactSharedInternals.ReactCurrentBatchConfig;
var NoTransition = 0;
function requestCurrentTransition() {
return ReactCurrentBatchConfig.transition;
}
var ReactStrictModeWarnings = {
recordUnsafeLifecycleWarnings: function(fiber, instance) {
},
flushPendingUnsafeLifecycleWarnings: function() {
},
recordLegacyContextWarning: function(fiber, instance) {
},
flushLegacyContextWarning: function() {
},
discardPendingWarnings: function() {
}
};
{
var findStrictRoot = function(fiber) {
var maybeStrictRoot = null;
var node = fiber;
while (node !== null) {
if (node.mode & StrictMode) {
maybeStrictRoot = node;
}
node = node.return;
}
return maybeStrictRoot;
};
var setToSortedString = function(set2) {
var array = [];
set2.forEach(function(value) {
array.push(value);
});
return array.sort().join(", ");
};
var pendingComponentWillMountWarnings = [];
var pendingUNSAFE_ComponentWillMountWarnings = [];
var pendingComponentWillReceivePropsWarnings = [];
var pendingUNSAFE_ComponentWillReceivePropsWarnings = [];
var pendingComponentWillUpdateWarnings = [];
var pendingUNSAFE_ComponentWillUpdateWarnings = [];
var didWarnAboutUnsafeLifecycles = new Set();
ReactStrictModeWarnings.recordUnsafeLifecycleWarnings = function(fiber, instance) {
if (didWarnAboutUnsafeLifecycles.has(fiber.type)) {
return;
}
if (typeof instance.componentWillMount === "function" && instance.componentWillMount.__suppressDeprecationWarning !== true) {
pendingComponentWillMountWarnings.push(fiber);
}
if (fiber.mode & StrictMode && typeof instance.UNSAFE_componentWillMount === "function") {
pendingUNSAFE_ComponentWillMountWarnings.push(fiber);
}
if (typeof instance.componentWillReceiveProps === "function" && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) {
pendingComponentWillReceivePropsWarnings.push(fiber);
}
if (fiber.mode & StrictMode && typeof instance.UNSAFE_componentWillReceiveProps === "function") {
pendingUNSAFE_ComponentWillReceivePropsWarnings.push(fiber);
}
if (typeof instance.componentWillUpdate === "function" && instance.componentWillUpdate.__suppressDeprecationWarning !== true) {
pendingComponentWillUpdateWarnings.push(fiber);
}
if (fiber.mode & StrictMode && typeof instance.UNSAFE_componentWillUpdate === "function") {
pendingUNSAFE_ComponentWillUpdateWarnings.push(fiber);
}
};
ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings = function() {
var componentWillMountUniqueNames = new Set();
if (pendingComponentWillMountWarnings.length > 0) {
pendingComponentWillMountWarnings.forEach(function(fiber) {
componentWillMountUniqueNames.add(getComponentName(fiber.type) || "Component");
didWarnAboutUnsafeLifecycles.add(fiber.type);
});
pendingComponentWillMountWarnings = [];
}
var UNSAFE_componentWillMountUniqueNames = new Set();
if (pendingUNSAFE_ComponentWillMountWarnings.length > 0) {
pendingUNSAFE_ComponentWillMountWarnings.forEach(function(fiber) {
UNSAFE_componentWillMountUniqueNames.add(getComponentName(fiber.type) || "Component");
didWarnAboutUnsafeLifecycles.add(fiber.type);
});
pendingUNSAFE_ComponentWillMountWarnings = [];
}
var componentWillReceivePropsUniqueNames = new Set();
if (pendingComponentWillReceivePropsWarnings.length > 0) {
pendingComponentWillReceivePropsWarnings.forEach(function(fiber) {
componentWillReceivePropsUniqueNames.add(getComponentName(fiber.type) || "Component");
didWarnAboutUnsafeLifecycles.add(fiber.type);
});
pendingComponentWillReceivePropsWarnings = [];
}
var UNSAFE_componentWillReceivePropsUniqueNames = new Set();
if (pendingUNSAFE_ComponentWillReceivePropsWarnings.length > 0) {
pendingUNSAFE_ComponentWillReceivePropsWarnings.forEach(function(fiber) {
UNSAFE_componentWillReceivePropsUniqueNames.add(getComponentName(fiber.type) || "Component");
didWarnAboutUnsafeLifecycles.add(fiber.type);
});
pendingUNSAFE_ComponentWillReceivePropsWarnings = [];
}
var componentWillUpdateUniqueNames = new Set();
if (pendingComponentWillUpdateWarnings.length > 0) {
pendingComponentWillUpdateWarnings.forEach(function(fiber) {
componentWillUpdateUniqueNames.add(getComponentName(fiber.type) || "Component");
didWarnAboutUnsafeLifecycles.add(fiber.type);
});
pendingComponentWillUpdateWarnings = [];
}
var UNSAFE_componentWillUpdateUniqueNames = new Set();
if (pendingUNSAFE_ComponentWillUpdateWarnings.length > 0) {
pendingUNSAFE_ComponentWillUpdateWarnings.forEach(function(fiber) {
UNSAFE_componentWillUpdateUniqueNames.add(getComponentName(fiber.type) || "Component");
didWarnAboutUnsafeLifecycles.add(fiber.type);
});
pendingUNSAFE_ComponentWillUpdateWarnings = [];
}
if (UNSAFE_componentWillMountUniqueNames.size > 0) {
var sortedNames = setToSortedString(UNSAFE_componentWillMountUniqueNames);
error("Using UNSAFE_componentWillMount in strict mode is not recommended and may indicate bugs in your code. See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n* Move code with side effects to componentDidMount, and set initial state in the constructor.\n\nPlease update the following components: %s", sortedNames);
}
if (UNSAFE_componentWillReceivePropsUniqueNames.size > 0) {
var _sortedNames = setToSortedString(UNSAFE_componentWillReceivePropsUniqueNames);
error("Using UNSAFE_componentWillReceiveProps in strict mode is not recommended and may indicate bugs in your code. See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n* Move data fetching code or side effects to componentDidUpdate.\n* If you're updating state whenever props change, refactor your code to use memoization techniques or move it to static getDerivedStateFromProps. Learn more at: https://reactjs.org/link/derived-state\n\nPlease update the following components: %s", _sortedNames);
}
if (UNSAFE_componentWillUpdateUniqueNames.size > 0) {
var _sortedNames2 = setToSortedString(UNSAFE_componentWillUpdateUniqueNames);
error("Using UNSAFE_componentWillUpdate in strict mode is not recommended and may indicate bugs in your code. See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n* Move data fetching code or side effects to componentDidUpdate.\n\nPlease update the following components: %s", _sortedNames2);
}
if (componentWillMountUniqueNames.size > 0) {
var _sortedNames3 = setToSortedString(componentWillMountUniqueNames);
warn("componentWillMount has been renamed, and is not recommended for use. See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n* Move code with side effects to componentDidMount, and set initial state in the constructor.\n* Rename componentWillMount to UNSAFE_componentWillMount to suppress this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. To rename all deprecated lifecycles to their new names, you can run `npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n\nPlease update the following components: %s", _sortedNames3);
}
if (componentWillReceivePropsUniqueNames.size > 0) {
var _sortedNames4 = setToSortedString(componentWillReceivePropsUniqueNames);
warn("componentWillReceiveProps has been renamed, and is not recommended for use. See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n* Move data fetching code or side effects to componentDidUpdate.\n* If you're updating state whenever props change, refactor your code to use memoization techniques or move it to static getDerivedStateFromProps. Learn more at: https://reactjs.org/link/derived-state\n* Rename componentWillReceiveProps to UNSAFE_componentWillReceiveProps to suppress this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. To rename all deprecated lifecycles to their new names, you can run `npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n\nPlease update the following components: %s", _sortedNames4);
}
if (componentWillUpdateUniqueNames.size > 0) {
var _sortedNames5 = setToSortedString(componentWillUpdateUniqueNames);
warn("componentWillUpdate has been renamed, and is not recommended for use. See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n* Move data fetching code or side effects to componentDidUpdate.\n* Rename componentWillUpdate to UNSAFE_componentWillUpdate to suppress this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. To rename all deprecated lifecycles to their new names, you can run `npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n\nPlease update the following components: %s", _sortedNames5);
}
};
var pendingLegacyContextWarning = new Map();
var didWarnAboutLegacyContext = new Set();
ReactStrictModeWarnings.recordLegacyContextWarning = function(fiber, instance) {
var strictRoot = findStrictRoot(fiber);
if (strictRoot === null) {
error("Expected to find a StrictMode component in a strict mode tree. This error is likely caused by a bug in React. Please file an issue.");
return;
}
if (didWarnAboutLegacyContext.has(fiber.type)) {
return;
}
var warningsForRoot = pendingLegacyContextWarning.get(strictRoot);
if (fiber.type.contextTypes != null || fiber.type.childContextTypes != null || instance !== null && typeof instance.getChildContext === "function") {
if (warningsForRoot === void 0) {
warningsForRoot = [];
pendingLegacyContextWarning.set(strictRoot, warningsForRoot);
}
warningsForRoot.push(fiber);
}
};
ReactStrictModeWarnings.flushLegacyContextWarning = function() {
pendingLegacyContextWarning.forEach(function(fiberArray, strictRoot) {
if (fiberArray.length === 0) {
return;
}
var firstFiber = fiberArray[0];
var uniqueNames = new Set();
fiberArray.forEach(function(fiber) {
uniqueNames.add(getComponentName(fiber.type) || "Component");
didWarnAboutLegacyContext.add(fiber.type);
});
var sortedNames = setToSortedString(uniqueNames);
try {
setCurrentFiber(firstFiber);
error("Legacy context API has been detected within a strict-mode tree.\n\nThe old API will be supported in all 16.x releases, but applications using it should migrate to the new version.\n\nPlease update the following components: %s\n\nLearn more about this warning here: https://reactjs.org/link/legacy-context", sortedNames);
} finally {
resetCurrentFiber();
}
});
};
ReactStrictModeWarnings.discardPendingWarnings = function() {
pendingComponentWillMountWarnings = [];
pendingUNSAFE_ComponentWillMountWarnings = [];
pendingComponentWillReceivePropsWarnings = [];
pendingUNSAFE_ComponentWillReceivePropsWarnings = [];
pendingComponentWillUpdateWarnings = [];
pendingUNSAFE_ComponentWillUpdateWarnings = [];
pendingLegacyContextWarning = new Map();
};
}
function resolveDefaultProps(Component, baseProps) {
if (Component && Component.defaultProps) {
var props = _assign({}, baseProps);
var defaultProps = Component.defaultProps;
for (var propName in defaultProps) {
if (props[propName] === void 0) {
props[propName] = defaultProps[propName];
}
}
return props;
}
return baseProps;
}
var MAX_SIGNED_31_BIT_INT = 1073741823;
var valueCursor = createCursor(null);
var rendererSigil;
{
rendererSigil = {};
}
var currentlyRenderingFiber = null;
var lastContextDependency = null;
var lastContextWithAllBitsObserved = null;
var isDisallowedContextReadInDEV = false;
function resetContextDependencies() {
currentlyRenderingFiber = null;
lastContextDependency = null;
lastContextWithAllBitsObserved = null;
{
isDisallowedContextReadInDEV = false;
}
}
function enterDisallowedContextReadInDEV() {
{
isDisallowedContextReadInDEV = true;
}
}
function exitDisallowedContextReadInDEV() {
{
isDisallowedContextReadInDEV = false;
}
}
function pushProvider(providerFiber, nextValue) {
var context = providerFiber.type._context;
{
push(valueCursor, context._currentValue, providerFiber);
context._currentValue = nextValue;
{
if (context._currentRenderer !== void 0 && context._currentRenderer !== null && context._currentRenderer !== rendererSigil) {
error("Detected multiple renderers concurrently rendering the same context provider. This is currently unsupported.");
}
context._currentRenderer = rendererSigil;
}
}
}
function popProvider(providerFiber) {
var currentValue = valueCursor.current;
pop(valueCursor, providerFiber);
var context = providerFiber.type._context;
{
context._currentValue = currentValue;
}
}
function calculateChangedBits(context, newValue, oldValue) {
if (objectIs(oldValue, newValue)) {
return 0;
} else {
var changedBits = typeof context._calculateChangedBits === "function" ? context._calculateChangedBits(oldValue, newValue) : MAX_SIGNED_31_BIT_INT;
{
if ((changedBits & MAX_SIGNED_31_BIT_INT) !== changedBits) {
error("calculateChangedBits: Expected the return value to be a 31-bit integer. Instead received: %s", changedBits);
}
}
return changedBits | 0;
}
}
function scheduleWorkOnParentPath(parent, renderLanes2) {
var node = parent;
while (node !== null) {
var alternate = node.alternate;
if (!isSubsetOfLanes(node.childLanes, renderLanes2)) {
node.childLanes = mergeLanes(node.childLanes, renderLanes2);
if (alternate !== null) {
alternate.childLanes = mergeLanes(alternate.childLanes, renderLanes2);
}
} else if (alternate !== null && !isSubsetOfLanes(alternate.childLanes, renderLanes2)) {
alternate.childLanes = mergeLanes(alternate.childLanes, renderLanes2);
} else {
break;
}
node = node.return;
}
}
function propagateContextChange(workInProgress2, context, changedBits, renderLanes2) {
var fiber = workInProgress2.child;
if (fiber !== null) {
fiber.return = workInProgress2;
}
while (fiber !== null) {
var nextFiber = void 0;
var list = fiber.dependencies;
if (list !== null) {
nextFiber = fiber.child;
var dependency = list.firstContext;
while (dependency !== null) {
if (dependency.context === context && (dependency.observedBits & changedBits) !== 0) {
if (fiber.tag === ClassComponent) {
var update = createUpdate(NoTimestamp, pickArbitraryLane(renderLanes2));
update.tag = ForceUpdate;
enqueueUpdate(fiber, update);
}
fiber.lanes = mergeLanes(fiber.lanes, renderLanes2);
var alternate = fiber.alternate;
if (alternate !== null) {
alternate.lanes = mergeLanes(alternate.lanes, renderLanes2);
}
scheduleWorkOnParentPath(fiber.return, renderLanes2);
list.lanes = mergeLanes(list.lanes, renderLanes2);
break;
}
dependency = dependency.next;
}
} else if (fiber.tag === ContextProvider) {
nextFiber = fiber.type === workInProgress2.type ? null : fiber.child;
} else {
nextFiber = fiber.child;
}
if (nextFiber !== null) {
nextFiber.return = fiber;
} else {
nextFiber = fiber;
while (nextFiber !== null) {
if (nextFiber === workInProgress2) {
nextFiber = null;
break;
}
var sibling = nextFiber.sibling;
if (sibling !== null) {
sibling.return = nextFiber.return;
nextFiber = sibling;
break;
}
nextFiber = nextFiber.return;
}
}
fiber = nextFiber;
}
}
function prepareToReadContext(workInProgress2, renderLanes2) {
currentlyRenderingFiber = workInProgress2;
lastContextDependency = null;
lastContextWithAllBitsObserved = null;
var dependencies = workInProgress2.dependencies;
if (dependencies !== null) {
var firstContext = dependencies.firstContext;
if (firstContext !== null) {
if (includesSomeLane(dependencies.lanes, renderLanes2)) {
markWorkInProgressReceivedUpdate();
}
dependencies.firstContext = null;
}
}
}
function readContext(context, observedBits) {
{
if (isDisallowedContextReadInDEV) {
error("Context can only be read while React is rendering. In classes, you can read it in the render method or getDerivedStateFromProps. In function components, you can read it directly in the function body, but not inside Hooks like useReducer() or useMemo().");
}
}
if (lastContextWithAllBitsObserved === context)
;
else if (observedBits === false || observedBits === 0)
;
else {
var resolvedObservedBits;
if (typeof observedBits !== "number" || observedBits === MAX_SIGNED_31_BIT_INT) {
lastContextWithAllBitsObserved = context;
resolvedObservedBits = MAX_SIGNED_31_BIT_INT;
} else {
resolvedObservedBits = observedBits;
}
var contextItem = {
context,
observedBits: resolvedObservedBits,
next: null
};
if (lastContextDependency === null) {
if (!(currentlyRenderingFiber !== null)) {
{
throw Error("Context can only be read while React is rendering. In classes, you can read it in the render method or getDerivedStateFromProps. In function components, you can read it directly in the function body, but not inside Hooks like useReducer() or useMemo().");
}
}
lastContextDependency = contextItem;
currentlyRenderingFiber.dependencies = {
lanes: NoLanes,
firstContext: contextItem,
responders: null
};
} else {
lastContextDependency = lastContextDependency.next = contextItem;
}
}
return context._currentValue;
}
var UpdateState = 0;
var ReplaceState = 1;
var ForceUpdate = 2;
var CaptureUpdate = 3;
var hasForceUpdate = false;
var didWarnUpdateInsideUpdate;
var currentlyProcessingQueue;
{
didWarnUpdateInsideUpdate = false;
currentlyProcessingQueue = null;
}
function initializeUpdateQueue(fiber) {
var queue = {
baseState: fiber.memoizedState,
firstBaseUpdate: null,
lastBaseUpdate: null,
shared: {
pending: null
},
effects: null
};
fiber.updateQueue = queue;
}
function cloneUpdateQueue(current2, workInProgress2) {
var queue = workInProgress2.updateQueue;
var currentQueue = current2.updateQueue;
if (queue === currentQueue) {
var clone = {
baseState: currentQueue.baseState,
firstBaseUpdate: currentQueue.firstBaseUpdate,
lastBaseUpdate: currentQueue.lastBaseUpdate,
shared: currentQueue.shared,
effects: currentQueue.effects
};
workInProgress2.updateQueue = clone;
}
}
function createUpdate(eventTime, lane) {
var update = {
eventTime,
lane,
tag: UpdateState,
payload: null,
callback: null,
next: null
};
return update;
}
function enqueueUpdate(fiber, update) {
var updateQueue = fiber.updateQueue;
if (updateQueue === null) {
return;
}
var sharedQueue = updateQueue.shared;
var pending = sharedQueue.pending;
if (pending === null) {
update.next = update;
} else {
update.next = pending.next;
pending.next = update;
}
sharedQueue.pending = update;
{
if (currentlyProcessingQueue === sharedQueue && !didWarnUpdateInsideUpdate) {
error("An update (setState, replaceState, or forceUpdate) was scheduled from inside an update function. Update functions should be pure, with zero side-effects. Consider using componentDidUpdate or a callback.");
didWarnUpdateInsideUpdate = true;
}
}
}
function enqueueCapturedUpdate(workInProgress2, capturedUpdate) {
var queue = workInProgress2.updateQueue;
var current2 = workInProgress2.alternate;
if (current2 !== null) {
var currentQueue = current2.updateQueue;
if (queue === currentQueue) {
var newFirst = null;
var newLast = null;
var firstBaseUpdate = queue.firstBaseUpdate;
if (firstBaseUpdate !== null) {
var update = firstBaseUpdate;
do {
var clone = {
eventTime: update.eventTime,
lane: update.lane,
tag: update.tag,
payload: update.payload,
callback: update.callback,
next: null
};
if (newLast === null) {
newFirst = newLast = clone;
} else {
newLast.next = clone;
newLast = clone;
}
update = update.next;
} while (update !== null);
if (newLast === null) {
newFirst = newLast = capturedUpdate;
} else {
newLast.next = capturedUpdate;
newLast = capturedUpdate;
}
} else {
newFirst = newLast = capturedUpdate;
}
queue = {
baseState: currentQueue.baseState,
firstBaseUpdate: newFirst,
lastBaseUpdate: newLast,
shared: currentQueue.shared,
effects: currentQueue.effects
};
workInProgress2.updateQueue = queue;
return;
}
}
var lastBaseUpdate = queue.lastBaseUpdate;
if (lastBaseUpdate === null) {
queue.firstBaseUpdate = capturedUpdate;
} else {
lastBaseUpdate.next = capturedUpdate;
}
queue.lastBaseUpdate = capturedUpdate;
}
function getStateFromUpdate(workInProgress2, queue, update, prevState, nextProps, instance) {
switch (update.tag) {
case ReplaceState: {
var payload = update.payload;
if (typeof payload === "function") {
{
enterDisallowedContextReadInDEV();
}
var nextState = payload.call(instance, prevState, nextProps);
{
if (workInProgress2.mode & StrictMode) {
disableLogs();
try {
payload.call(instance, prevState, nextProps);
} finally {
reenableLogs();
}
}
exitDisallowedContextReadInDEV();
}
return nextState;
}
return payload;
}
case CaptureUpdate: {
workInProgress2.flags = workInProgress2.flags & ~ShouldCapture | DidCapture;
}
case UpdateState: {
var _payload = update.payload;
var partialState;
if (typeof _payload === "function") {
{
enterDisallowedContextReadInDEV();
}
partialState = _payload.call(instance, prevState, nextProps);
{
if (workInProgress2.mode & StrictMode) {
disableLogs();
try {
_payload.call(instance, prevState, nextProps);
} finally {
reenableLogs();
}
}
exitDisallowedContextReadInDEV();
}
} else {
partialState = _payload;
}
if (partialState === null || partialState === void 0) {
return prevState;
}
return _assign({}, prevState, partialState);
}
case ForceUpdate: {
hasForceUpdate = true;
return prevState;
}
}
return prevState;
}
function processUpdateQueue(workInProgress2, props, instance, renderLanes2) {
var queue = workInProgress2.updateQueue;
hasForceUpdate = false;
{
currentlyProcessingQueue = queue.shared;
}
var firstBaseUpdate = queue.firstBaseUpdate;
var lastBaseUpdate = queue.lastBaseUpdate;
var pendingQueue = queue.shared.pending;
if (pendingQueue !== null) {
queue.shared.pending = null;
var lastPendingUpdate = pendingQueue;
var firstPendingUpdate = lastPendingUpdate.next;
lastPendingUpdate.next = null;
if (lastBaseUpdate === null) {
firstBaseUpdate = firstPendingUpdate;
} else {
lastBaseUpdate.next = firstPendingUpdate;
}
lastBaseUpdate = lastPendingUpdate;
var current2 = workInProgress2.alternate;
if (current2 !== null) {
var currentQueue = current2.updateQueue;
var currentLastBaseUpdate = currentQueue.lastBaseUpdate;
if (currentLastBaseUpdate !== lastBaseUpdate) {
if (currentLastBaseUpdate === null) {
currentQueue.firstBaseUpdate = firstPendingUpdate;
} else {
currentLastBaseUpdate.next = firstPendingUpdate;
}
currentQueue.lastBaseUpdate = lastPendingUpdate;
}
}
}
if (firstBaseUpdate !== null) {
var newState = queue.baseState;
var newLanes = NoLanes;
var newBaseState = null;
var newFirstBaseUpdate = null;
var newLastBaseUpdate = null;
var update = firstBaseUpdate;
do {
var updateLane = update.lane;
var updateEventTime = update.eventTime;
if (!isSubsetOfLanes(renderLanes2, updateLane)) {
var clone = {
eventTime: updateEventTime,
lane: updateLane,
tag: update.tag,
payload: update.payload,
callback: update.callback,
next: null
};
if (newLastBaseUpdate === null) {
newFirstBaseUpdate = newLastBaseUpdate = clone;
newBaseState = newState;
} else {
newLastBaseUpdate = newLastBaseUpdate.next = clone;
}
newLanes = mergeLanes(newLanes, updateLane);
} else {
if (newLastBaseUpdate !== null) {
var _clone = {
eventTime: updateEventTime,
lane: NoLane,
tag: update.tag,
payload: update.payload,
callback: update.callback,
next: null
};
newLastBaseUpdate = newLastBaseUpdate.next = _clone;
}
newState = getStateFromUpdate(workInProgress2, queue, update, newState, props, instance);
var callback = update.callback;
if (callback !== null) {
workInProgress2.flags |= Callback;
var effects = queue.effects;
if (effects === null) {
queue.effects = [update];
} else {
effects.push(update);
}
}
}
update = update.next;
if (update === null) {
pendingQueue = queue.shared.pending;
if (pendingQueue === null) {
break;
} else {
var _lastPendingUpdate = pendingQueue;
var _firstPendingUpdate = _lastPendingUpdate.next;
_lastPendingUpdate.next = null;
update = _firstPendingUpdate;
queue.lastBaseUpdate = _lastPendingUpdate;
queue.shared.pending = null;
}
}
} while (true);
if (newLastBaseUpdate === null) {
newBaseState = newState;
}
queue.baseState = newBaseState;
queue.firstBaseUpdate = newFirstBaseUpdate;
queue.lastBaseUpdate = newLastBaseUpdate;
markSkippedUpdateLanes(newLanes);
workInProgress2.lanes = newLanes;
workInProgress2.memoizedState = newState;
}
{
currentlyProcessingQueue = null;
}
}
function callCallback(callback, context) {
if (!(typeof callback === "function")) {
{
throw Error("Invalid argument passed as callback. Expected a function. Instead received: " + callback);
}
}
callback.call(context);
}
function resetHasForceUpdateBeforeProcessing() {
hasForceUpdate = false;
}
function checkHasForceUpdateAfterProcessing() {
return hasForceUpdate;
}
function commitUpdateQueue(finishedWork, finishedQueue, instance) {
var effects = finishedQueue.effects;
finishedQueue.effects = null;
if (effects !== null) {
for (var i = 0; i < effects.length; i++) {
var effect = effects[i];
var callback = effect.callback;
if (callback !== null) {
effect.callback = null;
callCallback(callback, instance);
}
}
}
}
var fakeInternalInstance = {};
var isArray = Array.isArray;
var emptyRefsObject = new React3.Component().refs;
var didWarnAboutStateAssignmentForComponent;
var didWarnAboutUninitializedState;
var didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate;
var didWarnAboutLegacyLifecyclesAndDerivedState;
var didWarnAboutUndefinedDerivedState;
var warnOnUndefinedDerivedState;
var warnOnInvalidCallback;
var didWarnAboutDirectlyAssigningPropsToState;
var didWarnAboutContextTypeAndContextTypes;
var didWarnAboutInvalidateContextType;
{
didWarnAboutStateAssignmentForComponent = new Set();
didWarnAboutUninitializedState = new Set();
didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = new Set();
didWarnAboutLegacyLifecyclesAndDerivedState = new Set();
didWarnAboutDirectlyAssigningPropsToState = new Set();
didWarnAboutUndefinedDerivedState = new Set();
didWarnAboutContextTypeAndContextTypes = new Set();
didWarnAboutInvalidateContextType = new Set();
var didWarnOnInvalidCallback = new Set();
warnOnInvalidCallback = function(callback, callerName) {
if (callback === null || typeof callback === "function") {
return;
}
var key = callerName + "_" + callback;
if (!didWarnOnInvalidCallback.has(key)) {
didWarnOnInvalidCallback.add(key);
error("%s(...): Expected the last optional `callback` argument to be a function. Instead received: %s.", callerName, callback);
}
};
warnOnUndefinedDerivedState = function(type, partialState) {
if (partialState === void 0) {
var componentName = getComponentName(type) || "Component";
if (!didWarnAboutUndefinedDerivedState.has(componentName)) {
didWarnAboutUndefinedDerivedState.add(componentName);
error("%s.getDerivedStateFromProps(): A valid state object (or null) must be returned. You have returned undefined.", componentName);
}
}
};
Object.defineProperty(fakeInternalInstance, "_processChildContext", {
enumerable: false,
value: function() {
{
{
throw Error("_processChildContext is not available in React 16+. This likely means you have multiple copies of React and are attempting to nest a React 15 tree inside a React 16 tree using unstable_renderSubtreeIntoContainer, which isn't supported. Try to make sure you have only one copy of React (and ideally, switch to ReactDOM.createPortal).");
}
}
}
});
Object.freeze(fakeInternalInstance);
}
function applyDerivedStateFromProps(workInProgress2, ctor, getDerivedStateFromProps, nextProps) {
var prevState = workInProgress2.memoizedState;
{
if (workInProgress2.mode & StrictMode) {
disableLogs();
try {
getDerivedStateFromProps(nextProps, prevState);
} finally {
reenableLogs();
}
}
}
var partialState = getDerivedStateFromProps(nextProps, prevState);
{
warnOnUndefinedDerivedState(ctor, partialState);
}
var memoizedState = partialState === null || partialState === void 0 ? prevState : _assign({}, prevState, partialState);
workInProgress2.memoizedState = memoizedState;
if (workInProgress2.lanes === NoLanes) {
var updateQueue = workInProgress2.updateQueue;
updateQueue.baseState = memoizedState;
}
}
var classComponentUpdater = {
isMounted,
enqueueSetState: function(inst, payload, callback) {
var fiber = get(inst);
var eventTime = requestEventTime();
var lane = requestUpdateLane(fiber);
var update = createUpdate(eventTime, lane);
update.payload = payload;
if (callback !== void 0 && callback !== null) {
{
warnOnInvalidCallback(callback, "setState");
}
update.callback = callback;
}
enqueueUpdate(fiber, update);
scheduleUpdateOnFiber(fiber, lane, eventTime);
},
enqueueReplaceState: function(inst, payload, callback) {
var fiber = get(inst);
var eventTime = requestEventTime();
var lane = requestUpdateLane(fiber);
var update = createUpdate(eventTime, lane);
update.tag = ReplaceState;
update.payload = payload;
if (callback !== void 0 && callback !== null) {
{
warnOnInvalidCallback(callback, "replaceState");
}
update.callback = callback;
}
enqueueUpdate(fiber, update);
scheduleUpdateOnFiber(fiber, lane, eventTime);
},
enqueueForceUpdate: function(inst, callback) {
var fiber = get(inst);
var eventTime = requestEventTime();
var lane = requestUpdateLane(fiber);
var update = createUpdate(eventTime, lane);
update.tag = ForceUpdate;
if (callback !== void 0 && callback !== null) {
{
warnOnInvalidCallback(callback, "forceUpdate");
}
update.callback = callback;
}
enqueueUpdate(fiber, update);
scheduleUpdateOnFiber(fiber, lane, eventTime);
}
};
function checkShouldComponentUpdate(workInProgress2, ctor, oldProps, newProps, oldState, newState, nextContext) {
var instance = workInProgress2.stateNode;
if (typeof instance.shouldComponentUpdate === "function") {
{
if (workInProgress2.mode & StrictMode) {
disableLogs();
try {
instance.shouldComponentUpdate(newProps, newState, nextContext);
} finally {
reenableLogs();
}
}
}
var shouldUpdate = instance.shouldComponentUpdate(newProps, newState, nextContext);
{
if (shouldUpdate === void 0) {
error("%s.shouldComponentUpdate(): Returned undefined instead of a boolean value. Make sure to return true or false.", getComponentName(ctor) || "Component");
}
}
return shouldUpdate;
}
if (ctor.prototype && ctor.prototype.isPureReactComponent) {
return !shallowEqual(oldProps, newProps) || !shallowEqual(oldState, newState);
}
return true;
}
function checkClassInstance(workInProgress2, ctor, newProps) {
var instance = workInProgress2.stateNode;
{
var name = getComponentName(ctor) || "Component";
var renderPresent = instance.render;
if (!renderPresent) {
if (ctor.prototype && typeof ctor.prototype.render === "function") {
error("%s(...): No `render` method found on the returned component instance: did you accidentally return an object from the constructor?", name);
} else {
error("%s(...): No `render` method found on the returned component instance: you may have forgotten to define `render`.", name);
}
}
if (instance.getInitialState && !instance.getInitialState.isReactClassApproved && !instance.state) {
error("getInitialState was defined on %s, a plain JavaScript class. This is only supported for classes created using React.createClass. Did you mean to define a state property instead?", name);
}
if (instance.getDefaultProps && !instance.getDefaultProps.isReactClassApproved) {
error("getDefaultProps was defined on %s, a plain JavaScript class. This is only supported for classes created using React.createClass. Use a static property to define defaultProps instead.", name);
}
if (instance.propTypes) {
error("propTypes was defined as an instance property on %s. Use a static property to define propTypes instead.", name);
}
if (instance.contextType) {
error("contextType was defined as an instance property on %s. Use a static property to define contextType instead.", name);
}
{
if (instance.contextTypes) {
error("contextTypes was defined as an instance property on %s. Use a static property to define contextTypes instead.", name);
}
if (ctor.contextType && ctor.contextTypes && !didWarnAboutContextTypeAndContextTypes.has(ctor)) {
didWarnAboutContextTypeAndContextTypes.add(ctor);
error("%s declares both contextTypes and contextType static properties. The legacy contextTypes property will be ignored.", name);
}
}
if (typeof instance.componentShouldUpdate === "function") {
error("%s has a method called componentShouldUpdate(). Did you mean shouldComponentUpdate()? The name is phrased as a question because the function is expected to return a value.", name);
}
if (ctor.prototype && ctor.prototype.isPureReactComponent && typeof instance.shouldComponentUpdate !== "undefined") {
error("%s has a method called shouldComponentUpdate(). shouldComponentUpdate should not be used when extending React.PureComponent. Please extend React.Component if shouldComponentUpdate is used.", getComponentName(ctor) || "A pure component");
}
if (typeof instance.componentDidUnmount === "function") {
error("%s has a method called componentDidUnmount(). But there is no such lifecycle method. Did you mean componentWillUnmount()?", name);
}
if (typeof instance.componentDidReceiveProps === "function") {
error("%s has a method called componentDidReceiveProps(). But there is no such lifecycle method. If you meant to update the state in response to changing props, use componentWillReceiveProps(). If you meant to fetch data or run side-effects or mutations after React has updated the UI, use componentDidUpdate().", name);
}
if (typeof instance.componentWillRecieveProps === "function") {
error("%s has a method called componentWillRecieveProps(). Did you mean componentWillReceiveProps()?", name);
}
if (typeof instance.UNSAFE_componentWillRecieveProps === "function") {
error("%s has a method called UNSAFE_componentWillRecieveProps(). Did you mean UNSAFE_componentWillReceiveProps()?", name);
}
var hasMutatedProps = instance.props !== newProps;
if (instance.props !== void 0 && hasMutatedProps) {
error("%s(...): When calling super() in `%s`, make sure to pass up the same props that your component's constructor was passed.", name, name);
}
if (instance.defaultProps) {
error("Setting defaultProps as an instance property on %s is not supported and will be ignored. Instead, define defaultProps as a static property on %s.", name, name);
}
if (typeof instance.getSnapshotBeforeUpdate === "function" && typeof instance.componentDidUpdate !== "function" && !didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.has(ctor)) {
didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.add(ctor);
error("%s: getSnapshotBeforeUpdate() should be used with componentDidUpdate(). This component defines getSnapshotBeforeUpdate() only.", getComponentName(ctor));
}
if (typeof instance.getDerivedStateFromProps === "function") {
error("%s: getDerivedStateFromProps() is defined as an instance method and will be ignored. Instead, declare it as a static method.", name);
}
if (typeof instance.getDerivedStateFromError === "function") {
error("%s: getDerivedStateFromError() is defined as an instance method and will be ignored. Instead, declare it as a static method.", name);
}
if (typeof ctor.getSnapshotBeforeUpdate === "function") {
error("%s: getSnapshotBeforeUpdate() is defined as a static method and will be ignored. Instead, declare it as an instance method.", name);
}
var _state = instance.state;
if (_state && (typeof _state !== "object" || isArray(_state))) {
error("%s.state: must be set to an object or null", name);
}
if (typeof instance.getChildContext === "function" && typeof ctor.childContextTypes !== "object") {
error("%s.getChildContext(): childContextTypes must be defined in order to use getChildContext().", name);
}
}
}
function adoptClassInstance(workInProgress2, instance) {
instance.updater = classComponentUpdater;
workInProgress2.stateNode = instance;
set(instance, workInProgress2);
{
instance._reactInternalInstance = fakeInternalInstance;
}
}
function constructClassInstance(workInProgress2, ctor, props) {
var isLegacyContextConsumer = false;
var unmaskedContext = emptyContextObject;
var context = emptyContextObject;
var contextType = ctor.contextType;
{
if ("contextType" in ctor) {
var isValid = contextType === null || contextType !== void 0 && contextType.$$typeof === REACT_CONTEXT_TYPE && contextType._context === void 0;
if (!isValid && !didWarnAboutInvalidateContextType.has(ctor)) {
didWarnAboutInvalidateContextType.add(ctor);
var addendum = "";
if (contextType === void 0) {
addendum = " However, it is set to undefined. This can be caused by a typo or by mixing up named and default imports. This can also happen due to a circular dependency, so try moving the createContext() call to a separate file.";
} else if (typeof contextType !== "object") {
addendum = " However, it is set to a " + typeof contextType + ".";
} else if (contextType.$$typeof === REACT_PROVIDER_TYPE) {
addendum = " Did you accidentally pass the Context.Provider instead?";
} else if (contextType._context !== void 0) {
addendum = " Did you accidentally pass the Context.Consumer instead?";
} else {
addendum = " However, it is set to an object with keys {" + Object.keys(contextType).join(", ") + "}.";
}
error("%s defines an invalid contextType. contextType should point to the Context object returned by React.createContext().%s", getComponentName(ctor) || "Component", addendum);
}
}
}
if (typeof contextType === "object" && contextType !== null) {
context = readContext(contextType);
} else {
unmaskedContext = getUnmaskedContext(workInProgress2, ctor, true);
var contextTypes = ctor.contextTypes;
isLegacyContextConsumer = contextTypes !== null && contextTypes !== void 0;
context = isLegacyContextConsumer ? getMaskedContext(workInProgress2, unmaskedContext) : emptyContextObject;
}
{
if (workInProgress2.mode & StrictMode) {
disableLogs();
try {
new ctor(props, context);
} finally {
reenableLogs();
}
}
}
var instance = new ctor(props, context);
var state = workInProgress2.memoizedState = instance.state !== null && instance.state !== void 0 ? instance.state : null;
adoptClassInstance(workInProgress2, instance);
{
if (typeof ctor.getDerivedStateFromProps === "function" && state === null) {
var componentName = getComponentName(ctor) || "Component";
if (!didWarnAboutUninitializedState.has(componentName)) {
didWarnAboutUninitializedState.add(componentName);
error("`%s` uses `getDerivedStateFromProps` but its initial state is %s. This is not recommended. Instead, define the initial state by assigning an object to `this.state` in the constructor of `%s`. This ensures that `getDerivedStateFromProps` arguments have a consistent shape.", componentName, instance.state === null ? "null" : "undefined", componentName);
}
}
if (typeof ctor.getDerivedStateFromProps === "function" || typeof instance.getSnapshotBeforeUpdate === "function") {
var foundWillMountName = null;
var foundWillReceivePropsName = null;
var foundWillUpdateName = null;
if (typeof instance.componentWillMount === "function" && instance.componentWillMount.__suppressDeprecationWarning !== true) {
foundWillMountName = "componentWillMount";
} else if (typeof instance.UNSAFE_componentWillMount === "function") {
foundWillMountName = "UNSAFE_componentWillMount";
}
if (typeof instance.componentWillReceiveProps === "function" && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) {
foundWillReceivePropsName = "componentWillReceiveProps";
} else if (typeof instance.UNSAFE_componentWillReceiveProps === "function") {
foundWillReceivePropsName = "UNSAFE_componentWillReceiveProps";
}
if (typeof instance.componentWillUpdate === "function" && instance.componentWillUpdate.__suppressDeprecationWarning !== true) {
foundWillUpdateName = "componentWillUpdate";
} else if (typeof instance.UNSAFE_componentWillUpdate === "function") {
foundWillUpdateName = "UNSAFE_componentWillUpdate";
}
if (foundWillMountName !== null || foundWillReceivePropsName !== null || foundWillUpdateName !== null) {
var _componentName = getComponentName(ctor) || "Component";
var newApiName = typeof ctor.getDerivedStateFromProps === "function" ? "getDerivedStateFromProps()" : "getSnapshotBeforeUpdate()";
if (!didWarnAboutLegacyLifecyclesAndDerivedState.has(_componentName)) {
didWarnAboutLegacyLifecyclesAndDerivedState.add(_componentName);
error("Unsafe legacy lifecycles will not be called for components using new component APIs.\n\n%s uses %s but also contains the following legacy lifecycles:%s%s%s\n\nThe above lifecycles should be removed. Learn more about this warning here:\nhttps://reactjs.org/link/unsafe-component-lifecycles", _componentName, newApiName, foundWillMountName !== null ? "\n " + foundWillMountName : "", foundWillReceivePropsName !== null ? "\n " + foundWillReceivePropsName : "", foundWillUpdateName !== null ? "\n " + foundWillUpdateName : "");
}
}
}
}
if (isLegacyContextConsumer) {
cacheContext(workInProgress2, unmaskedContext, context);
}
return instance;
}
function callComponentWillMount(workInProgress2, instance) {
var oldState = instance.state;
if (typeof instance.componentWillMount === "function") {
instance.componentWillMount();
}
if (typeof instance.UNSAFE_componentWillMount === "function") {
instance.UNSAFE_componentWillMount();
}
if (oldState !== instance.state) {
{
error("%s.componentWillMount(): Assigning directly to this.state is deprecated (except inside a component's constructor). Use setState instead.", getComponentName(workInProgress2.type) || "Component");
}
classComponentUpdater.enqueueReplaceState(instance, instance.state, null);
}
}
function callComponentWillReceiveProps(workInProgress2, instance, newProps, nextContext) {
var oldState = instance.state;
if (typeof instance.componentWillReceiveProps === "function") {
instance.componentWillReceiveProps(newProps, nextContext);
}
if (typeof instance.UNSAFE_componentWillReceiveProps === "function") {
instance.UNSAFE_componentWillReceiveProps(newProps, nextContext);
}
if (instance.state !== oldState) {
{
var componentName = getComponentName(workInProgress2.type) || "Component";
if (!didWarnAboutStateAssignmentForComponent.has(componentName)) {
didWarnAboutStateAssignmentForComponent.add(componentName);
error("%s.componentWillReceiveProps(): Assigning directly to this.state is deprecated (except inside a component's constructor). Use setState instead.", componentName);
}
}
classComponentUpdater.enqueueReplaceState(instance, instance.state, null);
}
}
function mountClassInstance(workInProgress2, ctor, newProps, renderLanes2) {
{
checkClassInstance(workInProgress2, ctor, newProps);
}
var instance = workInProgress2.stateNode;
instance.props = newProps;
instance.state = workInProgress2.memoizedState;
instance.refs = emptyRefsObject;
initializeUpdateQueue(workInProgress2);
var contextType = ctor.contextType;
if (typeof contextType === "object" && contextType !== null) {
instance.context = readContext(contextType);
} else {
var unmaskedContext = getUnmaskedContext(workInProgress2, ctor, true);
instance.context = getMaskedContext(workInProgress2, unmaskedContext);
}
{
if (instance.state === newProps) {
var componentName = getComponentName(ctor) || "Component";
if (!didWarnAboutDirectlyAssigningPropsToState.has(componentName)) {
didWarnAboutDirectlyAssigningPropsToState.add(componentName);
error("%s: It is not recommended to assign props directly to state because updates to props won't be reflected in state. In most cases, it is better to use props directly.", componentName);
}
}
if (workInProgress2.mode & StrictMode) {
ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress2, instance);
}
{
ReactStrictModeWarnings.recordUnsafeLifecycleWarnings(workInProgress2, instance);
}
}
processUpdateQueue(workInProgress2, newProps, instance, renderLanes2);
instance.state = workInProgress2.memoizedState;
var getDerivedStateFromProps = ctor.getDerivedStateFromProps;
if (typeof getDerivedStateFromProps === "function") {
applyDerivedStateFromProps(workInProgress2, ctor, getDerivedStateFromProps, newProps);
instance.state = workInProgress2.memoizedState;
}
if (typeof ctor.getDerivedStateFromProps !== "function" && typeof instance.getSnapshotBeforeUpdate !== "function" && (typeof instance.UNSAFE_componentWillMount === "function" || typeof instance.componentWillMount === "function")) {
callComponentWillMount(workInProgress2, instance);
processUpdateQueue(workInProgress2, newProps, instance, renderLanes2);
instance.state = workInProgress2.memoizedState;
}
if (typeof instance.componentDidMount === "function") {
workInProgress2.flags |= Update;
}
}
function resumeMountClassInstance(workInProgress2, ctor, newProps, renderLanes2) {
var instance = workInProgress2.stateNode;
var oldProps = workInProgress2.memoizedProps;
instance.props = oldProps;
var oldContext = instance.context;
var contextType = ctor.contextType;
var nextContext = emptyContextObject;
if (typeof contextType === "object" && contextType !== null) {
nextContext = readContext(contextType);
} else {
var nextLegacyUnmaskedContext = getUnmaskedContext(workInProgress2, ctor, true);
nextContext = getMaskedContext(workInProgress2, nextLegacyUnmaskedContext);
}
var getDerivedStateFromProps = ctor.getDerivedStateFromProps;
var hasNewLifecycles = typeof getDerivedStateFromProps === "function" || typeof instance.getSnapshotBeforeUpdate === "function";
if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === "function" || typeof instance.componentWillReceiveProps === "function")) {
if (oldProps !== newProps || oldContext !== nextContext) {
callComponentWillReceiveProps(workInProgress2, instance, newProps, nextContext);
}
}
resetHasForceUpdateBeforeProcessing();
var oldState = workInProgress2.memoizedState;
var newState = instance.state = oldState;
processUpdateQueue(workInProgress2, newProps, instance, renderLanes2);
newState = workInProgress2.memoizedState;
if (oldProps === newProps && oldState === newState && !hasContextChanged() && !checkHasForceUpdateAfterProcessing()) {
if (typeof instance.componentDidMount === "function") {
workInProgress2.flags |= Update;
}
return false;
}
if (typeof getDerivedStateFromProps === "function") {
applyDerivedStateFromProps(workInProgress2, ctor, getDerivedStateFromProps, newProps);
newState = workInProgress2.memoizedState;
}
var shouldUpdate = checkHasForceUpdateAfterProcessing() || checkShouldComponentUpdate(workInProgress2, ctor, oldProps, newProps, oldState, newState, nextContext);
if (shouldUpdate) {
if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillMount === "function" || typeof instance.componentWillMount === "function")) {
if (typeof instance.componentWillMount === "function") {
instance.componentWillMount();
}
if (typeof instance.UNSAFE_componentWillMount === "function") {
instance.UNSAFE_componentWillMount();
}
}
if (typeof instance.componentDidMount === "function") {
workInProgress2.flags |= Update;
}
} else {
if (typeof instance.componentDidMount === "function") {
workInProgress2.flags |= Update;
}
workInProgress2.memoizedProps = newProps;
workInProgress2.memoizedState = newState;
}
instance.props = newProps;
instance.state = newState;
instance.context = nextContext;
return shouldUpdate;
}
function updateClassInstance(current2, workInProgress2, ctor, newProps, renderLanes2) {
var instance = workInProgress2.stateNode;
cloneUpdateQueue(current2, workInProgress2);
var unresolvedOldProps = workInProgress2.memoizedProps;
var oldProps = workInProgress2.type === workInProgress2.elementType ? unresolvedOldProps : resolveDefaultProps(workInProgress2.type, unresolvedOldProps);
instance.props = oldProps;
var unresolvedNewProps = workInProgress2.pendingProps;
var oldContext = instance.context;
var contextType = ctor.contextType;
var nextContext = emptyContextObject;
if (typeof contextType === "object" && contextType !== null) {
nextContext = readContext(contextType);
} else {
var nextUnmaskedContext = getUnmaskedContext(workInProgress2, ctor, true);
nextContext = getMaskedContext(workInProgress2, nextUnmaskedContext);
}
var getDerivedStateFromProps = ctor.getDerivedStateFromProps;
var hasNewLifecycles = typeof getDerivedStateFromProps === "function" || typeof instance.getSnapshotBeforeUpdate === "function";
if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === "function" || typeof instance.componentWillReceiveProps === "function")) {
if (unresolvedOldProps !== unresolvedNewProps || oldContext !== nextContext) {
callComponentWillReceiveProps(workInProgress2, instance, newProps, nextContext);
}
}
resetHasForceUpdateBeforeProcessing();
var oldState = workInProgress2.memoizedState;
var newState = instance.state = oldState;
processUpdateQueue(workInProgress2, newProps, instance, renderLanes2);
newState = workInProgress2.memoizedState;
if (unresolvedOldProps === unresolvedNewProps && oldState === newState && !hasContextChanged() && !checkHasForceUpdateAfterProcessing()) {
if (typeof instance.componentDidUpdate === "function") {
if (unresolvedOldProps !== current2.memoizedProps || oldState !== current2.memoizedState) {
workInProgress2.flags |= Update;
}
}
if (typeof instance.getSnapshotBeforeUpdate === "function") {
if (unresolvedOldProps !== current2.memoizedProps || oldState !== current2.memoizedState) {
workInProgress2.flags |= Snapshot;
}
}
return false;
}
if (typeof getDerivedStateFromProps === "function") {
applyDerivedStateFromProps(workInProgress2, ctor, getDerivedStateFromProps, newProps);
newState = workInProgress2.memoizedState;
}
var shouldUpdate = checkHasForceUpdateAfterProcessing() || checkShouldComponentUpdate(workInProgress2, ctor, oldProps, newProps, oldState, newState, nextContext);
if (shouldUpdate) {
if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillUpdate === "function" || typeof instance.componentWillUpdate === "function")) {
if (typeof instance.componentWillUpdate === "function") {
instance.componentWillUpdate(newProps, newState, nextContext);
}
if (typeof instance.UNSAFE_componentWillUpdate === "function") {
instance.UNSAFE_componentWillUpdate(newProps, newState, nextContext);
}
}
if (typeof instance.componentDidUpdate === "function") {
workInProgress2.flags |= Update;
}
if (typeof instance.getSnapshotBeforeUpdate === "function") {
workInProgress2.flags |= Snapshot;
}
} else {
if (typeof instance.componentDidUpdate === "function") {
if (unresolvedOldProps !== current2.memoizedProps || oldState !== current2.memoizedState) {
workInProgress2.flags |= Update;
}
}
if (typeof instance.getSnapshotBeforeUpdate === "function") {
if (unresolvedOldProps !== current2.memoizedProps || oldState !== current2.memoizedState) {
workInProgress2.flags |= Snapshot;
}
}
workInProgress2.memoizedProps = newProps;
workInProgress2.memoizedState = newState;
}
instance.props = newProps;
instance.state = newState;
instance.context = nextContext;
return shouldUpdate;
}
var didWarnAboutMaps;
var didWarnAboutGenerators;
var didWarnAboutStringRefs;
var ownerHasKeyUseWarning;
var ownerHasFunctionTypeWarning;
var warnForMissingKey = function(child, returnFiber) {
};
{
didWarnAboutMaps = false;
didWarnAboutGenerators = false;
didWarnAboutStringRefs = {};
ownerHasKeyUseWarning = {};
ownerHasFunctionTypeWarning = {};
warnForMissingKey = function(child, returnFiber) {
if (child === null || typeof child !== "object") {
return;
}
if (!child._store || child._store.validated || child.key != null) {
return;
}
if (!(typeof child._store === "object")) {
{
throw Error("React Component in warnForMissingKey should have a _store. This error is likely caused by a bug in React. Please file an issue.");
}
}
child._store.validated = true;
var componentName = getComponentName(returnFiber.type) || "Component";
if (ownerHasKeyUseWarning[componentName]) {
return;
}
ownerHasKeyUseWarning[componentName] = true;
error('Each child in a list should have a unique "key" prop. See https://reactjs.org/link/warning-keys for more information.');
};
}
var isArray$1 = Array.isArray;
function coerceRef(returnFiber, current2, element) {
var mixedRef = element.ref;
if (mixedRef !== null && typeof mixedRef !== "function" && typeof mixedRef !== "object") {
{
if ((returnFiber.mode & StrictMode || warnAboutStringRefs) && !(element._owner && element._self && element._owner.stateNode !== element._self)) {
var componentName = getComponentName(returnFiber.type) || "Component";
if (!didWarnAboutStringRefs[componentName]) {
{
error('A string ref, "%s", has been found within a strict mode tree. String refs are a source of potential bugs and should be avoided. We recommend using useRef() or createRef() instead. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref', mixedRef);
}
didWarnAboutStringRefs[componentName] = true;
}
}
}
if (element._owner) {
var owner = element._owner;
var inst;
if (owner) {
var ownerFiber = owner;
if (!(ownerFiber.tag === ClassComponent)) {
{
throw Error("Function components cannot have string refs. We recommend using useRef() instead. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref");
}
}
inst = ownerFiber.stateNode;
}
if (!inst) {
{
throw Error("Missing owner for string ref " + mixedRef + ". This error is likely caused by a bug in React. Please file an issue.");
}
}
var stringRef = "" + mixedRef;
if (current2 !== null && current2.ref !== null && typeof current2.ref === "function" && current2.ref._stringRef === stringRef) {
return current2.ref;
}
var ref = function(value) {
var refs = inst.refs;
if (refs === emptyRefsObject) {
refs = inst.refs = {};
}
if (value === null) {
delete refs[stringRef];
} else {
refs[stringRef] = value;
}
};
ref._stringRef = stringRef;
return ref;
} else {
if (!(typeof mixedRef === "string")) {
{
throw Error("Expected ref to be a function, a string, an object returned by React.createRef(), or null.");
}
}
if (!element._owner) {
{
throw Error("Element ref was specified as a string (" + mixedRef + ") but no owner was set. This could happen for one of the following reasons:\n1. You may be adding a ref to a function component\n2. You may be adding a ref to a component that was not created inside a component's render method\n3. You have multiple copies of React loaded\nSee https://reactjs.org/link/refs-must-have-owner for more information.");
}
}
}
}
return mixedRef;
}
function throwOnInvalidObjectType(returnFiber, newChild) {
if (returnFiber.type !== "textarea") {
{
{
throw Error("Objects are not valid as a React child (found: " + (Object.prototype.toString.call(newChild) === "[object Object]" ? "object with keys {" + Object.keys(newChild).join(", ") + "}" : newChild) + "). If you meant to render a collection of children, use an array instead.");
}
}
}
}
function warnOnFunctionType(returnFiber) {
{
var componentName = getComponentName(returnFiber.type) || "Component";
if (ownerHasFunctionTypeWarning[componentName]) {
return;
}
ownerHasFunctionTypeWarning[componentName] = true;
error("Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render. Or maybe you meant to call this function rather than return it.");
}
}
function ChildReconciler(shouldTrackSideEffects) {
function deleteChild(returnFiber, childToDelete) {
if (!shouldTrackSideEffects) {
return;
}
var last = returnFiber.lastEffect;
if (last !== null) {
last.nextEffect = childToDelete;
returnFiber.lastEffect = childToDelete;
} else {
returnFiber.firstEffect = returnFiber.lastEffect = childToDelete;
}
childToDelete.nextEffect = null;
childToDelete.flags = Deletion;
}
function deleteRemainingChildren(returnFiber, currentFirstChild) {
if (!shouldTrackSideEffects) {
return null;
}
var childToDelete = currentFirstChild;
while (childToDelete !== null) {
deleteChild(returnFiber, childToDelete);
childToDelete = childToDelete.sibling;
}
return null;
}
function mapRemainingChildren(returnFiber, currentFirstChild) {
var existingChildren = new Map();
var existingChild = currentFirstChild;
while (existingChild !== null) {
if (existingChild.key !== null) {
existingChildren.set(existingChild.key, existingChild);
} else {
existingChildren.set(existingChild.index, existingChild);
}
existingChild = existingChild.sibling;
}
return existingChildren;
}
function useFiber(fiber, pendingProps) {
var clone = createWorkInProgress(fiber, pendingProps);
clone.index = 0;
clone.sibling = null;
return clone;
}
function placeChild(newFiber, lastPlacedIndex, newIndex) {
newFiber.index = newIndex;
if (!shouldTrackSideEffects) {
return lastPlacedIndex;
}
var current2 = newFiber.alternate;
if (current2 !== null) {
var oldIndex = current2.index;
if (oldIndex < lastPlacedIndex) {
newFiber.flags = Placement;
return lastPlacedIndex;
} else {
return oldIndex;
}
} else {
newFiber.flags = Placement;
return lastPlacedIndex;
}
}
function placeSingleChild(newFiber) {
if (shouldTrackSideEffects && newFiber.alternate === null) {
newFiber.flags = Placement;
}
return newFiber;
}
function updateTextNode(returnFiber, current2, textContent, lanes) {
if (current2 === null || current2.tag !== HostText) {
var created = createFiberFromText(textContent, returnFiber.mode, lanes);
created.return = returnFiber;
return created;
} else {
var existing = useFiber(current2, textContent);
existing.return = returnFiber;
return existing;
}
}
function updateElement(returnFiber, current2, element, lanes) {
if (current2 !== null) {
if (current2.elementType === element.type || isCompatibleFamilyForHotReloading(current2, element)) {
var existing = useFiber(current2, element.props);
existing.ref = coerceRef(returnFiber, current2, element);
existing.return = returnFiber;
{
existing._debugSource = element._source;
existing._debugOwner = element._owner;
}
return existing;
}
}
var created = createFiberFromElement(element, returnFiber.mode, lanes);
created.ref = coerceRef(returnFiber, current2, element);
created.return = returnFiber;
return created;
}
function updatePortal(returnFiber, current2, portal, lanes) {
if (current2 === null || current2.tag !== HostPortal || current2.stateNode.containerInfo !== portal.containerInfo || current2.stateNode.implementation !== portal.implementation) {
var created = createFiberFromPortal(portal, returnFiber.mode, lanes);
created.return = returnFiber;
return created;
} else {
var existing = useFiber(current2, portal.children || []);
existing.return = returnFiber;
return existing;
}
}
function updateFragment2(returnFiber, current2, fragment, lanes, key) {
if (current2 === null || current2.tag !== Fragment) {
var created = createFiberFromFragment(fragment, returnFiber.mode, lanes, key);
created.return = returnFiber;
return created;
} else {
var existing = useFiber(current2, fragment);
existing.return = returnFiber;
return existing;
}
}
function createChild(returnFiber, newChild, lanes) {
if (typeof newChild === "string" || typeof newChild === "number") {
var created = createFiberFromText("" + newChild, returnFiber.mode, lanes);
created.return = returnFiber;
return created;
}
if (typeof newChild === "object" && newChild !== null) {
switch (newChild.$$typeof) {
case REACT_ELEMENT_TYPE: {
var _created = createFiberFromElement(newChild, returnFiber.mode, lanes);
_created.ref = coerceRef(returnFiber, null, newChild);
_created.return = returnFiber;
return _created;
}
case REACT_PORTAL_TYPE: {
var _created2 = createFiberFromPortal(newChild, returnFiber.mode, lanes);
_created2.return = returnFiber;
return _created2;
}
}
if (isArray$1(newChild) || getIteratorFn(newChild)) {
var _created3 = createFiberFromFragment(newChild, returnFiber.mode, lanes, null);
_created3.return = returnFiber;
return _created3;
}
throwOnInvalidObjectType(returnFiber, newChild);
}
{
if (typeof newChild === "function") {
warnOnFunctionType(returnFiber);
}
}
return null;
}
function updateSlot(returnFiber, oldFiber, newChild, lanes) {
var key = oldFiber !== null ? oldFiber.key : null;
if (typeof newChild === "string" || typeof newChild === "number") {
if (key !== null) {
return null;
}
return updateTextNode(returnFiber, oldFiber, "" + newChild, lanes);
}
if (typeof newChild === "object" && newChild !== null) {
switch (newChild.$$typeof) {
case REACT_ELEMENT_TYPE: {
if (newChild.key === key) {
if (newChild.type === REACT_FRAGMENT_TYPE) {
return updateFragment2(returnFiber, oldFiber, newChild.props.children, lanes, key);
}
return updateElement(returnFiber, oldFiber, newChild, lanes);
} else {
return null;
}
}
case REACT_PORTAL_TYPE: {
if (newChild.key === key) {
return updatePortal(returnFiber, oldFiber, newChild, lanes);
} else {
return null;
}
}
}
if (isArray$1(newChild) || getIteratorFn(newChild)) {
if (key !== null) {
return null;
}
return updateFragment2(returnFiber, oldFiber, newChild, lanes, null);
}
throwOnInvalidObjectType(returnFiber, newChild);
}
{
if (typeof newChild === "function") {
warnOnFunctionType(returnFiber);
}
}
return null;
}
function updateFromMap(existingChildren, returnFiber, newIdx, newChild, lanes) {
if (typeof newChild === "string" || typeof newChild === "number") {
var matchedFiber = existingChildren.get(newIdx) || null;
return updateTextNode(returnFiber, matchedFiber, "" + newChild, lanes);
}
if (typeof newChild === "object" && newChild !== null) {
switch (newChild.$$typeof) {
case REACT_ELEMENT_TYPE: {
var _matchedFiber = existingChildren.get(newChild.key === null ? newIdx : newChild.key) || null;
if (newChild.type === REACT_FRAGMENT_TYPE) {
return updateFragment2(returnFiber, _matchedFiber, newChild.props.children, lanes, newChild.key);
}
return updateElement(returnFiber, _matchedFiber, newChild, lanes);
}
case REACT_PORTAL_TYPE: {
var _matchedFiber2 = existingChildren.get(newChild.key === null ? newIdx : newChild.key) || null;
return updatePortal(returnFiber, _matchedFiber2, newChild, lanes);
}
}
if (isArray$1(newChild) || getIteratorFn(newChild)) {
var _matchedFiber3 = existingChildren.get(newIdx) || null;
return updateFragment2(returnFiber, _matchedFiber3, newChild, lanes, null);
}
throwOnInvalidObjectType(returnFiber, newChild);
}
{
if (typeof newChild === "function") {
warnOnFunctionType(returnFiber);
}
}
return null;
}
function warnOnInvalidKey(child, knownKeys, returnFiber) {
{
if (typeof child !== "object" || child === null) {
return knownKeys;
}
switch (child.$$typeof) {
case REACT_ELEMENT_TYPE:
case REACT_PORTAL_TYPE:
warnForMissingKey(child, returnFiber);
var key = child.key;
if (typeof key !== "string") {
break;
}
if (knownKeys === null) {
knownKeys = new Set();
knownKeys.add(key);
break;
}
if (!knownKeys.has(key)) {
knownKeys.add(key);
break;
}
error("Encountered two children with the same key, `%s`. Keys should be unique so that components maintain their identity across updates. Non-unique keys may cause children to be duplicated and/or omitted \u2014 the behavior is unsupported and could change in a future version.", key);
break;
}
}
return knownKeys;
}
function reconcileChildrenArray(returnFiber, currentFirstChild, newChildren, lanes) {
{
var knownKeys = null;
for (var i = 0; i < newChildren.length; i++) {
var child = newChildren[i];
knownKeys = warnOnInvalidKey(child, knownKeys, returnFiber);
}
}
var resultingFirstChild = null;
var previousNewFiber = null;
var oldFiber = currentFirstChild;
var lastPlacedIndex = 0;
var newIdx = 0;
var nextOldFiber = null;
for (; oldFiber !== null && newIdx < newChildren.length; newIdx++) {
if (oldFiber.index > newIdx) {
nextOldFiber = oldFiber;
oldFiber = null;
} else {
nextOldFiber = oldFiber.sibling;
}
var newFiber = updateSlot(returnFiber, oldFiber, newChildren[newIdx], lanes);
if (newFiber === null) {
if (oldFiber === null) {
oldFiber = nextOldFiber;
}
break;
}
if (shouldTrackSideEffects) {
if (oldFiber && newFiber.alternate === null) {
deleteChild(returnFiber, oldFiber);
}
}
lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx);
if (previousNewFiber === null) {
resultingFirstChild = newFiber;
} else {
previousNewFiber.sibling = newFiber;
}
previousNewFiber = newFiber;
oldFiber = nextOldFiber;
}
if (newIdx === newChildren.length) {
deleteRemainingChildren(returnFiber, oldFiber);
return resultingFirstChild;
}
if (oldFiber === null) {
for (; newIdx < newChildren.length; newIdx++) {
var _newFiber = createChild(returnFiber, newChildren[newIdx], lanes);
if (_newFiber === null) {
continue;
}
lastPlacedIndex = placeChild(_newFiber, lastPlacedIndex, newIdx);
if (previousNewFiber === null) {
resultingFirstChild = _newFiber;
} else {
previousNewFiber.sibling = _newFiber;
}
previousNewFiber = _newFiber;
}
return resultingFirstChild;
}
var existingChildren = mapRemainingChildren(returnFiber, oldFiber);
for (; newIdx < newChildren.length; newIdx++) {
var _newFiber2 = updateFromMap(existingChildren, returnFiber, newIdx, newChildren[newIdx], lanes);
if (_newFiber2 !== null) {
if (shouldTrackSideEffects) {
if (_newFiber2.alternate !== null) {
existingChildren.delete(_newFiber2.key === null ? newIdx : _newFiber2.key);
}
}
lastPlacedIndex = placeChild(_newFiber2, lastPlacedIndex, newIdx);
if (previousNewFiber === null) {
resultingFirstChild = _newFiber2;
} else {
previousNewFiber.sibling = _newFiber2;
}
previousNewFiber = _newFiber2;
}
}
if (shouldTrackSideEffects) {
existingChildren.forEach(function(child2) {
return deleteChild(returnFiber, child2);
});
}
return resultingFirstChild;
}
function reconcileChildrenIterator(returnFiber, currentFirstChild, newChildrenIterable, lanes) {
var iteratorFn = getIteratorFn(newChildrenIterable);
if (!(typeof iteratorFn === "function")) {
{
throw Error("An object is not an iterable. This error is likely caused by a bug in React. Please file an issue.");
}
}
{
if (typeof Symbol === "function" && newChildrenIterable[Symbol.toStringTag] === "Generator") {
if (!didWarnAboutGenerators) {
error("Using Generators as children is unsupported and will likely yield unexpected results because enumerating a generator mutates it. You may convert it to an array with `Array.from()` or the `[...spread]` operator before rendering. Keep in mind you might need to polyfill these features for older browsers.");
}
didWarnAboutGenerators = true;
}
if (newChildrenIterable.entries === iteratorFn) {
if (!didWarnAboutMaps) {
error("Using Maps as children is not supported. Use an array of keyed ReactElements instead.");
}
didWarnAboutMaps = true;
}
var _newChildren = iteratorFn.call(newChildrenIterable);
if (_newChildren) {
var knownKeys = null;
var _step = _newChildren.next();
for (; !_step.done; _step = _newChildren.next()) {
var child = _step.value;
knownKeys = warnOnInvalidKey(child, knownKeys, returnFiber);
}
}
}
var newChildren = iteratorFn.call(newChildrenIterable);
if (!(newChildren != null)) {
{
throw Error("An iterable object provided no iterator.");
}
}
var resultingFirstChild = null;
var previousNewFiber = null;
var oldFiber = currentFirstChild;
var lastPlacedIndex = 0;
var newIdx = 0;
var nextOldFiber = null;
var step = newChildren.next();
for (; oldFiber !== null && !step.done; newIdx++, step = newChildren.next()) {
if (oldFiber.index > newIdx) {
nextOldFiber = oldFiber;
oldFiber = null;
} else {
nextOldFiber = oldFiber.sibling;
}
var newFiber = updateSlot(returnFiber, oldFiber, step.value, lanes);
if (newFiber === null) {
if (oldFiber === null) {
oldFiber = nextOldFiber;
}
break;
}
if (shouldTrackSideEffects) {
if (oldFiber && newFiber.alternate === null) {
deleteChild(returnFiber, oldFiber);
}
}
lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx);
if (previousNewFiber === null) {
resultingFirstChild = newFiber;
} else {
previousNewFiber.sibling = newFiber;
}
previousNewFiber = newFiber;
oldFiber = nextOldFiber;
}
if (step.done) {
deleteRemainingChildren(returnFiber, oldFiber);
return resultingFirstChild;
}
if (oldFiber === null) {
for (; !step.done; newIdx++, step = newChildren.next()) {
var _newFiber3 = createChild(returnFiber, step.value, lanes);
if (_newFiber3 === null) {
continue;
}
lastPlacedIndex = placeChild(_newFiber3, lastPlacedIndex, newIdx);
if (previousNewFiber === null) {
resultingFirstChild = _newFiber3;
} else {
previousNewFiber.sibling = _newFiber3;
}
previousNewFiber = _newFiber3;
}
return resultingFirstChild;
}
var existingChildren = mapRemainingChildren(returnFiber, oldFiber);
for (; !step.done; newIdx++, step = newChildren.next()) {
var _newFiber4 = updateFromMap(existingChildren, returnFiber, newIdx, step.value, lanes);
if (_newFiber4 !== null) {
if (shouldTrackSideEffects) {
if (_newFiber4.alternate !== null) {
existingChildren.delete(_newFiber4.key === null ? newIdx : _newFiber4.key);
}
}
lastPlacedIndex = placeChild(_newFiber4, lastPlacedIndex, newIdx);
if (previousNewFiber === null) {
resultingFirstChild = _newFiber4;
} else {
previousNewFiber.sibling = _newFiber4;
}
previousNewFiber = _newFiber4;
}
}
if (shouldTrackSideEffects) {
existingChildren.forEach(function(child2) {
return deleteChild(returnFiber, child2);
});
}
return resultingFirstChild;
}
function reconcileSingleTextNode(returnFiber, currentFirstChild, textContent, lanes) {
if (currentFirstChild !== null && currentFirstChild.tag === HostText) {
deleteRemainingChildren(returnFiber, currentFirstChild.sibling);
var existing = useFiber(currentFirstChild, textContent);
existing.return = returnFiber;
return existing;
}
deleteRemainingChildren(returnFiber, currentFirstChild);
var created = createFiberFromText(textContent, returnFiber.mode, lanes);
created.return = returnFiber;
return created;
}
function reconcileSingleElement(returnFiber, currentFirstChild, element, lanes) {
var key = element.key;
var child = currentFirstChild;
while (child !== null) {
if (child.key === key) {
switch (child.tag) {
case Fragment: {
if (element.type === REACT_FRAGMENT_TYPE) {
deleteRemainingChildren(returnFiber, child.sibling);
var existing = useFiber(child, element.props.children);
existing.return = returnFiber;
{
existing._debugSource = element._source;
existing._debugOwner = element._owner;
}
return existing;
}
break;
}
case Block:
default: {
if (child.elementType === element.type || isCompatibleFamilyForHotReloading(child, element)) {
deleteRemainingChildren(returnFiber, child.sibling);
var _existing3 = useFiber(child, element.props);
_existing3.ref = coerceRef(returnFiber, child, element);
_existing3.return = returnFiber;
{
_existing3._debugSource = element._source;
_existing3._debugOwner = element._owner;
}
return _existing3;
}
break;
}
}
deleteRemainingChildren(returnFiber, child);
break;
} else {
deleteChild(returnFiber, child);
}
child = child.sibling;
}
if (element.type === REACT_FRAGMENT_TYPE) {
var created = createFiberFromFragment(element.props.children, returnFiber.mode, lanes, element.key);
created.return = returnFiber;
return created;
} else {
var _created4 = createFiberFromElement(element, returnFiber.mode, lanes);
_created4.ref = coerceRef(returnFiber, currentFirstChild, element);
_created4.return = returnFiber;
return _created4;
}
}
function reconcileSinglePortal(returnFiber, currentFirstChild, portal, lanes) {
var key = portal.key;
var child = currentFirstChild;
while (child !== null) {
if (child.key === key) {
if (child.tag === HostPortal && child.stateNode.containerInfo === portal.containerInfo && child.stateNode.implementation === portal.implementation) {
deleteRemainingChildren(returnFiber, child.sibling);
var existing = useFiber(child, portal.children || []);
existing.return = returnFiber;
return existing;
} else {
deleteRemainingChildren(returnFiber, child);
break;
}
} else {
deleteChild(returnFiber, child);
}
child = child.sibling;
}
var created = createFiberFromPortal(portal, returnFiber.mode, lanes);
created.return = returnFiber;
return created;
}
function reconcileChildFibers2(returnFiber, currentFirstChild, newChild, lanes) {
var isUnkeyedTopLevelFragment = typeof newChild === "object" && newChild !== null && newChild.type === REACT_FRAGMENT_TYPE && newChild.key === null;
if (isUnkeyedTopLevelFragment) {
newChild = newChild.props.children;
}
var isObject = typeof newChild === "object" && newChild !== null;
if (isObject) {
switch (newChild.$$typeof) {
case REACT_ELEMENT_TYPE:
return placeSingleChild(reconcileSingleElement(returnFiber, currentFirstChild, newChild, lanes));
case REACT_PORTAL_TYPE:
return placeSingleChild(reconcileSinglePortal(returnFiber, currentFirstChild, newChild, lanes));
}
}
if (typeof newChild === "string" || typeof newChild === "number") {
return placeSingleChild(reconcileSingleTextNode(returnFiber, currentFirstChild, "" + newChild, lanes));
}
if (isArray$1(newChild)) {
return reconcileChildrenArray(returnFiber, currentFirstChild, newChild, lanes);
}
if (getIteratorFn(newChild)) {
return reconcileChildrenIterator(returnFiber, currentFirstChild, newChild, lanes);
}
if (isObject) {
throwOnInvalidObjectType(returnFiber, newChild);
}
{
if (typeof newChild === "function") {
warnOnFunctionType(returnFiber);
}
}
if (typeof newChild === "undefined" && !isUnkeyedTopLevelFragment) {
switch (returnFiber.tag) {
case ClassComponent: {
{
var instance = returnFiber.stateNode;
if (instance.render._isMockFunction) {
break;
}
}
}
case Block:
case FunctionComponent:
case ForwardRef:
case SimpleMemoComponent: {
{
{
throw Error((getComponentName(returnFiber.type) || "Component") + "(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.");
}
}
}
}
}
return deleteRemainingChildren(returnFiber, currentFirstChild);
}
return reconcileChildFibers2;
}
var reconcileChildFibers = ChildReconciler(true);
var mountChildFibers = ChildReconciler(false);
function cloneChildFibers(current2, workInProgress2) {
if (!(current2 === null || workInProgress2.child === current2.child)) {
{
throw Error("Resuming work not yet implemented.");
}
}
if (workInProgress2.child === null) {
return;
}
var currentChild = workInProgress2.child;
var newChild = createWorkInProgress(currentChild, currentChild.pendingProps);
workInProgress2.child = newChild;
newChild.return = workInProgress2;
while (currentChild.sibling !== null) {
currentChild = currentChild.sibling;
newChild = newChild.sibling = createWorkInProgress(currentChild, currentChild.pendingProps);
newChild.return = workInProgress2;
}
newChild.sibling = null;
}
function resetChildFibers(workInProgress2, lanes) {
var child = workInProgress2.child;
while (child !== null) {
resetWorkInProgress(child, lanes);
child = child.sibling;
}
}
var NO_CONTEXT = {};
var contextStackCursor$1 = createCursor(NO_CONTEXT);
var contextFiberStackCursor = createCursor(NO_CONTEXT);
var rootInstanceStackCursor = createCursor(NO_CONTEXT);
function requiredContext(c) {
if (!(c !== NO_CONTEXT)) {
{
throw Error("Expected host context to exist. This error is likely caused by a bug in React. Please file an issue.");
}
}
return c;
}
function getRootHostContainer() {
var rootInstance = requiredContext(rootInstanceStackCursor.current);
return rootInstance;
}
function pushHostContainer(fiber, nextRootInstance) {
push(rootInstanceStackCursor, nextRootInstance, fiber);
push(contextFiberStackCursor, fiber, fiber);
push(contextStackCursor$1, NO_CONTEXT, fiber);
var nextRootContext = getRootHostContext(nextRootInstance);
pop(contextStackCursor$1, fiber);
push(contextStackCursor$1, nextRootContext, fiber);
}
function popHostContainer(fiber) {
pop(contextStackCursor$1, fiber);
pop(contextFiberStackCursor, fiber);
pop(rootInstanceStackCursor, fiber);
}
function getHostContext() {
var context = requiredContext(contextStackCursor$1.current);
return context;
}
function pushHostContext(fiber) {
var rootInstance = requiredContext(rootInstanceStackCursor.current);
var context = requiredContext(contextStackCursor$1.current);
var nextContext = getChildHostContext(context, fiber.type);
if (context === nextContext) {
return;
}
push(contextFiberStackCursor, fiber, fiber);
push(contextStackCursor$1, nextContext, fiber);
}
function popHostContext(fiber) {
if (contextFiberStackCursor.current !== fiber) {
return;
}
pop(contextStackCursor$1, fiber);
pop(contextFiberStackCursor, fiber);
}
var DefaultSuspenseContext = 0;
var SubtreeSuspenseContextMask = 1;
var InvisibleParentSuspenseContext = 1;
var ForceSuspenseFallback = 2;
var suspenseStackCursor = createCursor(DefaultSuspenseContext);
function hasSuspenseContext(parentContext, flag) {
return (parentContext & flag) !== 0;
}
function setDefaultShallowSuspenseContext(parentContext) {
return parentContext & SubtreeSuspenseContextMask;
}
function setShallowSuspenseContext(parentContext, shallowContext) {
return parentContext & SubtreeSuspenseContextMask | shallowContext;
}
function addSubtreeSuspenseContext(parentContext, subtreeContext) {
return parentContext | subtreeContext;
}
function pushSuspenseContext(fiber, newContext) {
push(suspenseStackCursor, newContext, fiber);
}
function popSuspenseContext(fiber) {
pop(suspenseStackCursor, fiber);
}
function shouldCaptureSuspense(workInProgress2, hasInvisibleParent) {
var nextState = workInProgress2.memoizedState;
if (nextState !== null) {
if (nextState.dehydrated !== null) {
return true;
}
return false;
}
var props = workInProgress2.memoizedProps;
if (props.fallback === void 0) {
return false;
}
if (props.unstable_avoidThisFallback !== true) {
return true;
}
if (hasInvisibleParent) {
return false;
}
return true;
}
function findFirstSuspended(row) {
var node = row;
while (node !== null) {
if (node.tag === SuspenseComponent) {
var state = node.memoizedState;
if (state !== null) {
var dehydrated = state.dehydrated;
if (dehydrated === null || isSuspenseInstancePending(dehydrated) || isSuspenseInstanceFallback(dehydrated)) {
return node;
}
}
} else if (node.tag === SuspenseListComponent && node.memoizedProps.revealOrder !== void 0) {
var didSuspend = (node.flags & DidCapture) !== NoFlags;
if (didSuspend) {
return node;
}
} else if (node.child !== null) {
node.child.return = node;
node = node.child;
continue;
}
if (node === row) {
return null;
}
while (node.sibling === null) {
if (node.return === null || node.return === row) {
return null;
}
node = node.return;
}
node.sibling.return = node.return;
node = node.sibling;
}
return null;
}
var NoFlags$1 = 0;
var HasEffect = 1;
var Layout = 2;
var Passive$1 = 4;
var hydrationParentFiber = null;
var nextHydratableInstance = null;
var isHydrating = false;
function enterHydrationState(fiber) {
var parentInstance = fiber.stateNode.containerInfo;
nextHydratableInstance = getFirstHydratableChild(parentInstance);
hydrationParentFiber = fiber;
isHydrating = true;
return true;
}
function deleteHydratableInstance(returnFiber, instance) {
{
switch (returnFiber.tag) {
case HostRoot:
didNotHydrateContainerInstance(returnFiber.stateNode.containerInfo, instance);
break;
case HostComponent:
didNotHydrateInstance(returnFiber.type, returnFiber.memoizedProps, returnFiber.stateNode, instance);
break;
}
}
var childToDelete = createFiberFromHostInstanceForDeletion();
childToDelete.stateNode = instance;
childToDelete.return = returnFiber;
childToDelete.flags = Deletion;
if (returnFiber.lastEffect !== null) {
returnFiber.lastEffect.nextEffect = childToDelete;
returnFiber.lastEffect = childToDelete;
} else {
returnFiber.firstEffect = returnFiber.lastEffect = childToDelete;
}
}
function insertNonHydratedInstance(returnFiber, fiber) {
fiber.flags = fiber.flags & ~Hydrating | Placement;
{
switch (returnFiber.tag) {
case HostRoot: {
var parentContainer = returnFiber.stateNode.containerInfo;
switch (fiber.tag) {
case HostComponent:
var type = fiber.type;
var props = fiber.pendingProps;
didNotFindHydratableContainerInstance(parentContainer, type);
break;
case HostText:
var text = fiber.pendingProps;
didNotFindHydratableContainerTextInstance(parentContainer, text);
break;
}
break;
}
case HostComponent: {
var parentType = returnFiber.type;
var parentProps = returnFiber.memoizedProps;
var parentInstance = returnFiber.stateNode;
switch (fiber.tag) {
case HostComponent:
var _type = fiber.type;
var _props = fiber.pendingProps;
didNotFindHydratableInstance(parentType, parentProps, parentInstance, _type);
break;
case HostText:
var _text = fiber.pendingProps;
didNotFindHydratableTextInstance(parentType, parentProps, parentInstance, _text);
break;
case SuspenseComponent:
didNotFindHydratableSuspenseInstance(parentType, parentProps);
break;
}
break;
}
default:
return;
}
}
}
function tryHydrate(fiber, nextInstance) {
switch (fiber.tag) {
case HostComponent: {
var type = fiber.type;
var props = fiber.pendingProps;
var instance = canHydrateInstance(nextInstance, type);
if (instance !== null) {
fiber.stateNode = instance;
return true;
}
return false;
}
case HostText: {
var text = fiber.pendingProps;
var textInstance = canHydrateTextInstance(nextInstance, text);
if (textInstance !== null) {
fiber.stateNode = textInstance;
return true;
}
return false;
}
case SuspenseComponent: {
return false;
}
default:
return false;
}
}
function tryToClaimNextHydratableInstance(fiber) {
if (!isHydrating) {
return;
}
var nextInstance = nextHydratableInstance;
if (!nextInstance) {
insertNonHydratedInstance(hydrationParentFiber, fiber);
isHydrating = false;
hydrationParentFiber = fiber;
return;
}
var firstAttemptedInstance = nextInstance;
if (!tryHydrate(fiber, nextInstance)) {
nextInstance = getNextHydratableSibling(firstAttemptedInstance);
if (!nextInstance || !tryHydrate(fiber, nextInstance)) {
insertNonHydratedInstance(hydrationParentFiber, fiber);
isHydrating = false;
hydrationParentFiber = fiber;
return;
}
deleteHydratableInstance(hydrationParentFiber, firstAttemptedInstance);
}
hydrationParentFiber = fiber;
nextHydratableInstance = getFirstHydratableChild(nextInstance);
}
function prepareToHydrateHostInstance(fiber, rootContainerInstance, hostContext) {
var instance = fiber.stateNode;
var updatePayload = hydrateInstance(instance, fiber.type, fiber.memoizedProps, rootContainerInstance, hostContext, fiber);
fiber.updateQueue = updatePayload;
if (updatePayload !== null) {
return true;
}
return false;
}
function prepareToHydrateHostTextInstance(fiber) {
var textInstance = fiber.stateNode;
var textContent = fiber.memoizedProps;
var shouldUpdate = hydrateTextInstance(textInstance, textContent, fiber);
{
if (shouldUpdate) {
var returnFiber = hydrationParentFiber;
if (returnFiber !== null) {
switch (returnFiber.tag) {
case HostRoot: {
var parentContainer = returnFiber.stateNode.containerInfo;
didNotMatchHydratedContainerTextInstance(parentContainer, textInstance, textContent);
break;
}
case HostComponent: {
var parentType = returnFiber.type;
var parentProps = returnFiber.memoizedProps;
var parentInstance = returnFiber.stateNode;
didNotMatchHydratedTextInstance(parentType, parentProps, parentInstance, textInstance, textContent);
break;
}
}
}
}
}
return shouldUpdate;
}
function skipPastDehydratedSuspenseInstance(fiber) {
var suspenseState = fiber.memoizedState;
var suspenseInstance = suspenseState !== null ? suspenseState.dehydrated : null;
if (!suspenseInstance) {
{
throw Error("Expected to have a hydrated suspense instance. This error is likely caused by a bug in React. Please file an issue.");
}
}
return getNextHydratableInstanceAfterSuspenseInstance(suspenseInstance);
}
function popToNextHostParent(fiber) {
var parent = fiber.return;
while (parent !== null && parent.tag !== HostComponent && parent.tag !== HostRoot && parent.tag !== SuspenseComponent) {
parent = parent.return;
}
hydrationParentFiber = parent;
}
function popHydrationState(fiber) {
if (fiber !== hydrationParentFiber) {
return false;
}
if (!isHydrating) {
popToNextHostParent(fiber);
isHydrating = true;
return false;
}
var type = fiber.type;
if (fiber.tag !== HostComponent || type !== "head" && type !== "body" && !shouldSetTextContent(type, fiber.memoizedProps)) {
var nextInstance = nextHydratableInstance;
while (nextInstance) {
deleteHydratableInstance(fiber, nextInstance);
nextInstance = getNextHydratableSibling(nextInstance);
}
}
popToNextHostParent(fiber);
if (fiber.tag === SuspenseComponent) {
nextHydratableInstance = skipPastDehydratedSuspenseInstance(fiber);
} else {
nextHydratableInstance = hydrationParentFiber ? getNextHydratableSibling(fiber.stateNode) : null;
}
return true;
}
function resetHydrationState() {
hydrationParentFiber = null;
nextHydratableInstance = null;
isHydrating = false;
}
function getIsHydrating() {
return isHydrating;
}
var workInProgressSources = [];
var rendererSigil$1;
{
rendererSigil$1 = {};
}
function markSourceAsDirty(mutableSource) {
workInProgressSources.push(mutableSource);
}
function resetWorkInProgressVersions() {
for (var i = 0; i < workInProgressSources.length; i++) {
var mutableSource = workInProgressSources[i];
{
mutableSource._workInProgressVersionPrimary = null;
}
}
workInProgressSources.length = 0;
}
function getWorkInProgressVersion(mutableSource) {
{
return mutableSource._workInProgressVersionPrimary;
}
}
function setWorkInProgressVersion(mutableSource, version) {
{
mutableSource._workInProgressVersionPrimary = version;
}
workInProgressSources.push(mutableSource);
}
function warnAboutMultipleRenderersDEV(mutableSource) {
{
{
if (mutableSource._currentPrimaryRenderer == null) {
mutableSource._currentPrimaryRenderer = rendererSigil$1;
} else if (mutableSource._currentPrimaryRenderer !== rendererSigil$1) {
error("Detected multiple renderers concurrently rendering the same mutable source. This is currently unsupported.");
}
}
}
}
var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher, ReactCurrentBatchConfig$1 = ReactSharedInternals.ReactCurrentBatchConfig;
var didWarnAboutMismatchedHooksForComponent;
var didWarnAboutUseOpaqueIdentifier;
{
didWarnAboutUseOpaqueIdentifier = {};
didWarnAboutMismatchedHooksForComponent = new Set();
}
var renderLanes = NoLanes;
var currentlyRenderingFiber$1 = null;
var currentHook = null;
var workInProgressHook = null;
var didScheduleRenderPhaseUpdate = false;
var didScheduleRenderPhaseUpdateDuringThisPass = false;
var RE_RENDER_LIMIT = 25;
var currentHookNameInDev = null;
var hookTypesDev = null;
var hookTypesUpdateIndexDev = -1;
var ignorePreviousDependencies = false;
function mountHookTypesDev() {
{
var hookName = currentHookNameInDev;
if (hookTypesDev === null) {
hookTypesDev = [hookName];
} else {
hookTypesDev.push(hookName);
}
}
}
function updateHookTypesDev() {
{
var hookName = currentHookNameInDev;
if (hookTypesDev !== null) {
hookTypesUpdateIndexDev++;
if (hookTypesDev[hookTypesUpdateIndexDev] !== hookName) {
warnOnHookMismatchInDev(hookName);
}
}
}
}
function checkDepsAreArrayDev(deps) {
{
if (deps !== void 0 && deps !== null && !Array.isArray(deps)) {
error("%s received a final argument that is not an array (instead, received `%s`). When specified, the final argument must be an array.", currentHookNameInDev, typeof deps);
}
}
}
function warnOnHookMismatchInDev(currentHookName) {
{
var componentName = getComponentName(currentlyRenderingFiber$1.type);
if (!didWarnAboutMismatchedHooksForComponent.has(componentName)) {
didWarnAboutMismatchedHooksForComponent.add(componentName);
if (hookTypesDev !== null) {
var table = "";
var secondColumnStart = 30;
for (var i = 0; i <= hookTypesUpdateIndexDev; i++) {
var oldHookName = hookTypesDev[i];
var newHookName = i === hookTypesUpdateIndexDev ? currentHookName : oldHookName;
var row = i + 1 + ". " + oldHookName;
while (row.length < secondColumnStart) {
row += " ";
}
row += newHookName + "\n";
table += row;
}
error("React has detected a change in the order of Hooks called by %s. This will lead to bugs and errors if not fixed. For more information, read the Rules of Hooks: https://reactjs.org/link/rules-of-hooks\n\n Previous render Next render\n ------------------------------------------------------\n%s ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n", componentName, table);
}
}
}
}
function throwInvalidHookError() {
{
{
throw Error("Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.");
}
}
}
function areHookInputsEqual(nextDeps, prevDeps) {
{
if (ignorePreviousDependencies) {
return false;
}
}
if (prevDeps === null) {
{
error("%s received a final argument during this render, but not during the previous render. Even though the final argument is optional, its type cannot change between renders.", currentHookNameInDev);
}
return false;
}
{
if (nextDeps.length !== prevDeps.length) {
error("The final argument passed to %s changed size between renders. The order and size of this array must remain constant.\n\nPrevious: %s\nIncoming: %s", currentHookNameInDev, "[" + prevDeps.join(", ") + "]", "[" + nextDeps.join(", ") + "]");
}
}
for (var i = 0; i < prevDeps.length && i < nextDeps.length; i++) {
if (objectIs(nextDeps[i], prevDeps[i])) {
continue;
}
return false;
}
return true;
}
function renderWithHooks(current2, workInProgress2, Component, props, secondArg, nextRenderLanes) {
renderLanes = nextRenderLanes;
currentlyRenderingFiber$1 = workInProgress2;
{
hookTypesDev = current2 !== null ? current2._debugHookTypes : null;
hookTypesUpdateIndexDev = -1;
ignorePreviousDependencies = current2 !== null && current2.type !== workInProgress2.type;
}
workInProgress2.memoizedState = null;
workInProgress2.updateQueue = null;
workInProgress2.lanes = NoLanes;
{
if (current2 !== null && current2.memoizedState !== null) {
ReactCurrentDispatcher$1.current = HooksDispatcherOnUpdateInDEV;
} else if (hookTypesDev !== null) {
ReactCurrentDispatcher$1.current = HooksDispatcherOnMountWithHookTypesInDEV;
} else {
ReactCurrentDispatcher$1.current = HooksDispatcherOnMountInDEV;
}
}
var children = Component(props, secondArg);
if (didScheduleRenderPhaseUpdateDuringThisPass) {
var numberOfReRenders = 0;
do {
didScheduleRenderPhaseUpdateDuringThisPass = false;
if (!(numberOfReRenders < RE_RENDER_LIMIT)) {
{
throw Error("Too many re-renders. React limits the number of renders to prevent an infinite loop.");
}
}
numberOfReRenders += 1;
{
ignorePreviousDependencies = false;
}
currentHook = null;
workInProgressHook = null;
workInProgress2.updateQueue = null;
{
hookTypesUpdateIndexDev = -1;
}
ReactCurrentDispatcher$1.current = HooksDispatcherOnRerenderInDEV;
children = Component(props, secondArg);
} while (didScheduleRenderPhaseUpdateDuringThisPass);
}
ReactCurrentDispatcher$1.current = ContextOnlyDispatcher;
{
workInProgress2._debugHookTypes = hookTypesDev;
}
var didRenderTooFewHooks = currentHook !== null && currentHook.next !== null;
renderLanes = NoLanes;
currentlyRenderingFiber$1 = null;
currentHook = null;
workInProgressHook = null;
{
currentHookNameInDev = null;
hookTypesDev = null;
hookTypesUpdateIndexDev = -1;
}
didScheduleRenderPhaseUpdate = false;
if (!!didRenderTooFewHooks) {
{
throw Error("Rendered fewer hooks than expected. This may be caused by an accidental early return statement.");
}
}
return children;
}
function bailoutHooks(current2, workInProgress2, lanes) {
workInProgress2.updateQueue = current2.updateQueue;
workInProgress2.flags &= ~(Passive | Update);
current2.lanes = removeLanes(current2.lanes, lanes);
}
function resetHooksAfterThrow() {
ReactCurrentDispatcher$1.current = ContextOnlyDispatcher;
if (didScheduleRenderPhaseUpdate) {
var hook = currentlyRenderingFiber$1.memoizedState;
while (hook !== null) {
var queue = hook.queue;
if (queue !== null) {
queue.pending = null;
}
hook = hook.next;
}
didScheduleRenderPhaseUpdate = false;
}
renderLanes = NoLanes;
currentlyRenderingFiber$1 = null;
currentHook = null;
workInProgressHook = null;
{
hookTypesDev = null;
hookTypesUpdateIndexDev = -1;
currentHookNameInDev = null;
isUpdatingOpaqueValueInRenderPhase = false;
}
didScheduleRenderPhaseUpdateDuringThisPass = false;
}
function mountWorkInProgressHook() {
var hook = {
memoizedState: null,
baseState: null,
baseQueue: null,
queue: null,
next: null
};
if (workInProgressHook === null) {
currentlyRenderingFiber$1.memoizedState = workInProgressHook = hook;
} else {
workInProgressHook = workInProgressHook.next = hook;
}
return workInProgressHook;
}
function updateWorkInProgressHook() {
var nextCurrentHook;
if (currentHook === null) {
var current2 = currentlyRenderingFiber$1.alternate;
if (current2 !== null) {
nextCurrentHook = current2.memoizedState;
} else {
nextCurrentHook = null;
}
} else {
nextCurrentHook = currentHook.next;
}
var nextWorkInProgressHook;
if (workInProgressHook === null) {
nextWorkInProgressHook = currentlyRenderingFiber$1.memoizedState;
} else {
nextWorkInProgressHook = workInProgressHook.next;
}
if (nextWorkInProgressHook !== null) {
workInProgressHook = nextWorkInProgressHook;
nextWorkInProgressHook = workInProgressHook.next;
currentHook = nextCurrentHook;
} else {
if (!(nextCurrentHook !== null)) {
{
throw Error("Rendered more hooks than during the previous render.");
}
}
currentHook = nextCurrentHook;
var newHook = {
memoizedState: currentHook.memoizedState,
baseState: currentHook.baseState,
baseQueue: currentHook.baseQueue,
queue: currentHook.queue,
next: null
};
if (workInProgressHook === null) {
currentlyRenderingFiber$1.memoizedState = workInProgressHook = newHook;
} else {
workInProgressHook = workInProgressHook.next = newHook;
}
}
return workInProgressHook;
}
function createFunctionComponentUpdateQueue() {
return {
lastEffect: null
};
}
function basicStateReducer(state, action) {
return typeof action === "function" ? action(state) : action;
}
function mountReducer(reducer, initialArg, init) {
var hook = mountWorkInProgressHook();
var initialState;
if (init !== void 0) {
initialState = init(initialArg);
} else {
initialState = initialArg;
}
hook.memoizedState = hook.baseState = initialState;
var queue = hook.queue = {
pending: null,
dispatch: null,
lastRenderedReducer: reducer,
lastRenderedState: initialState
};
var dispatch = queue.dispatch = dispatchAction.bind(null, currentlyRenderingFiber$1, queue);
return [hook.memoizedState, dispatch];
}
function updateReducer(reducer, initialArg, init) {
var hook = updateWorkInProgressHook();
var queue = hook.queue;
if (!(queue !== null)) {
{
throw Error("Should have a queue. This is likely a bug in React. Please file an issue.");
}
}
queue.lastRenderedReducer = reducer;
var current2 = currentHook;
var baseQueue = current2.baseQueue;
var pendingQueue = queue.pending;
if (pendingQueue !== null) {
if (baseQueue !== null) {
var baseFirst = baseQueue.next;
var pendingFirst = pendingQueue.next;
baseQueue.next = pendingFirst;
pendingQueue.next = baseFirst;
}
{
if (current2.baseQueue !== baseQueue) {
error("Internal error: Expected work-in-progress queue to be a clone. This is a bug in React.");
}
}
current2.baseQueue = baseQueue = pendingQueue;
queue.pending = null;
}
if (baseQueue !== null) {
var first = baseQueue.next;
var newState = current2.baseState;
var newBaseState = null;
var newBaseQueueFirst = null;
var newBaseQueueLast = null;
var update = first;
do {
var updateLane = update.lane;
if (!isSubsetOfLanes(renderLanes, updateLane)) {
var clone = {
lane: updateLane,
action: update.action,
eagerReducer: update.eagerReducer,
eagerState: update.eagerState,
next: null
};
if (newBaseQueueLast === null) {
newBaseQueueFirst = newBaseQueueLast = clone;
newBaseState = newState;
} else {
newBaseQueueLast = newBaseQueueLast.next = clone;
}
currentlyRenderingFiber$1.lanes = mergeLanes(currentlyRenderingFiber$1.lanes, updateLane);
markSkippedUpdateLanes(updateLane);
} else {
if (newBaseQueueLast !== null) {
var _clone = {
lane: NoLane,
action: update.action,
eagerReducer: update.eagerReducer,
eagerState: update.eagerState,
next: null
};
newBaseQueueLast = newBaseQueueLast.next = _clone;
}
if (update.eagerReducer === reducer) {
newState = update.eagerState;
} else {
var action = update.action;
newState = reducer(newState, action);
}
}
update = update.next;
} while (update !== null && update !== first);
if (newBaseQueueLast === null) {
newBaseState = newState;
} else {
newBaseQueueLast.next = newBaseQueueFirst;
}
if (!objectIs(newState, hook.memoizedState)) {
markWorkInProgressReceivedUpdate();
}
hook.memoizedState = newState;
hook.baseState = newBaseState;
hook.baseQueue = newBaseQueueLast;
queue.lastRenderedState = newState;
}
var dispatch = queue.dispatch;
return [hook.memoizedState, dispatch];
}
function rerenderReducer(reducer, initialArg, init) {
var hook = updateWorkInProgressHook();
var queue = hook.queue;
if (!(queue !== null)) {
{
throw Error("Should have a queue. This is likely a bug in React. Please file an issue.");
}
}
queue.lastRenderedReducer = reducer;
var dispatch = queue.dispatch;
var lastRenderPhaseUpdate = queue.pending;
var newState = hook.memoizedState;
if (lastRenderPhaseUpdate !== null) {
queue.pending = null;
var firstRenderPhaseUpdate = lastRenderPhaseUpdate.next;
var update = firstRenderPhaseUpdate;
do {
var action = update.action;
newState = reducer(newState, action);
update = update.next;
} while (update !== firstRenderPhaseUpdate);
if (!objectIs(newState, hook.memoizedState)) {
markWorkInProgressReceivedUpdate();
}
hook.memoizedState = newState;
if (hook.baseQueue === null) {
hook.baseState = newState;
}
queue.lastRenderedState = newState;
}
return [newState, dispatch];
}
function readFromUnsubcribedMutableSource(root2, source, getSnapshot) {
{
warnAboutMultipleRenderersDEV(source);
}
var getVersion = source._getVersion;
var version = getVersion(source._source);
var isSafeToReadFromSource = false;
var currentRenderVersion = getWorkInProgressVersion(source);
if (currentRenderVersion !== null) {
isSafeToReadFromSource = currentRenderVersion === version;
} else {
isSafeToReadFromSource = isSubsetOfLanes(renderLanes, root2.mutableReadLanes);
if (isSafeToReadFromSource) {
setWorkInProgressVersion(source, version);
}
}
if (isSafeToReadFromSource) {
var snapshot = getSnapshot(source._source);
{
if (typeof snapshot === "function") {
error("Mutable source should not return a function as the snapshot value. Functions may close over mutable values and cause tearing.");
}
}
return snapshot;
} else {
markSourceAsDirty(source);
{
{
throw Error("Cannot read from mutable source during the current render without tearing. This is a bug in React. Please file an issue.");
}
}
}
}
function useMutableSource(hook, source, getSnapshot, subscribe) {
var root2 = getWorkInProgressRoot();
if (!(root2 !== null)) {
{
throw Error("Expected a work-in-progress root. This is a bug in React. Please file an issue.");
}
}
var getVersion = source._getVersion;
var version = getVersion(source._source);
var dispatcher = ReactCurrentDispatcher$1.current;
var _dispatcher$useState = dispatcher.useState(function() {
return readFromUnsubcribedMutableSource(root2, source, getSnapshot);
}), currentSnapshot = _dispatcher$useState[0], setSnapshot = _dispatcher$useState[1];
var snapshot = currentSnapshot;
var stateHook = workInProgressHook;
var memoizedState = hook.memoizedState;
var refs = memoizedState.refs;
var prevGetSnapshot = refs.getSnapshot;
var prevSource = memoizedState.source;
var prevSubscribe = memoizedState.subscribe;
var fiber = currentlyRenderingFiber$1;
hook.memoizedState = {
refs,
source,
subscribe
};
dispatcher.useEffect(function() {
refs.getSnapshot = getSnapshot;
refs.setSnapshot = setSnapshot;
var maybeNewVersion = getVersion(source._source);
if (!objectIs(version, maybeNewVersion)) {
var maybeNewSnapshot = getSnapshot(source._source);
{
if (typeof maybeNewSnapshot === "function") {
error("Mutable source should not return a function as the snapshot value. Functions may close over mutable values and cause tearing.");
}
}
if (!objectIs(snapshot, maybeNewSnapshot)) {
setSnapshot(maybeNewSnapshot);
var lane = requestUpdateLane(fiber);
markRootMutableRead(root2, lane);
}
markRootEntangled(root2, root2.mutableReadLanes);
}
}, [getSnapshot, source, subscribe]);
dispatcher.useEffect(function() {
var handleChange = function() {
var latestGetSnapshot = refs.getSnapshot;
var latestSetSnapshot = refs.setSnapshot;
try {
latestSetSnapshot(latestGetSnapshot(source._source));
var lane = requestUpdateLane(fiber);
markRootMutableRead(root2, lane);
} catch (error2) {
latestSetSnapshot(function() {
throw error2;
});
}
};
var unsubscribe = subscribe(source._source, handleChange);
{
if (typeof unsubscribe !== "function") {
error("Mutable source subscribe function must return an unsubscribe function.");
}
}
return unsubscribe;
}, [source, subscribe]);
if (!objectIs(prevGetSnapshot, getSnapshot) || !objectIs(prevSource, source) || !objectIs(prevSubscribe, subscribe)) {
var newQueue = {
pending: null,
dispatch: null,
lastRenderedReducer: basicStateReducer,
lastRenderedState: snapshot
};
newQueue.dispatch = setSnapshot = dispatchAction.bind(null, currentlyRenderingFiber$1, newQueue);
stateHook.queue = newQueue;
stateHook.baseQueue = null;
snapshot = readFromUnsubcribedMutableSource(root2, source, getSnapshot);
stateHook.memoizedState = stateHook.baseState = snapshot;
}
return snapshot;
}
function mountMutableSource(source, getSnapshot, subscribe) {
var hook = mountWorkInProgressHook();
hook.memoizedState = {
refs: {
getSnapshot,
setSnapshot: null
},
source,
subscribe
};
return useMutableSource(hook, source, getSnapshot, subscribe);
}
function updateMutableSource(source, getSnapshot, subscribe) {
var hook = updateWorkInProgressHook();
return useMutableSource(hook, source, getSnapshot, subscribe);
}
function mountState(initialState) {
var hook = mountWorkInProgressHook();
if (typeof initialState === "function") {
initialState = initialState();
}
hook.memoizedState = hook.baseState = initialState;
var queue = hook.queue = {
pending: null,
dispatch: null,
lastRenderedReducer: basicStateReducer,
lastRenderedState: initialState
};
var dispatch = queue.dispatch = dispatchAction.bind(null, currentlyRenderingFiber$1, queue);
return [hook.memoizedState, dispatch];
}
function updateState(initialState) {
return updateReducer(basicStateReducer);
}
function rerenderState(initialState) {
return rerenderReducer(basicStateReducer);
}
function pushEffect(tag, create, destroy, deps) {
var effect = {
tag,
create,
destroy,
deps,
next: null
};
var componentUpdateQueue = currentlyRenderingFiber$1.updateQueue;
if (componentUpdateQueue === null) {
componentUpdateQueue = createFunctionComponentUpdateQueue();
currentlyRenderingFiber$1.updateQueue = componentUpdateQueue;
componentUpdateQueue.lastEffect = effect.next = effect;
} else {
var lastEffect = componentUpdateQueue.lastEffect;
if (lastEffect === null) {
componentUpdateQueue.lastEffect = effect.next = effect;
} else {
var firstEffect = lastEffect.next;
lastEffect.next = effect;
effect.next = firstEffect;
componentUpdateQueue.lastEffect = effect;
}
}
return effect;
}
function mountRef(initialValue) {
var hook = mountWorkInProgressHook();
var ref = {
current: initialValue
};
{
Object.seal(ref);
}
hook.memoizedState = ref;
return ref;
}
function updateRef(initialValue) {
var hook = updateWorkInProgressHook();
return hook.memoizedState;
}
function mountEffectImpl(fiberFlags, hookFlags, create, deps) {
var hook = mountWorkInProgressHook();
var nextDeps = deps === void 0 ? null : deps;
currentlyRenderingFiber$1.flags |= fiberFlags;
hook.memoizedState = pushEffect(HasEffect | hookFlags, create, void 0, nextDeps);
}
function updateEffectImpl(fiberFlags, hookFlags, create, deps) {
var hook = updateWorkInProgressHook();
var nextDeps = deps === void 0 ? null : deps;
var destroy = void 0;
if (currentHook !== null) {
var prevEffect = currentHook.memoizedState;
destroy = prevEffect.destroy;
if (nextDeps !== null) {
var prevDeps = prevEffect.deps;
if (areHookInputsEqual(nextDeps, prevDeps)) {
pushEffect(hookFlags, create, destroy, nextDeps);
return;
}
}
}
currentlyRenderingFiber$1.flags |= fiberFlags;
hook.memoizedState = pushEffect(HasEffect | hookFlags, create, destroy, nextDeps);
}
function mountEffect(create, deps) {
{
if (typeof jest !== "undefined") {
warnIfNotCurrentlyActingEffectsInDEV(currentlyRenderingFiber$1);
}
}
return mountEffectImpl(Update | Passive, Passive$1, create, deps);
}
function updateEffect(create, deps) {
{
if (typeof jest !== "undefined") {
warnIfNotCurrentlyActingEffectsInDEV(currentlyRenderingFiber$1);
}
}
return updateEffectImpl(Update | Passive, Passive$1, create, deps);
}
function mountLayoutEffect(create, deps) {
return mountEffectImpl(Update, Layout, create, deps);
}
function updateLayoutEffect(create, deps) {
return updateEffectImpl(Update, Layout, create, deps);
}
function imperativeHandleEffect(create, ref) {
if (typeof ref === "function") {
var refCallback = ref;
var _inst = create();
refCallback(_inst);
return function() {
refCallback(null);
};
} else if (ref !== null && ref !== void 0) {
var refObject = ref;
{
if (!refObject.hasOwnProperty("current")) {
error("Expected useImperativeHandle() first argument to either be a ref callback or React.createRef() object. Instead received: %s.", "an object with keys {" + Object.keys(refObject).join(", ") + "}");
}
}
var _inst2 = create();
refObject.current = _inst2;
return function() {
refObject.current = null;
};
}
}
function mountImperativeHandle(ref, create, deps) {
{
if (typeof create !== "function") {
error("Expected useImperativeHandle() second argument to be a function that creates a handle. Instead received: %s.", create !== null ? typeof create : "null");
}
}
var effectDeps = deps !== null && deps !== void 0 ? deps.concat([ref]) : null;
return mountEffectImpl(Update, Layout, imperativeHandleEffect.bind(null, create, ref), effectDeps);
}
function updateImperativeHandle(ref, create, deps) {
{
if (typeof create !== "function") {
error("Expected useImperativeHandle() second argument to be a function that creates a handle. Instead received: %s.", create !== null ? typeof create : "null");
}
}
var effectDeps = deps !== null && deps !== void 0 ? deps.concat([ref]) : null;
return updateEffectImpl(Update, Layout, imperativeHandleEffect.bind(null, create, ref), effectDeps);
}
function mountDebugValue(value, formatterFn) {
}
var updateDebugValue = mountDebugValue;
function mountCallback(callback, deps) {
var hook = mountWorkInProgressHook();
var nextDeps = deps === void 0 ? null : deps;
hook.memoizedState = [callback, nextDeps];
return callback;
}
function updateCallback(callback, deps) {
var hook = updateWorkInProgressHook();
var nextDeps = deps === void 0 ? null : deps;
var prevState = hook.memoizedState;
if (prevState !== null) {
if (nextDeps !== null) {
var prevDeps = prevState[1];
if (areHookInputsEqual(nextDeps, prevDeps)) {
return prevState[0];
}
}
}
hook.memoizedState = [callback, nextDeps];
return callback;
}
function mountMemo(nextCreate, deps) {
var hook = mountWorkInProgressHook();
var nextDeps = deps === void 0 ? null : deps;
var nextValue = nextCreate();
hook.memoizedState = [nextValue, nextDeps];
return nextValue;
}
function updateMemo(nextCreate, deps) {
var hook = updateWorkInProgressHook();
var nextDeps = deps === void 0 ? null : deps;
var prevState = hook.memoizedState;
if (prevState !== null) {
if (nextDeps !== null) {
var prevDeps = prevState[1];
if (areHookInputsEqual(nextDeps, prevDeps)) {
return prevState[0];
}
}
}
var nextValue = nextCreate();
hook.memoizedState = [nextValue, nextDeps];
return nextValue;
}
function mountDeferredValue(value) {
var _mountState = mountState(value), prevValue = _mountState[0], setValue = _mountState[1];
mountEffect(function() {
var prevTransition = ReactCurrentBatchConfig$1.transition;
ReactCurrentBatchConfig$1.transition = 1;
try {
setValue(value);
} finally {
ReactCurrentBatchConfig$1.transition = prevTransition;
}
}, [value]);
return prevValue;
}
function updateDeferredValue(value) {
var _updateState = updateState(), prevValue = _updateState[0], setValue = _updateState[1];
updateEffect(function() {
var prevTransition = ReactCurrentBatchConfig$1.transition;
ReactCurrentBatchConfig$1.transition = 1;
try {
setValue(value);
} finally {
ReactCurrentBatchConfig$1.transition = prevTransition;
}
}, [value]);
return prevValue;
}
function rerenderDeferredValue(value) {
var _rerenderState = rerenderState(), prevValue = _rerenderState[0], setValue = _rerenderState[1];
updateEffect(function() {
var prevTransition = ReactCurrentBatchConfig$1.transition;
ReactCurrentBatchConfig$1.transition = 1;
try {
setValue(value);
} finally {
ReactCurrentBatchConfig$1.transition = prevTransition;
}
}, [value]);
return prevValue;
}
function startTransition(setPending, callback) {
var priorityLevel = getCurrentPriorityLevel();
{
runWithPriority$1(priorityLevel < UserBlockingPriority$2 ? UserBlockingPriority$2 : priorityLevel, function() {
setPending(true);
});
runWithPriority$1(priorityLevel > NormalPriority$1 ? NormalPriority$1 : priorityLevel, function() {
var prevTransition = ReactCurrentBatchConfig$1.transition;
ReactCurrentBatchConfig$1.transition = 1;
try {
setPending(false);
callback();
} finally {
ReactCurrentBatchConfig$1.transition = prevTransition;
}
});
}
}
function mountTransition() {
var _mountState2 = mountState(false), isPending = _mountState2[0], setPending = _mountState2[1];
var start = startTransition.bind(null, setPending);
mountRef(start);
return [start, isPending];
}
function updateTransition() {
var _updateState2 = updateState(), isPending = _updateState2[0];
var startRef = updateRef();
var start = startRef.current;
return [start, isPending];
}
function rerenderTransition() {
var _rerenderState2 = rerenderState(), isPending = _rerenderState2[0];
var startRef = updateRef();
var start = startRef.current;
return [start, isPending];
}
var isUpdatingOpaqueValueInRenderPhase = false;
function getIsUpdatingOpaqueValueInRenderPhaseInDEV() {
{
return isUpdatingOpaqueValueInRenderPhase;
}
}
function warnOnOpaqueIdentifierAccessInDEV(fiber) {
{
var name = getComponentName(fiber.type) || "Unknown";
if (getIsRendering() && !didWarnAboutUseOpaqueIdentifier[name]) {
error("The object passed back from useOpaqueIdentifier is meant to be passed through to attributes only. Do not read the value directly.");
didWarnAboutUseOpaqueIdentifier[name] = true;
}
}
}
function mountOpaqueIdentifier() {
var makeId = makeClientIdInDEV.bind(null, warnOnOpaqueIdentifierAccessInDEV.bind(null, currentlyRenderingFiber$1));
if (getIsHydrating()) {
var didUpgrade = false;
var fiber = currentlyRenderingFiber$1;
var readValue = function() {
if (!didUpgrade) {
didUpgrade = true;
{
isUpdatingOpaqueValueInRenderPhase = true;
setId(makeId());
isUpdatingOpaqueValueInRenderPhase = false;
warnOnOpaqueIdentifierAccessInDEV(fiber);
}
}
{
{
throw Error("The object passed back from useOpaqueIdentifier is meant to be passed through to attributes only. Do not read the value directly.");
}
}
};
var id = makeOpaqueHydratingObject(readValue);
var setId = mountState(id)[1];
if ((currentlyRenderingFiber$1.mode & BlockingMode) === NoMode) {
currentlyRenderingFiber$1.flags |= Update | Passive;
pushEffect(HasEffect | Passive$1, function() {
setId(makeId());
}, void 0, null);
}
return id;
} else {
var _id = makeId();
mountState(_id);
return _id;
}
}
function updateOpaqueIdentifier() {
var id = updateState()[0];
return id;
}
function rerenderOpaqueIdentifier() {
var id = rerenderState()[0];
return id;
}
function dispatchAction(fiber, queue, action) {
{
if (typeof arguments[3] === "function") {
error("State updates from the useState() and useReducer() Hooks don't support the second callback argument. To execute a side effect after rendering, declare it in the component body with useEffect().");
}
}
var eventTime = requestEventTime();
var lane = requestUpdateLane(fiber);
var update = {
lane,
action,
eagerReducer: null,
eagerState: null,
next: null
};
var pending = queue.pending;
if (pending === null) {
update.next = update;
} else {
update.next = pending.next;
pending.next = update;
}
queue.pending = update;
var alternate = fiber.alternate;
if (fiber === currentlyRenderingFiber$1 || alternate !== null && alternate === currentlyRenderingFiber$1) {
didScheduleRenderPhaseUpdateDuringThisPass = didScheduleRenderPhaseUpdate = true;
} else {
if (fiber.lanes === NoLanes && (alternate === null || alternate.lanes === NoLanes)) {
var lastRenderedReducer = queue.lastRenderedReducer;
if (lastRenderedReducer !== null) {
var prevDispatcher;
{
prevDispatcher = ReactCurrentDispatcher$1.current;
ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
}
try {
var currentState = queue.lastRenderedState;
var eagerState = lastRenderedReducer(currentState, action);
update.eagerReducer = lastRenderedReducer;
update.eagerState = eagerState;
if (objectIs(eagerState, currentState)) {
return;
}
} catch (error2) {
} finally {
{
ReactCurrentDispatcher$1.current = prevDispatcher;
}
}
}
}
{
if (typeof jest !== "undefined") {
warnIfNotScopedWithMatchingAct(fiber);
warnIfNotCurrentlyActingUpdatesInDev(fiber);
}
}
scheduleUpdateOnFiber(fiber, lane, eventTime);
}
}
var ContextOnlyDispatcher = {
readContext,
useCallback: throwInvalidHookError,
useContext: throwInvalidHookError,
useEffect: throwInvalidHookError,
useImperativeHandle: throwInvalidHookError,
useLayoutEffect: throwInvalidHookError,
useMemo: throwInvalidHookError,
useReducer: throwInvalidHookError,
useRef: throwInvalidHookError,
useState: throwInvalidHookError,
useDebugValue: throwInvalidHookError,
useDeferredValue: throwInvalidHookError,
useTransition: throwInvalidHookError,
useMutableSource: throwInvalidHookError,
useOpaqueIdentifier: throwInvalidHookError,
unstable_isNewReconciler: enableNewReconciler
};
var HooksDispatcherOnMountInDEV = null;
var HooksDispatcherOnMountWithHookTypesInDEV = null;
var HooksDispatcherOnUpdateInDEV = null;
var HooksDispatcherOnRerenderInDEV = null;
var InvalidNestedHooksDispatcherOnMountInDEV = null;
var InvalidNestedHooksDispatcherOnUpdateInDEV = null;
var InvalidNestedHooksDispatcherOnRerenderInDEV = null;
{
var warnInvalidContextAccess = function() {
error("Context can only be read while React is rendering. In classes, you can read it in the render method or getDerivedStateFromProps. In function components, you can read it directly in the function body, but not inside Hooks like useReducer() or useMemo().");
};
var warnInvalidHookAccess = function() {
error("Do not call Hooks inside useEffect(...), useMemo(...), or other built-in Hooks. You can only call Hooks at the top level of your React function. For more information, see https://reactjs.org/link/rules-of-hooks");
};
HooksDispatcherOnMountInDEV = {
readContext: function(context, observedBits) {
return readContext(context, observedBits);
},
useCallback: function(callback, deps) {
currentHookNameInDev = "useCallback";
mountHookTypesDev();
checkDepsAreArrayDev(deps);
return mountCallback(callback, deps);
},
useContext: function(context, observedBits) {
currentHookNameInDev = "useContext";
mountHookTypesDev();
return readContext(context, observedBits);
},
useEffect: function(create, deps) {
currentHookNameInDev = "useEffect";
mountHookTypesDev();
checkDepsAreArrayDev(deps);
return mountEffect(create, deps);
},
useImperativeHandle: function(ref, create, deps) {
currentHookNameInDev = "useImperativeHandle";
mountHookTypesDev();
checkDepsAreArrayDev(deps);
return mountImperativeHandle(ref, create, deps);
},
useLayoutEffect: function(create, deps) {
currentHookNameInDev = "useLayoutEffect";
mountHookTypesDev();
checkDepsAreArrayDev(deps);
return mountLayoutEffect(create, deps);
},
useMemo: function(create, deps) {
currentHookNameInDev = "useMemo";
mountHookTypesDev();
checkDepsAreArrayDev(deps);
var prevDispatcher = ReactCurrentDispatcher$1.current;
ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
try {
return mountMemo(create, deps);
} finally {
ReactCurrentDispatcher$1.current = prevDispatcher;
}
},
useReducer: function(reducer, initialArg, init) {
currentHookNameInDev = "useReducer";
mountHookTypesDev();
var prevDispatcher = ReactCurrentDispatcher$1.current;
ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
try {
return mountReducer(reducer, initialArg, init);
} finally {
ReactCurrentDispatcher$1.current = prevDispatcher;
}
},
useRef: function(initialValue) {
currentHookNameInDev = "useRef";
mountHookTypesDev();
return mountRef(initialValue);
},
useState: function(initialState) {
currentHookNameInDev = "useState";
mountHookTypesDev();
var prevDispatcher = ReactCurrentDispatcher$1.current;
ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
try {
return mountState(initialState);
} finally {
ReactCurrentDispatcher$1.current = prevDispatcher;
}
},
useDebugValue: function(value, formatterFn) {
currentHookNameInDev = "useDebugValue";
mountHookTypesDev();
return mountDebugValue();
},
useDeferredValue: function(value) {
currentHookNameInDev = "useDeferredValue";
mountHookTypesDev();
return mountDeferredValue(value);
},
useTransition: function() {
currentHookNameInDev = "useTransition";
mountHookTypesDev();
return mountTransition();
},
useMutableSource: function(source, getSnapshot, subscribe) {
currentHookNameInDev = "useMutableSource";
mountHookTypesDev();
return mountMutableSource(source, getSnapshot, subscribe);
},
useOpaqueIdentifier: function() {
currentHookNameInDev = "useOpaqueIdentifier";
mountHookTypesDev();
return mountOpaqueIdentifier();
},
unstable_isNewReconciler: enableNewReconciler
};
HooksDispatcherOnMountWithHookTypesInDEV = {
readContext: function(context, observedBits) {
return readContext(context, observedBits);
},
useCallback: function(callback, deps) {
currentHookNameInDev = "useCallback";
updateHookTypesDev();
return mountCallback(callback, deps);
},
useContext: function(context, observedBits) {
currentHookNameInDev = "useContext";
updateHookTypesDev();
return readContext(context, observedBits);
},
useEffect: function(create, deps) {
currentHookNameInDev = "useEffect";
updateHookTypesDev();
return mountEffect(create, deps);
},
useImperativeHandle: function(ref, create, deps) {
currentHookNameInDev = "useImperativeHandle";
updateHookTypesDev();
return mountImperativeHandle(ref, create, deps);
},
useLayoutEffect: function(create, deps) {
currentHookNameInDev = "useLayoutEffect";
updateHookTypesDev();
return mountLayoutEffect(create, deps);
},
useMemo: function(create, deps) {
currentHookNameInDev = "useMemo";
updateHookTypesDev();
var prevDispatcher = ReactCurrentDispatcher$1.current;
ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
try {
return mountMemo(create, deps);
} finally {
ReactCurrentDispatcher$1.current = prevDispatcher;
}
},
useReducer: function(reducer, initialArg, init) {
currentHookNameInDev = "useReducer";
updateHookTypesDev();
var prevDispatcher = ReactCurrentDispatcher$1.current;
ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
try {
return mountReducer(reducer, initialArg, init);
} finally {
ReactCurrentDispatcher$1.current = prevDispatcher;
}
},
useRef: function(initialValue) {
currentHookNameInDev = "useRef";
updateHookTypesDev();
return mountRef(initialValue);
},
useState: function(initialState) {
currentHookNameInDev = "useState";
updateHookTypesDev();
var prevDispatcher = ReactCurrentDispatcher$1.current;
ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
try {
return mountState(initialState);
} finally {
ReactCurrentDispatcher$1.current = prevDispatcher;
}
},
useDebugValue: function(value, formatterFn) {
currentHookNameInDev = "useDebugValue";
updateHookTypesDev();
return mountDebugValue();
},
useDeferredValue: function(value) {
currentHookNameInDev = "useDeferredValue";
updateHookTypesDev();
return mountDeferredValue(value);
},
useTransition: function() {
currentHookNameInDev = "useTransition";
updateHookTypesDev();
return mountTransition();
},
useMutableSource: function(source, getSnapshot, subscribe) {
currentHookNameInDev = "useMutableSource";
updateHookTypesDev();
return mountMutableSource(source, getSnapshot, subscribe);
},
useOpaqueIdentifier: function() {
currentHookNameInDev = "useOpaqueIdentifier";
updateHookTypesDev();
return mountOpaqueIdentifier();
},
unstable_isNewReconciler: enableNewReconciler
};
HooksDispatcherOnUpdateInDEV = {
readContext: function(context, observedBits) {
return readContext(context, observedBits);
},
useCallback: function(callback, deps) {
currentHookNameInDev = "useCallback";
updateHookTypesDev();
return updateCallback(callback, deps);
},
useContext: function(context, observedBits) {
currentHookNameInDev = "useContext";
updateHookTypesDev();
return readContext(context, observedBits);
},
useEffect: function(create, deps) {
currentHookNameInDev = "useEffect";
updateHookTypesDev();
return updateEffect(create, deps);
},
useImperativeHandle: function(ref, create, deps) {
currentHookNameInDev = "useImperativeHandle";
updateHookTypesDev();
return updateImperativeHandle(ref, create, deps);
},
useLayoutEffect: function(create, deps) {
currentHookNameInDev = "useLayoutEffect";
updateHookTypesDev();
return updateLayoutEffect(create, deps);
},
useMemo: function(create, deps) {
currentHookNameInDev = "useMemo";
updateHookTypesDev();
var prevDispatcher = ReactCurrentDispatcher$1.current;
ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
try {
return updateMemo(create, deps);
} finally {
ReactCurrentDispatcher$1.current = prevDispatcher;
}
},
useReducer: function(reducer, initialArg, init) {
currentHookNameInDev = "useReducer";
updateHookTypesDev();
var prevDispatcher = ReactCurrentDispatcher$1.current;
ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
try {
return updateReducer(reducer, initialArg, init);
} finally {
ReactCurrentDispatcher$1.current = prevDispatcher;
}
},
useRef: function(initialValue) {
currentHookNameInDev = "useRef";
updateHookTypesDev();
return updateRef();
},
useState: function(initialState) {
currentHookNameInDev = "useState";
updateHookTypesDev();
var prevDispatcher = ReactCurrentDispatcher$1.current;
ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
try {
return updateState(initialState);
} finally {
ReactCurrentDispatcher$1.current = prevDispatcher;
}
},
useDebugValue: function(value, formatterFn) {
currentHookNameInDev = "useDebugValue";
updateHookTypesDev();
return updateDebugValue();
},
useDeferredValue: function(value) {
currentHookNameInDev = "useDeferredValue";
updateHookTypesDev();
return updateDeferredValue(value);
},
useTransition: function() {
currentHookNameInDev = "useTransition";
updateHookTypesDev();
return updateTransition();
},
useMutableSource: function(source, getSnapshot, subscribe) {
currentHookNameInDev = "useMutableSource";
updateHookTypesDev();
return updateMutableSource(source, getSnapshot, subscribe);
},
useOpaqueIdentifier: function() {
currentHookNameInDev = "useOpaqueIdentifier";
updateHookTypesDev();
return updateOpaqueIdentifier();
},
unstable_isNewReconciler: enableNewReconciler
};
HooksDispatcherOnRerenderInDEV = {
readContext: function(context, observedBits) {
return readContext(context, observedBits);
},
useCallback: function(callback, deps) {
currentHookNameInDev = "useCallback";
updateHookTypesDev();
return updateCallback(callback, deps);
},
useContext: function(context, observedBits) {
currentHookNameInDev = "useContext";
updateHookTypesDev();
return readContext(context, observedBits);
},
useEffect: function(create, deps) {
currentHookNameInDev = "useEffect";
updateHookTypesDev();
return updateEffect(create, deps);
},
useImperativeHandle: function(ref, create, deps) {
currentHookNameInDev = "useImperativeHandle";
updateHookTypesDev();
return updateImperativeHandle(ref, create, deps);
},
useLayoutEffect: function(create, deps) {
currentHookNameInDev = "useLayoutEffect";
updateHookTypesDev();
return updateLayoutEffect(create, deps);
},
useMemo: function(create, deps) {
currentHookNameInDev = "useMemo";
updateHookTypesDev();
var prevDispatcher = ReactCurrentDispatcher$1.current;
ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnRerenderInDEV;
try {
return updateMemo(create, deps);
} finally {
ReactCurrentDispatcher$1.current = prevDispatcher;
}
},
useReducer: function(reducer, initialArg, init) {
currentHookNameInDev = "useReducer";
updateHookTypesDev();
var prevDispatcher = ReactCurrentDispatcher$1.current;
ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnRerenderInDEV;
try {
return rerenderReducer(reducer, initialArg, init);
} finally {
ReactCurrentDispatcher$1.current = prevDispatcher;
}
},
useRef: function(initialValue) {
currentHookNameInDev = "useRef";
updateHookTypesDev();
return updateRef();
},
useState: function(initialState) {
currentHookNameInDev = "useState";
updateHookTypesDev();
var prevDispatcher = ReactCurrentDispatcher$1.current;
ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnRerenderInDEV;
try {
return rerenderState(initialState);
} finally {
ReactCurrentDispatcher$1.current = prevDispatcher;
}
},
useDebugValue: function(value, formatterFn) {
currentHookNameInDev = "useDebugValue";
updateHookTypesDev();
return updateDebugValue();
},
useDeferredValue: function(value) {
currentHookNameInDev = "useDeferredValue";
updateHookTypesDev();
return rerenderDeferredValue(value);
},
useTransition: function() {
currentHookNameInDev = "useTransition";
updateHookTypesDev();
return rerenderTransition();
},
useMutableSource: function(source, getSnapshot, subscribe) {
currentHookNameInDev = "useMutableSource";
updateHookTypesDev();
return updateMutableSource(source, getSnapshot, subscribe);
},
useOpaqueIdentifier: function() {
currentHookNameInDev = "useOpaqueIdentifier";
updateHookTypesDev();
return rerenderOpaqueIdentifier();
},
unstable_isNewReconciler: enableNewReconciler
};
InvalidNestedHooksDispatcherOnMountInDEV = {
readContext: function(context, observedBits) {
warnInvalidContextAccess();
return readContext(context, observedBits);
},
useCallback: function(callback, deps) {
currentHookNameInDev = "useCallback";
warnInvalidHookAccess();
mountHookTypesDev();
return mountCallback(callback, deps);
},
useContext: function(context, observedBits) {
currentHookNameInDev = "useContext";
warnInvalidHookAccess();
mountHookTypesDev();
return readContext(context, observedBits);
},
useEffect: function(create, deps) {
currentHookNameInDev = "useEffect";
warnInvalidHookAccess();
mountHookTypesDev();
return mountEffect(create, deps);
},
useImperativeHandle: function(ref, create, deps) {
currentHookNameInDev = "useImperativeHandle";
warnInvalidHookAccess();
mountHookTypesDev();
return mountImperativeHandle(ref, create, deps);
},
useLayoutEffect: function(create, deps) {
currentHookNameInDev = "useLayoutEffect";
warnInvalidHookAccess();
mountHookTypesDev();
return mountLayoutEffect(create, deps);
},
useMemo: function(create, deps) {
currentHookNameInDev = "useMemo";
warnInvalidHookAccess();
mountHookTypesDev();
var prevDispatcher = ReactCurrentDispatcher$1.current;
ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
try {
return mountMemo(create, deps);
} finally {
ReactCurrentDispatcher$1.current = prevDispatcher;
}
},
useReducer: function(reducer, initialArg, init) {
currentHookNameInDev = "useReducer";
warnInvalidHookAccess();
mountHookTypesDev();
var prevDispatcher = ReactCurrentDispatcher$1.current;
ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
try {
return mountReducer(reducer, initialArg, init);
} finally {
ReactCurrentDispatcher$1.current = prevDispatcher;
}
},
useRef: function(initialValue) {
currentHookNameInDev = "useRef";
warnInvalidHookAccess();
mountHookTypesDev();
return mountRef(initialValue);
},
useState: function(initialState) {
currentHookNameInDev = "useState";
warnInvalidHookAccess();
mountHookTypesDev();
var prevDispatcher = ReactCurrentDispatcher$1.current;
ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
try {
return mountState(initialState);
} finally {
ReactCurrentDispatcher$1.current = prevDispatcher;
}
},
useDebugValue: function(value, formatterFn) {
currentHookNameInDev = "useDebugValue";
warnInvalidHookAccess();
mountHookTypesDev();
return mountDebugValue();
},
useDeferredValue: function(value) {
currentHookNameInDev = "useDeferredValue";
warnInvalidHookAccess();
mountHookTypesDev();
return mountDeferredValue(value);
},
useTransition: function() {
currentHookNameInDev = "useTransition";
warnInvalidHookAccess();
mountHookTypesDev();
return mountTransition();
},
useMutableSource: function(source, getSnapshot, subscribe) {
currentHookNameInDev = "useMutableSource";
warnInvalidHookAccess();
mountHookTypesDev();
return mountMutableSource(source, getSnapshot, subscribe);
},
useOpaqueIdentifier: function() {
currentHookNameInDev = "useOpaqueIdentifier";
warnInvalidHookAccess();
mountHookTypesDev();
return mountOpaqueIdentifier();
},
unstable_isNewReconciler: enableNewReconciler
};
InvalidNestedHooksDispatcherOnUpdateInDEV = {
readContext: function(context, observedBits) {
warnInvalidContextAccess();
return readContext(context, observedBits);
},
useCallback: function(callback, deps) {
currentHookNameInDev = "useCallback";
warnInvalidHookAccess();
updateHookTypesDev();
return updateCallback(callback, deps);
},
useContext: function(context, observedBits) {
currentHookNameInDev = "useContext";
warnInvalidHookAccess();
updateHookTypesDev();
return readContext(context, observedBits);
},
useEffect: function(create, deps) {
currentHookNameInDev = "useEffect";
warnInvalidHookAccess();
updateHookTypesDev();
return updateEffect(create, deps);
},
useImperativeHandle: function(ref, create, deps) {
currentHookNameInDev = "useImperativeHandle";
warnInvalidHookAccess();
updateHookTypesDev();
return updateImperativeHandle(ref, create, deps);
},
useLayoutEffect: function(create, deps) {
currentHookNameInDev = "useLayoutEffect";
warnInvalidHookAccess();
updateHookTypesDev();
return updateLayoutEffect(create, deps);
},
useMemo: function(create, deps) {
currentHookNameInDev = "useMemo";
warnInvalidHookAccess();
updateHookTypesDev();
var prevDispatcher = ReactCurrentDispatcher$1.current;
ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
try {
return updateMemo(create, deps);
} finally {
ReactCurrentDispatcher$1.current = prevDispatcher;
}
},
useReducer: function(reducer, initialArg, init) {
currentHookNameInDev = "useReducer";
warnInvalidHookAccess();
updateHookTypesDev();
var prevDispatcher = ReactCurrentDispatcher$1.current;
ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
try {
return updateReducer(reducer, initialArg, init);
} finally {
ReactCurrentDispatcher$1.current = prevDispatcher;
}
},
useRef: function(initialValue) {
currentHookNameInDev = "useRef";
warnInvalidHookAccess();
updateHookTypesDev();
return updateRef();
},
useState: function(initialState) {
currentHookNameInDev = "useState";
warnInvalidHookAccess();
updateHookTypesDev();
var prevDispatcher = ReactCurrentDispatcher$1.current;
ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
try {
return updateState(initialState);
} finally {
ReactCurrentDispatcher$1.current = prevDispatcher;
}
},
useDebugValue: function(value, formatterFn) {
currentHookNameInDev = "useDebugValue";
warnInvalidHookAccess();
updateHookTypesDev();
return updateDebugValue();
},
useDeferredValue: function(value) {
currentHookNameInDev = "useDeferredValue";
warnInvalidHookAccess();
updateHookTypesDev();
return updateDeferredValue(value);
},
useTransition: function() {
currentHookNameInDev = "useTransition";
warnInvalidHookAccess();
updateHookTypesDev();
return updateTransition();
},
useMutableSource: function(source, getSnapshot, subscribe) {
currentHookNameInDev = "useMutableSource";
warnInvalidHookAccess();
updateHookTypesDev();
return updateMutableSource(source, getSnapshot, subscribe);
},
useOpaqueIdentifier: function() {
currentHookNameInDev = "useOpaqueIdentifier";
warnInvalidHookAccess();
updateHookTypesDev();
return updateOpaqueIdentifier();
},
unstable_isNewReconciler: enableNewReconciler
};
InvalidNestedHooksDispatcherOnRerenderInDEV = {
readContext: function(context, observedBits) {
warnInvalidContextAccess();
return readContext(context, observedBits);
},
useCallback: function(callback, deps) {
currentHookNameInDev = "useCallback";
warnInvalidHookAccess();
updateHookTypesDev();
return updateCallback(callback, deps);
},
useContext: function(context, observedBits) {
currentHookNameInDev = "useContext";
warnInvalidHookAccess();
updateHookTypesDev();
return readContext(context, observedBits);
},
useEffect: function(create, deps) {
currentHookNameInDev = "useEffect";
warnInvalidHookAccess();
updateHookTypesDev();
return updateEffect(create, deps);
},
useImperativeHandle: function(ref, create, deps) {
currentHookNameInDev = "useImperativeHandle";
warnInvalidHookAccess();
updateHookTypesDev();
return updateImperativeHandle(ref, create, deps);
},
useLayoutEffect: function(create, deps) {
currentHookNameInDev = "useLayoutEffect";
warnInvalidHookAccess();
updateHookTypesDev();
return updateLayoutEffect(create, deps);
},
useMemo: function(create, deps) {
currentHookNameInDev = "useMemo";
warnInvalidHookAccess();
updateHookTypesDev();
var prevDispatcher = ReactCurrentDispatcher$1.current;
ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
try {
return updateMemo(create, deps);
} finally {
ReactCurrentDispatcher$1.current = prevDispatcher;
}
},
useReducer: function(reducer, initialArg, init) {
currentHookNameInDev = "useReducer";
warnInvalidHookAccess();
updateHookTypesDev();
var prevDispatcher = ReactCurrentDispatcher$1.current;
ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
try {
return rerenderReducer(reducer, initialArg, init);
} finally {
ReactCurrentDispatcher$1.current = prevDispatcher;
}
},
useRef: function(initialValue) {
currentHookNameInDev = "useRef";
warnInvalidHookAccess();
updateHookTypesDev();
return updateRef();
},
useState: function(initialState) {
currentHookNameInDev = "useState";
warnInvalidHookAccess();
updateHookTypesDev();
var prevDispatcher = ReactCurrentDispatcher$1.current;
ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
try {
return rerenderState(initialState);
} finally {
ReactCurrentDispatcher$1.current = prevDispatcher;
}
},
useDebugValue: function(value, formatterFn) {
currentHookNameInDev = "useDebugValue";
warnInvalidHookAccess();
updateHookTypesDev();
return updateDebugValue();
},
useDeferredValue: function(value) {
currentHookNameInDev = "useDeferredValue";
warnInvalidHookAccess();
updateHookTypesDev();
return rerenderDeferredValue(value);
},
useTransition: function() {
currentHookNameInDev = "useTransition";
warnInvalidHookAccess();
updateHookTypesDev();
return rerenderTransition();
},
useMutableSource: function(source, getSnapshot, subscribe) {
currentHookNameInDev = "useMutableSource";
warnInvalidHookAccess();
updateHookTypesDev();
return updateMutableSource(source, getSnapshot, subscribe);
},
useOpaqueIdentifier: function() {
currentHookNameInDev = "useOpaqueIdentifier";
warnInvalidHookAccess();
updateHookTypesDev();
return rerenderOpaqueIdentifier();
},
unstable_isNewReconciler: enableNewReconciler
};
}
var now$1 = Scheduler.unstable_now;
var commitTime = 0;
var profilerStartTime = -1;
function getCommitTime() {
return commitTime;
}
function recordCommitTime() {
commitTime = now$1();
}
function startProfilerTimer(fiber) {
profilerStartTime = now$1();
if (fiber.actualStartTime < 0) {
fiber.actualStartTime = now$1();
}
}
function stopProfilerTimerIfRunning(fiber) {
profilerStartTime = -1;
}
function stopProfilerTimerIfRunningAndRecordDelta(fiber, overrideBaseTime) {
if (profilerStartTime >= 0) {
var elapsedTime = now$1() - profilerStartTime;
fiber.actualDuration += elapsedTime;
if (overrideBaseTime) {
fiber.selfBaseDuration = elapsedTime;
}
profilerStartTime = -1;
}
}
function transferActualDuration(fiber) {
var child = fiber.child;
while (child) {
fiber.actualDuration += child.actualDuration;
child = child.sibling;
}
}
var ReactCurrentOwner$1 = ReactSharedInternals.ReactCurrentOwner;
var didReceiveUpdate = false;
var didWarnAboutBadClass;
var didWarnAboutModulePatternComponent;
var didWarnAboutContextTypeOnFunctionComponent;
var didWarnAboutGetDerivedStateOnFunctionComponent;
var didWarnAboutFunctionRefs;
var didWarnAboutReassigningProps;
var didWarnAboutRevealOrder;
var didWarnAboutTailOptions;
{
didWarnAboutBadClass = {};
didWarnAboutModulePatternComponent = {};
didWarnAboutContextTypeOnFunctionComponent = {};
didWarnAboutGetDerivedStateOnFunctionComponent = {};
didWarnAboutFunctionRefs = {};
didWarnAboutReassigningProps = false;
didWarnAboutRevealOrder = {};
didWarnAboutTailOptions = {};
}
function reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2) {
if (current2 === null) {
workInProgress2.child = mountChildFibers(workInProgress2, null, nextChildren, renderLanes2);
} else {
workInProgress2.child = reconcileChildFibers(workInProgress2, current2.child, nextChildren, renderLanes2);
}
}
function forceUnmountCurrentAndReconcile(current2, workInProgress2, nextChildren, renderLanes2) {
workInProgress2.child = reconcileChildFibers(workInProgress2, current2.child, null, renderLanes2);
workInProgress2.child = reconcileChildFibers(workInProgress2, null, nextChildren, renderLanes2);
}
function updateForwardRef(current2, workInProgress2, Component, nextProps, renderLanes2) {
{
if (workInProgress2.type !== workInProgress2.elementType) {
var innerPropTypes = Component.propTypes;
if (innerPropTypes) {
checkPropTypes(innerPropTypes, nextProps, "prop", getComponentName(Component));
}
}
}
var render2 = Component.render;
var ref = workInProgress2.ref;
var nextChildren;
prepareToReadContext(workInProgress2, renderLanes2);
{
ReactCurrentOwner$1.current = workInProgress2;
setIsRendering(true);
nextChildren = renderWithHooks(current2, workInProgress2, render2, nextProps, ref, renderLanes2);
if (workInProgress2.mode & StrictMode) {
disableLogs();
try {
nextChildren = renderWithHooks(current2, workInProgress2, render2, nextProps, ref, renderLanes2);
} finally {
reenableLogs();
}
}
setIsRendering(false);
}
if (current2 !== null && !didReceiveUpdate) {
bailoutHooks(current2, workInProgress2, renderLanes2);
return bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2);
}
workInProgress2.flags |= PerformedWork;
reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2);
return workInProgress2.child;
}
function updateMemoComponent(current2, workInProgress2, Component, nextProps, updateLanes, renderLanes2) {
if (current2 === null) {
var type = Component.type;
if (isSimpleFunctionComponent(type) && Component.compare === null && Component.defaultProps === void 0) {
var resolvedType = type;
{
resolvedType = resolveFunctionForHotReloading(type);
}
workInProgress2.tag = SimpleMemoComponent;
workInProgress2.type = resolvedType;
{
validateFunctionComponentInDev(workInProgress2, type);
}
return updateSimpleMemoComponent(current2, workInProgress2, resolvedType, nextProps, updateLanes, renderLanes2);
}
{
var innerPropTypes = type.propTypes;
if (innerPropTypes) {
checkPropTypes(innerPropTypes, nextProps, "prop", getComponentName(type));
}
}
var child = createFiberFromTypeAndProps(Component.type, null, nextProps, workInProgress2, workInProgress2.mode, renderLanes2);
child.ref = workInProgress2.ref;
child.return = workInProgress2;
workInProgress2.child = child;
return child;
}
{
var _type = Component.type;
var _innerPropTypes = _type.propTypes;
if (_innerPropTypes) {
checkPropTypes(_innerPropTypes, nextProps, "prop", getComponentName(_type));
}
}
var currentChild = current2.child;
if (!includesSomeLane(updateLanes, renderLanes2)) {
var prevProps = currentChild.memoizedProps;
var compare = Component.compare;
compare = compare !== null ? compare : shallowEqual;
if (compare(prevProps, nextProps) && current2.ref === workInProgress2.ref) {
return bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2);
}
}
workInProgress2.flags |= PerformedWork;
var newChild = createWorkInProgress(currentChild, nextProps);
newChild.ref = workInProgress2.ref;
newChild.return = workInProgress2;
workInProgress2.child = newChild;
return newChild;
}
function updateSimpleMemoComponent(current2, workInProgress2, Component, nextProps, updateLanes, renderLanes2) {
{
if (workInProgress2.type !== workInProgress2.elementType) {
var outerMemoType = workInProgress2.elementType;
if (outerMemoType.$$typeof === REACT_LAZY_TYPE) {
var lazyComponent = outerMemoType;
var payload = lazyComponent._payload;
var init = lazyComponent._init;
try {
outerMemoType = init(payload);
} catch (x) {
outerMemoType = null;
}
var outerPropTypes = outerMemoType && outerMemoType.propTypes;
if (outerPropTypes) {
checkPropTypes(outerPropTypes, nextProps, "prop", getComponentName(outerMemoType));
}
}
}
}
if (current2 !== null) {
var prevProps = current2.memoizedProps;
if (shallowEqual(prevProps, nextProps) && current2.ref === workInProgress2.ref && workInProgress2.type === current2.type) {
didReceiveUpdate = false;
if (!includesSomeLane(renderLanes2, updateLanes)) {
workInProgress2.lanes = current2.lanes;
return bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2);
} else if ((current2.flags & ForceUpdateForLegacySuspense) !== NoFlags) {
didReceiveUpdate = true;
}
}
}
return updateFunctionComponent(current2, workInProgress2, Component, nextProps, renderLanes2);
}
function updateOffscreenComponent(current2, workInProgress2, renderLanes2) {
var nextProps = workInProgress2.pendingProps;
var nextChildren = nextProps.children;
var prevState = current2 !== null ? current2.memoizedState : null;
if (nextProps.mode === "hidden" || nextProps.mode === "unstable-defer-without-hiding") {
if ((workInProgress2.mode & ConcurrentMode) === NoMode) {
var nextState = {
baseLanes: NoLanes
};
workInProgress2.memoizedState = nextState;
pushRenderLanes(workInProgress2, renderLanes2);
} else if (!includesSomeLane(renderLanes2, OffscreenLane)) {
var nextBaseLanes;
if (prevState !== null) {
var prevBaseLanes = prevState.baseLanes;
nextBaseLanes = mergeLanes(prevBaseLanes, renderLanes2);
} else {
nextBaseLanes = renderLanes2;
}
{
markSpawnedWork(OffscreenLane);
}
workInProgress2.lanes = workInProgress2.childLanes = laneToLanes(OffscreenLane);
var _nextState = {
baseLanes: nextBaseLanes
};
workInProgress2.memoizedState = _nextState;
pushRenderLanes(workInProgress2, nextBaseLanes);
return null;
} else {
var _nextState2 = {
baseLanes: NoLanes
};
workInProgress2.memoizedState = _nextState2;
var subtreeRenderLanes2 = prevState !== null ? prevState.baseLanes : renderLanes2;
pushRenderLanes(workInProgress2, subtreeRenderLanes2);
}
} else {
var _subtreeRenderLanes;
if (prevState !== null) {
_subtreeRenderLanes = mergeLanes(prevState.baseLanes, renderLanes2);
workInProgress2.memoizedState = null;
} else {
_subtreeRenderLanes = renderLanes2;
}
pushRenderLanes(workInProgress2, _subtreeRenderLanes);
}
reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2);
return workInProgress2.child;
}
var updateLegacyHiddenComponent = updateOffscreenComponent;
function updateFragment(current2, workInProgress2, renderLanes2) {
var nextChildren = workInProgress2.pendingProps;
reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2);
return workInProgress2.child;
}
function updateMode(current2, workInProgress2, renderLanes2) {
var nextChildren = workInProgress2.pendingProps.children;
reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2);
return workInProgress2.child;
}
function updateProfiler(current2, workInProgress2, renderLanes2) {
{
workInProgress2.flags |= Update;
var stateNode = workInProgress2.stateNode;
stateNode.effectDuration = 0;
stateNode.passiveEffectDuration = 0;
}
var nextProps = workInProgress2.pendingProps;
var nextChildren = nextProps.children;
reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2);
return workInProgress2.child;
}
function markRef(current2, workInProgress2) {
var ref = workInProgress2.ref;
if (current2 === null && ref !== null || current2 !== null && current2.ref !== ref) {
workInProgress2.flags |= Ref;
}
}
function updateFunctionComponent(current2, workInProgress2, Component, nextProps, renderLanes2) {
{
if (workInProgress2.type !== workInProgress2.elementType) {
var innerPropTypes = Component.propTypes;
if (innerPropTypes) {
checkPropTypes(innerPropTypes, nextProps, "prop", getComponentName(Component));
}
}
}
var context;
{
var unmaskedContext = getUnmaskedContext(workInProgress2, Component, true);
context = getMaskedContext(workInProgress2, unmaskedContext);
}
var nextChildren;
prepareToReadContext(workInProgress2, renderLanes2);
{
ReactCurrentOwner$1.current = workInProgress2;
setIsRendering(true);
nextChildren = renderWithHooks(current2, workInProgress2, Component, nextProps, context, renderLanes2);
if (workInProgress2.mode & StrictMode) {
disableLogs();
try {
nextChildren = renderWithHooks(current2, workInProgress2, Component, nextProps, context, renderLanes2);
} finally {
reenableLogs();
}
}
setIsRendering(false);
}
if (current2 !== null && !didReceiveUpdate) {
bailoutHooks(current2, workInProgress2, renderLanes2);
return bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2);
}
workInProgress2.flags |= PerformedWork;
reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2);
return workInProgress2.child;
}
function updateClassComponent(current2, workInProgress2, Component, nextProps, renderLanes2) {
{
if (workInProgress2.type !== workInProgress2.elementType) {
var innerPropTypes = Component.propTypes;
if (innerPropTypes) {
checkPropTypes(innerPropTypes, nextProps, "prop", getComponentName(Component));
}
}
}
var hasContext;
if (isContextProvider(Component)) {
hasContext = true;
pushContextProvider(workInProgress2);
} else {
hasContext = false;
}
prepareToReadContext(workInProgress2, renderLanes2);
var instance = workInProgress2.stateNode;
var shouldUpdate;
if (instance === null) {
if (current2 !== null) {
current2.alternate = null;
workInProgress2.alternate = null;
workInProgress2.flags |= Placement;
}
constructClassInstance(workInProgress2, Component, nextProps);
mountClassInstance(workInProgress2, Component, nextProps, renderLanes2);
shouldUpdate = true;
} else if (current2 === null) {
shouldUpdate = resumeMountClassInstance(workInProgress2, Component, nextProps, renderLanes2);
} else {
shouldUpdate = updateClassInstance(current2, workInProgress2, Component, nextProps, renderLanes2);
}
var nextUnitOfWork = finishClassComponent(current2, workInProgress2, Component, shouldUpdate, hasContext, renderLanes2);
{
var inst = workInProgress2.stateNode;
if (shouldUpdate && inst.props !== nextProps) {
if (!didWarnAboutReassigningProps) {
error("It looks like %s is reassigning its own `this.props` while rendering. This is not supported and can lead to confusing bugs.", getComponentName(workInProgress2.type) || "a component");
}
didWarnAboutReassigningProps = true;
}
}
return nextUnitOfWork;
}
function finishClassComponent(current2, workInProgress2, Component, shouldUpdate, hasContext, renderLanes2) {
markRef(current2, workInProgress2);
var didCaptureError = (workInProgress2.flags & DidCapture) !== NoFlags;
if (!shouldUpdate && !didCaptureError) {
if (hasContext) {
invalidateContextProvider(workInProgress2, Component, false);
}
return bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2);
}
var instance = workInProgress2.stateNode;
ReactCurrentOwner$1.current = workInProgress2;
var nextChildren;
if (didCaptureError && typeof Component.getDerivedStateFromError !== "function") {
nextChildren = null;
{
stopProfilerTimerIfRunning();
}
} else {
{
setIsRendering(true);
nextChildren = instance.render();
if (workInProgress2.mode & StrictMode) {
disableLogs();
try {
instance.render();
} finally {
reenableLogs();
}
}
setIsRendering(false);
}
}
workInProgress2.flags |= PerformedWork;
if (current2 !== null && didCaptureError) {
forceUnmountCurrentAndReconcile(current2, workInProgress2, nextChildren, renderLanes2);
} else {
reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2);
}
workInProgress2.memoizedState = instance.state;
if (hasContext) {
invalidateContextProvider(workInProgress2, Component, true);
}
return workInProgress2.child;
}
function pushHostRootContext(workInProgress2) {
var root2 = workInProgress2.stateNode;
if (root2.pendingContext) {
pushTopLevelContextObject(workInProgress2, root2.pendingContext, root2.pendingContext !== root2.context);
} else if (root2.context) {
pushTopLevelContextObject(workInProgress2, root2.context, false);
}
pushHostContainer(workInProgress2, root2.containerInfo);
}
function updateHostRoot(current2, workInProgress2, renderLanes2) {
pushHostRootContext(workInProgress2);
var updateQueue = workInProgress2.updateQueue;
if (!(current2 !== null && updateQueue !== null)) {
{
throw Error("If the root does not have an updateQueue, we should have already bailed out. This error is likely caused by a bug in React. Please file an issue.");
}
}
var nextProps = workInProgress2.pendingProps;
var prevState = workInProgress2.memoizedState;
var prevChildren = prevState !== null ? prevState.element : null;
cloneUpdateQueue(current2, workInProgress2);
processUpdateQueue(workInProgress2, nextProps, null, renderLanes2);
var nextState = workInProgress2.memoizedState;
var nextChildren = nextState.element;
if (nextChildren === prevChildren) {
resetHydrationState();
return bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2);
}
var root2 = workInProgress2.stateNode;
if (root2.hydrate && enterHydrationState(workInProgress2)) {
{
var mutableSourceEagerHydrationData = root2.mutableSourceEagerHydrationData;
if (mutableSourceEagerHydrationData != null) {
for (var i = 0; i < mutableSourceEagerHydrationData.length; i += 2) {
var mutableSource = mutableSourceEagerHydrationData[i];
var version = mutableSourceEagerHydrationData[i + 1];
setWorkInProgressVersion(mutableSource, version);
}
}
}
var child = mountChildFibers(workInProgress2, null, nextChildren, renderLanes2);
workInProgress2.child = child;
var node = child;
while (node) {
node.flags = node.flags & ~Placement | Hydrating;
node = node.sibling;
}
} else {
reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2);
resetHydrationState();
}
return workInProgress2.child;
}
function updateHostComponent(current2, workInProgress2, renderLanes2) {
pushHostContext(workInProgress2);
if (current2 === null) {
tryToClaimNextHydratableInstance(workInProgress2);
}
var type = workInProgress2.type;
var nextProps = workInProgress2.pendingProps;
var prevProps = current2 !== null ? current2.memoizedProps : null;
var nextChildren = nextProps.children;
var isDirectTextChild = shouldSetTextContent(type, nextProps);
if (isDirectTextChild) {
nextChildren = null;
} else if (prevProps !== null && shouldSetTextContent(type, prevProps)) {
workInProgress2.flags |= ContentReset;
}
markRef(current2, workInProgress2);
reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2);
return workInProgress2.child;
}
function updateHostText(current2, workInProgress2) {
if (current2 === null) {
tryToClaimNextHydratableInstance(workInProgress2);
}
return null;
}
function mountLazyComponent(_current, workInProgress2, elementType, updateLanes, renderLanes2) {
if (_current !== null) {
_current.alternate = null;
workInProgress2.alternate = null;
workInProgress2.flags |= Placement;
}
var props = workInProgress2.pendingProps;
var lazyComponent = elementType;
var payload = lazyComponent._payload;
var init = lazyComponent._init;
var Component = init(payload);
workInProgress2.type = Component;
var resolvedTag = workInProgress2.tag = resolveLazyComponentTag(Component);
var resolvedProps = resolveDefaultProps(Component, props);
var child;
switch (resolvedTag) {
case FunctionComponent: {
{
validateFunctionComponentInDev(workInProgress2, Component);
workInProgress2.type = Component = resolveFunctionForHotReloading(Component);
}
child = updateFunctionComponent(null, workInProgress2, Component, resolvedProps, renderLanes2);
return child;
}
case ClassComponent: {
{
workInProgress2.type = Component = resolveClassForHotReloading(Component);
}
child = updateClassComponent(null, workInProgress2, Component, resolvedProps, renderLanes2);
return child;
}
case ForwardRef: {
{
workInProgress2.type = Component = resolveForwardRefForHotReloading(Component);
}
child = updateForwardRef(null, workInProgress2, Component, resolvedProps, renderLanes2);
return child;
}
case MemoComponent: {
{
if (workInProgress2.type !== workInProgress2.elementType) {
var outerPropTypes = Component.propTypes;
if (outerPropTypes) {
checkPropTypes(outerPropTypes, resolvedProps, "prop", getComponentName(Component));
}
}
}
child = updateMemoComponent(null, workInProgress2, Component, resolveDefaultProps(Component.type, resolvedProps), updateLanes, renderLanes2);
return child;
}
}
var hint = "";
{
if (Component !== null && typeof Component === "object" && Component.$$typeof === REACT_LAZY_TYPE) {
hint = " Did you wrap a component in React.lazy() more than once?";
}
}
{
{
throw Error("Element type is invalid. Received a promise that resolves to: " + Component + ". Lazy element type must resolve to a class or function." + hint);
}
}
}
function mountIncompleteClassComponent(_current, workInProgress2, Component, nextProps, renderLanes2) {
if (_current !== null) {
_current.alternate = null;
workInProgress2.alternate = null;
workInProgress2.flags |= Placement;
}
workInProgress2.tag = ClassComponent;
var hasContext;
if (isContextProvider(Component)) {
hasContext = true;
pushContextProvider(workInProgress2);
} else {
hasContext = false;
}
prepareToReadContext(workInProgress2, renderLanes2);
constructClassInstance(workInProgress2, Component, nextProps);
mountClassInstance(workInProgress2, Component, nextProps, renderLanes2);
return finishClassComponent(null, workInProgress2, Component, true, hasContext, renderLanes2);
}
function mountIndeterminateComponent(_current, workInProgress2, Component, renderLanes2) {
if (_current !== null) {
_current.alternate = null;
workInProgress2.alternate = null;
workInProgress2.flags |= Placement;
}
var props = workInProgress2.pendingProps;
var context;
{
var unmaskedContext = getUnmaskedContext(workInProgress2, Component, false);
context = getMaskedContext(workInProgress2, unmaskedContext);
}
prepareToReadContext(workInProgress2, renderLanes2);
var value;
{
if (Component.prototype && typeof Component.prototype.render === "function") {
var componentName = getComponentName(Component) || "Unknown";
if (!didWarnAboutBadClass[componentName]) {
error("The <%s /> component appears to have a render method, but doesn't extend React.Component. This is likely to cause errors. Change %s to extend React.Component instead.", componentName, componentName);
didWarnAboutBadClass[componentName] = true;
}
}
if (workInProgress2.mode & StrictMode) {
ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress2, null);
}
setIsRendering(true);
ReactCurrentOwner$1.current = workInProgress2;
value = renderWithHooks(null, workInProgress2, Component, props, context, renderLanes2);
setIsRendering(false);
}
workInProgress2.flags |= PerformedWork;
{
if (typeof value === "object" && value !== null && typeof value.render === "function" && value.$$typeof === void 0) {
var _componentName = getComponentName(Component) || "Unknown";
if (!didWarnAboutModulePatternComponent[_componentName]) {
error("The <%s /> component appears to be a function component that returns a class instance. Change %s to a class that extends React.Component instead. If you can't use a class try assigning the prototype on the function as a workaround. `%s.prototype = React.Component.prototype`. Don't use an arrow function since it cannot be called with `new` by React.", _componentName, _componentName, _componentName);
didWarnAboutModulePatternComponent[_componentName] = true;
}
}
}
if (typeof value === "object" && value !== null && typeof value.render === "function" && value.$$typeof === void 0) {
{
var _componentName2 = getComponentName(Component) || "Unknown";
if (!didWarnAboutModulePatternComponent[_componentName2]) {
error("The <%s /> component appears to be a function component that returns a class instance. Change %s to a class that extends React.Component instead. If you can't use a class try assigning the prototype on the function as a workaround. `%s.prototype = React.Component.prototype`. Don't use an arrow function since it cannot be called with `new` by React.", _componentName2, _componentName2, _componentName2);
didWarnAboutModulePatternComponent[_componentName2] = true;
}
}
workInProgress2.tag = ClassComponent;
workInProgress2.memoizedState = null;
workInProgress2.updateQueue = null;
var hasContext = false;
if (isContextProvider(Component)) {
hasContext = true;
pushContextProvider(workInProgress2);
} else {
hasContext = false;
}
workInProgress2.memoizedState = value.state !== null && value.state !== void 0 ? value.state : null;
initializeUpdateQueue(workInProgress2);
var getDerivedStateFromProps = Component.getDerivedStateFromProps;
if (typeof getDerivedStateFromProps === "function") {
applyDerivedStateFromProps(workInProgress2, Component, getDerivedStateFromProps, props);
}
adoptClassInstance(workInProgress2, value);
mountClassInstance(workInProgress2, Component, props, renderLanes2);
return finishClassComponent(null, workInProgress2, Component, true, hasContext, renderLanes2);
} else {
workInProgress2.tag = FunctionComponent;
{
if (workInProgress2.mode & StrictMode) {
disableLogs();
try {
value = renderWithHooks(null, workInProgress2, Component, props, context, renderLanes2);
} finally {
reenableLogs();
}
}
}
reconcileChildren(null, workInProgress2, value, renderLanes2);
{
validateFunctionComponentInDev(workInProgress2, Component);
}
return workInProgress2.child;
}
}
function validateFunctionComponentInDev(workInProgress2, Component) {
{
if (Component) {
if (Component.childContextTypes) {
error("%s(...): childContextTypes cannot be defined on a function component.", Component.displayName || Component.name || "Component");
}
}
if (workInProgress2.ref !== null) {
var info = "";
var ownerName = getCurrentFiberOwnerNameInDevOrNull();
if (ownerName) {
info += "\n\nCheck the render method of `" + ownerName + "`.";
}
var warningKey = ownerName || workInProgress2._debugID || "";
var debugSource = workInProgress2._debugSource;
if (debugSource) {
warningKey = debugSource.fileName + ":" + debugSource.lineNumber;
}
if (!didWarnAboutFunctionRefs[warningKey]) {
didWarnAboutFunctionRefs[warningKey] = true;
error("Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?%s", info);
}
}
if (typeof Component.getDerivedStateFromProps === "function") {
var _componentName3 = getComponentName(Component) || "Unknown";
if (!didWarnAboutGetDerivedStateOnFunctionComponent[_componentName3]) {
error("%s: Function components do not support getDerivedStateFromProps.", _componentName3);
didWarnAboutGetDerivedStateOnFunctionComponent[_componentName3] = true;
}
}
if (typeof Component.contextType === "object" && Component.contextType !== null) {
var _componentName4 = getComponentName(Component) || "Unknown";
if (!didWarnAboutContextTypeOnFunctionComponent[_componentName4]) {
error("%s: Function components do not support contextType.", _componentName4);
didWarnAboutContextTypeOnFunctionComponent[_componentName4] = true;
}
}
}
}
var SUSPENDED_MARKER = {
dehydrated: null,
retryLane: NoLane
};
function mountSuspenseOffscreenState(renderLanes2) {
return {
baseLanes: renderLanes2
};
}
function updateSuspenseOffscreenState(prevOffscreenState, renderLanes2) {
return {
baseLanes: mergeLanes(prevOffscreenState.baseLanes, renderLanes2)
};
}
function shouldRemainOnFallback(suspenseContext, current2, workInProgress2, renderLanes2) {
if (current2 !== null) {
var suspenseState = current2.memoizedState;
if (suspenseState === null) {
return false;
}
}
return hasSuspenseContext(suspenseContext, ForceSuspenseFallback);
}
function getRemainingWorkInPrimaryTree(current2, renderLanes2) {
return removeLanes(current2.childLanes, renderLanes2);
}
function updateSuspenseComponent(current2, workInProgress2, renderLanes2) {
var nextProps = workInProgress2.pendingProps;
{
if (shouldSuspend(workInProgress2)) {
workInProgress2.flags |= DidCapture;
}
}
var suspenseContext = suspenseStackCursor.current;
var showFallback = false;
var didSuspend = (workInProgress2.flags & DidCapture) !== NoFlags;
if (didSuspend || shouldRemainOnFallback(suspenseContext, current2)) {
showFallback = true;
workInProgress2.flags &= ~DidCapture;
} else {
if (current2 === null || current2.memoizedState !== null) {
if (nextProps.fallback !== void 0 && nextProps.unstable_avoidThisFallback !== true) {
suspenseContext = addSubtreeSuspenseContext(suspenseContext, InvisibleParentSuspenseContext);
}
}
}
suspenseContext = setDefaultShallowSuspenseContext(suspenseContext);
pushSuspenseContext(workInProgress2, suspenseContext);
if (current2 === null) {
if (nextProps.fallback !== void 0) {
tryToClaimNextHydratableInstance(workInProgress2);
}
var nextPrimaryChildren = nextProps.children;
var nextFallbackChildren = nextProps.fallback;
if (showFallback) {
var fallbackFragment = mountSuspenseFallbackChildren(workInProgress2, nextPrimaryChildren, nextFallbackChildren, renderLanes2);
var primaryChildFragment = workInProgress2.child;
primaryChildFragment.memoizedState = mountSuspenseOffscreenState(renderLanes2);
workInProgress2.memoizedState = SUSPENDED_MARKER;
return fallbackFragment;
} else if (typeof nextProps.unstable_expectedLoadTime === "number") {
var _fallbackFragment = mountSuspenseFallbackChildren(workInProgress2, nextPrimaryChildren, nextFallbackChildren, renderLanes2);
var _primaryChildFragment = workInProgress2.child;
_primaryChildFragment.memoizedState = mountSuspenseOffscreenState(renderLanes2);
workInProgress2.memoizedState = SUSPENDED_MARKER;
workInProgress2.lanes = SomeRetryLane;
{
markSpawnedWork(SomeRetryLane);
}
return _fallbackFragment;
} else {
return mountSuspensePrimaryChildren(workInProgress2, nextPrimaryChildren, renderLanes2);
}
} else {
var prevState = current2.memoizedState;
if (prevState !== null) {
if (showFallback) {
var _nextFallbackChildren2 = nextProps.fallback;
var _nextPrimaryChildren2 = nextProps.children;
var _fallbackChildFragment = updateSuspenseFallbackChildren(current2, workInProgress2, _nextPrimaryChildren2, _nextFallbackChildren2, renderLanes2);
var _primaryChildFragment3 = workInProgress2.child;
var prevOffscreenState = current2.child.memoizedState;
_primaryChildFragment3.memoizedState = prevOffscreenState === null ? mountSuspenseOffscreenState(renderLanes2) : updateSuspenseOffscreenState(prevOffscreenState, renderLanes2);
_primaryChildFragment3.childLanes = getRemainingWorkInPrimaryTree(current2, renderLanes2);
workInProgress2.memoizedState = SUSPENDED_MARKER;
return _fallbackChildFragment;
} else {
var _nextPrimaryChildren3 = nextProps.children;
var _primaryChildFragment4 = updateSuspensePrimaryChildren(current2, workInProgress2, _nextPrimaryChildren3, renderLanes2);
workInProgress2.memoizedState = null;
return _primaryChildFragment4;
}
} else {
if (showFallback) {
var _nextFallbackChildren3 = nextProps.fallback;
var _nextPrimaryChildren4 = nextProps.children;
var _fallbackChildFragment2 = updateSuspenseFallbackChildren(current2, workInProgress2, _nextPrimaryChildren4, _nextFallbackChildren3, renderLanes2);
var _primaryChildFragment5 = workInProgress2.child;
var _prevOffscreenState = current2.child.memoizedState;
_primaryChildFragment5.memoizedState = _prevOffscreenState === null ? mountSuspenseOffscreenState(renderLanes2) : updateSuspenseOffscreenState(_prevOffscreenState, renderLanes2);
_primaryChildFragment5.childLanes = getRemainingWorkInPrimaryTree(current2, renderLanes2);
workInProgress2.memoizedState = SUSPENDED_MARKER;
return _fallbackChildFragment2;
} else {
var _nextPrimaryChildren5 = nextProps.children;
var _primaryChildFragment6 = updateSuspensePrimaryChildren(current2, workInProgress2, _nextPrimaryChildren5, renderLanes2);
workInProgress2.memoizedState = null;
return _primaryChildFragment6;
}
}
}
}
function mountSuspensePrimaryChildren(workInProgress2, primaryChildren, renderLanes2) {
var mode = workInProgress2.mode;
var primaryChildProps = {
mode: "visible",
children: primaryChildren
};
var primaryChildFragment = createFiberFromOffscreen(primaryChildProps, mode, renderLanes2, null);
primaryChildFragment.return = workInProgress2;
workInProgress2.child = primaryChildFragment;
return primaryChildFragment;
}
function mountSuspenseFallbackChildren(workInProgress2, primaryChildren, fallbackChildren, renderLanes2) {
var mode = workInProgress2.mode;
var progressedPrimaryFragment = workInProgress2.child;
var primaryChildProps = {
mode: "hidden",
children: primaryChildren
};
var primaryChildFragment;
var fallbackChildFragment;
if ((mode & BlockingMode) === NoMode && progressedPrimaryFragment !== null) {
primaryChildFragment = progressedPrimaryFragment;
primaryChildFragment.childLanes = NoLanes;
primaryChildFragment.pendingProps = primaryChildProps;
if (workInProgress2.mode & ProfileMode) {
primaryChildFragment.actualDuration = 0;
primaryChildFragment.actualStartTime = -1;
primaryChildFragment.selfBaseDuration = 0;
primaryChildFragment.treeBaseDuration = 0;
}
fallbackChildFragment = createFiberFromFragment(fallbackChildren, mode, renderLanes2, null);
} else {
primaryChildFragment = createFiberFromOffscreen(primaryChildProps, mode, NoLanes, null);
fallbackChildFragment = createFiberFromFragment(fallbackChildren, mode, renderLanes2, null);
}
primaryChildFragment.return = workInProgress2;
fallbackChildFragment.return = workInProgress2;
primaryChildFragment.sibling = fallbackChildFragment;
workInProgress2.child = primaryChildFragment;
return fallbackChildFragment;
}
function createWorkInProgressOffscreenFiber(current2, offscreenProps) {
return createWorkInProgress(current2, offscreenProps);
}
function updateSuspensePrimaryChildren(current2, workInProgress2, primaryChildren, renderLanes2) {
var currentPrimaryChildFragment = current2.child;
var currentFallbackChildFragment = currentPrimaryChildFragment.sibling;
var primaryChildFragment = createWorkInProgressOffscreenFiber(currentPrimaryChildFragment, {
mode: "visible",
children: primaryChildren
});
if ((workInProgress2.mode & BlockingMode) === NoMode) {
primaryChildFragment.lanes = renderLanes2;
}
primaryChildFragment.return = workInProgress2;
primaryChildFragment.sibling = null;
if (currentFallbackChildFragment !== null) {
currentFallbackChildFragment.nextEffect = null;
currentFallbackChildFragment.flags = Deletion;
workInProgress2.firstEffect = workInProgress2.lastEffect = currentFallbackChildFragment;
}
workInProgress2.child = primaryChildFragment;
return primaryChildFragment;
}
function updateSuspenseFallbackChildren(current2, workInProgress2, primaryChildren, fallbackChildren, renderLanes2) {
var mode = workInProgress2.mode;
var currentPrimaryChildFragment = current2.child;
var currentFallbackChildFragment = currentPrimaryChildFragment.sibling;
var primaryChildProps = {
mode: "hidden",
children: primaryChildren
};
var primaryChildFragment;
if ((mode & BlockingMode) === NoMode && workInProgress2.child !== currentPrimaryChildFragment) {
var progressedPrimaryFragment = workInProgress2.child;
primaryChildFragment = progressedPrimaryFragment;
primaryChildFragment.childLanes = NoLanes;
primaryChildFragment.pendingProps = primaryChildProps;
if (workInProgress2.mode & ProfileMode) {
primaryChildFragment.actualDuration = 0;
primaryChildFragment.actualStartTime = -1;
primaryChildFragment.selfBaseDuration = currentPrimaryChildFragment.selfBaseDuration;
primaryChildFragment.treeBaseDuration = currentPrimaryChildFragment.treeBaseDuration;
}
var progressedLastEffect = primaryChildFragment.lastEffect;
if (progressedLastEffect !== null) {
workInProgress2.firstEffect = primaryChildFragment.firstEffect;
workInProgress2.lastEffect = progressedLastEffect;
progressedLastEffect.nextEffect = null;
} else {
workInProgress2.firstEffect = workInProgress2.lastEffect = null;
}
} else {
primaryChildFragment = createWorkInProgressOffscreenFiber(currentPrimaryChildFragment, primaryChildProps);
}
var fallbackChildFragment;
if (currentFallbackChildFragment !== null) {
fallbackChildFragment = createWorkInProgress(currentFallbackChildFragment, fallbackChildren);
} else {
fallbackChildFragment = createFiberFromFragment(fallbackChildren, mode, renderLanes2, null);
fallbackChildFragment.flags |= Placement;
}
fallbackChildFragment.return = workInProgress2;
primaryChildFragment.return = workInProgress2;
primaryChildFragment.sibling = fallbackChildFragment;
workInProgress2.child = primaryChildFragment;
return fallbackChildFragment;
}
function scheduleWorkOnFiber(fiber, renderLanes2) {
fiber.lanes = mergeLanes(fiber.lanes, renderLanes2);
var alternate = fiber.alternate;
if (alternate !== null) {
alternate.lanes = mergeLanes(alternate.lanes, renderLanes2);
}
scheduleWorkOnParentPath(fiber.return, renderLanes2);
}
function propagateSuspenseContextChange(workInProgress2, firstChild, renderLanes2) {
var node = firstChild;
while (node !== null) {
if (node.tag === SuspenseComponent) {
var state = node.memoizedState;
if (state !== null) {
scheduleWorkOnFiber(node, renderLanes2);
}
} else if (node.tag === SuspenseListComponent) {
scheduleWorkOnFiber(node, renderLanes2);
} else if (node.child !== null) {
node.child.return = node;
node = node.child;
continue;
}
if (node === workInProgress2) {
return;
}
while (node.sibling === null) {
if (node.return === null || node.return === workInProgress2) {
return;
}
node = node.return;
}
node.sibling.return = node.return;
node = node.sibling;
}
}
function findLastContentRow(firstChild) {
var row = firstChild;
var lastContentRow = null;
while (row !== null) {
var currentRow = row.alternate;
if (currentRow !== null && findFirstSuspended(currentRow) === null) {
lastContentRow = row;
}
row = row.sibling;
}
return lastContentRow;
}
function validateRevealOrder(revealOrder) {
{
if (revealOrder !== void 0 && revealOrder !== "forwards" && revealOrder !== "backwards" && revealOrder !== "together" && !didWarnAboutRevealOrder[revealOrder]) {
didWarnAboutRevealOrder[revealOrder] = true;
if (typeof revealOrder === "string") {
switch (revealOrder.toLowerCase()) {
case "together":
case "forwards":
case "backwards": {
error('"%s" is not a valid value for revealOrder on <SuspenseList />. Use lowercase "%s" instead.', revealOrder, revealOrder.toLowerCase());
break;
}
case "forward":
case "backward": {
error('"%s" is not a valid value for revealOrder on <SuspenseList />. React uses the -s suffix in the spelling. Use "%ss" instead.', revealOrder, revealOrder.toLowerCase());
break;
}
default:
error('"%s" is not a supported revealOrder on <SuspenseList />. Did you mean "together", "forwards" or "backwards"?', revealOrder);
break;
}
} else {
error('%s is not a supported value for revealOrder on <SuspenseList />. Did you mean "together", "forwards" or "backwards"?', revealOrder);
}
}
}
}
function validateTailOptions(tailMode, revealOrder) {
{
if (tailMode !== void 0 && !didWarnAboutTailOptions[tailMode]) {
if (tailMode !== "collapsed" && tailMode !== "hidden") {
didWarnAboutTailOptions[tailMode] = true;
error('"%s" is not a supported value for tail on <SuspenseList />. Did you mean "collapsed" or "hidden"?', tailMode);
} else if (revealOrder !== "forwards" && revealOrder !== "backwards") {
didWarnAboutTailOptions[tailMode] = true;
error('<SuspenseList tail="%s" /> is only valid if revealOrder is "forwards" or "backwards". Did you mean to specify revealOrder="forwards"?', tailMode);
}
}
}
}
function validateSuspenseListNestedChild(childSlot, index2) {
{
var isArray2 = Array.isArray(childSlot);
var isIterable = !isArray2 && typeof getIteratorFn(childSlot) === "function";
if (isArray2 || isIterable) {
var type = isArray2 ? "array" : "iterable";
error("A nested %s was passed to row #%s in <SuspenseList />. Wrap it in an additional SuspenseList to configure its revealOrder: <SuspenseList revealOrder=...> ... <SuspenseList revealOrder=...>{%s}</SuspenseList> ... </SuspenseList>", type, index2, type);
return false;
}
}
return true;
}
function validateSuspenseListChildren(children, revealOrder) {
{
if ((revealOrder === "forwards" || revealOrder === "backwards") && children !== void 0 && children !== null && children !== false) {
if (Array.isArray(children)) {
for (var i = 0; i < children.length; i++) {
if (!validateSuspenseListNestedChild(children[i], i)) {
return;
}
}
} else {
var iteratorFn = getIteratorFn(children);
if (typeof iteratorFn === "function") {
var childrenIterator = iteratorFn.call(children);
if (childrenIterator) {
var step = childrenIterator.next();
var _i = 0;
for (; !step.done; step = childrenIterator.next()) {
if (!validateSuspenseListNestedChild(step.value, _i)) {
return;
}
_i++;
}
}
} else {
error('A single row was passed to a <SuspenseList revealOrder="%s" />. This is not useful since it needs multiple rows. Did you mean to pass multiple children or an array?', revealOrder);
}
}
}
}
}
function initSuspenseListRenderState(workInProgress2, isBackwards, tail, lastContentRow, tailMode, lastEffectBeforeRendering) {
var renderState = workInProgress2.memoizedState;
if (renderState === null) {
workInProgress2.memoizedState = {
isBackwards,
rendering: null,
renderingStartTime: 0,
last: lastContentRow,
tail,
tailMode,
lastEffect: lastEffectBeforeRendering
};
} else {
renderState.isBackwards = isBackwards;
renderState.rendering = null;
renderState.renderingStartTime = 0;
renderState.last = lastContentRow;
renderState.tail = tail;
renderState.tailMode = tailMode;
renderState.lastEffect = lastEffectBeforeRendering;
}
}
function updateSuspenseListComponent(current2, workInProgress2, renderLanes2) {
var nextProps = workInProgress2.pendingProps;
var revealOrder = nextProps.revealOrder;
var tailMode = nextProps.tail;
var newChildren = nextProps.children;
validateRevealOrder(revealOrder);
validateTailOptions(tailMode, revealOrder);
validateSuspenseListChildren(newChildren, revealOrder);
reconcileChildren(current2, workInProgress2, newChildren, renderLanes2);
var suspenseContext = suspenseStackCursor.current;
var shouldForceFallback = hasSuspenseContext(suspenseContext, ForceSuspenseFallback);
if (shouldForceFallback) {
suspenseContext = setShallowSuspenseContext(suspenseContext, ForceSuspenseFallback);
workInProgress2.flags |= DidCapture;
} else {
var didSuspendBefore = current2 !== null && (current2.flags & DidCapture) !== NoFlags;
if (didSuspendBefore) {
propagateSuspenseContextChange(workInProgress2, workInProgress2.child, renderLanes2);
}
suspenseContext = setDefaultShallowSuspenseContext(suspenseContext);
}
pushSuspenseContext(workInProgress2, suspenseContext);
if ((workInProgress2.mode & BlockingMode) === NoMode) {
workInProgress2.memoizedState = null;
} else {
switch (revealOrder) {
case "forwards": {
var lastContentRow = findLastContentRow(workInProgress2.child);
var tail;
if (lastContentRow === null) {
tail = workInProgress2.child;
workInProgress2.child = null;
} else {
tail = lastContentRow.sibling;
lastContentRow.sibling = null;
}
initSuspenseListRenderState(workInProgress2, false, tail, lastContentRow, tailMode, workInProgress2.lastEffect);
break;
}
case "backwards": {
var _tail = null;
var row = workInProgress2.child;
workInProgress2.child = null;
while (row !== null) {
var currentRow = row.alternate;
if (currentRow !== null && findFirstSuspended(currentRow) === null) {
workInProgress2.child = row;
break;
}
var nextRow = row.sibling;
row.sibling = _tail;
_tail = row;
row = nextRow;
}
initSuspenseListRenderState(workInProgress2, true, _tail, null, tailMode, workInProgress2.lastEffect);
break;
}
case "together": {
initSuspenseListRenderState(workInProgress2, false, null, null, void 0, workInProgress2.lastEffect);
break;
}
default: {
workInProgress2.memoizedState = null;
}
}
}
return workInProgress2.child;
}
function updatePortalComponent(current2, workInProgress2, renderLanes2) {
pushHostContainer(workInProgress2, workInProgress2.stateNode.containerInfo);
var nextChildren = workInProgress2.pendingProps;
if (current2 === null) {
workInProgress2.child = reconcileChildFibers(workInProgress2, null, nextChildren, renderLanes2);
} else {
reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2);
}
return workInProgress2.child;
}
var hasWarnedAboutUsingNoValuePropOnContextProvider = false;
function updateContextProvider(current2, workInProgress2, renderLanes2) {
var providerType = workInProgress2.type;
var context = providerType._context;
var newProps = workInProgress2.pendingProps;
var oldProps = workInProgress2.memoizedProps;
var newValue = newProps.value;
{
if (!("value" in newProps)) {
if (!hasWarnedAboutUsingNoValuePropOnContextProvider) {
hasWarnedAboutUsingNoValuePropOnContextProvider = true;
error("The `value` prop is required for the `<Context.Provider>`. Did you misspell it or forget to pass it?");
}
}
var providerPropTypes = workInProgress2.type.propTypes;
if (providerPropTypes) {
checkPropTypes(providerPropTypes, newProps, "prop", "Context.Provider");
}
}
pushProvider(workInProgress2, newValue);
if (oldProps !== null) {
var oldValue = oldProps.value;
var changedBits = calculateChangedBits(context, newValue, oldValue);
if (changedBits === 0) {
if (oldProps.children === newProps.children && !hasContextChanged()) {
return bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2);
}
} else {
propagateContextChange(workInProgress2, context, changedBits, renderLanes2);
}
}
var newChildren = newProps.children;
reconcileChildren(current2, workInProgress2, newChildren, renderLanes2);
return workInProgress2.child;
}
var hasWarnedAboutUsingContextAsConsumer = false;
function updateContextConsumer(current2, workInProgress2, renderLanes2) {
var context = workInProgress2.type;
{
if (context._context === void 0) {
if (context !== context.Consumer) {
if (!hasWarnedAboutUsingContextAsConsumer) {
hasWarnedAboutUsingContextAsConsumer = true;
error("Rendering <Context> directly is not supported and will be removed in a future major release. Did you mean to render <Context.Consumer> instead?");
}
}
} else {
context = context._context;
}
}
var newProps = workInProgress2.pendingProps;
var render2 = newProps.children;
{
if (typeof render2 !== "function") {
error("A context consumer was rendered with multiple children, or a child that isn't a function. A context consumer expects a single child that is a function. If you did pass a function, make sure there is no trailing or leading whitespace around it.");
}
}
prepareToReadContext(workInProgress2, renderLanes2);
var newValue = readContext(context, newProps.unstable_observedBits);
var newChildren;
{
ReactCurrentOwner$1.current = workInProgress2;
setIsRendering(true);
newChildren = render2(newValue);
setIsRendering(false);
}
workInProgress2.flags |= PerformedWork;
reconcileChildren(current2, workInProgress2, newChildren, renderLanes2);
return workInProgress2.child;
}
function markWorkInProgressReceivedUpdate() {
didReceiveUpdate = true;
}
function bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2) {
if (current2 !== null) {
workInProgress2.dependencies = current2.dependencies;
}
{
stopProfilerTimerIfRunning();
}
markSkippedUpdateLanes(workInProgress2.lanes);
if (!includesSomeLane(renderLanes2, workInProgress2.childLanes)) {
return null;
} else {
cloneChildFibers(current2, workInProgress2);
return workInProgress2.child;
}
}
function remountFiber(current2, oldWorkInProgress, newWorkInProgress) {
{
var returnFiber = oldWorkInProgress.return;
if (returnFiber === null) {
throw new Error("Cannot swap the root fiber.");
}
current2.alternate = null;
oldWorkInProgress.alternate = null;
newWorkInProgress.index = oldWorkInProgress.index;
newWorkInProgress.sibling = oldWorkInProgress.sibling;
newWorkInProgress.return = oldWorkInProgress.return;
newWorkInProgress.ref = oldWorkInProgress.ref;
if (oldWorkInProgress === returnFiber.child) {
returnFiber.child = newWorkInProgress;
} else {
var prevSibling = returnFiber.child;
if (prevSibling === null) {
throw new Error("Expected parent to have a child.");
}
while (prevSibling.sibling !== oldWorkInProgress) {
prevSibling = prevSibling.sibling;
if (prevSibling === null) {
throw new Error("Expected to find the previous sibling.");
}
}
prevSibling.sibling = newWorkInProgress;
}
var last = returnFiber.lastEffect;
if (last !== null) {
last.nextEffect = current2;
returnFiber.lastEffect = current2;
} else {
returnFiber.firstEffect = returnFiber.lastEffect = current2;
}
current2.nextEffect = null;
current2.flags = Deletion;
newWorkInProgress.flags |= Placement;
return newWorkInProgress;
}
}
function beginWork(current2, workInProgress2, renderLanes2) {
var updateLanes = workInProgress2.lanes;
{
if (workInProgress2._debugNeedsRemount && current2 !== null) {
return remountFiber(current2, workInProgress2, createFiberFromTypeAndProps(workInProgress2.type, workInProgress2.key, workInProgress2.pendingProps, workInProgress2._debugOwner || null, workInProgress2.mode, workInProgress2.lanes));
}
}
if (current2 !== null) {
var oldProps = current2.memoizedProps;
var newProps = workInProgress2.pendingProps;
if (oldProps !== newProps || hasContextChanged() || workInProgress2.type !== current2.type) {
didReceiveUpdate = true;
} else if (!includesSomeLane(renderLanes2, updateLanes)) {
didReceiveUpdate = false;
switch (workInProgress2.tag) {
case HostRoot:
pushHostRootContext(workInProgress2);
resetHydrationState();
break;
case HostComponent:
pushHostContext(workInProgress2);
break;
case ClassComponent: {
var Component = workInProgress2.type;
if (isContextProvider(Component)) {
pushContextProvider(workInProgress2);
}
break;
}
case HostPortal:
pushHostContainer(workInProgress2, workInProgress2.stateNode.containerInfo);
break;
case ContextProvider: {
var newValue = workInProgress2.memoizedProps.value;
pushProvider(workInProgress2, newValue);
break;
}
case Profiler:
{
var hasChildWork = includesSomeLane(renderLanes2, workInProgress2.childLanes);
if (hasChildWork) {
workInProgress2.flags |= Update;
}
var stateNode = workInProgress2.stateNode;
stateNode.effectDuration = 0;
stateNode.passiveEffectDuration = 0;
}
break;
case SuspenseComponent: {
var state = workInProgress2.memoizedState;
if (state !== null) {
var primaryChildFragment = workInProgress2.child;
var primaryChildLanes = primaryChildFragment.childLanes;
if (includesSomeLane(renderLanes2, primaryChildLanes)) {
return updateSuspenseComponent(current2, workInProgress2, renderLanes2);
} else {
pushSuspenseContext(workInProgress2, setDefaultShallowSuspenseContext(suspenseStackCursor.current));
var child = bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2);
if (child !== null) {
return child.sibling;
} else {
return null;
}
}
} else {
pushSuspenseContext(workInProgress2, setDefaultShallowSuspenseContext(suspenseStackCursor.current));
}
break;
}
case SuspenseListComponent: {
var didSuspendBefore = (current2.flags & DidCapture) !== NoFlags;
var _hasChildWork = includesSomeLane(renderLanes2, workInProgress2.childLanes);
if (didSuspendBefore) {
if (_hasChildWork) {
return updateSuspenseListComponent(current2, workInProgress2, renderLanes2);
}
workInProgress2.flags |= DidCapture;
}
var renderState = workInProgress2.memoizedState;
if (renderState !== null) {
renderState.rendering = null;
renderState.tail = null;
renderState.lastEffect = null;
}
pushSuspenseContext(workInProgress2, suspenseStackCursor.current);
if (_hasChildWork) {
break;
} else {
return null;
}
}
case OffscreenComponent:
case LegacyHiddenComponent: {
workInProgress2.lanes = NoLanes;
return updateOffscreenComponent(current2, workInProgress2, renderLanes2);
}
}
return bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2);
} else {
if ((current2.flags & ForceUpdateForLegacySuspense) !== NoFlags) {
didReceiveUpdate = true;
} else {
didReceiveUpdate = false;
}
}
} else {
didReceiveUpdate = false;
}
workInProgress2.lanes = NoLanes;
switch (workInProgress2.tag) {
case IndeterminateComponent: {
return mountIndeterminateComponent(current2, workInProgress2, workInProgress2.type, renderLanes2);
}
case LazyComponent: {
var elementType = workInProgress2.elementType;
return mountLazyComponent(current2, workInProgress2, elementType, updateLanes, renderLanes2);
}
case FunctionComponent: {
var _Component = workInProgress2.type;
var unresolvedProps = workInProgress2.pendingProps;
var resolvedProps = workInProgress2.elementType === _Component ? unresolvedProps : resolveDefaultProps(_Component, unresolvedProps);
return updateFunctionComponent(current2, workInProgress2, _Component, resolvedProps, renderLanes2);
}
case ClassComponent: {
var _Component2 = workInProgress2.type;
var _unresolvedProps = workInProgress2.pendingProps;
var _resolvedProps = workInProgress2.elementType === _Component2 ? _unresolvedProps : resolveDefaultProps(_Component2, _unresolvedProps);
return updateClassComponent(current2, workInProgress2, _Component2, _resolvedProps, renderLanes2);
}
case HostRoot:
return updateHostRoot(current2, workInProgress2, renderLanes2);
case HostComponent:
return updateHostComponent(current2, workInProgress2, renderLanes2);
case HostText:
return updateHostText(current2, workInProgress2);
case SuspenseComponent:
return updateSuspenseComponent(current2, workInProgress2, renderLanes2);
case HostPortal:
return updatePortalComponent(current2, workInProgress2, renderLanes2);
case ForwardRef: {
var type = workInProgress2.type;
var _unresolvedProps2 = workInProgress2.pendingProps;
var _resolvedProps2 = workInProgress2.elementType === type ? _unresolvedProps2 : resolveDefaultProps(type, _unresolvedProps2);
return updateForwardRef(current2, workInProgress2, type, _resolvedProps2, renderLanes2);
}
case Fragment:
return updateFragment(current2, workInProgress2, renderLanes2);
case Mode:
return updateMode(current2, workInProgress2, renderLanes2);
case Profiler:
return updateProfiler(current2, workInProgress2, renderLanes2);
case ContextProvider:
return updateContextProvider(current2, workInProgress2, renderLanes2);
case ContextConsumer:
return updateContextConsumer(current2, workInProgress2, renderLanes2);
case MemoComponent: {
var _type2 = workInProgress2.type;
var _unresolvedProps3 = workInProgress2.pendingProps;
var _resolvedProps3 = resolveDefaultProps(_type2, _unresolvedProps3);
{
if (workInProgress2.type !== workInProgress2.elementType) {
var outerPropTypes = _type2.propTypes;
if (outerPropTypes) {
checkPropTypes(outerPropTypes, _resolvedProps3, "prop", getComponentName(_type2));
}
}
}
_resolvedProps3 = resolveDefaultProps(_type2.type, _resolvedProps3);
return updateMemoComponent(current2, workInProgress2, _type2, _resolvedProps3, updateLanes, renderLanes2);
}
case SimpleMemoComponent: {
return updateSimpleMemoComponent(current2, workInProgress2, workInProgress2.type, workInProgress2.pendingProps, updateLanes, renderLanes2);
}
case IncompleteClassComponent: {
var _Component3 = workInProgress2.type;
var _unresolvedProps4 = workInProgress2.pendingProps;
var _resolvedProps4 = workInProgress2.elementType === _Component3 ? _unresolvedProps4 : resolveDefaultProps(_Component3, _unresolvedProps4);
return mountIncompleteClassComponent(current2, workInProgress2, _Component3, _resolvedProps4, renderLanes2);
}
case SuspenseListComponent: {
return updateSuspenseListComponent(current2, workInProgress2, renderLanes2);
}
case FundamentalComponent: {
break;
}
case ScopeComponent: {
break;
}
case Block: {
break;
}
case OffscreenComponent: {
return updateOffscreenComponent(current2, workInProgress2, renderLanes2);
}
case LegacyHiddenComponent: {
return updateLegacyHiddenComponent(current2, workInProgress2, renderLanes2);
}
}
{
{
throw Error("Unknown unit of work tag (" + workInProgress2.tag + "). This error is likely caused by a bug in React. Please file an issue.");
}
}
}
function markUpdate(workInProgress2) {
workInProgress2.flags |= Update;
}
function markRef$1(workInProgress2) {
workInProgress2.flags |= Ref;
}
var appendAllChildren;
var updateHostContainer;
var updateHostComponent$1;
var updateHostText$1;
{
appendAllChildren = function(parent, workInProgress2, needsVisibilityToggle, isHidden) {
var node = workInProgress2.child;
while (node !== null) {
if (node.tag === HostComponent || node.tag === HostText) {
appendInitialChild(parent, node.stateNode);
} else if (node.tag === HostPortal)
;
else if (node.child !== null) {
node.child.return = node;
node = node.child;
continue;
}
if (node === workInProgress2) {
return;
}
while (node.sibling === null) {
if (node.return === null || node.return === workInProgress2) {
return;
}
node = node.return;
}
node.sibling.return = node.return;
node = node.sibling;
}
};
updateHostContainer = function(workInProgress2) {
};
updateHostComponent$1 = function(current2, workInProgress2, type, newProps, rootContainerInstance) {
var oldProps = current2.memoizedProps;
if (oldProps === newProps) {
return;
}
var instance = workInProgress2.stateNode;
var currentHostContext = getHostContext();
var updatePayload = prepareUpdate(instance, type, oldProps, newProps, rootContainerInstance, currentHostContext);
workInProgress2.updateQueue = updatePayload;
if (updatePayload) {
markUpdate(workInProgress2);
}
};
updateHostText$1 = function(current2, workInProgress2, oldText, newText) {
if (oldText !== newText) {
markUpdate(workInProgress2);
}
};
}
function cutOffTailIfNeeded(renderState, hasRenderedATailFallback) {
if (getIsHydrating()) {
return;
}
switch (renderState.tailMode) {
case "hidden": {
var tailNode = renderState.tail;
var lastTailNode = null;
while (tailNode !== null) {
if (tailNode.alternate !== null) {
lastTailNode = tailNode;
}
tailNode = tailNode.sibling;
}
if (lastTailNode === null) {
renderState.tail = null;
} else {
lastTailNode.sibling = null;
}
break;
}
case "collapsed": {
var _tailNode = renderState.tail;
var _lastTailNode = null;
while (_tailNode !== null) {
if (_tailNode.alternate !== null) {
_lastTailNode = _tailNode;
}
_tailNode = _tailNode.sibling;
}
if (_lastTailNode === null) {
if (!hasRenderedATailFallback && renderState.tail !== null) {
renderState.tail.sibling = null;
} else {
renderState.tail = null;
}
} else {
_lastTailNode.sibling = null;
}
break;
}
}
}
function completeWork(current2, workInProgress2, renderLanes2) {
var newProps = workInProgress2.pendingProps;
switch (workInProgress2.tag) {
case IndeterminateComponent:
case LazyComponent:
case SimpleMemoComponent:
case FunctionComponent:
case ForwardRef:
case Fragment:
case Mode:
case Profiler:
case ContextConsumer:
case MemoComponent:
return null;
case ClassComponent: {
var Component = workInProgress2.type;
if (isContextProvider(Component)) {
popContext(workInProgress2);
}
return null;
}
case HostRoot: {
popHostContainer(workInProgress2);
popTopLevelContextObject(workInProgress2);
resetWorkInProgressVersions();
var fiberRoot = workInProgress2.stateNode;
if (fiberRoot.pendingContext) {
fiberRoot.context = fiberRoot.pendingContext;
fiberRoot.pendingContext = null;
}
if (current2 === null || current2.child === null) {
var wasHydrated = popHydrationState(workInProgress2);
if (wasHydrated) {
markUpdate(workInProgress2);
} else if (!fiberRoot.hydrate) {
workInProgress2.flags |= Snapshot;
}
}
updateHostContainer(workInProgress2);
return null;
}
case HostComponent: {
popHostContext(workInProgress2);
var rootContainerInstance = getRootHostContainer();
var type = workInProgress2.type;
if (current2 !== null && workInProgress2.stateNode != null) {
updateHostComponent$1(current2, workInProgress2, type, newProps, rootContainerInstance);
if (current2.ref !== workInProgress2.ref) {
markRef$1(workInProgress2);
}
} else {
if (!newProps) {
if (!(workInProgress2.stateNode !== null)) {
{
throw Error("We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue.");
}
}
return null;
}
var currentHostContext = getHostContext();
var _wasHydrated = popHydrationState(workInProgress2);
if (_wasHydrated) {
if (prepareToHydrateHostInstance(workInProgress2, rootContainerInstance, currentHostContext)) {
markUpdate(workInProgress2);
}
} else {
var instance = createInstance(type, newProps, rootContainerInstance, currentHostContext, workInProgress2);
appendAllChildren(instance, workInProgress2, false, false);
workInProgress2.stateNode = instance;
if (finalizeInitialChildren(instance, type, newProps, rootContainerInstance)) {
markUpdate(workInProgress2);
}
}
if (workInProgress2.ref !== null) {
markRef$1(workInProgress2);
}
}
return null;
}
case HostText: {
var newText = newProps;
if (current2 && workInProgress2.stateNode != null) {
var oldText = current2.memoizedProps;
updateHostText$1(current2, workInProgress2, oldText, newText);
} else {
if (typeof newText !== "string") {
if (!(workInProgress2.stateNode !== null)) {
{
throw Error("We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue.");
}
}
}
var _rootContainerInstance = getRootHostContainer();
var _currentHostContext = getHostContext();
var _wasHydrated2 = popHydrationState(workInProgress2);
if (_wasHydrated2) {
if (prepareToHydrateHostTextInstance(workInProgress2)) {
markUpdate(workInProgress2);
}
} else {
workInProgress2.stateNode = createTextInstance(newText, _rootContainerInstance, _currentHostContext, workInProgress2);
}
}
return null;
}
case SuspenseComponent: {
popSuspenseContext(workInProgress2);
var nextState = workInProgress2.memoizedState;
if ((workInProgress2.flags & DidCapture) !== NoFlags) {
workInProgress2.lanes = renderLanes2;
if ((workInProgress2.mode & ProfileMode) !== NoMode) {
transferActualDuration(workInProgress2);
}
return workInProgress2;
}
var nextDidTimeout = nextState !== null;
var prevDidTimeout = false;
if (current2 === null) {
if (workInProgress2.memoizedProps.fallback !== void 0) {
popHydrationState(workInProgress2);
}
} else {
var prevState = current2.memoizedState;
prevDidTimeout = prevState !== null;
}
if (nextDidTimeout && !prevDidTimeout) {
if ((workInProgress2.mode & BlockingMode) !== NoMode) {
var hasInvisibleChildContext = current2 === null && workInProgress2.memoizedProps.unstable_avoidThisFallback !== true;
if (hasInvisibleChildContext || hasSuspenseContext(suspenseStackCursor.current, InvisibleParentSuspenseContext)) {
renderDidSuspend();
} else {
renderDidSuspendDelayIfPossible();
}
}
}
{
if (nextDidTimeout || prevDidTimeout) {
workInProgress2.flags |= Update;
}
}
return null;
}
case HostPortal:
popHostContainer(workInProgress2);
updateHostContainer(workInProgress2);
if (current2 === null) {
preparePortalMount(workInProgress2.stateNode.containerInfo);
}
return null;
case ContextProvider:
popProvider(workInProgress2);
return null;
case IncompleteClassComponent: {
var _Component = workInProgress2.type;
if (isContextProvider(_Component)) {
popContext(workInProgress2);
}
return null;
}
case SuspenseListComponent: {
popSuspenseContext(workInProgress2);
var renderState = workInProgress2.memoizedState;
if (renderState === null) {
return null;
}
var didSuspendAlready = (workInProgress2.flags & DidCapture) !== NoFlags;
var renderedTail = renderState.rendering;
if (renderedTail === null) {
if (!didSuspendAlready) {
var cannotBeSuspended = renderHasNotSuspendedYet() && (current2 === null || (current2.flags & DidCapture) === NoFlags);
if (!cannotBeSuspended) {
var row = workInProgress2.child;
while (row !== null) {
var suspended = findFirstSuspended(row);
if (suspended !== null) {
didSuspendAlready = true;
workInProgress2.flags |= DidCapture;
cutOffTailIfNeeded(renderState, false);
var newThennables = suspended.updateQueue;
if (newThennables !== null) {
workInProgress2.updateQueue = newThennables;
workInProgress2.flags |= Update;
}
if (renderState.lastEffect === null) {
workInProgress2.firstEffect = null;
}
workInProgress2.lastEffect = renderState.lastEffect;
resetChildFibers(workInProgress2, renderLanes2);
pushSuspenseContext(workInProgress2, setShallowSuspenseContext(suspenseStackCursor.current, ForceSuspenseFallback));
return workInProgress2.child;
}
row = row.sibling;
}
}
if (renderState.tail !== null && now() > getRenderTargetTime()) {
workInProgress2.flags |= DidCapture;
didSuspendAlready = true;
cutOffTailIfNeeded(renderState, false);
workInProgress2.lanes = SomeRetryLane;
{
markSpawnedWork(SomeRetryLane);
}
}
} else {
cutOffTailIfNeeded(renderState, false);
}
} else {
if (!didSuspendAlready) {
var _suspended = findFirstSuspended(renderedTail);
if (_suspended !== null) {
workInProgress2.flags |= DidCapture;
didSuspendAlready = true;
var _newThennables = _suspended.updateQueue;
if (_newThennables !== null) {
workInProgress2.updateQueue = _newThennables;
workInProgress2.flags |= Update;
}
cutOffTailIfNeeded(renderState, true);
if (renderState.tail === null && renderState.tailMode === "hidden" && !renderedTail.alternate && !getIsHydrating()) {
var lastEffect = workInProgress2.lastEffect = renderState.lastEffect;
if (lastEffect !== null) {
lastEffect.nextEffect = null;
}
return null;
}
} else if (now() * 2 - renderState.renderingStartTime > getRenderTargetTime() && renderLanes2 !== OffscreenLane) {
workInProgress2.flags |= DidCapture;
didSuspendAlready = true;
cutOffTailIfNeeded(renderState, false);
workInProgress2.lanes = SomeRetryLane;
{
markSpawnedWork(SomeRetryLane);
}
}
}
if (renderState.isBackwards) {
renderedTail.sibling = workInProgress2.child;
workInProgress2.child = renderedTail;
} else {
var previousSibling = renderState.last;
if (previousSibling !== null) {
previousSibling.sibling = renderedTail;
} else {
workInProgress2.child = renderedTail;
}
renderState.last = renderedTail;
}
}
if (renderState.tail !== null) {
var next = renderState.tail;
renderState.rendering = next;
renderState.tail = next.sibling;
renderState.lastEffect = workInProgress2.lastEffect;
renderState.renderingStartTime = now();
next.sibling = null;
var suspenseContext = suspenseStackCursor.current;
if (didSuspendAlready) {
suspenseContext = setShallowSuspenseContext(suspenseContext, ForceSuspenseFallback);
} else {
suspenseContext = setDefaultShallowSuspenseContext(suspenseContext);
}
pushSuspenseContext(workInProgress2, suspenseContext);
return next;
}
return null;
}
case FundamentalComponent: {
break;
}
case ScopeComponent: {
break;
}
case Block:
break;
case OffscreenComponent:
case LegacyHiddenComponent: {
popRenderLanes(workInProgress2);
if (current2 !== null) {
var _nextState = workInProgress2.memoizedState;
var _prevState = current2.memoizedState;
var prevIsHidden = _prevState !== null;
var nextIsHidden = _nextState !== null;
if (prevIsHidden !== nextIsHidden && newProps.mode !== "unstable-defer-without-hiding") {
workInProgress2.flags |= Update;
}
}
return null;
}
}
{
{
throw Error("Unknown unit of work tag (" + workInProgress2.tag + "). This error is likely caused by a bug in React. Please file an issue.");
}
}
}
function unwindWork(workInProgress2, renderLanes2) {
switch (workInProgress2.tag) {
case ClassComponent: {
var Component = workInProgress2.type;
if (isContextProvider(Component)) {
popContext(workInProgress2);
}
var flags = workInProgress2.flags;
if (flags & ShouldCapture) {
workInProgress2.flags = flags & ~ShouldCapture | DidCapture;
if ((workInProgress2.mode & ProfileMode) !== NoMode) {
transferActualDuration(workInProgress2);
}
return workInProgress2;
}
return null;
}
case HostRoot: {
popHostContainer(workInProgress2);
popTopLevelContextObject(workInProgress2);
resetWorkInProgressVersions();
var _flags = workInProgress2.flags;
if (!((_flags & DidCapture) === NoFlags)) {
{
throw Error("The root failed to unmount after an error. This is likely a bug in React. Please file an issue.");
}
}
workInProgress2.flags = _flags & ~ShouldCapture | DidCapture;
return workInProgress2;
}
case HostComponent: {
popHostContext(workInProgress2);
return null;
}
case SuspenseComponent: {
popSuspenseContext(workInProgress2);
var _flags2 = workInProgress2.flags;
if (_flags2 & ShouldCapture) {
workInProgress2.flags = _flags2 & ~ShouldCapture | DidCapture;
if ((workInProgress2.mode & ProfileMode) !== NoMode) {
transferActualDuration(workInProgress2);
}
return workInProgress2;
}
return null;
}
case SuspenseListComponent: {
popSuspenseContext(workInProgress2);
return null;
}
case HostPortal:
popHostContainer(workInProgress2);
return null;
case ContextProvider:
popProvider(workInProgress2);
return null;
case OffscreenComponent:
case LegacyHiddenComponent:
popRenderLanes(workInProgress2);
return null;
default:
return null;
}
}
function unwindInterruptedWork(interruptedWork) {
switch (interruptedWork.tag) {
case ClassComponent: {
var childContextTypes = interruptedWork.type.childContextTypes;
if (childContextTypes !== null && childContextTypes !== void 0) {
popContext(interruptedWork);
}
break;
}
case HostRoot: {
popHostContainer(interruptedWork);
popTopLevelContextObject(interruptedWork);
resetWorkInProgressVersions();
break;
}
case HostComponent: {
popHostContext(interruptedWork);
break;
}
case HostPortal:
popHostContainer(interruptedWork);
break;
case SuspenseComponent:
popSuspenseContext(interruptedWork);
break;
case SuspenseListComponent:
popSuspenseContext(interruptedWork);
break;
case ContextProvider:
popProvider(interruptedWork);
break;
case OffscreenComponent:
case LegacyHiddenComponent:
popRenderLanes(interruptedWork);
break;
}
}
function createCapturedValue(value, source) {
return {
value,
source,
stack: getStackByFiberInDevAndProd(source)
};
}
function showErrorDialog(boundary, errorInfo) {
return true;
}
function logCapturedError(boundary, errorInfo) {
try {
var logError = showErrorDialog(boundary, errorInfo);
if (logError === false) {
return;
}
var error2 = errorInfo.value;
if (true) {
var source = errorInfo.source;
var stack = errorInfo.stack;
var componentStack = stack !== null ? stack : "";
if (error2 != null && error2._suppressLogging) {
if (boundary.tag === ClassComponent) {
return;
}
console["error"](error2);
}
var componentName = source ? getComponentName(source.type) : null;
var componentNameMessage = componentName ? "The above error occurred in the <" + componentName + "> component:" : "The above error occurred in one of your React components:";
var errorBoundaryMessage;
var errorBoundaryName = getComponentName(boundary.type);
if (errorBoundaryName) {
errorBoundaryMessage = "React will try to recreate this component tree from scratch " + ("using the error boundary you provided, " + errorBoundaryName + ".");
} else {
errorBoundaryMessage = "Consider adding an error boundary to your tree to customize error handling behavior.\nVisit https://reactjs.org/link/error-boundaries to learn more about error boundaries.";
}
var combinedMessage = componentNameMessage + "\n" + componentStack + "\n\n" + ("" + errorBoundaryMessage);
console["error"](combinedMessage);
} else {
console["error"](error2);
}
} catch (e) {
setTimeout(function() {
throw e;
});
}
}
var PossiblyWeakMap$1 = typeof WeakMap === "function" ? WeakMap : Map;
function createRootErrorUpdate(fiber, errorInfo, lane) {
var update = createUpdate(NoTimestamp, lane);
update.tag = CaptureUpdate;
update.payload = {
element: null
};
var error2 = errorInfo.value;
update.callback = function() {
onUncaughtError(error2);
logCapturedError(fiber, errorInfo);
};
return update;
}
function createClassErrorUpdate(fiber, errorInfo, lane) {
var update = createUpdate(NoTimestamp, lane);
update.tag = CaptureUpdate;
var getDerivedStateFromError = fiber.type.getDerivedStateFromError;
if (typeof getDerivedStateFromError === "function") {
var error$1 = errorInfo.value;
update.payload = function() {
logCapturedError(fiber, errorInfo);
return getDerivedStateFromError(error$1);
};
}
var inst = fiber.stateNode;
if (inst !== null && typeof inst.componentDidCatch === "function") {
update.callback = function callback() {
{
markFailedErrorBoundaryForHotReloading(fiber);
}
if (typeof getDerivedStateFromError !== "function") {
markLegacyErrorBoundaryAsFailed(this);
logCapturedError(fiber, errorInfo);
}
var error$12 = errorInfo.value;
var stack = errorInfo.stack;
this.componentDidCatch(error$12, {
componentStack: stack !== null ? stack : ""
});
{
if (typeof getDerivedStateFromError !== "function") {
if (!includesSomeLane(fiber.lanes, SyncLane)) {
error("%s: Error boundaries should implement getDerivedStateFromError(). In that method, return a state update to display an error message or fallback UI.", getComponentName(fiber.type) || "Unknown");
}
}
}
};
} else {
update.callback = function() {
markFailedErrorBoundaryForHotReloading(fiber);
};
}
return update;
}
function attachPingListener(root2, wakeable, lanes) {
var pingCache = root2.pingCache;
var threadIDs;
if (pingCache === null) {
pingCache = root2.pingCache = new PossiblyWeakMap$1();
threadIDs = new Set();
pingCache.set(wakeable, threadIDs);
} else {
threadIDs = pingCache.get(wakeable);
if (threadIDs === void 0) {
threadIDs = new Set();
pingCache.set(wakeable, threadIDs);
}
}
if (!threadIDs.has(lanes)) {
threadIDs.add(lanes);
var ping = pingSuspendedRoot.bind(null, root2, wakeable, lanes);
wakeable.then(ping, ping);
}
}
function throwException(root2, returnFiber, sourceFiber, value, rootRenderLanes) {
sourceFiber.flags |= Incomplete;
sourceFiber.firstEffect = sourceFiber.lastEffect = null;
if (value !== null && typeof value === "object" && typeof value.then === "function") {
var wakeable = value;
if ((sourceFiber.mode & BlockingMode) === NoMode) {
var currentSource = sourceFiber.alternate;
if (currentSource) {
sourceFiber.updateQueue = currentSource.updateQueue;
sourceFiber.memoizedState = currentSource.memoizedState;
sourceFiber.lanes = currentSource.lanes;
} else {
sourceFiber.updateQueue = null;
sourceFiber.memoizedState = null;
}
}
var hasInvisibleParentBoundary = hasSuspenseContext(suspenseStackCursor.current, InvisibleParentSuspenseContext);
var _workInProgress = returnFiber;
do {
if (_workInProgress.tag === SuspenseComponent && shouldCaptureSuspense(_workInProgress, hasInvisibleParentBoundary)) {
var wakeables = _workInProgress.updateQueue;
if (wakeables === null) {
var updateQueue = new Set();
updateQueue.add(wakeable);
_workInProgress.updateQueue = updateQueue;
} else {
wakeables.add(wakeable);
}
if ((_workInProgress.mode & BlockingMode) === NoMode) {
_workInProgress.flags |= DidCapture;
sourceFiber.flags |= ForceUpdateForLegacySuspense;
sourceFiber.flags &= ~(LifecycleEffectMask | Incomplete);
if (sourceFiber.tag === ClassComponent) {
var currentSourceFiber = sourceFiber.alternate;
if (currentSourceFiber === null) {
sourceFiber.tag = IncompleteClassComponent;
} else {
var update = createUpdate(NoTimestamp, SyncLane);
update.tag = ForceUpdate;
enqueueUpdate(sourceFiber, update);
}
}
sourceFiber.lanes = mergeLanes(sourceFiber.lanes, SyncLane);
return;
}
attachPingListener(root2, wakeable, rootRenderLanes);
_workInProgress.flags |= ShouldCapture;
_workInProgress.lanes = rootRenderLanes;
return;
}
_workInProgress = _workInProgress.return;
} while (_workInProgress !== null);
value = new Error((getComponentName(sourceFiber.type) || "A React component") + " suspended while rendering, but no fallback UI was specified.\n\nAdd a <Suspense fallback=...> component higher in the tree to provide a loading indicator or placeholder to display.");
}
renderDidError();
value = createCapturedValue(value, sourceFiber);
var workInProgress2 = returnFiber;
do {
switch (workInProgress2.tag) {
case HostRoot: {
var _errorInfo = value;
workInProgress2.flags |= ShouldCapture;
var lane = pickArbitraryLane(rootRenderLanes);
workInProgress2.lanes = mergeLanes(workInProgress2.lanes, lane);
var _update = createRootErrorUpdate(workInProgress2, _errorInfo, lane);
enqueueCapturedUpdate(workInProgress2, _update);
return;
}
case ClassComponent:
var errorInfo = value;
var ctor = workInProgress2.type;
var instance = workInProgress2.stateNode;
if ((workInProgress2.flags & DidCapture) === NoFlags && (typeof ctor.getDerivedStateFromError === "function" || instance !== null && typeof instance.componentDidCatch === "function" && !isAlreadyFailedLegacyErrorBoundary(instance))) {
workInProgress2.flags |= ShouldCapture;
var _lane = pickArbitraryLane(rootRenderLanes);
workInProgress2.lanes = mergeLanes(workInProgress2.lanes, _lane);
var _update2 = createClassErrorUpdate(workInProgress2, errorInfo, _lane);
enqueueCapturedUpdate(workInProgress2, _update2);
return;
}
break;
}
workInProgress2 = workInProgress2.return;
} while (workInProgress2 !== null);
}
var didWarnAboutUndefinedSnapshotBeforeUpdate = null;
{
didWarnAboutUndefinedSnapshotBeforeUpdate = new Set();
}
var PossiblyWeakSet = typeof WeakSet === "function" ? WeakSet : Set;
var callComponentWillUnmountWithTimer = function(current2, instance) {
instance.props = current2.memoizedProps;
instance.state = current2.memoizedState;
{
instance.componentWillUnmount();
}
};
function safelyCallComponentWillUnmount(current2, instance) {
{
invokeGuardedCallback(null, callComponentWillUnmountWithTimer, null, current2, instance);
if (hasCaughtError()) {
var unmountError = clearCaughtError();
captureCommitPhaseError(current2, unmountError);
}
}
}
function safelyDetachRef(current2) {
var ref = current2.ref;
if (ref !== null) {
if (typeof ref === "function") {
{
invokeGuardedCallback(null, ref, null, null);
if (hasCaughtError()) {
var refError = clearCaughtError();
captureCommitPhaseError(current2, refError);
}
}
} else {
ref.current = null;
}
}
}
function safelyCallDestroy(current2, destroy) {
{
invokeGuardedCallback(null, destroy, null);
if (hasCaughtError()) {
var error2 = clearCaughtError();
captureCommitPhaseError(current2, error2);
}
}
}
function commitBeforeMutationLifeCycles(current2, finishedWork) {
switch (finishedWork.tag) {
case FunctionComponent:
case ForwardRef:
case SimpleMemoComponent:
case Block: {
return;
}
case ClassComponent: {
if (finishedWork.flags & Snapshot) {
if (current2 !== null) {
var prevProps = current2.memoizedProps;
var prevState = current2.memoizedState;
var instance = finishedWork.stateNode;
{
if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
if (instance.props !== finishedWork.memoizedProps) {
error("Expected %s props to match memoized props before getSnapshotBeforeUpdate. This might either be because of a bug in React, or because a component reassigns its own `this.props`. Please file an issue.", getComponentName(finishedWork.type) || "instance");
}
if (instance.state !== finishedWork.memoizedState) {
error("Expected %s state to match memoized state before getSnapshotBeforeUpdate. This might either be because of a bug in React, or because a component reassigns its own `this.state`. Please file an issue.", getComponentName(finishedWork.type) || "instance");
}
}
}
var snapshot = instance.getSnapshotBeforeUpdate(finishedWork.elementType === finishedWork.type ? prevProps : resolveDefaultProps(finishedWork.type, prevProps), prevState);
{
var didWarnSet = didWarnAboutUndefinedSnapshotBeforeUpdate;
if (snapshot === void 0 && !didWarnSet.has(finishedWork.type)) {
didWarnSet.add(finishedWork.type);
error("%s.getSnapshotBeforeUpdate(): A snapshot value (or null) must be returned. You have returned undefined.", getComponentName(finishedWork.type));
}
}
instance.__reactInternalSnapshotBeforeUpdate = snapshot;
}
}
return;
}
case HostRoot: {
{
if (finishedWork.flags & Snapshot) {
var root2 = finishedWork.stateNode;
clearContainer(root2.containerInfo);
}
}
return;
}
case HostComponent:
case HostText:
case HostPortal:
case IncompleteClassComponent:
return;
}
{
{
throw Error("This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue.");
}
}
}
function commitHookEffectListUnmount(tag, finishedWork) {
var updateQueue = finishedWork.updateQueue;
var lastEffect = updateQueue !== null ? updateQueue.lastEffect : null;
if (lastEffect !== null) {
var firstEffect = lastEffect.next;
var effect = firstEffect;
do {
if ((effect.tag & tag) === tag) {
var destroy = effect.destroy;
effect.destroy = void 0;
if (destroy !== void 0) {
destroy();
}
}
effect = effect.next;
} while (effect !== firstEffect);
}
}
function commitHookEffectListMount(tag, finishedWork) {
var updateQueue = finishedWork.updateQueue;
var lastEffect = updateQueue !== null ? updateQueue.lastEffect : null;
if (lastEffect !== null) {
var firstEffect = lastEffect.next;
var effect = firstEffect;
do {
if ((effect.tag & tag) === tag) {
var create = effect.create;
effect.destroy = create();
{
var destroy = effect.destroy;
if (destroy !== void 0 && typeof destroy !== "function") {
var addendum = void 0;
if (destroy === null) {
addendum = " You returned null. If your effect does not require clean up, return undefined (or nothing).";
} else if (typeof destroy.then === "function") {
addendum = "\n\nIt looks like you wrote useEffect(async () => ...) or returned a Promise. Instead, write the async function inside your effect and call it immediately:\n\nuseEffect(() => {\n async function fetchData() {\n // You can await here\n const response = await MyAPI.getData(someId);\n // ...\n }\n fetchData();\n}, [someId]); // Or [] if effect doesn't need props or state\n\nLearn more about data fetching with Hooks: https://reactjs.org/link/hooks-data-fetching";
} else {
addendum = " You returned: " + destroy;
}
error("An effect function must not return anything besides a function, which is used for clean-up.%s", addendum);
}
}
}
effect = effect.next;
} while (effect !== firstEffect);
}
}
function schedulePassiveEffects(finishedWork) {
var updateQueue = finishedWork.updateQueue;
var lastEffect = updateQueue !== null ? updateQueue.lastEffect : null;
if (lastEffect !== null) {
var firstEffect = lastEffect.next;
var effect = firstEffect;
do {
var _effect = effect, next = _effect.next, tag = _effect.tag;
if ((tag & Passive$1) !== NoFlags$1 && (tag & HasEffect) !== NoFlags$1) {
enqueuePendingPassiveHookEffectUnmount(finishedWork, effect);
enqueuePendingPassiveHookEffectMount(finishedWork, effect);
}
effect = next;
} while (effect !== firstEffect);
}
}
function commitLifeCycles(finishedRoot, current2, finishedWork, committedLanes) {
switch (finishedWork.tag) {
case FunctionComponent:
case ForwardRef:
case SimpleMemoComponent:
case Block: {
{
commitHookEffectListMount(Layout | HasEffect, finishedWork);
}
schedulePassiveEffects(finishedWork);
return;
}
case ClassComponent: {
var instance = finishedWork.stateNode;
if (finishedWork.flags & Update) {
if (current2 === null) {
{
if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
if (instance.props !== finishedWork.memoizedProps) {
error("Expected %s props to match memoized props before componentDidMount. This might either be because of a bug in React, or because a component reassigns its own `this.props`. Please file an issue.", getComponentName(finishedWork.type) || "instance");
}
if (instance.state !== finishedWork.memoizedState) {
error("Expected %s state to match memoized state before componentDidMount. This might either be because of a bug in React, or because a component reassigns its own `this.state`. Please file an issue.", getComponentName(finishedWork.type) || "instance");
}
}
}
{
instance.componentDidMount();
}
} else {
var prevProps = finishedWork.elementType === finishedWork.type ? current2.memoizedProps : resolveDefaultProps(finishedWork.type, current2.memoizedProps);
var prevState = current2.memoizedState;
{
if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
if (instance.props !== finishedWork.memoizedProps) {
error("Expected %s props to match memoized props before componentDidUpdate. This might either be because of a bug in React, or because a component reassigns its own `this.props`. Please file an issue.", getComponentName(finishedWork.type) || "instance");
}
if (instance.state !== finishedWork.memoizedState) {
error("Expected %s state to match memoized state before componentDidUpdate. This might either be because of a bug in React, or because a component reassigns its own `this.state`. Please file an issue.", getComponentName(finishedWork.type) || "instance");
}
}
}
{
instance.componentDidUpdate(prevProps, prevState, instance.__reactInternalSnapshotBeforeUpdate);
}
}
}
var updateQueue = finishedWork.updateQueue;
if (updateQueue !== null) {
{
if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
if (instance.props !== finishedWork.memoizedProps) {
error("Expected %s props to match memoized props before processing the update queue. This might either be because of a bug in React, or because a component reassigns its own `this.props`. Please file an issue.", getComponentName(finishedWork.type) || "instance");
}
if (instance.state !== finishedWork.memoizedState) {
error("Expected %s state to match memoized state before processing the update queue. This might either be because of a bug in React, or because a component reassigns its own `this.state`. Please file an issue.", getComponentName(finishedWork.type) || "instance");
}
}
}
commitUpdateQueue(finishedWork, updateQueue, instance);
}
return;
}
case HostRoot: {
var _updateQueue = finishedWork.updateQueue;
if (_updateQueue !== null) {
var _instance = null;
if (finishedWork.child !== null) {
switch (finishedWork.child.tag) {
case HostComponent:
_instance = getPublicInstance(finishedWork.child.stateNode);
break;
case ClassComponent:
_instance = finishedWork.child.stateNode;
break;
}
}
commitUpdateQueue(finishedWork, _updateQueue, _instance);
}
return;
}
case HostComponent: {
var _instance2 = finishedWork.stateNode;
if (current2 === null && finishedWork.flags & Update) {
var type = finishedWork.type;
var props = finishedWork.memoizedProps;
commitMount(_instance2, type, props);
}
return;
}
case HostText: {
return;
}
case HostPortal: {
return;
}
case Profiler: {
{
var _finishedWork$memoize2 = finishedWork.memoizedProps, onCommit = _finishedWork$memoize2.onCommit, onRender = _finishedWork$memoize2.onRender;
var effectDuration = finishedWork.stateNode.effectDuration;
var commitTime2 = getCommitTime();
if (typeof onRender === "function") {
{
onRender(finishedWork.memoizedProps.id, current2 === null ? "mount" : "update", finishedWork.actualDuration, finishedWork.treeBaseDuration, finishedWork.actualStartTime, commitTime2, finishedRoot.memoizedInteractions);
}
}
}
return;
}
case SuspenseComponent: {
commitSuspenseHydrationCallbacks(finishedRoot, finishedWork);
return;
}
case SuspenseListComponent:
case IncompleteClassComponent:
case FundamentalComponent:
case ScopeComponent:
case OffscreenComponent:
case LegacyHiddenComponent:
return;
}
{
{
throw Error("This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue.");
}
}
}
function hideOrUnhideAllChildren(finishedWork, isHidden) {
{
var node = finishedWork;
while (true) {
if (node.tag === HostComponent) {
var instance = node.stateNode;
if (isHidden) {
hideInstance(instance);
} else {
unhideInstance(node.stateNode, node.memoizedProps);
}
} else if (node.tag === HostText) {
var _instance3 = node.stateNode;
if (isHidden) {
hideTextInstance(_instance3);
} else {
unhideTextInstance(_instance3, node.memoizedProps);
}
} else if ((node.tag === OffscreenComponent || node.tag === LegacyHiddenComponent) && node.memoizedState !== null && node !== finishedWork)
;
else if (node.child !== null) {
node.child.return = node;
node = node.child;
continue;
}
if (node === finishedWork) {
return;
}
while (node.sibling === null) {
if (node.return === null || node.return === finishedWork) {
return;
}
node = node.return;
}
node.sibling.return = node.return;
node = node.sibling;
}
}
}
function commitAttachRef(finishedWork) {
var ref = finishedWork.ref;
if (ref !== null) {
var instance = finishedWork.stateNode;
var instanceToUse;
switch (finishedWork.tag) {
case HostComponent:
instanceToUse = getPublicInstance(instance);
break;
default:
instanceToUse = instance;
}
if (typeof ref === "function") {
ref(instanceToUse);
} else {
{
if (!ref.hasOwnProperty("current")) {
error("Unexpected ref object provided for %s. Use either a ref-setter function or React.createRef().", getComponentName(finishedWork.type));
}
}
ref.current = instanceToUse;
}
}
}
function commitDetachRef(current2) {
var currentRef = current2.ref;
if (currentRef !== null) {
if (typeof currentRef === "function") {
currentRef(null);
} else {
currentRef.current = null;
}
}
}
function commitUnmount(finishedRoot, current2, renderPriorityLevel) {
onCommitUnmount(current2);
switch (current2.tag) {
case FunctionComponent:
case ForwardRef:
case MemoComponent:
case SimpleMemoComponent:
case Block: {
var updateQueue = current2.updateQueue;
if (updateQueue !== null) {
var lastEffect = updateQueue.lastEffect;
if (lastEffect !== null) {
var firstEffect = lastEffect.next;
var effect = firstEffect;
do {
var _effect2 = effect, destroy = _effect2.destroy, tag = _effect2.tag;
if (destroy !== void 0) {
if ((tag & Passive$1) !== NoFlags$1) {
enqueuePendingPassiveHookEffectUnmount(current2, effect);
} else {
{
safelyCallDestroy(current2, destroy);
}
}
}
effect = effect.next;
} while (effect !== firstEffect);
}
}
return;
}
case ClassComponent: {
safelyDetachRef(current2);
var instance = current2.stateNode;
if (typeof instance.componentWillUnmount === "function") {
safelyCallComponentWillUnmount(current2, instance);
}
return;
}
case HostComponent: {
safelyDetachRef(current2);
return;
}
case HostPortal: {
{
unmountHostComponents(finishedRoot, current2);
}
return;
}
case FundamentalComponent: {
return;
}
case DehydratedFragment: {
return;
}
case ScopeComponent: {
return;
}
}
}
function commitNestedUnmounts(finishedRoot, root2, renderPriorityLevel) {
var node = root2;
while (true) {
commitUnmount(finishedRoot, node);
if (node.child !== null && node.tag !== HostPortal) {
node.child.return = node;
node = node.child;
continue;
}
if (node === root2) {
return;
}
while (node.sibling === null) {
if (node.return === null || node.return === root2) {
return;
}
node = node.return;
}
node.sibling.return = node.return;
node = node.sibling;
}
}
function detachFiberMutation(fiber) {
fiber.alternate = null;
fiber.child = null;
fiber.dependencies = null;
fiber.firstEffect = null;
fiber.lastEffect = null;
fiber.memoizedProps = null;
fiber.memoizedState = null;
fiber.pendingProps = null;
fiber.return = null;
fiber.updateQueue = null;
{
fiber._debugOwner = null;
}
}
function getHostParentFiber(fiber) {
var parent = fiber.return;
while (parent !== null) {
if (isHostParent(parent)) {
return parent;
}
parent = parent.return;
}
{
{
throw Error("Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue.");
}
}
}
function isHostParent(fiber) {
return fiber.tag === HostComponent || fiber.tag === HostRoot || fiber.tag === HostPortal;
}
function getHostSibling(fiber) {
var node = fiber;
siblings:
while (true) {
while (node.sibling === null) {
if (node.return === null || isHostParent(node.return)) {
return null;
}
node = node.return;
}
node.sibling.return = node.return;
node = node.sibling;
while (node.tag !== HostComponent && node.tag !== HostText && node.tag !== DehydratedFragment) {
if (node.flags & Placement) {
continue siblings;
}
if (node.child === null || node.tag === HostPortal) {
continue siblings;
} else {
node.child.return = node;
node = node.child;
}
}
if (!(node.flags & Placement)) {
return node.stateNode;
}
}
}
function commitPlacement(finishedWork) {
var parentFiber = getHostParentFiber(finishedWork);
var parent;
var isContainer;
var parentStateNode = parentFiber.stateNode;
switch (parentFiber.tag) {
case HostComponent:
parent = parentStateNode;
isContainer = false;
break;
case HostRoot:
parent = parentStateNode.containerInfo;
isContainer = true;
break;
case HostPortal:
parent = parentStateNode.containerInfo;
isContainer = true;
break;
case FundamentalComponent:
default: {
{
throw Error("Invalid host parent fiber. This error is likely caused by a bug in React. Please file an issue.");
}
}
}
if (parentFiber.flags & ContentReset) {
resetTextContent(parent);
parentFiber.flags &= ~ContentReset;
}
var before = getHostSibling(finishedWork);
if (isContainer) {
insertOrAppendPlacementNodeIntoContainer(finishedWork, before, parent);
} else {
insertOrAppendPlacementNode(finishedWork, before, parent);
}
}
function insertOrAppendPlacementNodeIntoContainer(node, before, parent) {
var tag = node.tag;
var isHost = tag === HostComponent || tag === HostText;
if (isHost || enableFundamentalAPI) {
var stateNode = isHost ? node.stateNode : node.stateNode.instance;
if (before) {
insertInContainerBefore(parent, stateNode, before);
} else {
appendChildToContainer(parent, stateNode);
}
} else if (tag === HostPortal)
;
else {
var child = node.child;
if (child !== null) {
insertOrAppendPlacementNodeIntoContainer(child, before, parent);
var sibling = child.sibling;
while (sibling !== null) {
insertOrAppendPlacementNodeIntoContainer(sibling, before, parent);
sibling = sibling.sibling;
}
}
}
}
function insertOrAppendPlacementNode(node, before, parent) {
var tag = node.tag;
var isHost = tag === HostComponent || tag === HostText;
if (isHost || enableFundamentalAPI) {
var stateNode = isHost ? node.stateNode : node.stateNode.instance;
if (before) {
insertBefore(parent, stateNode, before);
} else {
appendChild(parent, stateNode);
}
} else if (tag === HostPortal)
;
else {
var child = node.child;
if (child !== null) {
insertOrAppendPlacementNode(child, before, parent);
var sibling = child.sibling;
while (sibling !== null) {
insertOrAppendPlacementNode(sibling, before, parent);
sibling = sibling.sibling;
}
}
}
}
function unmountHostComponents(finishedRoot, current2, renderPriorityLevel) {
var node = current2;
var currentParentIsValid = false;
var currentParent;
var currentParentIsContainer;
while (true) {
if (!currentParentIsValid) {
var parent = node.return;
findParent:
while (true) {
if (!(parent !== null)) {
{
throw Error("Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue.");
}
}
var parentStateNode = parent.stateNode;
switch (parent.tag) {
case HostComponent:
currentParent = parentStateNode;
currentParentIsContainer = false;
break findParent;
case HostRoot:
currentParent = parentStateNode.containerInfo;
currentParentIsContainer = true;
break findParent;
case HostPortal:
currentParent = parentStateNode.containerInfo;
currentParentIsContainer = true;
break findParent;
}
parent = parent.return;
}
currentParentIsValid = true;
}
if (node.tag === HostComponent || node.tag === HostText) {
commitNestedUnmounts(finishedRoot, node);
if (currentParentIsContainer) {
removeChildFromContainer(currentParent, node.stateNode);
} else {
removeChild(currentParent, node.stateNode);
}
} else if (node.tag === HostPortal) {
if (node.child !== null) {
currentParent = node.stateNode.containerInfo;
currentParentIsContainer = true;
node.child.return = node;
node = node.child;
continue;
}
} else {
commitUnmount(finishedRoot, node);
if (node.child !== null) {
node.child.return = node;
node = node.child;
continue;
}
}
if (node === current2) {
return;
}
while (node.sibling === null) {
if (node.return === null || node.return === current2) {
return;
}
node = node.return;
if (node.tag === HostPortal) {
currentParentIsValid = false;
}
}
node.sibling.return = node.return;
node = node.sibling;
}
}
function commitDeletion(finishedRoot, current2, renderPriorityLevel) {
{
unmountHostComponents(finishedRoot, current2);
}
var alternate = current2.alternate;
detachFiberMutation(current2);
if (alternate !== null) {
detachFiberMutation(alternate);
}
}
function commitWork(current2, finishedWork) {
switch (finishedWork.tag) {
case FunctionComponent:
case ForwardRef:
case MemoComponent:
case SimpleMemoComponent:
case Block: {
{
commitHookEffectListUnmount(Layout | HasEffect, finishedWork);
}
return;
}
case ClassComponent: {
return;
}
case HostComponent: {
var instance = finishedWork.stateNode;
if (instance != null) {
var newProps = finishedWork.memoizedProps;
var oldProps = current2 !== null ? current2.memoizedProps : newProps;
var type = finishedWork.type;
var updatePayload = finishedWork.updateQueue;
finishedWork.updateQueue = null;
if (updatePayload !== null) {
commitUpdate(instance, updatePayload, type, oldProps, newProps);
}
}
return;
}
case HostText: {
if (!(finishedWork.stateNode !== null)) {
{
throw Error("This should have a text node initialized. This error is likely caused by a bug in React. Please file an issue.");
}
}
var textInstance = finishedWork.stateNode;
var newText = finishedWork.memoizedProps;
var oldText = current2 !== null ? current2.memoizedProps : newText;
commitTextUpdate(textInstance, oldText, newText);
return;
}
case HostRoot: {
{
var _root = finishedWork.stateNode;
if (_root.hydrate) {
_root.hydrate = false;
commitHydratedContainer(_root.containerInfo);
}
}
return;
}
case Profiler: {
return;
}
case SuspenseComponent: {
commitSuspenseComponent(finishedWork);
attachSuspenseRetryListeners(finishedWork);
return;
}
case SuspenseListComponent: {
attachSuspenseRetryListeners(finishedWork);
return;
}
case IncompleteClassComponent: {
return;
}
case FundamentalComponent: {
break;
}
case ScopeComponent: {
break;
}
case OffscreenComponent:
case LegacyHiddenComponent: {
var newState = finishedWork.memoizedState;
var isHidden = newState !== null;
hideOrUnhideAllChildren(finishedWork, isHidden);
return;
}
}
{
{
throw Error("This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue.");
}
}
}
function commitSuspenseComponent(finishedWork) {
var newState = finishedWork.memoizedState;
if (newState !== null) {
markCommitTimeOfFallback();
{
var primaryChildParent = finishedWork.child;
hideOrUnhideAllChildren(primaryChildParent, true);
}
}
}
function commitSuspenseHydrationCallbacks(finishedRoot, finishedWork) {
var newState = finishedWork.memoizedState;
if (newState === null) {
var current2 = finishedWork.alternate;
if (current2 !== null) {
var prevState = current2.memoizedState;
if (prevState !== null) {
var suspenseInstance = prevState.dehydrated;
if (suspenseInstance !== null) {
commitHydratedSuspenseInstance(suspenseInstance);
}
}
}
}
}
function attachSuspenseRetryListeners(finishedWork) {
var wakeables = finishedWork.updateQueue;
if (wakeables !== null) {
finishedWork.updateQueue = null;
var retryCache = finishedWork.stateNode;
if (retryCache === null) {
retryCache = finishedWork.stateNode = new PossiblyWeakSet();
}
wakeables.forEach(function(wakeable) {
var retry = resolveRetryWakeable.bind(null, finishedWork, wakeable);
if (!retryCache.has(wakeable)) {
{
if (wakeable.__reactDoNotTraceInteractions !== true) {
retry = tracing.unstable_wrap(retry);
}
}
retryCache.add(wakeable);
wakeable.then(retry, retry);
}
});
}
}
function isSuspenseBoundaryBeingHidden(current2, finishedWork) {
if (current2 !== null) {
var oldState = current2.memoizedState;
if (oldState === null || oldState.dehydrated !== null) {
var newState = finishedWork.memoizedState;
return newState !== null && newState.dehydrated === null;
}
}
return false;
}
function commitResetTextContent(current2) {
resetTextContent(current2.stateNode);
}
var COMPONENT_TYPE = 0;
var HAS_PSEUDO_CLASS_TYPE = 1;
var ROLE_TYPE = 2;
var TEST_NAME_TYPE = 3;
var TEXT_TYPE = 4;
if (typeof Symbol === "function" && Symbol.for) {
var symbolFor$1 = Symbol.for;
COMPONENT_TYPE = symbolFor$1("selector.component");
HAS_PSEUDO_CLASS_TYPE = symbolFor$1("selector.has_pseudo_class");
ROLE_TYPE = symbolFor$1("selector.role");
TEST_NAME_TYPE = symbolFor$1("selector.test_id");
TEXT_TYPE = symbolFor$1("selector.text");
}
var commitHooks = [];
function onCommitRoot$1() {
{
commitHooks.forEach(function(commitHook) {
return commitHook();
});
}
}
var ceil = Math.ceil;
var ReactCurrentDispatcher$2 = ReactSharedInternals.ReactCurrentDispatcher, ReactCurrentOwner$2 = ReactSharedInternals.ReactCurrentOwner, IsSomeRendererActing = ReactSharedInternals.IsSomeRendererActing;
var NoContext = 0;
var BatchedContext = 1;
var EventContext = 2;
var DiscreteEventContext = 4;
var LegacyUnbatchedContext = 8;
var RenderContext = 16;
var CommitContext = 32;
var RetryAfterError = 64;
var RootIncomplete = 0;
var RootFatalErrored = 1;
var RootErrored = 2;
var RootSuspended = 3;
var RootSuspendedWithDelay = 4;
var RootCompleted = 5;
var executionContext = NoContext;
var workInProgressRoot = null;
var workInProgress = null;
var workInProgressRootRenderLanes = NoLanes;
var subtreeRenderLanes = NoLanes;
var subtreeRenderLanesCursor = createCursor(NoLanes);
var workInProgressRootExitStatus = RootIncomplete;
var workInProgressRootFatalError = null;
var workInProgressRootIncludedLanes = NoLanes;
var workInProgressRootSkippedLanes = NoLanes;
var workInProgressRootUpdatedLanes = NoLanes;
var workInProgressRootPingedLanes = NoLanes;
var mostRecentlyUpdatedRoot = null;
var globalMostRecentFallbackTime = 0;
var FALLBACK_THROTTLE_MS = 500;
var workInProgressRootRenderTargetTime = Infinity;
var RENDER_TIMEOUT_MS = 500;
function resetRenderTimer() {
workInProgressRootRenderTargetTime = now() + RENDER_TIMEOUT_MS;
}
function getRenderTargetTime() {
return workInProgressRootRenderTargetTime;
}
var nextEffect = null;
var hasUncaughtError = false;
var firstUncaughtError = null;
var legacyErrorBoundariesThatAlreadyFailed = null;
var rootDoesHavePassiveEffects = false;
var rootWithPendingPassiveEffects = null;
var pendingPassiveEffectsRenderPriority = NoPriority$1;
var pendingPassiveEffectsLanes = NoLanes;
var pendingPassiveHookEffectsMount = [];
var pendingPassiveHookEffectsUnmount = [];
var rootsWithPendingDiscreteUpdates = null;
var NESTED_UPDATE_LIMIT = 50;
var nestedUpdateCount = 0;
var rootWithNestedUpdates = null;
var NESTED_PASSIVE_UPDATE_LIMIT = 50;
var nestedPassiveUpdateCount = 0;
var spawnedWorkDuringRender = null;
var currentEventTime = NoTimestamp;
var currentEventWipLanes = NoLanes;
var currentEventPendingLanes = NoLanes;
var isFlushingPassiveEffects = false;
var focusedInstanceHandle = null;
var shouldFireAfterActiveInstanceBlur = false;
function getWorkInProgressRoot() {
return workInProgressRoot;
}
function requestEventTime() {
if ((executionContext & (RenderContext | CommitContext)) !== NoContext) {
return now();
}
if (currentEventTime !== NoTimestamp) {
return currentEventTime;
}
currentEventTime = now();
return currentEventTime;
}
function requestUpdateLane(fiber) {
var mode = fiber.mode;
if ((mode & BlockingMode) === NoMode) {
return SyncLane;
} else if ((mode & ConcurrentMode) === NoMode) {
return getCurrentPriorityLevel() === ImmediatePriority$1 ? SyncLane : SyncBatchedLane;
}
if (currentEventWipLanes === NoLanes) {
currentEventWipLanes = workInProgressRootIncludedLanes;
}
var isTransition = requestCurrentTransition() !== NoTransition;
if (isTransition) {
if (currentEventPendingLanes !== NoLanes) {
currentEventPendingLanes = mostRecentlyUpdatedRoot !== null ? mostRecentlyUpdatedRoot.pendingLanes : NoLanes;
}
return findTransitionLane(currentEventWipLanes, currentEventPendingLanes);
}
var schedulerPriority = getCurrentPriorityLevel();
var lane;
if ((executionContext & DiscreteEventContext) !== NoContext && schedulerPriority === UserBlockingPriority$2) {
lane = findUpdateLane(InputDiscreteLanePriority, currentEventWipLanes);
} else {
var schedulerLanePriority = schedulerPriorityToLanePriority(schedulerPriority);
lane = findUpdateLane(schedulerLanePriority, currentEventWipLanes);
}
return lane;
}
function requestRetryLane(fiber) {
var mode = fiber.mode;
if ((mode & BlockingMode) === NoMode) {
return SyncLane;
} else if ((mode & ConcurrentMode) === NoMode) {
return getCurrentPriorityLevel() === ImmediatePriority$1 ? SyncLane : SyncBatchedLane;
}
if (currentEventWipLanes === NoLanes) {
currentEventWipLanes = workInProgressRootIncludedLanes;
}
return findRetryLane(currentEventWipLanes);
}
function scheduleUpdateOnFiber(fiber, lane, eventTime) {
checkForNestedUpdates();
warnAboutRenderPhaseUpdatesInDEV(fiber);
var root2 = markUpdateLaneFromFiberToRoot(fiber, lane);
if (root2 === null) {
warnAboutUpdateOnUnmountedFiberInDEV(fiber);
return null;
}
markRootUpdated(root2, lane, eventTime);
if (root2 === workInProgressRoot) {
{
workInProgressRootUpdatedLanes = mergeLanes(workInProgressRootUpdatedLanes, lane);
}
if (workInProgressRootExitStatus === RootSuspendedWithDelay) {
markRootSuspended$1(root2, workInProgressRootRenderLanes);
}
}
var priorityLevel = getCurrentPriorityLevel();
if (lane === SyncLane) {
if ((executionContext & LegacyUnbatchedContext) !== NoContext && (executionContext & (RenderContext | CommitContext)) === NoContext) {
schedulePendingInteractions(root2, lane);
performSyncWorkOnRoot(root2);
} else {
ensureRootIsScheduled(root2, eventTime);
schedulePendingInteractions(root2, lane);
if (executionContext === NoContext) {
resetRenderTimer();
flushSyncCallbackQueue();
}
}
} else {
if ((executionContext & DiscreteEventContext) !== NoContext && (priorityLevel === UserBlockingPriority$2 || priorityLevel === ImmediatePriority$1)) {
if (rootsWithPendingDiscreteUpdates === null) {
rootsWithPendingDiscreteUpdates = new Set([root2]);
} else {
rootsWithPendingDiscreteUpdates.add(root2);
}
}
ensureRootIsScheduled(root2, eventTime);
schedulePendingInteractions(root2, lane);
}
mostRecentlyUpdatedRoot = root2;
}
function markUpdateLaneFromFiberToRoot(sourceFiber, lane) {
sourceFiber.lanes = mergeLanes(sourceFiber.lanes, lane);
var alternate = sourceFiber.alternate;
if (alternate !== null) {
alternate.lanes = mergeLanes(alternate.lanes, lane);
}
{
if (alternate === null && (sourceFiber.flags & (Placement | Hydrating)) !== NoFlags) {
warnAboutUpdateOnNotYetMountedFiberInDEV(sourceFiber);
}
}
var node = sourceFiber;
var parent = sourceFiber.return;
while (parent !== null) {
parent.childLanes = mergeLanes(parent.childLanes, lane);
alternate = parent.alternate;
if (alternate !== null) {
alternate.childLanes = mergeLanes(alternate.childLanes, lane);
} else {
{
if ((parent.flags & (Placement | Hydrating)) !== NoFlags) {
warnAboutUpdateOnNotYetMountedFiberInDEV(sourceFiber);
}
}
}
node = parent;
parent = parent.return;
}
if (node.tag === HostRoot) {
var root2 = node.stateNode;
return root2;
} else {
return null;
}
}
function ensureRootIsScheduled(root2, currentTime) {
var existingCallbackNode = root2.callbackNode;
markStarvedLanesAsExpired(root2, currentTime);
var nextLanes = getNextLanes(root2, root2 === workInProgressRoot ? workInProgressRootRenderLanes : NoLanes);
var newCallbackPriority = returnNextLanesPriority();
if (nextLanes === NoLanes) {
if (existingCallbackNode !== null) {
cancelCallback(existingCallbackNode);
root2.callbackNode = null;
root2.callbackPriority = NoLanePriority;
}
return;
}
if (existingCallbackNode !== null) {
var existingCallbackPriority = root2.callbackPriority;
if (existingCallbackPriority === newCallbackPriority) {
return;
}
cancelCallback(existingCallbackNode);
}
var newCallbackNode;
if (newCallbackPriority === SyncLanePriority) {
newCallbackNode = scheduleSyncCallback(performSyncWorkOnRoot.bind(null, root2));
} else if (newCallbackPriority === SyncBatchedLanePriority) {
newCallbackNode = scheduleCallback(ImmediatePriority$1, performSyncWorkOnRoot.bind(null, root2));
} else {
var schedulerPriorityLevel = lanePriorityToSchedulerPriority(newCallbackPriority);
newCallbackNode = scheduleCallback(schedulerPriorityLevel, performConcurrentWorkOnRoot.bind(null, root2));
}
root2.callbackPriority = newCallbackPriority;
root2.callbackNode = newCallbackNode;
}
function performConcurrentWorkOnRoot(root2) {
currentEventTime = NoTimestamp;
currentEventWipLanes = NoLanes;
currentEventPendingLanes = NoLanes;
if (!((executionContext & (RenderContext | CommitContext)) === NoContext)) {
{
throw Error("Should not already be working.");
}
}
var originalCallbackNode = root2.callbackNode;
var didFlushPassiveEffects = flushPassiveEffects();
if (didFlushPassiveEffects) {
if (root2.callbackNode !== originalCallbackNode) {
return null;
}
}
var lanes = getNextLanes(root2, root2 === workInProgressRoot ? workInProgressRootRenderLanes : NoLanes);
if (lanes === NoLanes) {
return null;
}
var exitStatus = renderRootConcurrent(root2, lanes);
if (includesSomeLane(workInProgressRootIncludedLanes, workInProgressRootUpdatedLanes)) {
prepareFreshStack(root2, NoLanes);
} else if (exitStatus !== RootIncomplete) {
if (exitStatus === RootErrored) {
executionContext |= RetryAfterError;
if (root2.hydrate) {
root2.hydrate = false;
clearContainer(root2.containerInfo);
}
lanes = getLanesToRetrySynchronouslyOnError(root2);
if (lanes !== NoLanes) {
exitStatus = renderRootSync(root2, lanes);
}
}
if (exitStatus === RootFatalErrored) {
var fatalError = workInProgressRootFatalError;
prepareFreshStack(root2, NoLanes);
markRootSuspended$1(root2, lanes);
ensureRootIsScheduled(root2, now());
throw fatalError;
}
var finishedWork = root2.current.alternate;
root2.finishedWork = finishedWork;
root2.finishedLanes = lanes;
finishConcurrentRender(root2, exitStatus, lanes);
}
ensureRootIsScheduled(root2, now());
if (root2.callbackNode === originalCallbackNode) {
return performConcurrentWorkOnRoot.bind(null, root2);
}
return null;
}
function finishConcurrentRender(root2, exitStatus, lanes) {
switch (exitStatus) {
case RootIncomplete:
case RootFatalErrored: {
{
{
throw Error("Root did not complete. This is a bug in React.");
}
}
}
case RootErrored: {
commitRoot(root2);
break;
}
case RootSuspended: {
markRootSuspended$1(root2, lanes);
if (includesOnlyRetries(lanes) && !shouldForceFlushFallbacksInDEV()) {
var msUntilTimeout = globalMostRecentFallbackTime + FALLBACK_THROTTLE_MS - now();
if (msUntilTimeout > 10) {
var nextLanes = getNextLanes(root2, NoLanes);
if (nextLanes !== NoLanes) {
break;
}
var suspendedLanes = root2.suspendedLanes;
if (!isSubsetOfLanes(suspendedLanes, lanes)) {
var eventTime = requestEventTime();
markRootPinged(root2, suspendedLanes);
break;
}
root2.timeoutHandle = scheduleTimeout(commitRoot.bind(null, root2), msUntilTimeout);
break;
}
}
commitRoot(root2);
break;
}
case RootSuspendedWithDelay: {
markRootSuspended$1(root2, lanes);
if (includesOnlyTransitions(lanes)) {
break;
}
if (!shouldForceFlushFallbacksInDEV()) {
var mostRecentEventTime = getMostRecentEventTime(root2, lanes);
var eventTimeMs = mostRecentEventTime;
var timeElapsedMs = now() - eventTimeMs;
var _msUntilTimeout = jnd(timeElapsedMs) - timeElapsedMs;
if (_msUntilTimeout > 10) {
root2.timeoutHandle = scheduleTimeout(commitRoot.bind(null, root2), _msUntilTimeout);
break;
}
}
commitRoot(root2);
break;
}
case RootCompleted: {
commitRoot(root2);
break;
}
default: {
{
{
throw Error("Unknown root exit status.");
}
}
}
}
}
function markRootSuspended$1(root2, suspendedLanes) {
suspendedLanes = removeLanes(suspendedLanes, workInProgressRootPingedLanes);
suspendedLanes = removeLanes(suspendedLanes, workInProgressRootUpdatedLanes);
markRootSuspended(root2, suspendedLanes);
}
function performSyncWorkOnRoot(root2) {
if (!((executionContext & (RenderContext | CommitContext)) === NoContext)) {
{
throw Error("Should not already be working.");
}
}
flushPassiveEffects();
var lanes;
var exitStatus;
if (root2 === workInProgressRoot && includesSomeLane(root2.expiredLanes, workInProgressRootRenderLanes)) {
lanes = workInProgressRootRenderLanes;
exitStatus = renderRootSync(root2, lanes);
if (includesSomeLane(workInProgressRootIncludedLanes, workInProgressRootUpdatedLanes)) {
lanes = getNextLanes(root2, lanes);
exitStatus = renderRootSync(root2, lanes);
}
} else {
lanes = getNextLanes(root2, NoLanes);
exitStatus = renderRootSync(root2, lanes);
}
if (root2.tag !== LegacyRoot && exitStatus === RootErrored) {
executionContext |= RetryAfterError;
if (root2.hydrate) {
root2.hydrate = false;
clearContainer(root2.containerInfo);
}
lanes = getLanesToRetrySynchronouslyOnError(root2);
if (lanes !== NoLanes) {
exitStatus = renderRootSync(root2, lanes);
}
}
if (exitStatus === RootFatalErrored) {
var fatalError = workInProgressRootFatalError;
prepareFreshStack(root2, NoLanes);
markRootSuspended$1(root2, lanes);
ensureRootIsScheduled(root2, now());
throw fatalError;
}
var finishedWork = root2.current.alternate;
root2.finishedWork = finishedWork;
root2.finishedLanes = lanes;
commitRoot(root2);
ensureRootIsScheduled(root2, now());
return null;
}
function flushDiscreteUpdates() {
if ((executionContext & (BatchedContext | RenderContext | CommitContext)) !== NoContext) {
{
if ((executionContext & RenderContext) !== NoContext) {
error("unstable_flushDiscreteUpdates: Cannot flush updates when React is already rendering.");
}
}
return;
}
flushPendingDiscreteUpdates();
flushPassiveEffects();
}
function flushPendingDiscreteUpdates() {
if (rootsWithPendingDiscreteUpdates !== null) {
var roots = rootsWithPendingDiscreteUpdates;
rootsWithPendingDiscreteUpdates = null;
roots.forEach(function(root2) {
markDiscreteUpdatesExpired(root2);
ensureRootIsScheduled(root2, now());
});
}
flushSyncCallbackQueue();
}
function batchedUpdates$1(fn, a) {
var prevExecutionContext = executionContext;
executionContext |= BatchedContext;
try {
return fn(a);
} finally {
executionContext = prevExecutionContext;
if (executionContext === NoContext) {
resetRenderTimer();
flushSyncCallbackQueue();
}
}
}
function batchedEventUpdates$1(fn, a) {
var prevExecutionContext = executionContext;
executionContext |= EventContext;
try {
return fn(a);
} finally {
executionContext = prevExecutionContext;
if (executionContext === NoContext) {
resetRenderTimer();
flushSyncCallbackQueue();
}
}
}
function discreteUpdates$1(fn, a, b, c, d) {
var prevExecutionContext = executionContext;
executionContext |= DiscreteEventContext;
{
try {
return runWithPriority$1(UserBlockingPriority$2, fn.bind(null, a, b, c, d));
} finally {
executionContext = prevExecutionContext;
if (executionContext === NoContext) {
resetRenderTimer();
flushSyncCallbackQueue();
}
}
}
}
function unbatchedUpdates(fn, a) {
var prevExecutionContext = executionContext;
executionContext &= ~BatchedContext;
executionContext |= LegacyUnbatchedContext;
try {
return fn(a);
} finally {
executionContext = prevExecutionContext;
if (executionContext === NoContext) {
resetRenderTimer();
flushSyncCallbackQueue();
}
}
}
function flushSync(fn, a) {
var prevExecutionContext = executionContext;
if ((prevExecutionContext & (RenderContext | CommitContext)) !== NoContext) {
{
error("flushSync was called from inside a lifecycle method. React cannot flush when React is already rendering. Consider moving this call to a scheduler task or micro task.");
}
return fn(a);
}
executionContext |= BatchedContext;
{
try {
if (fn) {
return runWithPriority$1(ImmediatePriority$1, fn.bind(null, a));
} else {
return void 0;
}
} finally {
executionContext = prevExecutionContext;
flushSyncCallbackQueue();
}
}
}
function pushRenderLanes(fiber, lanes) {
push(subtreeRenderLanesCursor, subtreeRenderLanes, fiber);
subtreeRenderLanes = mergeLanes(subtreeRenderLanes, lanes);
workInProgressRootIncludedLanes = mergeLanes(workInProgressRootIncludedLanes, lanes);
}
function popRenderLanes(fiber) {
subtreeRenderLanes = subtreeRenderLanesCursor.current;
pop(subtreeRenderLanesCursor, fiber);
}
function prepareFreshStack(root2, lanes) {
root2.finishedWork = null;
root2.finishedLanes = NoLanes;
var timeoutHandle = root2.timeoutHandle;
if (timeoutHandle !== noTimeout) {
root2.timeoutHandle = noTimeout;
cancelTimeout(timeoutHandle);
}
if (workInProgress !== null) {
var interruptedWork = workInProgress.return;
while (interruptedWork !== null) {
unwindInterruptedWork(interruptedWork);
interruptedWork = interruptedWork.return;
}
}
workInProgressRoot = root2;
workInProgress = createWorkInProgress(root2.current, null);
workInProgressRootRenderLanes = subtreeRenderLanes = workInProgressRootIncludedLanes = lanes;
workInProgressRootExitStatus = RootIncomplete;
workInProgressRootFatalError = null;
workInProgressRootSkippedLanes = NoLanes;
workInProgressRootUpdatedLanes = NoLanes;
workInProgressRootPingedLanes = NoLanes;
{
spawnedWorkDuringRender = null;
}
{
ReactStrictModeWarnings.discardPendingWarnings();
}
}
function handleError(root2, thrownValue) {
do {
var erroredWork = workInProgress;
try {
resetContextDependencies();
resetHooksAfterThrow();
resetCurrentFiber();
ReactCurrentOwner$2.current = null;
if (erroredWork === null || erroredWork.return === null) {
workInProgressRootExitStatus = RootFatalErrored;
workInProgressRootFatalError = thrownValue;
workInProgress = null;
return;
}
if (enableProfilerTimer && erroredWork.mode & ProfileMode) {
stopProfilerTimerIfRunningAndRecordDelta(erroredWork, true);
}
throwException(root2, erroredWork.return, erroredWork, thrownValue, workInProgressRootRenderLanes);
completeUnitOfWork(erroredWork);
} catch (yetAnotherThrownValue) {
thrownValue = yetAnotherThrownValue;
if (workInProgress === erroredWork && erroredWork !== null) {
erroredWork = erroredWork.return;
workInProgress = erroredWork;
} else {
erroredWork = workInProgress;
}
continue;
}
return;
} while (true);
}
function pushDispatcher() {
var prevDispatcher = ReactCurrentDispatcher$2.current;
ReactCurrentDispatcher$2.current = ContextOnlyDispatcher;
if (prevDispatcher === null) {
return ContextOnlyDispatcher;
} else {
return prevDispatcher;
}
}
function popDispatcher(prevDispatcher) {
ReactCurrentDispatcher$2.current = prevDispatcher;
}
function pushInteractions(root2) {
{
var prevInteractions = tracing.__interactionsRef.current;
tracing.__interactionsRef.current = root2.memoizedInteractions;
return prevInteractions;
}
}
function popInteractions(prevInteractions) {
{
tracing.__interactionsRef.current = prevInteractions;
}
}
function markCommitTimeOfFallback() {
globalMostRecentFallbackTime = now();
}
function markSkippedUpdateLanes(lane) {
workInProgressRootSkippedLanes = mergeLanes(lane, workInProgressRootSkippedLanes);
}
function renderDidSuspend() {
if (workInProgressRootExitStatus === RootIncomplete) {
workInProgressRootExitStatus = RootSuspended;
}
}
function renderDidSuspendDelayIfPossible() {
if (workInProgressRootExitStatus === RootIncomplete || workInProgressRootExitStatus === RootSuspended) {
workInProgressRootExitStatus = RootSuspendedWithDelay;
}
if (workInProgressRoot !== null && (includesNonIdleWork(workInProgressRootSkippedLanes) || includesNonIdleWork(workInProgressRootUpdatedLanes))) {
markRootSuspended$1(workInProgressRoot, workInProgressRootRenderLanes);
}
}
function renderDidError() {
if (workInProgressRootExitStatus !== RootCompleted) {
workInProgressRootExitStatus = RootErrored;
}
}
function renderHasNotSuspendedYet() {
return workInProgressRootExitStatus === RootIncomplete;
}
function renderRootSync(root2, lanes) {
var prevExecutionContext = executionContext;
executionContext |= RenderContext;
var prevDispatcher = pushDispatcher();
if (workInProgressRoot !== root2 || workInProgressRootRenderLanes !== lanes) {
prepareFreshStack(root2, lanes);
startWorkOnPendingInteractions(root2, lanes);
}
var prevInteractions = pushInteractions(root2);
do {
try {
workLoopSync();
break;
} catch (thrownValue) {
handleError(root2, thrownValue);
}
} while (true);
resetContextDependencies();
{
popInteractions(prevInteractions);
}
executionContext = prevExecutionContext;
popDispatcher(prevDispatcher);
if (workInProgress !== null) {
{
{
throw Error("Cannot commit an incomplete root. This error is likely caused by a bug in React. Please file an issue.");
}
}
}
workInProgressRoot = null;
workInProgressRootRenderLanes = NoLanes;
return workInProgressRootExitStatus;
}
function workLoopSync() {
while (workInProgress !== null) {
performUnitOfWork(workInProgress);
}
}
function renderRootConcurrent(root2, lanes) {
var prevExecutionContext = executionContext;
executionContext |= RenderContext;
var prevDispatcher = pushDispatcher();
if (workInProgressRoot !== root2 || workInProgressRootRenderLanes !== lanes) {
resetRenderTimer();
prepareFreshStack(root2, lanes);
startWorkOnPendingInteractions(root2, lanes);
}
var prevInteractions = pushInteractions(root2);
do {
try {
workLoopConcurrent();
break;
} catch (thrownValue) {
handleError(root2, thrownValue);
}
} while (true);
resetContextDependencies();
{
popInteractions(prevInteractions);
}
popDispatcher(prevDispatcher);
executionContext = prevExecutionContext;
if (workInProgress !== null) {
return RootIncomplete;
} else {
workInProgressRoot = null;
workInProgressRootRenderLanes = NoLanes;
return workInProgressRootExitStatus;
}
}
function workLoopConcurrent() {
while (workInProgress !== null && !shouldYield()) {
performUnitOfWork(workInProgress);
}
}
function performUnitOfWork(unitOfWork) {
var current2 = unitOfWork.alternate;
setCurrentFiber(unitOfWork);
var next;
if ((unitOfWork.mode & ProfileMode) !== NoMode) {
startProfilerTimer(unitOfWork);
next = beginWork$1(current2, unitOfWork, subtreeRenderLanes);
stopProfilerTimerIfRunningAndRecordDelta(unitOfWork, true);
} else {
next = beginWork$1(current2, unitOfWork, subtreeRenderLanes);
}
resetCurrentFiber();
unitOfWork.memoizedProps = unitOfWork.pendingProps;
if (next === null) {
completeUnitOfWork(unitOfWork);
} else {
workInProgress = next;
}
ReactCurrentOwner$2.current = null;
}
function completeUnitOfWork(unitOfWork) {
var completedWork = unitOfWork;
do {
var current2 = completedWork.alternate;
var returnFiber = completedWork.return;
if ((completedWork.flags & Incomplete) === NoFlags) {
setCurrentFiber(completedWork);
var next = void 0;
if ((completedWork.mode & ProfileMode) === NoMode) {
next = completeWork(current2, completedWork, subtreeRenderLanes);
} else {
startProfilerTimer(completedWork);
next = completeWork(current2, completedWork, subtreeRenderLanes);
stopProfilerTimerIfRunningAndRecordDelta(completedWork, false);
}
resetCurrentFiber();
if (next !== null) {
workInProgress = next;
return;
}
resetChildLanes(completedWork);
if (returnFiber !== null && (returnFiber.flags & Incomplete) === NoFlags) {
if (returnFiber.firstEffect === null) {
returnFiber.firstEffect = completedWork.firstEffect;
}
if (completedWork.lastEffect !== null) {
if (returnFiber.lastEffect !== null) {
returnFiber.lastEffect.nextEffect = completedWork.firstEffect;
}
returnFiber.lastEffect = completedWork.lastEffect;
}
var flags = completedWork.flags;
if (flags > PerformedWork) {
if (returnFiber.lastEffect !== null) {
returnFiber.lastEffect.nextEffect = completedWork;
} else {
returnFiber.firstEffect = completedWork;
}
returnFiber.lastEffect = completedWork;
}
}
} else {
var _next = unwindWork(completedWork);
if (_next !== null) {
_next.flags &= HostEffectMask;
workInProgress = _next;
return;
}
if ((completedWork.mode & ProfileMode) !== NoMode) {
stopProfilerTimerIfRunningAndRecordDelta(completedWork, false);
var actualDuration = completedWork.actualDuration;
var child = completedWork.child;
while (child !== null) {
actualDuration += child.actualDuration;
child = child.sibling;
}
completedWork.actualDuration = actualDuration;
}
if (returnFiber !== null) {
returnFiber.firstEffect = returnFiber.lastEffect = null;
returnFiber.flags |= Incomplete;
}
}
var siblingFiber = completedWork.sibling;
if (siblingFiber !== null) {
workInProgress = siblingFiber;
return;
}
completedWork = returnFiber;
workInProgress = completedWork;
} while (completedWork !== null);
if (workInProgressRootExitStatus === RootIncomplete) {
workInProgressRootExitStatus = RootCompleted;
}
}
function resetChildLanes(completedWork) {
if ((completedWork.tag === LegacyHiddenComponent || completedWork.tag === OffscreenComponent) && completedWork.memoizedState !== null && !includesSomeLane(subtreeRenderLanes, OffscreenLane) && (completedWork.mode & ConcurrentMode) !== NoLanes) {
return;
}
var newChildLanes = NoLanes;
if ((completedWork.mode & ProfileMode) !== NoMode) {
var actualDuration = completedWork.actualDuration;
var treeBaseDuration = completedWork.selfBaseDuration;
var shouldBubbleActualDurations = completedWork.alternate === null || completedWork.child !== completedWork.alternate.child;
var child = completedWork.child;
while (child !== null) {
newChildLanes = mergeLanes(newChildLanes, mergeLanes(child.lanes, child.childLanes));
if (shouldBubbleActualDurations) {
actualDuration += child.actualDuration;
}
treeBaseDuration += child.treeBaseDuration;
child = child.sibling;
}
var isTimedOutSuspense = completedWork.tag === SuspenseComponent && completedWork.memoizedState !== null;
if (isTimedOutSuspense) {
var primaryChildFragment = completedWork.child;
if (primaryChildFragment !== null) {
treeBaseDuration -= primaryChildFragment.treeBaseDuration;
}
}
completedWork.actualDuration = actualDuration;
completedWork.treeBaseDuration = treeBaseDuration;
} else {
var _child = completedWork.child;
while (_child !== null) {
newChildLanes = mergeLanes(newChildLanes, mergeLanes(_child.lanes, _child.childLanes));
_child = _child.sibling;
}
}
completedWork.childLanes = newChildLanes;
}
function commitRoot(root2) {
var renderPriorityLevel = getCurrentPriorityLevel();
runWithPriority$1(ImmediatePriority$1, commitRootImpl.bind(null, root2, renderPriorityLevel));
return null;
}
function commitRootImpl(root2, renderPriorityLevel) {
do {
flushPassiveEffects();
} while (rootWithPendingPassiveEffects !== null);
flushRenderPhaseStrictModeWarningsInDEV();
if (!((executionContext & (RenderContext | CommitContext)) === NoContext)) {
{
throw Error("Should not already be working.");
}
}
var finishedWork = root2.finishedWork;
var lanes = root2.finishedLanes;
if (finishedWork === null) {
return null;
}
root2.finishedWork = null;
root2.finishedLanes = NoLanes;
if (!(finishedWork !== root2.current)) {
{
throw Error("Cannot commit the same tree as before. This error is likely caused by a bug in React. Please file an issue.");
}
}
root2.callbackNode = null;
var remainingLanes = mergeLanes(finishedWork.lanes, finishedWork.childLanes);
markRootFinished(root2, remainingLanes);
if (rootsWithPendingDiscreteUpdates !== null) {
if (!hasDiscreteLanes(remainingLanes) && rootsWithPendingDiscreteUpdates.has(root2)) {
rootsWithPendingDiscreteUpdates.delete(root2);
}
}
if (root2 === workInProgressRoot) {
workInProgressRoot = null;
workInProgress = null;
workInProgressRootRenderLanes = NoLanes;
}
var firstEffect;
if (finishedWork.flags > PerformedWork) {
if (finishedWork.lastEffect !== null) {
finishedWork.lastEffect.nextEffect = finishedWork;
firstEffect = finishedWork.firstEffect;
} else {
firstEffect = finishedWork;
}
} else {
firstEffect = finishedWork.firstEffect;
}
if (firstEffect !== null) {
var prevExecutionContext = executionContext;
executionContext |= CommitContext;
var prevInteractions = pushInteractions(root2);
ReactCurrentOwner$2.current = null;
focusedInstanceHandle = prepareForCommit(root2.containerInfo);
shouldFireAfterActiveInstanceBlur = false;
nextEffect = firstEffect;
do {
{
invokeGuardedCallback(null, commitBeforeMutationEffects, null);
if (hasCaughtError()) {
if (!(nextEffect !== null)) {
{
throw Error("Should be working on an effect.");
}
}
var error2 = clearCaughtError();
captureCommitPhaseError(nextEffect, error2);
nextEffect = nextEffect.nextEffect;
}
}
} while (nextEffect !== null);
focusedInstanceHandle = null;
{
recordCommitTime();
}
nextEffect = firstEffect;
do {
{
invokeGuardedCallback(null, commitMutationEffects, null, root2, renderPriorityLevel);
if (hasCaughtError()) {
if (!(nextEffect !== null)) {
{
throw Error("Should be working on an effect.");
}
}
var _error = clearCaughtError();
captureCommitPhaseError(nextEffect, _error);
nextEffect = nextEffect.nextEffect;
}
}
} while (nextEffect !== null);
resetAfterCommit(root2.containerInfo);
root2.current = finishedWork;
nextEffect = firstEffect;
do {
{
invokeGuardedCallback(null, commitLayoutEffects, null, root2, lanes);
if (hasCaughtError()) {
if (!(nextEffect !== null)) {
{
throw Error("Should be working on an effect.");
}
}
var _error2 = clearCaughtError();
captureCommitPhaseError(nextEffect, _error2);
nextEffect = nextEffect.nextEffect;
}
}
} while (nextEffect !== null);
nextEffect = null;
requestPaint();
{
popInteractions(prevInteractions);
}
executionContext = prevExecutionContext;
} else {
root2.current = finishedWork;
{
recordCommitTime();
}
}
var rootDidHavePassiveEffects = rootDoesHavePassiveEffects;
if (rootDoesHavePassiveEffects) {
rootDoesHavePassiveEffects = false;
rootWithPendingPassiveEffects = root2;
pendingPassiveEffectsLanes = lanes;
pendingPassiveEffectsRenderPriority = renderPriorityLevel;
} else {
nextEffect = firstEffect;
while (nextEffect !== null) {
var nextNextEffect = nextEffect.nextEffect;
nextEffect.nextEffect = null;
if (nextEffect.flags & Deletion) {
detachFiberAfterEffects(nextEffect);
}
nextEffect = nextNextEffect;
}
}
remainingLanes = root2.pendingLanes;
if (remainingLanes !== NoLanes) {
{
if (spawnedWorkDuringRender !== null) {
var expirationTimes = spawnedWorkDuringRender;
spawnedWorkDuringRender = null;
for (var i = 0; i < expirationTimes.length; i++) {
scheduleInteractions(root2, expirationTimes[i], root2.memoizedInteractions);
}
}
schedulePendingInteractions(root2, remainingLanes);
}
} else {
legacyErrorBoundariesThatAlreadyFailed = null;
}
{
if (!rootDidHavePassiveEffects) {
finishPendingInteractions(root2, lanes);
}
}
if (remainingLanes === SyncLane) {
if (root2 === rootWithNestedUpdates) {
nestedUpdateCount++;
} else {
nestedUpdateCount = 0;
rootWithNestedUpdates = root2;
}
} else {
nestedUpdateCount = 0;
}
onCommitRoot(finishedWork.stateNode, renderPriorityLevel);
{
onCommitRoot$1();
}
ensureRootIsScheduled(root2, now());
if (hasUncaughtError) {
hasUncaughtError = false;
var _error3 = firstUncaughtError;
firstUncaughtError = null;
throw _error3;
}
if ((executionContext & LegacyUnbatchedContext) !== NoContext) {
return null;
}
flushSyncCallbackQueue();
return null;
}
function commitBeforeMutationEffects() {
while (nextEffect !== null) {
var current2 = nextEffect.alternate;
if (!shouldFireAfterActiveInstanceBlur && focusedInstanceHandle !== null) {
if ((nextEffect.flags & Deletion) !== NoFlags) {
if (doesFiberContain(nextEffect, focusedInstanceHandle)) {
shouldFireAfterActiveInstanceBlur = true;
}
} else {
if (nextEffect.tag === SuspenseComponent && isSuspenseBoundaryBeingHidden(current2, nextEffect) && doesFiberContain(nextEffect, focusedInstanceHandle)) {
shouldFireAfterActiveInstanceBlur = true;
}
}
}
var flags = nextEffect.flags;
if ((flags & Snapshot) !== NoFlags) {
setCurrentFiber(nextEffect);
commitBeforeMutationLifeCycles(current2, nextEffect);
resetCurrentFiber();
}
if ((flags & Passive) !== NoFlags) {
if (!rootDoesHavePassiveEffects) {
rootDoesHavePassiveEffects = true;
scheduleCallback(NormalPriority$1, function() {
flushPassiveEffects();
return null;
});
}
}
nextEffect = nextEffect.nextEffect;
}
}
function commitMutationEffects(root2, renderPriorityLevel) {
while (nextEffect !== null) {
setCurrentFiber(nextEffect);
var flags = nextEffect.flags;
if (flags & ContentReset) {
commitResetTextContent(nextEffect);
}
if (flags & Ref) {
var current2 = nextEffect.alternate;
if (current2 !== null) {
commitDetachRef(current2);
}
}
var primaryFlags = flags & (Placement | Update | Deletion | Hydrating);
switch (primaryFlags) {
case Placement: {
commitPlacement(nextEffect);
nextEffect.flags &= ~Placement;
break;
}
case PlacementAndUpdate: {
commitPlacement(nextEffect);
nextEffect.flags &= ~Placement;
var _current = nextEffect.alternate;
commitWork(_current, nextEffect);
break;
}
case Hydrating: {
nextEffect.flags &= ~Hydrating;
break;
}
case HydratingAndUpdate: {
nextEffect.flags &= ~Hydrating;
var _current2 = nextEffect.alternate;
commitWork(_current2, nextEffect);
break;
}
case Update: {
var _current3 = nextEffect.alternate;
commitWork(_current3, nextEffect);
break;
}
case Deletion: {
commitDeletion(root2, nextEffect);
break;
}
}
resetCurrentFiber();
nextEffect = nextEffect.nextEffect;
}
}
function commitLayoutEffects(root2, committedLanes) {
while (nextEffect !== null) {
setCurrentFiber(nextEffect);
var flags = nextEffect.flags;
if (flags & (Update | Callback)) {
var current2 = nextEffect.alternate;
commitLifeCycles(root2, current2, nextEffect);
}
{
if (flags & Ref) {
commitAttachRef(nextEffect);
}
}
resetCurrentFiber();
nextEffect = nextEffect.nextEffect;
}
}
function flushPassiveEffects() {
if (pendingPassiveEffectsRenderPriority !== NoPriority$1) {
var priorityLevel = pendingPassiveEffectsRenderPriority > NormalPriority$1 ? NormalPriority$1 : pendingPassiveEffectsRenderPriority;
pendingPassiveEffectsRenderPriority = NoPriority$1;
{
return runWithPriority$1(priorityLevel, flushPassiveEffectsImpl);
}
}
return false;
}
function enqueuePendingPassiveHookEffectMount(fiber, effect) {
pendingPassiveHookEffectsMount.push(effect, fiber);
if (!rootDoesHavePassiveEffects) {
rootDoesHavePassiveEffects = true;
scheduleCallback(NormalPriority$1, function() {
flushPassiveEffects();
return null;
});
}
}
function enqueuePendingPassiveHookEffectUnmount(fiber, effect) {
pendingPassiveHookEffectsUnmount.push(effect, fiber);
{
fiber.flags |= PassiveUnmountPendingDev;
var alternate = fiber.alternate;
if (alternate !== null) {
alternate.flags |= PassiveUnmountPendingDev;
}
}
if (!rootDoesHavePassiveEffects) {
rootDoesHavePassiveEffects = true;
scheduleCallback(NormalPriority$1, function() {
flushPassiveEffects();
return null;
});
}
}
function invokePassiveEffectCreate(effect) {
var create = effect.create;
effect.destroy = create();
}
function flushPassiveEffectsImpl() {
if (rootWithPendingPassiveEffects === null) {
return false;
}
var root2 = rootWithPendingPassiveEffects;
var lanes = pendingPassiveEffectsLanes;
rootWithPendingPassiveEffects = null;
pendingPassiveEffectsLanes = NoLanes;
if (!((executionContext & (RenderContext | CommitContext)) === NoContext)) {
{
throw Error("Cannot flush passive effects while already rendering.");
}
}
{
isFlushingPassiveEffects = true;
}
var prevExecutionContext = executionContext;
executionContext |= CommitContext;
var prevInteractions = pushInteractions(root2);
var unmountEffects = pendingPassiveHookEffectsUnmount;
pendingPassiveHookEffectsUnmount = [];
for (var i = 0; i < unmountEffects.length; i += 2) {
var _effect = unmountEffects[i];
var fiber = unmountEffects[i + 1];
var destroy = _effect.destroy;
_effect.destroy = void 0;
{
fiber.flags &= ~PassiveUnmountPendingDev;
var alternate = fiber.alternate;
if (alternate !== null) {
alternate.flags &= ~PassiveUnmountPendingDev;
}
}
if (typeof destroy === "function") {
{
setCurrentFiber(fiber);
{
invokeGuardedCallback(null, destroy, null);
}
if (hasCaughtError()) {
if (!(fiber !== null)) {
{
throw Error("Should be working on an effect.");
}
}
var error2 = clearCaughtError();
captureCommitPhaseError(fiber, error2);
}
resetCurrentFiber();
}
}
}
var mountEffects = pendingPassiveHookEffectsMount;
pendingPassiveHookEffectsMount = [];
for (var _i = 0; _i < mountEffects.length; _i += 2) {
var _effect2 = mountEffects[_i];
var _fiber = mountEffects[_i + 1];
{
setCurrentFiber(_fiber);
{
invokeGuardedCallback(null, invokePassiveEffectCreate, null, _effect2);
}
if (hasCaughtError()) {
if (!(_fiber !== null)) {
{
throw Error("Should be working on an effect.");
}
}
var _error4 = clearCaughtError();
captureCommitPhaseError(_fiber, _error4);
}
resetCurrentFiber();
}
}
var effect = root2.current.firstEffect;
while (effect !== null) {
var nextNextEffect = effect.nextEffect;
effect.nextEffect = null;
if (effect.flags & Deletion) {
detachFiberAfterEffects(effect);
}
effect = nextNextEffect;
}
{
popInteractions(prevInteractions);
finishPendingInteractions(root2, lanes);
}
{
isFlushingPassiveEffects = false;
}
executionContext = prevExecutionContext;
flushSyncCallbackQueue();
nestedPassiveUpdateCount = rootWithPendingPassiveEffects === null ? 0 : nestedPassiveUpdateCount + 1;
return true;
}
function isAlreadyFailedLegacyErrorBoundary(instance) {
return legacyErrorBoundariesThatAlreadyFailed !== null && legacyErrorBoundariesThatAlreadyFailed.has(instance);
}
function markLegacyErrorBoundaryAsFailed(instance) {
if (legacyErrorBoundariesThatAlreadyFailed === null) {
legacyErrorBoundariesThatAlreadyFailed = new Set([instance]);
} else {
legacyErrorBoundariesThatAlreadyFailed.add(instance);
}
}
function prepareToThrowUncaughtError(error2) {
if (!hasUncaughtError) {
hasUncaughtError = true;
firstUncaughtError = error2;
}
}
var onUncaughtError = prepareToThrowUncaughtError;
function captureCommitPhaseErrorOnRoot(rootFiber, sourceFiber, error2) {
var errorInfo = createCapturedValue(error2, sourceFiber);
var update = createRootErrorUpdate(rootFiber, errorInfo, SyncLane);
enqueueUpdate(rootFiber, update);
var eventTime = requestEventTime();
var root2 = markUpdateLaneFromFiberToRoot(rootFiber, SyncLane);
if (root2 !== null) {
markRootUpdated(root2, SyncLane, eventTime);
ensureRootIsScheduled(root2, eventTime);
schedulePendingInteractions(root2, SyncLane);
}
}
function captureCommitPhaseError(sourceFiber, error2) {
if (sourceFiber.tag === HostRoot) {
captureCommitPhaseErrorOnRoot(sourceFiber, sourceFiber, error2);
return;
}
var fiber = sourceFiber.return;
while (fiber !== null) {
if (fiber.tag === HostRoot) {
captureCommitPhaseErrorOnRoot(fiber, sourceFiber, error2);
return;
} else if (fiber.tag === ClassComponent) {
var ctor = fiber.type;
var instance = fiber.stateNode;
if (typeof ctor.getDerivedStateFromError === "function" || typeof instance.componentDidCatch === "function" && !isAlreadyFailedLegacyErrorBoundary(instance)) {
var errorInfo = createCapturedValue(error2, sourceFiber);
var update = createClassErrorUpdate(fiber, errorInfo, SyncLane);
enqueueUpdate(fiber, update);
var eventTime = requestEventTime();
var root2 = markUpdateLaneFromFiberToRoot(fiber, SyncLane);
if (root2 !== null) {
markRootUpdated(root2, SyncLane, eventTime);
ensureRootIsScheduled(root2, eventTime);
schedulePendingInteractions(root2, SyncLane);
} else {
if (typeof instance.componentDidCatch === "function" && !isAlreadyFailedLegacyErrorBoundary(instance)) {
try {
instance.componentDidCatch(error2, errorInfo);
} catch (errorToIgnore) {
}
}
}
return;
}
}
fiber = fiber.return;
}
}
function pingSuspendedRoot(root2, wakeable, pingedLanes) {
var pingCache = root2.pingCache;
if (pingCache !== null) {
pingCache.delete(wakeable);
}
var eventTime = requestEventTime();
markRootPinged(root2, pingedLanes);
if (workInProgressRoot === root2 && isSubsetOfLanes(workInProgressRootRenderLanes, pingedLanes)) {
if (workInProgressRootExitStatus === RootSuspendedWithDelay || workInProgressRootExitStatus === RootSuspended && includesOnlyRetries(workInProgressRootRenderLanes) && now() - globalMostRecentFallbackTime < FALLBACK_THROTTLE_MS) {
prepareFreshStack(root2, NoLanes);
} else {
workInProgressRootPingedLanes = mergeLanes(workInProgressRootPingedLanes, pingedLanes);
}
}
ensureRootIsScheduled(root2, eventTime);
schedulePendingInteractions(root2, pingedLanes);
}
function retryTimedOutBoundary(boundaryFiber, retryLane) {
if (retryLane === NoLane) {
retryLane = requestRetryLane(boundaryFiber);
}
var eventTime = requestEventTime();
var root2 = markUpdateLaneFromFiberToRoot(boundaryFiber, retryLane);
if (root2 !== null) {
markRootUpdated(root2, retryLane, eventTime);
ensureRootIsScheduled(root2, eventTime);
schedulePendingInteractions(root2, retryLane);
}
}
function resolveRetryWakeable(boundaryFiber, wakeable) {
var retryLane = NoLane;
var retryCache;
{
retryCache = boundaryFiber.stateNode;
}
if (retryCache !== null) {
retryCache.delete(wakeable);
}
retryTimedOutBoundary(boundaryFiber, retryLane);
}
function jnd(timeElapsed) {
return timeElapsed < 120 ? 120 : timeElapsed < 480 ? 480 : timeElapsed < 1080 ? 1080 : timeElapsed < 1920 ? 1920 : timeElapsed < 3e3 ? 3e3 : timeElapsed < 4320 ? 4320 : ceil(timeElapsed / 1960) * 1960;
}
function checkForNestedUpdates() {
if (nestedUpdateCount > NESTED_UPDATE_LIMIT) {
nestedUpdateCount = 0;
rootWithNestedUpdates = null;
{
{
throw Error("Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.");
}
}
}
{
if (nestedPassiveUpdateCount > NESTED_PASSIVE_UPDATE_LIMIT) {
nestedPassiveUpdateCount = 0;
error("Maximum update depth exceeded. This can happen when a component calls setState inside useEffect, but useEffect either doesn't have a dependency array, or one of the dependencies changes on every render.");
}
}
}
function flushRenderPhaseStrictModeWarningsInDEV() {
{
ReactStrictModeWarnings.flushLegacyContextWarning();
{
ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings();
}
}
}
var didWarnStateUpdateForNotYetMountedComponent = null;
function warnAboutUpdateOnNotYetMountedFiberInDEV(fiber) {
{
if ((executionContext & RenderContext) !== NoContext) {
return;
}
if (!(fiber.mode & (BlockingMode | ConcurrentMode))) {
return;
}
var tag = fiber.tag;
if (tag !== IndeterminateComponent && tag !== HostRoot && tag !== ClassComponent && tag !== FunctionComponent && tag !== ForwardRef && tag !== MemoComponent && tag !== SimpleMemoComponent && tag !== Block) {
return;
}
var componentName = getComponentName(fiber.type) || "ReactComponent";
if (didWarnStateUpdateForNotYetMountedComponent !== null) {
if (didWarnStateUpdateForNotYetMountedComponent.has(componentName)) {
return;
}
didWarnStateUpdateForNotYetMountedComponent.add(componentName);
} else {
didWarnStateUpdateForNotYetMountedComponent = new Set([componentName]);
}
var previousFiber = current;
try {
setCurrentFiber(fiber);
error("Can't perform a React state update on a component that hasn't mounted yet. This indicates that you have a side-effect in your render function that asynchronously later calls tries to update the component. Move this work to useEffect instead.");
} finally {
if (previousFiber) {
setCurrentFiber(fiber);
} else {
resetCurrentFiber();
}
}
}
}
var didWarnStateUpdateForUnmountedComponent = null;
function warnAboutUpdateOnUnmountedFiberInDEV(fiber) {
{
var tag = fiber.tag;
if (tag !== HostRoot && tag !== ClassComponent && tag !== FunctionComponent && tag !== ForwardRef && tag !== MemoComponent && tag !== SimpleMemoComponent && tag !== Block) {
return;
}
if ((fiber.flags & PassiveUnmountPendingDev) !== NoFlags) {
return;
}
var componentName = getComponentName(fiber.type) || "ReactComponent";
if (didWarnStateUpdateForUnmountedComponent !== null) {
if (didWarnStateUpdateForUnmountedComponent.has(componentName)) {
return;
}
didWarnStateUpdateForUnmountedComponent.add(componentName);
} else {
didWarnStateUpdateForUnmountedComponent = new Set([componentName]);
}
if (isFlushingPassiveEffects)
;
else {
var previousFiber = current;
try {
setCurrentFiber(fiber);
error("Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in %s.", tag === ClassComponent ? "the componentWillUnmount method" : "a useEffect cleanup function");
} finally {
if (previousFiber) {
setCurrentFiber(fiber);
} else {
resetCurrentFiber();
}
}
}
}
}
var beginWork$1;
{
var dummyFiber = null;
beginWork$1 = function(current2, unitOfWork, lanes) {
var originalWorkInProgressCopy = assignFiberPropertiesInDEV(dummyFiber, unitOfWork);
try {
return beginWork(current2, unitOfWork, lanes);
} catch (originalError) {
if (originalError !== null && typeof originalError === "object" && typeof originalError.then === "function") {
throw originalError;
}
resetContextDependencies();
resetHooksAfterThrow();
unwindInterruptedWork(unitOfWork);
assignFiberPropertiesInDEV(unitOfWork, originalWorkInProgressCopy);
if (unitOfWork.mode & ProfileMode) {
startProfilerTimer(unitOfWork);
}
invokeGuardedCallback(null, beginWork, null, current2, unitOfWork, lanes);
if (hasCaughtError()) {
var replayError = clearCaughtError();
throw replayError;
} else {
throw originalError;
}
}
};
}
var didWarnAboutUpdateInRender = false;
var didWarnAboutUpdateInRenderForAnotherComponent;
{
didWarnAboutUpdateInRenderForAnotherComponent = new Set();
}
function warnAboutRenderPhaseUpdatesInDEV(fiber) {
{
if (isRendering && (executionContext & RenderContext) !== NoContext && !getIsUpdatingOpaqueValueInRenderPhaseInDEV()) {
switch (fiber.tag) {
case FunctionComponent:
case ForwardRef:
case SimpleMemoComponent: {
var renderingComponentName = workInProgress && getComponentName(workInProgress.type) || "Unknown";
var dedupeKey = renderingComponentName;
if (!didWarnAboutUpdateInRenderForAnotherComponent.has(dedupeKey)) {
didWarnAboutUpdateInRenderForAnotherComponent.add(dedupeKey);
var setStateComponentName = getComponentName(fiber.type) || "Unknown";
error("Cannot update a component (`%s`) while rendering a different component (`%s`). To locate the bad setState() call inside `%s`, follow the stack trace as described in https://reactjs.org/link/setstate-in-render", setStateComponentName, renderingComponentName, renderingComponentName);
}
break;
}
case ClassComponent: {
if (!didWarnAboutUpdateInRender) {
error("Cannot update during an existing state transition (such as within `render`). Render methods should be a pure function of props and state.");
didWarnAboutUpdateInRender = true;
}
break;
}
}
}
}
}
var IsThisRendererActing = {
current: false
};
function warnIfNotScopedWithMatchingAct(fiber) {
{
if (IsSomeRendererActing.current === true && IsThisRendererActing.current !== true) {
var previousFiber = current;
try {
setCurrentFiber(fiber);
error("It looks like you're using the wrong act() around your test interactions.\nBe sure to use the matching version of act() corresponding to your renderer:\n\n// for react-dom:\nimport {act} from 'react-dom/test-utils';\n// ...\nact(() => ...);\n\n// for react-test-renderer:\nimport TestRenderer from react-test-renderer';\nconst {act} = TestRenderer;\n// ...\nact(() => ...);");
} finally {
if (previousFiber) {
setCurrentFiber(fiber);
} else {
resetCurrentFiber();
}
}
}
}
}
function warnIfNotCurrentlyActingEffectsInDEV(fiber) {
{
if ((fiber.mode & StrictMode) !== NoMode && IsSomeRendererActing.current === false && IsThisRendererActing.current === false) {
error("An update to %s ran an effect, but was not wrapped in act(...).\n\nWhen testing, code that causes React state updates should be wrapped into act(...):\n\nact(() => {\n /* fire events that update state */\n});\n/* assert on the output */\n\nThis ensures that you're testing the behavior the user would see in the browser. Learn more at https://reactjs.org/link/wrap-tests-with-act", getComponentName(fiber.type));
}
}
}
function warnIfNotCurrentlyActingUpdatesInDEV(fiber) {
{
if (executionContext === NoContext && IsSomeRendererActing.current === false && IsThisRendererActing.current === false) {
var previousFiber = current;
try {
setCurrentFiber(fiber);
error("An update to %s inside a test was not wrapped in act(...).\n\nWhen testing, code that causes React state updates should be wrapped into act(...):\n\nact(() => {\n /* fire events that update state */\n});\n/* assert on the output */\n\nThis ensures that you're testing the behavior the user would see in the browser. Learn more at https://reactjs.org/link/wrap-tests-with-act", getComponentName(fiber.type));
} finally {
if (previousFiber) {
setCurrentFiber(fiber);
} else {
resetCurrentFiber();
}
}
}
}
}
var warnIfNotCurrentlyActingUpdatesInDev = warnIfNotCurrentlyActingUpdatesInDEV;
var didWarnAboutUnmockedScheduler = false;
function warnIfUnmockedScheduler(fiber) {
{
if (didWarnAboutUnmockedScheduler === false && Scheduler.unstable_flushAllWithoutAsserting === void 0) {
if (fiber.mode & BlockingMode || fiber.mode & ConcurrentMode) {
didWarnAboutUnmockedScheduler = true;
error(`In Concurrent or Sync modes, the "scheduler" module needs to be mocked to guarantee consistent behaviour across tests and browsers. For example, with jest:
jest.mock('scheduler', () => require('scheduler/unstable_mock'));
For more info, visit https://reactjs.org/link/mock-scheduler`);
}
}
}
}
function computeThreadID(root2, lane) {
return lane * 1e3 + root2.interactionThreadID;
}
function markSpawnedWork(lane) {
if (spawnedWorkDuringRender === null) {
spawnedWorkDuringRender = [lane];
} else {
spawnedWorkDuringRender.push(lane);
}
}
function scheduleInteractions(root2, lane, interactions) {
if (interactions.size > 0) {
var pendingInteractionMap = root2.pendingInteractionMap;
var pendingInteractions = pendingInteractionMap.get(lane);
if (pendingInteractions != null) {
interactions.forEach(function(interaction) {
if (!pendingInteractions.has(interaction)) {
interaction.__count++;
}
pendingInteractions.add(interaction);
});
} else {
pendingInteractionMap.set(lane, new Set(interactions));
interactions.forEach(function(interaction) {
interaction.__count++;
});
}
var subscriber = tracing.__subscriberRef.current;
if (subscriber !== null) {
var threadID = computeThreadID(root2, lane);
subscriber.onWorkScheduled(interactions, threadID);
}
}
}
function schedulePendingInteractions(root2, lane) {
scheduleInteractions(root2, lane, tracing.__interactionsRef.current);
}
function startWorkOnPendingInteractions(root2, lanes) {
var interactions = new Set();
root2.pendingInteractionMap.forEach(function(scheduledInteractions, scheduledLane) {
if (includesSomeLane(lanes, scheduledLane)) {
scheduledInteractions.forEach(function(interaction) {
return interactions.add(interaction);
});
}
});
root2.memoizedInteractions = interactions;
if (interactions.size > 0) {
var subscriber = tracing.__subscriberRef.current;
if (subscriber !== null) {
var threadID = computeThreadID(root2, lanes);
try {
subscriber.onWorkStarted(interactions, threadID);
} catch (error2) {
scheduleCallback(ImmediatePriority$1, function() {
throw error2;
});
}
}
}
}
function finishPendingInteractions(root2, committedLanes) {
var remainingLanesAfterCommit = root2.pendingLanes;
var subscriber;
try {
subscriber = tracing.__subscriberRef.current;
if (subscriber !== null && root2.memoizedInteractions.size > 0) {
var threadID = computeThreadID(root2, committedLanes);
subscriber.onWorkStopped(root2.memoizedInteractions, threadID);
}
} catch (error2) {
scheduleCallback(ImmediatePriority$1, function() {
throw error2;
});
} finally {
var pendingInteractionMap = root2.pendingInteractionMap;
pendingInteractionMap.forEach(function(scheduledInteractions, lane) {
if (!includesSomeLane(remainingLanesAfterCommit, lane)) {
pendingInteractionMap.delete(lane);
scheduledInteractions.forEach(function(interaction) {
interaction.__count--;
if (subscriber !== null && interaction.__count === 0) {
try {
subscriber.onInteractionScheduledWorkCompleted(interaction);
} catch (error2) {
scheduleCallback(ImmediatePriority$1, function() {
throw error2;
});
}
}
});
}
});
}
}
function shouldForceFlushFallbacksInDEV() {
return actingUpdatesScopeDepth > 0;
}
var actingUpdatesScopeDepth = 0;
function detachFiberAfterEffects(fiber) {
fiber.sibling = null;
fiber.stateNode = null;
}
var resolveFamily = null;
var failedBoundaries = null;
var setRefreshHandler = function(handler) {
{
resolveFamily = handler;
}
};
function resolveFunctionForHotReloading(type) {
{
if (resolveFamily === null) {
return type;
}
var family = resolveFamily(type);
if (family === void 0) {
return type;
}
return family.current;
}
}
function resolveClassForHotReloading(type) {
return resolveFunctionForHotReloading(type);
}
function resolveForwardRefForHotReloading(type) {
{
if (resolveFamily === null) {
return type;
}
var family = resolveFamily(type);
if (family === void 0) {
if (type !== null && type !== void 0 && typeof type.render === "function") {
var currentRender = resolveFunctionForHotReloading(type.render);
if (type.render !== currentRender) {
var syntheticType = {
$$typeof: REACT_FORWARD_REF_TYPE,
render: currentRender
};
if (type.displayName !== void 0) {
syntheticType.displayName = type.displayName;
}
return syntheticType;
}
}
return type;
}
return family.current;
}
}
function isCompatibleFamilyForHotReloading(fiber, element) {
{
if (resolveFamily === null) {
return false;
}
var prevType = fiber.elementType;
var nextType = element.type;
var needsCompareFamilies = false;
var $$typeofNextType = typeof nextType === "object" && nextType !== null ? nextType.$$typeof : null;
switch (fiber.tag) {
case ClassComponent: {
if (typeof nextType === "function") {
needsCompareFamilies = true;
}
break;
}
case FunctionComponent: {
if (typeof nextType === "function") {
needsCompareFamilies = true;
} else if ($$typeofNextType === REACT_LAZY_TYPE) {
needsCompareFamilies = true;
}
break;
}
case ForwardRef: {
if ($$typeofNextType === REACT_FORWARD_REF_TYPE) {
needsCompareFamilies = true;
} else if ($$typeofNextType === REACT_LAZY_TYPE) {
needsCompareFamilies = true;
}
break;
}
case MemoComponent:
case SimpleMemoComponent: {
if ($$typeofNextType === REACT_MEMO_TYPE) {
needsCompareFamilies = true;
} else if ($$typeofNextType === REACT_LAZY_TYPE) {
needsCompareFamilies = true;
}
break;
}
default:
return false;
}
if (needsCompareFamilies) {
var prevFamily = resolveFamily(prevType);
if (prevFamily !== void 0 && prevFamily === resolveFamily(nextType)) {
return true;
}
}
return false;
}
}
function markFailedErrorBoundaryForHotReloading(fiber) {
{
if (resolveFamily === null) {
return;
}
if (typeof WeakSet !== "function") {
return;
}
if (failedBoundaries === null) {
failedBoundaries = new WeakSet();
}
failedBoundaries.add(fiber);
}
}
var scheduleRefresh = function(root2, update) {
{
if (resolveFamily === null) {
return;
}
var staleFamilies = update.staleFamilies, updatedFamilies = update.updatedFamilies;
flushPassiveEffects();
flushSync(function() {
scheduleFibersWithFamiliesRecursively(root2.current, updatedFamilies, staleFamilies);
});
}
};
var scheduleRoot = function(root2, element) {
{
if (root2.context !== emptyContextObject) {
return;
}
flushPassiveEffects();
flushSync(function() {
updateContainer(element, root2, null, null);
});
}
};
function scheduleFibersWithFamiliesRecursively(fiber, updatedFamilies, staleFamilies) {
{
var alternate = fiber.alternate, child = fiber.child, sibling = fiber.sibling, tag = fiber.tag, type = fiber.type;
var candidateType = null;
switch (tag) {
case FunctionComponent:
case SimpleMemoComponent:
case ClassComponent:
candidateType = type;
break;
case ForwardRef:
candidateType = type.render;
break;
}
if (resolveFamily === null) {
throw new Error("Expected resolveFamily to be set during hot reload.");
}
var needsRender = false;
var needsRemount = false;
if (candidateType !== null) {
var family = resolveFamily(candidateType);
if (family !== void 0) {
if (staleFamilies.has(family)) {
needsRemount = true;
} else if (updatedFamilies.has(family)) {
if (tag === ClassComponent) {
needsRemount = true;
} else {
needsRender = true;
}
}
}
}
if (failedBoundaries !== null) {
if (failedBoundaries.has(fiber) || alternate !== null && failedBoundaries.has(alternate)) {
needsRemount = true;
}
}
if (needsRemount) {
fiber._debugNeedsRemount = true;
}
if (needsRemount || needsRender) {
scheduleUpdateOnFiber(fiber, SyncLane, NoTimestamp);
}
if (child !== null && !needsRemount) {
scheduleFibersWithFamiliesRecursively(child, updatedFamilies, staleFamilies);
}
if (sibling !== null) {
scheduleFibersWithFamiliesRecursively(sibling, updatedFamilies, staleFamilies);
}
}
}
var findHostInstancesForRefresh = function(root2, families) {
{
var hostInstances = new Set();
var types = new Set(families.map(function(family) {
return family.current;
}));
findHostInstancesForMatchingFibersRecursively(root2.current, types, hostInstances);
return hostInstances;
}
};
function findHostInstancesForMatchingFibersRecursively(fiber, types, hostInstances) {
{
var child = fiber.child, sibling = fiber.sibling, tag = fiber.tag, type = fiber.type;
var candidateType = null;
switch (tag) {
case FunctionComponent:
case SimpleMemoComponent:
case ClassComponent:
candidateType = type;
break;
case ForwardRef:
candidateType = type.render;
break;
}
var didMatch = false;
if (candidateType !== null) {
if (types.has(candidateType)) {
didMatch = true;
}
}
if (didMatch) {
findHostInstancesForFiberShallowly(fiber, hostInstances);
} else {
if (child !== null) {
findHostInstancesForMatchingFibersRecursively(child, types, hostInstances);
}
}
if (sibling !== null) {
findHostInstancesForMatchingFibersRecursively(sibling, types, hostInstances);
}
}
}
function findHostInstancesForFiberShallowly(fiber, hostInstances) {
{
var foundHostInstances = findChildHostInstancesForFiberShallowly(fiber, hostInstances);
if (foundHostInstances) {
return;
}
var node = fiber;
while (true) {
switch (node.tag) {
case HostComponent:
hostInstances.add(node.stateNode);
return;
case HostPortal:
hostInstances.add(node.stateNode.containerInfo);
return;
case HostRoot:
hostInstances.add(node.stateNode.containerInfo);
return;
}
if (node.return === null) {
throw new Error("Expected to reach root first.");
}
node = node.return;
}
}
}
function findChildHostInstancesForFiberShallowly(fiber, hostInstances) {
{
var node = fiber;
var foundHostInstances = false;
while (true) {
if (node.tag === HostComponent) {
foundHostInstances = true;
hostInstances.add(node.stateNode);
} else if (node.child !== null) {
node.child.return = node;
node = node.child;
continue;
}
if (node === fiber) {
return foundHostInstances;
}
while (node.sibling === null) {
if (node.return === null || node.return === fiber) {
return foundHostInstances;
}
node = node.return;
}
node.sibling.return = node.return;
node = node.sibling;
}
}
return false;
}
var hasBadMapPolyfill;
{
hasBadMapPolyfill = false;
try {
var nonExtensibleObject = Object.preventExtensions({});
new Map([[nonExtensibleObject, null]]);
new Set([nonExtensibleObject]);
} catch (e) {
hasBadMapPolyfill = true;
}
}
var debugCounter = 1;
function FiberNode(tag, pendingProps, key, mode) {
this.tag = tag;
this.key = key;
this.elementType = null;
this.type = null;
this.stateNode = null;
this.return = null;
this.child = null;
this.sibling = null;
this.index = 0;
this.ref = null;
this.pendingProps = pendingProps;
this.memoizedProps = null;
this.updateQueue = null;
this.memoizedState = null;
this.dependencies = null;
this.mode = mode;
this.flags = NoFlags;
this.nextEffect = null;
this.firstEffect = null;
this.lastEffect = null;
this.lanes = NoLanes;
this.childLanes = NoLanes;
this.alternate = null;
{
this.actualDuration = Number.NaN;
this.actualStartTime = Number.NaN;
this.selfBaseDuration = Number.NaN;
this.treeBaseDuration = Number.NaN;
this.actualDuration = 0;
this.actualStartTime = -1;
this.selfBaseDuration = 0;
this.treeBaseDuration = 0;
}
{
this._debugID = debugCounter++;
this._debugSource = null;
this._debugOwner = null;
this._debugNeedsRemount = false;
this._debugHookTypes = null;
if (!hasBadMapPolyfill && typeof Object.preventExtensions === "function") {
Object.preventExtensions(this);
}
}
}
var createFiber = function(tag, pendingProps, key, mode) {
return new FiberNode(tag, pendingProps, key, mode);
};
function shouldConstruct$1(Component) {
var prototype = Component.prototype;
return !!(prototype && prototype.isReactComponent);
}
function isSimpleFunctionComponent(type) {
return typeof type === "function" && !shouldConstruct$1(type) && type.defaultProps === void 0;
}
function resolveLazyComponentTag(Component) {
if (typeof Component === "function") {
return shouldConstruct$1(Component) ? ClassComponent : FunctionComponent;
} else if (Component !== void 0 && Component !== null) {
var $$typeof = Component.$$typeof;
if ($$typeof === REACT_FORWARD_REF_TYPE) {
return ForwardRef;
}
if ($$typeof === REACT_MEMO_TYPE) {
return MemoComponent;
}
}
return IndeterminateComponent;
}
function createWorkInProgress(current2, pendingProps) {
var workInProgress2 = current2.alternate;
if (workInProgress2 === null) {
workInProgress2 = createFiber(current2.tag, pendingProps, current2.key, current2.mode);
workInProgress2.elementType = current2.elementType;
workInProgress2.type = current2.type;
workInProgress2.stateNode = current2.stateNode;
{
workInProgress2._debugID = current2._debugID;
workInProgress2._debugSource = current2._debugSource;
workInProgress2._debugOwner = current2._debugOwner;
workInProgress2._debugHookTypes = current2._debugHookTypes;
}
workInProgress2.alternate = current2;
current2.alternate = workInProgress2;
} else {
workInProgress2.pendingProps = pendingProps;
workInProgress2.type = current2.type;
workInProgress2.flags = NoFlags;
workInProgress2.nextEffect = null;
workInProgress2.firstEffect = null;
workInProgress2.lastEffect = null;
{
workInProgress2.actualDuration = 0;
workInProgress2.actualStartTime = -1;
}
}
workInProgress2.childLanes = current2.childLanes;
workInProgress2.lanes = current2.lanes;
workInProgress2.child = current2.child;
workInProgress2.memoizedProps = current2.memoizedProps;
workInProgress2.memoizedState = current2.memoizedState;
workInProgress2.updateQueue = current2.updateQueue;
var currentDependencies = current2.dependencies;
workInProgress2.dependencies = currentDependencies === null ? null : {
lanes: currentDependencies.lanes,
firstContext: currentDependencies.firstContext
};
workInProgress2.sibling = current2.sibling;
workInProgress2.index = current2.index;
workInProgress2.ref = current2.ref;
{
workInProgress2.selfBaseDuration = current2.selfBaseDuration;
workInProgress2.treeBaseDuration = current2.treeBaseDuration;
}
{
workInProgress2._debugNeedsRemount = current2._debugNeedsRemount;
switch (workInProgress2.tag) {
case IndeterminateComponent:
case FunctionComponent:
case SimpleMemoComponent:
workInProgress2.type = resolveFunctionForHotReloading(current2.type);
break;
case ClassComponent:
workInProgress2.type = resolveClassForHotReloading(current2.type);
break;
case ForwardRef:
workInProgress2.type = resolveForwardRefForHotReloading(current2.type);
break;
}
}
return workInProgress2;
}
function resetWorkInProgress(workInProgress2, renderLanes2) {
workInProgress2.flags &= Placement;
workInProgress2.nextEffect = null;
workInProgress2.firstEffect = null;
workInProgress2.lastEffect = null;
var current2 = workInProgress2.alternate;
if (current2 === null) {
workInProgress2.childLanes = NoLanes;
workInProgress2.lanes = renderLanes2;
workInProgress2.child = null;
workInProgress2.memoizedProps = null;
workInProgress2.memoizedState = null;
workInProgress2.updateQueue = null;
workInProgress2.dependencies = null;
workInProgress2.stateNode = null;
{
workInProgress2.selfBaseDuration = 0;
workInProgress2.treeBaseDuration = 0;
}
} else {
workInProgress2.childLanes = current2.childLanes;
workInProgress2.lanes = current2.lanes;
workInProgress2.child = current2.child;
workInProgress2.memoizedProps = current2.memoizedProps;
workInProgress2.memoizedState = current2.memoizedState;
workInProgress2.updateQueue = current2.updateQueue;
workInProgress2.type = current2.type;
var currentDependencies = current2.dependencies;
workInProgress2.dependencies = currentDependencies === null ? null : {
lanes: currentDependencies.lanes,
firstContext: currentDependencies.firstContext
};
{
workInProgress2.selfBaseDuration = current2.selfBaseDuration;
workInProgress2.treeBaseDuration = current2.treeBaseDuration;
}
}
return workInProgress2;
}
function createHostRootFiber(tag) {
var mode;
if (tag === ConcurrentRoot) {
mode = ConcurrentMode | BlockingMode | StrictMode;
} else if (tag === BlockingRoot) {
mode = BlockingMode | StrictMode;
} else {
mode = NoMode;
}
if (isDevToolsPresent) {
mode |= ProfileMode;
}
return createFiber(HostRoot, null, null, mode);
}
function createFiberFromTypeAndProps(type, key, pendingProps, owner, mode, lanes) {
var fiberTag = IndeterminateComponent;
var resolvedType = type;
if (typeof type === "function") {
if (shouldConstruct$1(type)) {
fiberTag = ClassComponent;
{
resolvedType = resolveClassForHotReloading(resolvedType);
}
} else {
{
resolvedType = resolveFunctionForHotReloading(resolvedType);
}
}
} else if (typeof type === "string") {
fiberTag = HostComponent;
} else {
getTag:
switch (type) {
case REACT_FRAGMENT_TYPE:
return createFiberFromFragment(pendingProps.children, mode, lanes, key);
case REACT_DEBUG_TRACING_MODE_TYPE:
fiberTag = Mode;
mode |= DebugTracingMode;
break;
case REACT_STRICT_MODE_TYPE:
fiberTag = Mode;
mode |= StrictMode;
break;
case REACT_PROFILER_TYPE:
return createFiberFromProfiler(pendingProps, mode, lanes, key);
case REACT_SUSPENSE_TYPE:
return createFiberFromSuspense(pendingProps, mode, lanes, key);
case REACT_SUSPENSE_LIST_TYPE:
return createFiberFromSuspenseList(pendingProps, mode, lanes, key);
case REACT_OFFSCREEN_TYPE:
return createFiberFromOffscreen(pendingProps, mode, lanes, key);
case REACT_LEGACY_HIDDEN_TYPE:
return createFiberFromLegacyHidden(pendingProps, mode, lanes, key);
case REACT_SCOPE_TYPE:
default: {
if (typeof type === "object" && type !== null) {
switch (type.$$typeof) {
case REACT_PROVIDER_TYPE:
fiberTag = ContextProvider;
break getTag;
case REACT_CONTEXT_TYPE:
fiberTag = ContextConsumer;
break getTag;
case REACT_FORWARD_REF_TYPE:
fiberTag = ForwardRef;
{
resolvedType = resolveForwardRefForHotReloading(resolvedType);
}
break getTag;
case REACT_MEMO_TYPE:
fiberTag = MemoComponent;
break getTag;
case REACT_LAZY_TYPE:
fiberTag = LazyComponent;
resolvedType = null;
break getTag;
case REACT_BLOCK_TYPE:
fiberTag = Block;
break getTag;
}
}
var info = "";
{
if (type === void 0 || typeof type === "object" && type !== null && Object.keys(type).length === 0) {
info += " You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.";
}
var ownerName = owner ? getComponentName(owner.type) : null;
if (ownerName) {
info += "\n\nCheck the render method of `" + ownerName + "`.";
}
}
{
{
throw Error("Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: " + (type == null ? type : typeof type) + "." + info);
}
}
}
}
}
var fiber = createFiber(fiberTag, pendingProps, key, mode);
fiber.elementType = type;
fiber.type = resolvedType;
fiber.lanes = lanes;
{
fiber._debugOwner = owner;
}
return fiber;
}
function createFiberFromElement(element, mode, lanes) {
var owner = null;
{
owner = element._owner;
}
var type = element.type;
var key = element.key;
var pendingProps = element.props;
var fiber = createFiberFromTypeAndProps(type, key, pendingProps, owner, mode, lanes);
{
fiber._debugSource = element._source;
fiber._debugOwner = element._owner;
}
return fiber;
}
function createFiberFromFragment(elements, mode, lanes, key) {
var fiber = createFiber(Fragment, elements, key, mode);
fiber.lanes = lanes;
return fiber;
}
function createFiberFromProfiler(pendingProps, mode, lanes, key) {
{
if (typeof pendingProps.id !== "string") {
error('Profiler must specify an "id" as a prop');
}
}
var fiber = createFiber(Profiler, pendingProps, key, mode | ProfileMode);
fiber.elementType = REACT_PROFILER_TYPE;
fiber.type = REACT_PROFILER_TYPE;
fiber.lanes = lanes;
{
fiber.stateNode = {
effectDuration: 0,
passiveEffectDuration: 0
};
}
return fiber;
}
function createFiberFromSuspense(pendingProps, mode, lanes, key) {
var fiber = createFiber(SuspenseComponent, pendingProps, key, mode);
fiber.type = REACT_SUSPENSE_TYPE;
fiber.elementType = REACT_SUSPENSE_TYPE;
fiber.lanes = lanes;
return fiber;
}
function createFiberFromSuspenseList(pendingProps, mode, lanes, key) {
var fiber = createFiber(SuspenseListComponent, pendingProps, key, mode);
{
fiber.type = REACT_SUSPENSE_LIST_TYPE;
}
fiber.elementType = REACT_SUSPENSE_LIST_TYPE;
fiber.lanes = lanes;
return fiber;
}
function createFiberFromOffscreen(pendingProps, mode, lanes, key) {
var fiber = createFiber(OffscreenComponent, pendingProps, key, mode);
{
fiber.type = REACT_OFFSCREEN_TYPE;
}
fiber.elementType = REACT_OFFSCREEN_TYPE;
fiber.lanes = lanes;
return fiber;
}
function createFiberFromLegacyHidden(pendingProps, mode, lanes, key) {
var fiber = createFiber(LegacyHiddenComponent, pendingProps, key, mode);
{
fiber.type = REACT_LEGACY_HIDDEN_TYPE;
}
fiber.elementType = REACT_LEGACY_HIDDEN_TYPE;
fiber.lanes = lanes;
return fiber;
}
function createFiberFromText(content, mode, lanes) {
var fiber = createFiber(HostText, content, null, mode);
fiber.lanes = lanes;
return fiber;
}
function createFiberFromHostInstanceForDeletion() {
var fiber = createFiber(HostComponent, null, null, NoMode);
fiber.elementType = "DELETED";
fiber.type = "DELETED";
return fiber;
}
function createFiberFromPortal(portal, mode, lanes) {
var pendingProps = portal.children !== null ? portal.children : [];
var fiber = createFiber(HostPortal, pendingProps, portal.key, mode);
fiber.lanes = lanes;
fiber.stateNode = {
containerInfo: portal.containerInfo,
pendingChildren: null,
implementation: portal.implementation
};
return fiber;
}
function assignFiberPropertiesInDEV(target, source) {
if (target === null) {
target = createFiber(IndeterminateComponent, null, null, NoMode);
}
target.tag = source.tag;
target.key = source.key;
target.elementType = source.elementType;
target.type = source.type;
target.stateNode = source.stateNode;
target.return = source.return;
target.child = source.child;
target.sibling = source.sibling;
target.index = source.index;
target.ref = source.ref;
target.pendingProps = source.pendingProps;
target.memoizedProps = source.memoizedProps;
target.updateQueue = source.updateQueue;
target.memoizedState = source.memoizedState;
target.dependencies = source.dependencies;
target.mode = source.mode;
target.flags = source.flags;
target.nextEffect = source.nextEffect;
target.firstEffect = source.firstEffect;
target.lastEffect = source.lastEffect;
target.lanes = source.lanes;
target.childLanes = source.childLanes;
target.alternate = source.alternate;
{
target.actualDuration = source.actualDuration;
target.actualStartTime = source.actualStartTime;
target.selfBaseDuration = source.selfBaseDuration;
target.treeBaseDuration = source.treeBaseDuration;
}
target._debugID = source._debugID;
target._debugSource = source._debugSource;
target._debugOwner = source._debugOwner;
target._debugNeedsRemount = source._debugNeedsRemount;
target._debugHookTypes = source._debugHookTypes;
return target;
}
function FiberRootNode(containerInfo, tag, hydrate2) {
this.tag = tag;
this.containerInfo = containerInfo;
this.pendingChildren = null;
this.current = null;
this.pingCache = null;
this.finishedWork = null;
this.timeoutHandle = noTimeout;
this.context = null;
this.pendingContext = null;
this.hydrate = hydrate2;
this.callbackNode = null;
this.callbackPriority = NoLanePriority;
this.eventTimes = createLaneMap(NoLanes);
this.expirationTimes = createLaneMap(NoTimestamp);
this.pendingLanes = NoLanes;
this.suspendedLanes = NoLanes;
this.pingedLanes = NoLanes;
this.expiredLanes = NoLanes;
this.mutableReadLanes = NoLanes;
this.finishedLanes = NoLanes;
this.entangledLanes = NoLanes;
this.entanglements = createLaneMap(NoLanes);
{
this.mutableSourceEagerHydrationData = null;
}
{
this.interactionThreadID = tracing.unstable_getThreadID();
this.memoizedInteractions = new Set();
this.pendingInteractionMap = new Map();
}
{
switch (tag) {
case BlockingRoot:
this._debugRootType = "createBlockingRoot()";
break;
case ConcurrentRoot:
this._debugRootType = "createRoot()";
break;
case LegacyRoot:
this._debugRootType = "createLegacyRoot()";
break;
}
}
}
function createFiberRoot(containerInfo, tag, hydrate2, hydrationCallbacks) {
var root2 = new FiberRootNode(containerInfo, tag, hydrate2);
var uninitializedFiber = createHostRootFiber(tag);
root2.current = uninitializedFiber;
uninitializedFiber.stateNode = root2;
initializeUpdateQueue(uninitializedFiber);
return root2;
}
function registerMutableSourceForHydration(root2, mutableSource) {
var getVersion = mutableSource._getVersion;
var version = getVersion(mutableSource._source);
if (root2.mutableSourceEagerHydrationData == null) {
root2.mutableSourceEagerHydrationData = [mutableSource, version];
} else {
root2.mutableSourceEagerHydrationData.push(mutableSource, version);
}
}
function createPortal(children, containerInfo, implementation) {
var key = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : null;
return {
$$typeof: REACT_PORTAL_TYPE,
key: key == null ? null : "" + key,
children,
containerInfo,
implementation
};
}
var didWarnAboutNestedUpdates;
var didWarnAboutFindNodeInStrictMode;
{
didWarnAboutNestedUpdates = false;
didWarnAboutFindNodeInStrictMode = {};
}
function getContextForSubtree(parentComponent) {
if (!parentComponent) {
return emptyContextObject;
}
var fiber = get(parentComponent);
var parentContext = findCurrentUnmaskedContext(fiber);
if (fiber.tag === ClassComponent) {
var Component = fiber.type;
if (isContextProvider(Component)) {
return processChildContext(fiber, Component, parentContext);
}
}
return parentContext;
}
function findHostInstanceWithWarning(component, methodName) {
{
var fiber = get(component);
if (fiber === void 0) {
if (typeof component.render === "function") {
{
{
throw Error("Unable to find node on an unmounted component.");
}
}
} else {
{
{
throw Error("Argument appears to not be a ReactComponent. Keys: " + Object.keys(component));
}
}
}
}
var hostFiber = findCurrentHostFiber(fiber);
if (hostFiber === null) {
return null;
}
if (hostFiber.mode & StrictMode) {
var componentName = getComponentName(fiber.type) || "Component";
if (!didWarnAboutFindNodeInStrictMode[componentName]) {
didWarnAboutFindNodeInStrictMode[componentName] = true;
var previousFiber = current;
try {
setCurrentFiber(hostFiber);
if (fiber.mode & StrictMode) {
error("%s is deprecated in StrictMode. %s was passed an instance of %s which is inside StrictMode. Instead, add a ref directly to the element you want to reference. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-find-node", methodName, methodName, componentName);
} else {
error("%s is deprecated in StrictMode. %s was passed an instance of %s which renders StrictMode children. Instead, add a ref directly to the element you want to reference. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-find-node", methodName, methodName, componentName);
}
} finally {
if (previousFiber) {
setCurrentFiber(previousFiber);
} else {
resetCurrentFiber();
}
}
}
}
return hostFiber.stateNode;
}
}
function createContainer(containerInfo, tag, hydrate2, hydrationCallbacks) {
return createFiberRoot(containerInfo, tag, hydrate2);
}
function updateContainer(element, container, parentComponent, callback) {
{
onScheduleRoot(container, element);
}
var current$1 = container.current;
var eventTime = requestEventTime();
{
if (typeof jest !== "undefined") {
warnIfUnmockedScheduler(current$1);
warnIfNotScopedWithMatchingAct(current$1);
}
}
var lane = requestUpdateLane(current$1);
var context = getContextForSubtree(parentComponent);
if (container.context === null) {
container.context = context;
} else {
container.pendingContext = context;
}
{
if (isRendering && current !== null && !didWarnAboutNestedUpdates) {
didWarnAboutNestedUpdates = true;
error("Render methods should be a pure function of props and state; triggering nested component updates from render is not allowed. If necessary, trigger nested updates in componentDidUpdate.\n\nCheck the render method of %s.", getComponentName(current.type) || "Unknown");
}
}
var update = createUpdate(eventTime, lane);
update.payload = {
element
};
callback = callback === void 0 ? null : callback;
if (callback !== null) {
{
if (typeof callback !== "function") {
error("render(...): Expected the last optional `callback` argument to be a function. Instead received: %s.", callback);
}
}
update.callback = callback;
}
enqueueUpdate(current$1, update);
scheduleUpdateOnFiber(current$1, lane, eventTime);
return lane;
}
function getPublicRootInstance(container) {
var containerFiber = container.current;
if (!containerFiber.child) {
return null;
}
switch (containerFiber.child.tag) {
case HostComponent:
return getPublicInstance(containerFiber.child.stateNode);
default:
return containerFiber.child.stateNode;
}
}
function markRetryLaneImpl(fiber, retryLane) {
var suspenseState = fiber.memoizedState;
if (suspenseState !== null && suspenseState.dehydrated !== null) {
suspenseState.retryLane = higherPriorityLane(suspenseState.retryLane, retryLane);
}
}
function markRetryLaneIfNotHydrated(fiber, retryLane) {
markRetryLaneImpl(fiber, retryLane);
var alternate = fiber.alternate;
if (alternate) {
markRetryLaneImpl(alternate, retryLane);
}
}
function attemptUserBlockingHydration$1(fiber) {
if (fiber.tag !== SuspenseComponent) {
return;
}
var eventTime = requestEventTime();
var lane = InputDiscreteHydrationLane;
scheduleUpdateOnFiber(fiber, lane, eventTime);
markRetryLaneIfNotHydrated(fiber, lane);
}
function attemptContinuousHydration$1(fiber) {
if (fiber.tag !== SuspenseComponent) {
return;
}
var eventTime = requestEventTime();
var lane = SelectiveHydrationLane;
scheduleUpdateOnFiber(fiber, lane, eventTime);
markRetryLaneIfNotHydrated(fiber, lane);
}
function attemptHydrationAtCurrentPriority$1(fiber) {
if (fiber.tag !== SuspenseComponent) {
return;
}
var eventTime = requestEventTime();
var lane = requestUpdateLane(fiber);
scheduleUpdateOnFiber(fiber, lane, eventTime);
markRetryLaneIfNotHydrated(fiber, lane);
}
function runWithPriority$2(priority, fn) {
try {
setCurrentUpdateLanePriority(priority);
return fn();
} finally {
}
}
function findHostInstanceWithNoPortals(fiber) {
var hostFiber = findCurrentHostFiberWithNoPortals(fiber);
if (hostFiber === null) {
return null;
}
if (hostFiber.tag === FundamentalComponent) {
return hostFiber.stateNode.instance;
}
return hostFiber.stateNode;
}
var shouldSuspendImpl = function(fiber) {
return false;
};
function shouldSuspend(fiber) {
return shouldSuspendImpl(fiber);
}
var overrideHookState = null;
var overrideHookStateDeletePath = null;
var overrideHookStateRenamePath = null;
var overrideProps = null;
var overridePropsDeletePath = null;
var overridePropsRenamePath = null;
var scheduleUpdate = null;
var setSuspenseHandler = null;
{
var copyWithDeleteImpl = function(obj, path, index2) {
var key = path[index2];
var updated = Array.isArray(obj) ? obj.slice() : _assign({}, obj);
if (index2 + 1 === path.length) {
if (Array.isArray(updated)) {
updated.splice(key, 1);
} else {
delete updated[key];
}
return updated;
}
updated[key] = copyWithDeleteImpl(obj[key], path, index2 + 1);
return updated;
};
var copyWithDelete = function(obj, path) {
return copyWithDeleteImpl(obj, path, 0);
};
var copyWithRenameImpl = function(obj, oldPath, newPath, index2) {
var oldKey = oldPath[index2];
var updated = Array.isArray(obj) ? obj.slice() : _assign({}, obj);
if (index2 + 1 === oldPath.length) {
var newKey = newPath[index2];
updated[newKey] = updated[oldKey];
if (Array.isArray(updated)) {
updated.splice(oldKey, 1);
} else {
delete updated[oldKey];
}
} else {
updated[oldKey] = copyWithRenameImpl(obj[oldKey], oldPath, newPath, index2 + 1);
}
return updated;
};
var copyWithRename = function(obj, oldPath, newPath) {
if (oldPath.length !== newPath.length) {
warn("copyWithRename() expects paths of the same length");
return;
} else {
for (var i = 0; i < newPath.length - 1; i++) {
if (oldPath[i] !== newPath[i]) {
warn("copyWithRename() expects paths to be the same except for the deepest key");
return;
}
}
}
return copyWithRenameImpl(obj, oldPath, newPath, 0);
};
var copyWithSetImpl = function(obj, path, index2, value) {
if (index2 >= path.length) {
return value;
}
var key = path[index2];
var updated = Array.isArray(obj) ? obj.slice() : _assign({}, obj);
updated[key] = copyWithSetImpl(obj[key], path, index2 + 1, value);
return updated;
};
var copyWithSet = function(obj, path, value) {
return copyWithSetImpl(obj, path, 0, value);
};
var findHook = function(fiber, id) {
var currentHook2 = fiber.memoizedState;
while (currentHook2 !== null && id > 0) {
currentHook2 = currentHook2.next;
id--;
}
return currentHook2;
};
overrideHookState = function(fiber, id, path, value) {
var hook = findHook(fiber, id);
if (hook !== null) {
var newState = copyWithSet(hook.memoizedState, path, value);
hook.memoizedState = newState;
hook.baseState = newState;
fiber.memoizedProps = _assign({}, fiber.memoizedProps);
scheduleUpdateOnFiber(fiber, SyncLane, NoTimestamp);
}
};
overrideHookStateDeletePath = function(fiber, id, path) {
var hook = findHook(fiber, id);
if (hook !== null) {
var newState = copyWithDelete(hook.memoizedState, path);
hook.memoizedState = newState;
hook.baseState = newState;
fiber.memoizedProps = _assign({}, fiber.memoizedProps);
scheduleUpdateOnFiber(fiber, SyncLane, NoTimestamp);
}
};
overrideHookStateRenamePath = function(fiber, id, oldPath, newPath) {
var hook = findHook(fiber, id);
if (hook !== null) {
var newState = copyWithRename(hook.memoizedState, oldPath, newPath);
hook.memoizedState = newState;
hook.baseState = newState;
fiber.memoizedProps = _assign({}, fiber.memoizedProps);
scheduleUpdateOnFiber(fiber, SyncLane, NoTimestamp);
}
};
overrideProps = function(fiber, path, value) {
fiber.pendingProps = copyWithSet(fiber.memoizedProps, path, value);
if (fiber.alternate) {
fiber.alternate.pendingProps = fiber.pendingProps;
}
scheduleUpdateOnFiber(fiber, SyncLane, NoTimestamp);
};
overridePropsDeletePath = function(fiber, path) {
fiber.pendingProps = copyWithDelete(fiber.memoizedProps, path);
if (fiber.alternate) {
fiber.alternate.pendingProps = fiber.pendingProps;
}
scheduleUpdateOnFiber(fiber, SyncLane, NoTimestamp);
};
overridePropsRenamePath = function(fiber, oldPath, newPath) {
fiber.pendingProps = copyWithRename(fiber.memoizedProps, oldPath, newPath);
if (fiber.alternate) {
fiber.alternate.pendingProps = fiber.pendingProps;
}
scheduleUpdateOnFiber(fiber, SyncLane, NoTimestamp);
};
scheduleUpdate = function(fiber) {
scheduleUpdateOnFiber(fiber, SyncLane, NoTimestamp);
};
setSuspenseHandler = function(newShouldSuspendImpl) {
shouldSuspendImpl = newShouldSuspendImpl;
};
}
function findHostInstanceByFiber(fiber) {
var hostFiber = findCurrentHostFiber(fiber);
if (hostFiber === null) {
return null;
}
return hostFiber.stateNode;
}
function emptyFindFiberByHostInstance(instance) {
return null;
}
function getCurrentFiberForDevTools() {
return current;
}
function injectIntoDevTools(devToolsConfig) {
var findFiberByHostInstance = devToolsConfig.findFiberByHostInstance;
var ReactCurrentDispatcher2 = ReactSharedInternals.ReactCurrentDispatcher;
return injectInternals({
bundleType: devToolsConfig.bundleType,
version: devToolsConfig.version,
rendererPackageName: devToolsConfig.rendererPackageName,
rendererConfig: devToolsConfig.rendererConfig,
overrideHookState,
overrideHookStateDeletePath,
overrideHookStateRenamePath,
overrideProps,
overridePropsDeletePath,
overridePropsRenamePath,
setSuspenseHandler,
scheduleUpdate,
currentDispatcherRef: ReactCurrentDispatcher2,
findHostInstanceByFiber,
findFiberByHostInstance: findFiberByHostInstance || emptyFindFiberByHostInstance,
findHostInstancesForRefresh,
scheduleRefresh,
scheduleRoot,
setRefreshHandler,
getCurrentFiber: getCurrentFiberForDevTools
});
}
function ReactDOMRoot(container, options2) {
this._internalRoot = createRootImpl(container, ConcurrentRoot, options2);
}
function ReactDOMBlockingRoot(container, tag, options2) {
this._internalRoot = createRootImpl(container, tag, options2);
}
ReactDOMRoot.prototype.render = ReactDOMBlockingRoot.prototype.render = function(children) {
var root2 = this._internalRoot;
{
if (typeof arguments[1] === "function") {
error("render(...): does not support the second callback argument. To execute a side effect after rendering, declare it in a component body with useEffect().");
}
var container = root2.containerInfo;
if (container.nodeType !== COMMENT_NODE) {
var hostInstance = findHostInstanceWithNoPortals(root2.current);
if (hostInstance) {
if (hostInstance.parentNode !== container) {
error("render(...): It looks like the React-rendered content of the root container was removed without using React. This is not supported and will cause errors. Instead, call root.unmount() to empty a root's container.");
}
}
}
}
updateContainer(children, root2, null, null);
};
ReactDOMRoot.prototype.unmount = ReactDOMBlockingRoot.prototype.unmount = function() {
{
if (typeof arguments[0] === "function") {
error("unmount(...): does not support a callback argument. To execute a side effect after rendering, declare it in a component body with useEffect().");
}
}
var root2 = this._internalRoot;
var container = root2.containerInfo;
updateContainer(null, root2, null, function() {
unmarkContainerAsRoot(container);
});
};
function createRootImpl(container, tag, options2) {
var hydrate2 = options2 != null && options2.hydrate === true;
var hydrationCallbacks = options2 != null && options2.hydrationOptions || null;
var mutableSources = options2 != null && options2.hydrationOptions != null && options2.hydrationOptions.mutableSources || null;
var root2 = createContainer(container, tag, hydrate2);
markContainerAsRoot(root2.current, container);
var containerNodeType = container.nodeType;
{
var rootContainerElement = container.nodeType === COMMENT_NODE ? container.parentNode : container;
listenToAllSupportedEvents(rootContainerElement);
}
if (mutableSources) {
for (var i = 0; i < mutableSources.length; i++) {
var mutableSource = mutableSources[i];
registerMutableSourceForHydration(root2, mutableSource);
}
}
return root2;
}
function createLegacyRoot(container, options2) {
return new ReactDOMBlockingRoot(container, LegacyRoot, options2);
}
function isValidContainer(node) {
return !!(node && (node.nodeType === ELEMENT_NODE || node.nodeType === DOCUMENT_NODE || node.nodeType === DOCUMENT_FRAGMENT_NODE || node.nodeType === COMMENT_NODE && node.nodeValue === " react-mount-point-unstable "));
}
var ReactCurrentOwner$3 = ReactSharedInternals.ReactCurrentOwner;
var topLevelUpdateWarnings;
var warnedAboutHydrateAPI = false;
{
topLevelUpdateWarnings = function(container) {
if (container._reactRootContainer && container.nodeType !== COMMENT_NODE) {
var hostInstance = findHostInstanceWithNoPortals(container._reactRootContainer._internalRoot.current);
if (hostInstance) {
if (hostInstance.parentNode !== container) {
error("render(...): It looks like the React-rendered content of this container was removed without using React. This is not supported and will cause errors. Instead, call ReactDOM.unmountComponentAtNode to empty a container.");
}
}
}
var isRootRenderedBySomeReact = !!container._reactRootContainer;
var rootEl = getReactRootElementInContainer(container);
var hasNonRootReactChild = !!(rootEl && getInstanceFromNode(rootEl));
if (hasNonRootReactChild && !isRootRenderedBySomeReact) {
error("render(...): Replacing React-rendered children with a new root component. If you intended to update the children of this node, you should instead have the existing children update their state and render the new components instead of calling ReactDOM.render.");
}
if (container.nodeType === ELEMENT_NODE && container.tagName && container.tagName.toUpperCase() === "BODY") {
error("render(): Rendering components directly into document.body is discouraged, since its children are often manipulated by third-party scripts and browser extensions. This may lead to subtle reconciliation issues. Try rendering into a container element created for your app.");
}
};
}
function getReactRootElementInContainer(container) {
if (!container) {
return null;
}
if (container.nodeType === DOCUMENT_NODE) {
return container.documentElement;
} else {
return container.firstChild;
}
}
function shouldHydrateDueToLegacyHeuristic(container) {
var rootElement = getReactRootElementInContainer(container);
return !!(rootElement && rootElement.nodeType === ELEMENT_NODE && rootElement.hasAttribute(ROOT_ATTRIBUTE_NAME));
}
function legacyCreateRootFromDOMContainer(container, forceHydrate) {
var shouldHydrate = forceHydrate || shouldHydrateDueToLegacyHeuristic(container);
if (!shouldHydrate) {
var warned = false;
var rootSibling;
while (rootSibling = container.lastChild) {
{
if (!warned && rootSibling.nodeType === ELEMENT_NODE && rootSibling.hasAttribute(ROOT_ATTRIBUTE_NAME)) {
warned = true;
error("render(): Target node has markup rendered by React, but there are unrelated nodes as well. This is most commonly caused by white-space inserted around server-rendered markup.");
}
}
container.removeChild(rootSibling);
}
}
{
if (shouldHydrate && !forceHydrate && !warnedAboutHydrateAPI) {
warnedAboutHydrateAPI = true;
warn("render(): Calling ReactDOM.render() to hydrate server-rendered markup will stop working in React v18. Replace the ReactDOM.render() call with ReactDOM.hydrate() if you want React to attach to the server HTML.");
}
}
return createLegacyRoot(container, shouldHydrate ? {
hydrate: true
} : void 0);
}
function warnOnInvalidCallback$1(callback, callerName) {
{
if (callback !== null && typeof callback !== "function") {
error("%s(...): Expected the last optional `callback` argument to be a function. Instead received: %s.", callerName, callback);
}
}
}
function legacyRenderSubtreeIntoContainer(parentComponent, children, container, forceHydrate, callback) {
{
topLevelUpdateWarnings(container);
warnOnInvalidCallback$1(callback === void 0 ? null : callback, "render");
}
var root2 = container._reactRootContainer;
var fiberRoot;
if (!root2) {
root2 = container._reactRootContainer = legacyCreateRootFromDOMContainer(container, forceHydrate);
fiberRoot = root2._internalRoot;
if (typeof callback === "function") {
var originalCallback = callback;
callback = function() {
var instance = getPublicRootInstance(fiberRoot);
originalCallback.call(instance);
};
}
unbatchedUpdates(function() {
updateContainer(children, fiberRoot, parentComponent, callback);
});
} else {
fiberRoot = root2._internalRoot;
if (typeof callback === "function") {
var _originalCallback = callback;
callback = function() {
var instance = getPublicRootInstance(fiberRoot);
_originalCallback.call(instance);
};
}
updateContainer(children, fiberRoot, parentComponent, callback);
}
return getPublicRootInstance(fiberRoot);
}
function findDOMNode(componentOrElement) {
{
var owner = ReactCurrentOwner$3.current;
if (owner !== null && owner.stateNode !== null) {
var warnedAboutRefsInRender = owner.stateNode._warnedAboutRefsInRender;
if (!warnedAboutRefsInRender) {
error("%s is accessing findDOMNode inside its render(). render() should be a pure function of props and state. It should never access something that requires stale data from the previous render, such as refs. Move this logic to componentDidMount and componentDidUpdate instead.", getComponentName(owner.type) || "A component");
}
owner.stateNode._warnedAboutRefsInRender = true;
}
}
if (componentOrElement == null) {
return null;
}
if (componentOrElement.nodeType === ELEMENT_NODE) {
return componentOrElement;
}
{
return findHostInstanceWithWarning(componentOrElement, "findDOMNode");
}
}
function hydrate(element, container, callback) {
if (!isValidContainer(container)) {
{
throw Error("Target container is not a DOM element.");
}
}
{
var isModernRoot = isContainerMarkedAsRoot(container) && container._reactRootContainer === void 0;
if (isModernRoot) {
error("You are calling ReactDOM.hydrate() on a container that was previously passed to ReactDOM.createRoot(). This is not supported. Did you mean to call createRoot(container, {hydrate: true}).render(element)?");
}
}
return legacyRenderSubtreeIntoContainer(null, element, container, true, callback);
}
function render(element, container, callback) {
if (!isValidContainer(container)) {
{
throw Error("Target container is not a DOM element.");
}
}
{
var isModernRoot = isContainerMarkedAsRoot(container) && container._reactRootContainer === void 0;
if (isModernRoot) {
error("You are calling ReactDOM.render() on a container that was previously passed to ReactDOM.createRoot(). This is not supported. Did you mean to call root.render(element)?");
}
}
return legacyRenderSubtreeIntoContainer(null, element, container, false, callback);
}
function unstable_renderSubtreeIntoContainer(parentComponent, element, containerNode, callback) {
if (!isValidContainer(containerNode)) {
{
throw Error("Target container is not a DOM element.");
}
}
if (!(parentComponent != null && has(parentComponent))) {
{
throw Error("parentComponent must be a valid React Component");
}
}
return legacyRenderSubtreeIntoContainer(parentComponent, element, containerNode, false, callback);
}
function unmountComponentAtNode(container) {
if (!isValidContainer(container)) {
{
throw Error("unmountComponentAtNode(...): Target container is not a DOM element.");
}
}
{
var isModernRoot = isContainerMarkedAsRoot(container) && container._reactRootContainer === void 0;
if (isModernRoot) {
error("You are calling ReactDOM.unmountComponentAtNode() on a container that was previously passed to ReactDOM.createRoot(). This is not supported. Did you mean to call root.unmount()?");
}
}
if (container._reactRootContainer) {
{
var rootEl = getReactRootElementInContainer(container);
var renderedByDifferentReact = rootEl && !getInstanceFromNode(rootEl);
if (renderedByDifferentReact) {
error("unmountComponentAtNode(): The node you're attempting to unmount was rendered by another copy of React.");
}
}
unbatchedUpdates(function() {
legacyRenderSubtreeIntoContainer(null, null, container, false, function() {
container._reactRootContainer = null;
unmarkContainerAsRoot(container);
});
});
return true;
} else {
{
var _rootEl = getReactRootElementInContainer(container);
var hasNonRootReactChild = !!(_rootEl && getInstanceFromNode(_rootEl));
var isContainerReactRoot = container.nodeType === ELEMENT_NODE && isValidContainer(container.parentNode) && !!container.parentNode._reactRootContainer;
if (hasNonRootReactChild) {
error("unmountComponentAtNode(): The node you're attempting to unmount was rendered by React and is not a top-level container. %s", isContainerReactRoot ? "You may have accidentally passed in a React root node instead of its container." : "Instead, have the parent component update its state and rerender in order to remove this component.");
}
}
return false;
}
}
setAttemptUserBlockingHydration(attemptUserBlockingHydration$1);
setAttemptContinuousHydration(attemptContinuousHydration$1);
setAttemptHydrationAtCurrentPriority(attemptHydrationAtCurrentPriority$1);
setAttemptHydrationAtPriority(runWithPriority$2);
var didWarnAboutUnstableCreatePortal = false;
{
if (typeof Map !== "function" || Map.prototype == null || typeof Map.prototype.forEach !== "function" || typeof Set !== "function" || Set.prototype == null || typeof Set.prototype.clear !== "function" || typeof Set.prototype.forEach !== "function") {
error("React depends on Map and Set built-in types. Make sure that you load a polyfill in older browsers. https://reactjs.org/link/react-polyfills");
}
}
setRestoreImplementation(restoreControlledState$3);
setBatchingImplementation(batchedUpdates$1, discreteUpdates$1, flushDiscreteUpdates, batchedEventUpdates$1);
function createPortal$1(children, container) {
var key = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : null;
if (!isValidContainer(container)) {
{
throw Error("Target container is not a DOM element.");
}
}
return createPortal(children, container, null, key);
}
function renderSubtreeIntoContainer(parentComponent, element, containerNode, callback) {
return unstable_renderSubtreeIntoContainer(parentComponent, element, containerNode, callback);
}
function unstable_createPortal(children, container) {
var key = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : null;
{
if (!didWarnAboutUnstableCreatePortal) {
didWarnAboutUnstableCreatePortal = true;
warn('The ReactDOM.unstable_createPortal() alias has been deprecated, and will be removed in React 18+. Update your code to use ReactDOM.createPortal() instead. It has the exact same API, but without the "unstable_" prefix.');
}
}
return createPortal$1(children, container, key);
}
var Internals = {
Events: [
getInstanceFromNode,
getNodeFromInstance,
getFiberCurrentPropsFromNode,
enqueueStateRestore,
restoreStateIfNeeded,
flushPassiveEffects,
IsThisRendererActing
]
};
var foundDevTools = injectIntoDevTools({
findFiberByHostInstance: getClosestInstanceFromNode,
bundleType: 1,
version: ReactVersion,
rendererPackageName: "react-dom"
});
{
if (!foundDevTools && canUseDOM && window.top === window.self) {
if (navigator.userAgent.indexOf("Chrome") > -1 && navigator.userAgent.indexOf("Edge") === -1 || navigator.userAgent.indexOf("Firefox") > -1) {
var protocol = window.location.protocol;
if (/^(https?|file):$/.test(protocol)) {
console.info("%cDownload the React DevTools for a better development experience: https://reactjs.org/link/react-devtools" + (protocol === "file:" ? "\nYou might need to use a local HTTP server (instead of file://): https://reactjs.org/link/react-devtools-faq" : ""), "font-weight:bold");
}
}
}
}
exports2.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = Internals;
exports2.createPortal = createPortal$1;
exports2.findDOMNode = findDOMNode;
exports2.flushSync = flushSync;
exports2.hydrate = hydrate;
exports2.render = render;
exports2.unmountComponentAtNode = unmountComponentAtNode;
exports2.unstable_batchedUpdates = batchedUpdates$1;
exports2.unstable_createPortal = unstable_createPortal;
exports2.unstable_renderSubtreeIntoContainer = renderSubtreeIntoContainer;
exports2.version = ReactVersion;
})();
}
}
});
// node_modules/react-dom/index.js
var require_react_dom = __commonJS({
"node_modules/react-dom/index.js"(exports2, module2) {
"use strict";
if (false) {
checkDCE();
module2.exports = null;
} else {
module2.exports = require_react_dom_development();
}
}
});
// src/index.tsx
var import_react2 = __toModule(require_react());
var import_react_dom = __toModule(require_react_dom());
// src/App.tsx
var import_react = __toModule(require_react());
function App() {
return /* @__PURE__ */ import_react.default.createElement("div", null, "Hello World!");
}
// src/index.tsx
import_react_dom.default.render(/* @__PURE__ */ import_react2.default.createElement(App, null), document.getElementById("root"));
/*
object-assign
(c) Sindre Sorhus
@license MIT
*/
/**
* Checks if an event is supported in the current execution environment.
*
* NOTE: This will not work correctly for non-generic events such as `change`,
* `reset`, `load`, `error`, and `select`.
*
* Borrows from Modernizr.
*
* @param {string} eventNameSuffix Event name, e.g. "click".
* @return {boolean} True if the event is supported.
* @internal
* @license Modernizr 3.0.0pre (Custom Build) | MIT
*/
/** @license React v0.20.2
* scheduler-tracing.development.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/** @license React v0.20.2
* scheduler.development.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/** @license React v17.0.2
* react-dom.development.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/** @license React v17.0.2
* react.development.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
//# sourceMappingURL=index.js.map
| {
"content_hash": "df9ae021bbbea59f2d569629b776597f",
"timestamp": "",
"source": "github",
"line_count": 20486,
"max_line_length": 807,
"avg_line_length": 42.55369520648247,
"alnum_prop": 0.5476561648628342,
"repo_name": "yuanliang/pharos",
"id": "1d19fd91b9909fda9486e5c3ce47c53bb06c5d0a",
"size": "871755",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/public/index.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "28772"
},
{
"name": "HTML",
"bytes": "15361"
},
{
"name": "JavaScript",
"bytes": "5094"
}
],
"symlink_target": ""
} |
#import <CoreSimulator/SimDeviceIO.h>
#import <CoreSimulator/SimDeviceIOInterface-Protocol.h>
@class NSArray, NSDictionary;
@interface SimDeviceIOServer : SimDeviceIO <SimDeviceIOInterface>
{
NSDictionary *_loadedBundles;
NSArray *_ioPorts;
NSArray *_ioPortProxies;
}
@property (nonatomic, copy) NSArray *ioPortProxies;
@property (nonatomic, copy) NSArray *ioPorts;
@property (nonatomic, copy) NSDictionary *loadedBundles;
- (BOOL)unregisterService:(id)arg1 error:(id *)arg2;
- (BOOL)registerPort:(unsigned int)arg1 service:(id)arg2 error:(id *)arg3;
- (id)tvOutDisplayDescriptorState;
- (id)mainDisplayDescriptorState;
- (id)integratedDisplayDescriptorState;
- (BOOL)unloadAllBundles;
- (BOOL)loadAllBundles;
@end
| {
"content_hash": "98b57a9493dbc03f3003a4ad15b48362",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 74,
"avg_line_length": 26.25,
"alnum_prop": 0.7700680272108843,
"repo_name": "plu/FBSimulatorControl",
"id": "30c109e16380faed8c6d2f2dd8f794601b144ae9",
"size": "1043",
"binary": false,
"copies": "3",
"ref": "refs/heads/pxctest",
"path": "PrivateHeaders/CoreSimulator/SimDeviceIOServer.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "1043"
},
{
"name": "Objective-C",
"bytes": "2180393"
},
{
"name": "Python",
"bytes": "27477"
},
{
"name": "Shell",
"bytes": "9821"
},
{
"name": "Swift",
"bytes": "221667"
}
],
"symlink_target": ""
} |
//
// Symbol tracker/synchronizer
//
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#define DEBUG_SYMTRACK 0
#define DEBUG_SYMTRACK_PRINT 0
#define DEBUG_SYMTRACK_FILENAME "symtrack_internal_debug.m"
#define DEBUG_BUFFER_LEN (1024)
//
// forward declaration of internal methods
//
// internal structure
struct SYMTRACK(_s) {
// parameters
int filter_type; // filter type (e.g. LIQUID_FIRFILT_RRC)
unsigned int k; // samples/symbol
unsigned int m; // filter semi-length
float beta; // filter excess bandwidth
int mod_scheme; // demodulator
// automatic gain control
AGC() agc; // agc object
float agc_bandwidth; // agc bandwidth
// symbol timing recovery
SYMSYNC() symsync; // symbol timing recovery object
float symsync_bandwidth; // symsync loop bandwidth
TO symsync_buf[8]; // symsync output buffer
unsigned int symsync_index; // symsync output sample index
// equalizer/decimator
EQLMS() eq; // equalizer (LMS)
unsigned int eq_len; // equalizer length
float eq_bandwidth; // equalizer bandwidth
enum {
SYMTRACK_EQ_CM, // equalizer strategy: constant modulus
SYMTRACK_EQ_DD, // equalizer strategy: decision directed
SYMTRACK_EQ_OFF, // equalizer strategy: disabled
} eq_strategy;
// nco/phase-locked loop
NCO() nco; // nco (carrier recovery)
float pll_bandwidth; // phase-locked loop bandwidth
// demodulator
MODEM() demod; // linear modem demodulator
// state and counters
unsigned int num_syms_rx; // number of symbols recovered
};
// create symtrack object with basic parameters
// _ftype : filter type (e.g. LIQUID_FIRFILT_RRC)
// _k : samples per symbol
// _m : filter delay (symbols)
// _beta : filter excess bandwidth
// _ms : modulation scheme (e.g. LIQUID_MODEM_QPSK)
SYMTRACK() SYMTRACK(_create)(int _ftype,
unsigned int _k,
unsigned int _m,
float _beta,
int _ms)
{
// validate input
if (_k < 2)
return liquid_error_config("symtrack_%s_create(), filter samples/symbol must be at least 2", EXTENSION_FULL);
if (_m == 0)
return liquid_error_config("symtrack_%s_create(), filter delay must be greater than zero", EXTENSION_FULL);
if (_beta <= 0.0f || _beta > 1.0f)
return liquid_error_config("symtrack_%s_create(), filter excess bandwidth must be in (0,1]", EXTENSION_FULL);
if (_ms == LIQUID_MODEM_UNKNOWN || _ms >= LIQUID_MODEM_NUM_SCHEMES)
return liquid_error_config("symtrack_%s_create(), invalid modulation scheme", EXTENSION_FULL);
// allocate memory for main object
SYMTRACK() q = (SYMTRACK()) malloc( sizeof(struct SYMTRACK(_s)) );
// set input parameters
q->filter_type = _ftype;
q->k = _k;
q->m = _m;
q->beta = _beta;
q->mod_scheme = _ms == LIQUID_MODEM_UNKNOWN ? LIQUID_MODEM_BPSK : _ms;
// create automatic gain control
q->agc = AGC(_create)();
// create symbol synchronizer (output rate: 2 samples per symbol)
if (q->filter_type == LIQUID_FIRFILT_UNKNOWN)
q->symsync = SYMSYNC(_create_kaiser)(q->k, q->m, 0.9f, 16);
else
q->symsync = SYMSYNC(_create_rnyquist)(q->filter_type, q->k, q->m, q->beta, 16);
SYMSYNC(_set_output_rate)(q->symsync, 2);
// create equalizer as default low-pass filter with integer symbol delay (2 samples/symbol)
q->eq_len = 2 * 4 + 1;
q->eq = EQLMS(_create_lowpass)(q->eq_len,0.45f);
q->eq_strategy = SYMTRACK_EQ_CM;
// nco and phase-locked loop
q->nco = NCO(_create)(LIQUID_VCO);
// demodulator
q->demod = MODEM(_create)(q->mod_scheme);
// set default bandwidth
SYMTRACK(_set_bandwidth)(q, 0.9f);
// reset and return main object
SYMTRACK(_reset)(q);
return q;
}
// create symtrack object using default parameters
SYMTRACK() SYMTRACK(_create_default)()
{
return SYMTRACK(_create)(LIQUID_FIRFILT_ARKAISER,
2, // samples/symbol
7, // filter delay
0.3f, // filter excess bandwidth
LIQUID_MODEM_QPSK);
}
// destroy symtrack object, freeing all internal memory
int SYMTRACK(_destroy)(SYMTRACK() _q)
{
// destroy objects
AGC (_destroy)(_q->agc);
SYMSYNC(_destroy)(_q->symsync);
EQLMS (_destroy)(_q->eq);
NCO (_destroy)(_q->nco);
MODEM (_destroy)(_q->demod);
// free main object
free(_q);
return LIQUID_OK;
}
// print symtrack object's parameters
int SYMTRACK(_print)(SYMTRACK() _q)
{
printf("symtrack_%s:\n", EXTENSION_FULL);
printf(" k:%u, m:%u, beta:%.3f, ms:%s\n", _q->k, _q->m, _q->beta,
modulation_types[_q->mod_scheme].name);
printf(" equalization strategy: ");
switch (_q->eq_strategy) {
case SYMTRACK_EQ_CM: printf("constant modulus\n"); break;
case SYMTRACK_EQ_DD: printf("decision directed\n"); break;
case SYMTRACK_EQ_OFF: printf("disabled\n"); break;
default:
printf("?\n");
return liquid_error(LIQUID_EINT,"symtrack_%s_print(), invalid equalization strategy");
}
return LIQUID_OK;
}
// reset symtrack internal state
int SYMTRACK(_reset)(SYMTRACK() _q)
{
// reset objects
AGC (_reset)(_q->agc);
SYMSYNC(_reset)(_q->symsync);
EQLMS (_reset)(_q->eq);
NCO (_reset)(_q->nco);
MODEM (_reset)(_q->demod);
// reset internal counters
_q->symsync_index = 0;
_q->num_syms_rx = 0;
return LIQUID_OK;
}
// set symtrack modulation scheme
int SYMTRACK(_set_modscheme)(SYMTRACK() _q,
int _ms)
{
// validate input
if (_ms >= LIQUID_MODEM_NUM_SCHEMES)
return liquid_error(LIQUID_EICONFIG,"symtrack_%s_set_modscheme(), invalid/unsupported modulation scheme", EXTENSION_FULL);
// set internal modulation scheme
_q->mod_scheme = _ms == LIQUID_MODEM_UNKNOWN ? LIQUID_MODEM_BPSK : _ms;
// re-create modem
_q->demod = MODEM(_recreate)(_q->demod, _q->mod_scheme);
return LIQUID_OK;
}
// set symtrack internal bandwidth
int SYMTRACK(_set_bandwidth)(SYMTRACK() _q,
float _bw)
{
// validate input
if (_bw < 0)
return liquid_error(LIQUID_EICONFIG,"symtrack_%s_set_bandwidth(), bandwidth must be in [0,1]", EXTENSION_FULL);
// set bandwidths accordingly
float agc_bandwidth = 0.02f * _bw;
float symsync_bandwidth = 0.001f * _bw;
float eq_bandwidth = 0.02f * _bw;
float pll_bandwidth = 0.001f * _bw;
// automatic gain control
AGC(_set_bandwidth)(_q->agc, agc_bandwidth);
// symbol timing recovery
SYMSYNC(_set_lf_bw)(_q->symsync, symsync_bandwidth);
// equalizer
EQLMS(_set_bw)(_q->eq, eq_bandwidth);
// phase-locked loop
NCO(_pll_set_bandwidth)(_q->nco, pll_bandwidth);
return LIQUID_OK;
}
// adjust internal nco by requested phase
int SYMTRACK(_adjust_phase)(SYMTRACK() _q,
T _dphi)
{
// adjust internal nco phase
NCO(_adjust_phase)(_q->nco, _dphi);
return LIQUID_OK;
}
// set equalization strategy to constant modulus (default)
int SYMTRACK(_set_eq_cm)(SYMTRACK() _q)
{
_q->eq_strategy = SYMTRACK_EQ_CM;
return LIQUID_OK;
}
// set equalization strategy to decision directed
int SYMTRACK(_set_eq_dd)(SYMTRACK() _q)
{
_q->eq_strategy = SYMTRACK_EQ_DD;
return LIQUID_OK;
}
// disable equalization
int SYMTRACK(_set_eq_off)(SYMTRACK() _q)
{
_q->eq_strategy = SYMTRACK_EQ_OFF;
return LIQUID_OK;
}
// execute synchronizer on single input sample
// _q : synchronizer object
// _x : input data sample
// _y : output data array
// _ny : number of samples written to output buffer
int SYMTRACK(_execute)(SYMTRACK() _q,
TI _x,
TO * _y,
unsigned int * _ny)
{
TO v; // output sample
unsigned int i;
unsigned int num_outputs = 0;
// run sample through automatic gain control
AGC(_execute)(_q->agc, _x, &v);
// symbol synchronizer
unsigned int nw = 0;
SYMSYNC(_execute)(_q->symsync, &v, 1, _q->symsync_buf, &nw);
// process each output sample
for (i=0; i<nw; i++) {
// update phase-locked loop
NCO(_step)(_q->nco);
nco_crcf_mix_down(_q->nco, _q->symsync_buf[i], &v);
// equalizer/decimator
EQLMS(_push)(_q->eq, v);
// decimate result, noting that symsync outputs at exactly 2 samples/symbol
_q->symsync_index++;
if ( !(_q->symsync_index % 2) )
continue;
// increment number of symbols received
_q->num_syms_rx++;
// compute equalizer filter output; updating coefficients is dependent upon strategy
TO d_hat;
EQLMS(_execute)(_q->eq, &d_hat);
// demodulate result, apply phase correction
unsigned int sym_out;
MODEM(_demodulate)(_q->demod, d_hat, &sym_out);
float phase_error = MODEM(_get_demodulator_phase_error)(_q->demod);
// update pll
NCO(_pll_step)(_q->nco, phase_error);
// update equalizer independent of the signal: estimate error
// assuming constant modulus signal
// TODO: check lock conditions of previous object to determine when to run equalizer
float complex d_prime = 0.0f;
if (_q->num_syms_rx > 200 && _q->eq_strategy != SYMTRACK_EQ_OFF) {
switch (_q->eq_strategy) {
case SYMTRACK_EQ_CM: d_prime = d_hat/cabsf(d_hat); break;
case SYMTRACK_EQ_DD: MODEM(_get_demodulator_sample)(_q->demod, &d_prime); break;
default:
return liquid_error(LIQUID_EINT,"symtrack_%s_execute(), invalid equalizer strategy", EXTENSION_FULL);
}
EQLMS(_step)(_q->eq, d_prime, d_hat);
}
// save result to output
_y[num_outputs++] = d_hat;
}
#if DEBUG_SYMTRACK
printf("symsync wrote %u samples, %u outputs\n", nw, num_outputs);
#endif
//
*_ny = num_outputs;
return LIQUID_OK;
}
// execute synchronizer on input data array
// _q : synchronizer object
// _x : input data array
// _nx : number of input samples
// _y : output data array
// _ny : number of samples written to output buffer
int SYMTRACK(_execute_block)(SYMTRACK() _q,
TI * _x,
unsigned int _nx,
TO * _y,
unsigned int * _ny)
{
//
unsigned int i;
unsigned int num_written = 0;
//
for (i=0; i<_nx; i++) {
unsigned int nw = 0;
SYMTRACK(_execute)(_q, _x[i], &_y[num_written], &nw);
num_written += nw;
}
//
*_ny = num_written;
return LIQUID_OK;
}
| {
"content_hash": "baba8b36f45f39333aee0d58e834ed52",
"timestamp": "",
"source": "github",
"line_count": 361,
"max_line_length": 130,
"avg_line_length": 31.84764542936288,
"alnum_prop": 0.5612768548316952,
"repo_name": "wangning223/liquid-dsp",
"id": "90c90d5037e4cc1d566dd5ad27e46f475340893d",
"size": "12623",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/framing/src/symtrack.c",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "181"
},
{
"name": "C",
"bytes": "4763924"
},
{
"name": "C++",
"bytes": "313046"
},
{
"name": "Matlab",
"bytes": "29973"
},
{
"name": "Python",
"bytes": "5102"
},
{
"name": "Shell",
"bytes": "14537"
}
],
"symlink_target": ""
} |
import os
import socket
import uuid
import eventlet
import netaddr
from oslo.config import cfg
from quantum.agent.common import config
from quantum.agent.linux import dhcp
from quantum.agent.linux import external_process
from quantum.agent.linux import interface
from quantum.agent.linux import ip_lib
from quantum.agent import rpc as agent_rpc
from quantum.common import constants
from quantum.common import exceptions
from quantum.common import topics
from quantum import context
from quantum import manager
from quantum.openstack.common import importutils
from quantum.openstack.common import jsonutils
from quantum.openstack.common import log as logging
from quantum.openstack.common import lockutils
from quantum.openstack.common import loopingcall
from quantum.openstack.common.rpc import proxy
from quantum.openstack.common import service
from quantum.openstack.common import uuidutils
from quantum import service as quantum_service
LOG = logging.getLogger(__name__)
NS_PREFIX = 'qdhcp-'
METADATA_DEFAULT_PREFIX = 16
METADATA_DEFAULT_IP = '169.254.169.254/%d' % METADATA_DEFAULT_PREFIX
METADATA_PORT = 80
class DhcpAgent(manager.Manager):
OPTS = [
cfg.IntOpt('resync_interval', default=5,
help=_("Interval to resync.")),
cfg.StrOpt('dhcp_driver',
default='quantum.agent.linux.dhcp.Dnsmasq',
help=_("The driver used to manage the DHCP server.")),
cfg.BoolOpt('use_namespaces', default=True,
help=_("Allow overlapping IP.")),
cfg.BoolOpt('enable_isolated_metadata', default=False,
help=_("Support Metadata requests on isolated networks.")),
cfg.BoolOpt('enable_metadata_network', default=False,
help=_("Allows for serving metadata requests from a "
"dedicate network. Requires "
"enable isolated_metadata = True ")),
]
def __init__(self, host=None):
super(DhcpAgent, self).__init__(host=host)
self.needs_resync = False
self.conf = cfg.CONF
self.cache = NetworkCache()
self.root_helper = config.get_root_helper(self.conf)
self.dhcp_driver_cls = importutils.import_class(self.conf.dhcp_driver)
ctx = context.get_admin_context_without_session()
self.plugin_rpc = DhcpPluginApi(topics.PLUGIN, ctx)
self.device_manager = DeviceManager(self.conf, self.plugin_rpc)
self.lease_relay = DhcpLeaseRelay(self.update_lease)
self._populate_networks_cache()
def _populate_networks_cache(self):
"""Populate the networks cache when the DHCP-agent starts"""
try:
existing_networks = self.dhcp_driver_cls.existing_dhcp_networks(
self.conf,
self.root_helper
)
for net_id in existing_networks:
net = DictModel({"id": net_id, "subnets": [], "ports": []})
self.cache.put(net)
except NotImplementedError:
# just go ahead with an empty networks cache
LOG.debug(
_("The '%s' DHCP-driver does not support retrieving of a "
"list of existing networks"),
self.conf.dhcp_driver
)
def after_start(self):
self.run()
LOG.info(_("DHCP agent started"))
def run(self):
"""Activate the DHCP agent."""
self.sync_state()
self.periodic_resync()
self.lease_relay.start()
def _ns_name(self, network):
if self.conf.use_namespaces:
return NS_PREFIX + network.id
def call_driver(self, action, network):
"""Invoke an action on a DHCP driver instance."""
try:
# the Driver expects something that is duck typed similar to
# the base models.
driver = self.dhcp_driver_cls(self.conf,
network,
self.root_helper,
self.device_manager,
self._ns_name(network))
getattr(driver, action)()
return True
except Exception:
self.needs_resync = True
LOG.exception(_('Unable to %s dhcp.'), action)
def update_lease(self, network_id, ip_address, time_remaining):
try:
self.plugin_rpc.update_lease_expiration(network_id, ip_address,
time_remaining)
except:
self.needs_resync = True
LOG.exception(_('Unable to update lease'))
def sync_state(self):
"""Sync the local DHCP state with Quantum."""
LOG.info(_('Synchronizing state'))
known_networks = set(self.cache.get_network_ids())
try:
active_networks = set(self.plugin_rpc.get_active_networks())
for deleted_id in known_networks - active_networks:
self.disable_dhcp_helper(deleted_id)
for network_id in active_networks:
self.refresh_dhcp_helper(network_id)
except:
self.needs_resync = True
LOG.exception(_('Unable to sync network state.'))
def _periodic_resync_helper(self):
"""Resync the dhcp state at the configured interval."""
while True:
eventlet.sleep(self.conf.resync_interval)
if self.needs_resync:
self.needs_resync = False
self.sync_state()
def periodic_resync(self):
"""Spawn a thread to periodically resync the dhcp state."""
eventlet.spawn(self._periodic_resync_helper)
def enable_dhcp_helper(self, network_id):
"""Enable DHCP for a network that meets enabling criteria."""
try:
network = self.plugin_rpc.get_network_info(network_id)
except:
self.needs_resync = True
LOG.exception(_('Network %s RPC info call failed.'), network_id)
return
if not network.admin_state_up:
return
for subnet in network.subnets:
if subnet.enable_dhcp:
if self.call_driver('enable', network):
if self.conf.use_namespaces:
self.enable_isolated_metadata_proxy(network)
self.cache.put(network)
break
def disable_dhcp_helper(self, network_id):
"""Disable DHCP for a network known to the agent."""
network = self.cache.get_network_by_id(network_id)
if network:
if self.conf.use_namespaces:
self.disable_isolated_metadata_proxy(network)
if self.call_driver('disable', network):
self.cache.remove(network)
def refresh_dhcp_helper(self, network_id):
"""Refresh or disable DHCP for a network depending on the current state
of the network.
"""
old_network = self.cache.get_network_by_id(network_id)
if not old_network:
# DHCP current not running for network.
return self.enable_dhcp_helper(network_id)
try:
network = self.plugin_rpc.get_network_info(network_id)
except:
self.needs_resync = True
LOG.exception(_('Network %s RPC info call failed.'), network_id)
return
old_cidrs = set(s.cidr for s in old_network.subnets if s.enable_dhcp)
new_cidrs = set(s.cidr for s in network.subnets if s.enable_dhcp)
if new_cidrs and old_cidrs == new_cidrs:
self.call_driver('reload_allocations', network)
self.cache.put(network)
elif new_cidrs:
if self.call_driver('restart', network):
self.cache.put(network)
else:
self.disable_dhcp_helper(network.id)
@lockutils.synchronized('agent', 'dhcp-')
def network_create_end(self, context, payload):
"""Handle the network.create.end notification event."""
network_id = payload['network']['id']
self.enable_dhcp_helper(network_id)
@lockutils.synchronized('agent', 'dhcp-')
def network_update_end(self, context, payload):
"""Handle the network.update.end notification event."""
network_id = payload['network']['id']
if payload['network']['admin_state_up']:
self.enable_dhcp_helper(network_id)
else:
self.disable_dhcp_helper(network_id)
@lockutils.synchronized('agent', 'dhcp-')
def network_delete_end(self, context, payload):
"""Handle the network.delete.end notification event."""
self.disable_dhcp_helper(payload['network_id'])
@lockutils.synchronized('agent', 'dhcp-')
def subnet_update_end(self, context, payload):
"""Handle the subnet.update.end notification event."""
network_id = payload['subnet']['network_id']
self.refresh_dhcp_helper(network_id)
# Use the update handler for the subnet create event.
subnet_create_end = subnet_update_end
@lockutils.synchronized('agent', 'dhcp-')
def subnet_delete_end(self, context, payload):
"""Handle the subnet.delete.end notification event."""
subnet_id = payload['subnet_id']
network = self.cache.get_network_by_subnet_id(subnet_id)
if network:
self.refresh_dhcp_helper(network.id)
@lockutils.synchronized('agent', 'dhcp-')
def port_update_end(self, context, payload):
"""Handle the port.update.end notification event."""
port = DictModel(payload['port'])
network = self.cache.get_network_by_id(port.network_id)
if network:
self.cache.put_port(port)
self.call_driver('reload_allocations', network)
# Use the update handler for the port create event.
port_create_end = port_update_end
@lockutils.synchronized('agent', 'dhcp-')
def port_delete_end(self, context, payload):
"""Handle the port.delete.end notification event."""
port = self.cache.get_port_by_id(payload['port_id'])
if port:
network = self.cache.get_network_by_id(port.network_id)
self.cache.remove_port(port)
self.call_driver('reload_allocations', network)
def enable_isolated_metadata_proxy(self, network):
# The proxy might work for either a single network
# or all the networks connected via a router
# to the one passed as a parameter
quantum_lookup_param = '--network_id=%s' % network.id
meta_cidr = netaddr.IPNetwork(METADATA_DEFAULT_IP)
has_metadata_subnet = any(netaddr.IPNetwork(s.cidr) in meta_cidr
for s in network.subnets)
if (self.conf.enable_metadata_network and has_metadata_subnet):
router_ports = [port for port in network.ports
if (port.device_owner ==
constants.DEVICE_OWNER_ROUTER_INTF)]
if router_ports:
# Multiple router ports should not be allowed
if len(router_ports) > 1:
LOG.warning(_("%(port_num)d router ports found on the "
"metadata access network. Only the port "
"%(port_id)s, for router %(router_id)s "
"will be considered"),
{'port_num': len(router_ports),
'port_id': router_ports[0].id,
'router_id': router_ports[0].device_id})
quantum_lookup_param = ('--router_id=%s' %
router_ports[0].device_id)
def callback(pid_file):
proxy_cmd = ['quantum-ns-metadata-proxy',
'--pid_file=%s' % pid_file,
quantum_lookup_param,
'--state_path=%s' % self.conf.state_path,
'--metadata_port=%d' % METADATA_PORT]
proxy_cmd.extend(config.get_log_args(
cfg.CONF, 'quantum-ns-metadata-proxy-%s.log' % network.id))
return proxy_cmd
pm = external_process.ProcessManager(
self.conf,
network.id,
self.conf.root_helper,
self._ns_name(network))
pm.enable(callback)
def disable_isolated_metadata_proxy(self, network):
pm = external_process.ProcessManager(
self.conf,
network.id,
self.conf.root_helper,
self._ns_name(network))
pm.disable()
class DhcpPluginApi(proxy.RpcProxy):
"""Agent side of the dhcp rpc API.
API version history:
1.0 - Initial version.
"""
BASE_RPC_API_VERSION = '1.0'
def __init__(self, topic, context):
super(DhcpPluginApi, self).__init__(
topic=topic, default_version=self.BASE_RPC_API_VERSION)
self.context = context
self.host = cfg.CONF.host
def get_active_networks(self):
"""Make a remote process call to retrieve the active networks."""
return self.call(self.context,
self.make_msg('get_active_networks', host=self.host),
topic=self.topic)
def get_network_info(self, network_id):
"""Make a remote process call to retrieve network info."""
return DictModel(self.call(self.context,
self.make_msg('get_network_info',
network_id=network_id,
host=self.host),
topic=self.topic))
def get_dhcp_port(self, network_id, device_id):
"""Make a remote process call to create the dhcp port."""
return DictModel(self.call(self.context,
self.make_msg('get_dhcp_port',
network_id=network_id,
device_id=device_id,
host=self.host),
topic=self.topic))
def release_dhcp_port(self, network_id, device_id):
"""Make a remote process call to release the dhcp port."""
return self.call(self.context,
self.make_msg('release_dhcp_port',
network_id=network_id,
device_id=device_id,
host=self.host),
topic=self.topic)
def release_port_fixed_ip(self, network_id, device_id, subnet_id):
"""Make a remote process call to release a fixed_ip on the port."""
return self.call(self.context,
self.make_msg('release_port_fixed_ip',
network_id=network_id,
subnet_id=subnet_id,
device_id=device_id,
host=self.host),
topic=self.topic)
def update_lease_expiration(self, network_id, ip_address, lease_remaining):
"""Make a remote process call to update the ip lease expiration."""
self.cast(self.context,
self.make_msg('update_lease_expiration',
network_id=network_id,
ip_address=ip_address,
lease_remaining=lease_remaining,
host=self.host),
topic=self.topic)
class NetworkCache(object):
"""Agent cache of the current network state."""
def __init__(self):
self.cache = {}
self.subnet_lookup = {}
self.port_lookup = {}
def get_network_ids(self):
return self.cache.keys()
def get_network_by_id(self, network_id):
return self.cache.get(network_id)
def get_network_by_subnet_id(self, subnet_id):
return self.cache.get(self.subnet_lookup.get(subnet_id))
def get_network_by_port_id(self, port_id):
return self.cache.get(self.port_lookup.get(port_id))
def put(self, network):
if network.id in self.cache:
self.remove(self.cache[network.id])
self.cache[network.id] = network
for subnet in network.subnets:
self.subnet_lookup[subnet.id] = network.id
for port in network.ports:
self.port_lookup[port.id] = network.id
def remove(self, network):
del self.cache[network.id]
for subnet in network.subnets:
del self.subnet_lookup[subnet.id]
for port in network.ports:
del self.port_lookup[port.id]
def put_port(self, port):
network = self.get_network_by_id(port.network_id)
for index in range(len(network.ports)):
if network.ports[index].id == port.id:
network.ports[index] = port
break
else:
network.ports.append(port)
self.port_lookup[port.id] = network.id
def remove_port(self, port):
network = self.get_network_by_port_id(port.id)
for index in range(len(network.ports)):
if network.ports[index] == port:
del network.ports[index]
del self.port_lookup[port.id]
break
def get_port_by_id(self, port_id):
network = self.get_network_by_port_id(port_id)
if network:
for port in network.ports:
if port.id == port_id:
return port
def get_state(self):
net_ids = self.get_network_ids()
num_nets = len(net_ids)
num_subnets = 0
num_ports = 0
for net_id in net_ids:
network = self.get_network_by_id(net_id)
num_subnets += len(network.subnets)
num_ports += len(network.ports)
return {'networks': num_nets,
'subnets': num_subnets,
'ports': num_ports}
class DeviceManager(object):
OPTS = [
cfg.StrOpt('interface_driver',
help=_("The driver used to manage the virtual interface."))
]
def __init__(self, conf, plugin):
self.conf = conf
self.root_helper = config.get_root_helper(conf)
self.plugin = plugin
if not conf.interface_driver:
raise SystemExit(_('You must specify an interface driver'))
try:
self.driver = importutils.import_object(conf.interface_driver,
conf)
except:
msg = _("Error importing interface driver "
"'%s'") % conf.interface_driver
raise SystemExit(msg)
def get_interface_name(self, network, port=None):
"""Return interface(device) name for use by the DHCP process."""
if not port:
device_id = self.get_device_id(network)
port = self.plugin.get_dhcp_port(network.id, device_id)
return self.driver.get_device_name(port)
def get_device_id(self, network):
"""Return a unique DHCP device ID for this host on the network."""
# There could be more than one dhcp server per network, so create
# a device id that combines host and network ids
host_uuid = uuid.uuid5(uuid.NAMESPACE_DNS, socket.gethostname())
return 'dhcp%s-%s' % (host_uuid, network.id)
def setup(self, network, reuse_existing=False):
"""Create and initialize a device for network's DHCP on this host."""
device_id = self.get_device_id(network)
port = self.plugin.get_dhcp_port(network.id, device_id)
interface_name = self.get_interface_name(network, port)
if self.conf.use_namespaces:
namespace = NS_PREFIX + network.id
else:
namespace = None
if ip_lib.device_exists(interface_name,
self.root_helper,
namespace):
if not reuse_existing:
raise exceptions.PreexistingDeviceFailure(
dev_name=interface_name)
LOG.debug(_('Reusing existing device: %s.'), interface_name)
else:
self.driver.plug(network.id,
port.id,
interface_name,
port.mac_address,
namespace=namespace)
ip_cidrs = []
for fixed_ip in port.fixed_ips:
subnet = fixed_ip.subnet
net = netaddr.IPNetwork(subnet.cidr)
ip_cidr = '%s/%s' % (fixed_ip.ip_address, net.prefixlen)
ip_cidrs.append(ip_cidr)
if (self.conf.enable_isolated_metadata and
self.conf.use_namespaces):
ip_cidrs.append(METADATA_DEFAULT_IP)
self.driver.init_l3(interface_name, ip_cidrs,
namespace=namespace)
# ensure that the dhcp interface is first in the list
if namespace is None:
device = ip_lib.IPDevice(interface_name,
self.root_helper)
device.route.pullup_route(interface_name)
if self.conf.enable_metadata_network:
meta_cidr = netaddr.IPNetwork(METADATA_DEFAULT_IP)
metadata_subnets = [s for s in network.subnets if
netaddr.IPNetwork(s.cidr) in meta_cidr]
if metadata_subnets:
# Add a gateway so that packets can be routed back to VMs
device = ip_lib.IPDevice(interface_name,
self.root_helper,
namespace)
# Only 1 subnet on metadata access network
gateway_ip = metadata_subnets[0].gateway_ip
device.route.add_gateway(gateway_ip)
return interface_name
def destroy(self, network, device_name):
"""Destroy the device used for the network's DHCP on this host."""
if self.conf.use_namespaces:
namespace = NS_PREFIX + network.id
else:
namespace = None
self.driver.unplug(device_name, namespace=namespace)
self.plugin.release_dhcp_port(network.id,
self.get_device_id(network))
class DictModel(object):
"""Convert dict into an object that provides attribute access to values."""
def __init__(self, d):
for key, value in d.iteritems():
if isinstance(value, list):
value = [DictModel(item) if isinstance(item, dict) else item
for item in value]
elif isinstance(value, dict):
value = DictModel(value)
setattr(self, key, value)
class DhcpLeaseRelay(object):
"""UNIX domain socket server for processing lease updates.
Network namespace isolation prevents the DHCP process from notifying
Quantum directly. This class works around the limitation by using the
domain socket to pass the information. This class handles message.
receiving and then calls the callback method.
"""
OPTS = [
cfg.StrOpt('dhcp_lease_relay_socket',
default='$state_path/dhcp/lease_relay',
help=_('Location to DHCP lease relay UNIX domain socket'))
]
def __init__(self, lease_update_callback):
self.callback = lease_update_callback
dirname = os.path.dirname(cfg.CONF.dhcp_lease_relay_socket)
if os.path.isdir(dirname):
try:
os.unlink(cfg.CONF.dhcp_lease_relay_socket)
except OSError:
if os.path.exists(cfg.CONF.dhcp_lease_relay_socket):
raise
else:
os.makedirs(dirname, 0755)
def _handler(self, client_sock, client_addr):
"""Handle incoming lease relay stream connection.
This method will only read the first 1024 bytes and then close the
connection. The limit exists to limit the impact of misbehaving
clients.
"""
try:
msg = client_sock.recv(1024)
data = jsonutils.loads(msg)
client_sock.close()
network_id = data['network_id']
if not uuidutils.is_uuid_like(network_id):
raise ValueError(_("Network ID %s is not a valid UUID") %
network_id)
ip_address = str(netaddr.IPAddress(data['ip_address']))
lease_remaining = int(data['lease_remaining'])
self.callback(network_id, ip_address, lease_remaining)
except ValueError, e:
LOG.warn(_('Unable to parse lease relay msg to dict.'))
LOG.warn(_('Exception value: %s'), e)
LOG.warn(_('Message representation: %s'), repr(msg))
except Exception, e:
LOG.exception(_('Unable update lease. Exception'))
def start(self):
"""Spawn a green thread to run the lease relay unix socket server."""
listener = eventlet.listen(cfg.CONF.dhcp_lease_relay_socket,
family=socket.AF_UNIX)
eventlet.spawn(eventlet.serve, listener, self._handler)
class DhcpAgentWithStateReport(DhcpAgent):
def __init__(self, host=None):
super(DhcpAgentWithStateReport, self).__init__(host=host)
self.state_rpc = agent_rpc.PluginReportStateAPI(topics.PLUGIN)
self.agent_state = {
'binary': 'quantum-dhcp-agent',
'host': host,
'topic': topics.DHCP_AGENT,
'configurations': {
'dhcp_driver': cfg.CONF.dhcp_driver,
'use_namespaces': cfg.CONF.use_namespaces,
'dhcp_lease_time': cfg.CONF.dhcp_lease_time},
'start_flag': True,
'agent_type': constants.AGENT_TYPE_DHCP}
report_interval = cfg.CONF.AGENT.report_interval
if report_interval:
self.heartbeat = loopingcall.LoopingCall(self._report_state)
self.heartbeat.start(interval=report_interval)
def _report_state(self):
try:
self.agent_state.get('configurations').update(
self.cache.get_state())
ctx = context.get_admin_context_without_session()
self.state_rpc.report_state(ctx,
self.agent_state)
except AttributeError:
# This means the server does not support report_state
LOG.warn(_("Quantum server does not support state report."
" State report for this agent will be disabled."))
self.heartbeat.stop()
self.run()
return
except Exception:
LOG.exception(_("Failed reporting state!"))
return
if self.agent_state.pop('start_flag', None):
self.run()
def agent_updated(self, context, payload):
"""Handle the agent_updated notification event."""
self.needs_resync = True
LOG.info(_("agent_updated by server side %s!"), payload)
def after_start(self):
LOG.info(_("DHCP agent started"))
def register_options():
cfg.CONF.register_opts(DhcpAgent.OPTS)
config.register_agent_state_opts_helper(cfg.CONF)
config.register_root_helper(cfg.CONF)
cfg.CONF.register_opts(DeviceManager.OPTS)
cfg.CONF.register_opts(DhcpLeaseRelay.OPTS)
cfg.CONF.register_opts(dhcp.OPTS)
cfg.CONF.register_opts(interface.OPTS)
def main():
eventlet.monkey_patch()
register_options()
cfg.CONF(project='quantum')
config.setup_logging(cfg.CONF)
server = quantum_service.Service.create(
binary='quantum-dhcp-agent',
topic=topics.DHCP_AGENT,
report_interval=cfg.CONF.AGENT.report_interval,
manager='quantum.agent.dhcp_agent.DhcpAgentWithStateReport')
service.launch(server).wait()
| {
"content_hash": "6402d9ff86cf2f3d86c7e480d2cd8b46",
"timestamp": "",
"source": "github",
"line_count": 724,
"max_line_length": 79,
"avg_line_length": 38.87845303867403,
"alnum_prop": 0.5664700866846668,
"repo_name": "tpaszkowski/quantum",
"id": "42c9f0a04117db8bc9ccdcc15c4bf72d12064018",
"size": "28829",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "quantum/agent/dhcp_agent.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "JavaScript",
"bytes": "67928"
},
{
"name": "Perl",
"bytes": "235"
},
{
"name": "Python",
"bytes": "4007121"
},
{
"name": "Scala",
"bytes": "4561"
},
{
"name": "Shell",
"bytes": "8090"
},
{
"name": "XML",
"bytes": "50907"
}
],
"symlink_target": ""
} |
package com.intellij.vcs.log.ui.table;
import com.google.common.primitives.Ints;
import com.intellij.ide.CopyProvider;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.actionSystem.DataProvider;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.ide.CopyPasteManager;
import com.intellij.openapi.ui.LoadingDecorator;
import com.intellij.openapi.util.Couple;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.NlsContexts;
import com.intellij.openapi.util.ValueKey;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vcs.FilePath;
import com.intellij.openapi.vcs.VcsDataKeys;
import com.intellij.openapi.vcs.changes.issueLinks.TableLinkMouseListener;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.wm.IdeFocusManager;
import com.intellij.ui.*;
import com.intellij.ui.scale.JBUIScale;
import com.intellij.util.Consumer;
import com.intellij.util.ObjectUtils;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.ui.JBInsets;
import com.intellij.util.ui.JBUI;
import com.intellij.util.ui.UIUtil;
import com.intellij.vcs.log.*;
import com.intellij.vcs.log.VcsLogHighlighter.VcsCommitStyle;
import com.intellij.vcs.log.data.VcsLogData;
import com.intellij.vcs.log.data.VcsLogProgress;
import com.intellij.vcs.log.graph.RowInfo;
import com.intellij.vcs.log.graph.RowType;
import com.intellij.vcs.log.graph.VisibleGraph;
import com.intellij.vcs.log.graph.actions.GraphAnswer;
import com.intellij.vcs.log.impl.CommonUiProperties;
import com.intellij.vcs.log.impl.VcsLogUiProperties;
import com.intellij.vcs.log.paint.PositionUtil;
import com.intellij.vcs.log.statistics.VcsLogUsageTriggerCollector;
import com.intellij.vcs.log.ui.VcsLogColorManager;
import com.intellij.vcs.log.ui.VcsLogColorManagerImpl;
import com.intellij.vcs.log.ui.render.GraphCommitCellRenderer;
import com.intellij.vcs.log.ui.render.SimpleColoredComponentLinkMouseListener;
import com.intellij.vcs.log.ui.table.column.*;
import com.intellij.vcs.log.util.VcsLogUiUtil;
import com.intellij.vcs.log.util.VcsLogUtil;
import com.intellij.vcs.log.visible.VisiblePack;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.event.CellEditorListener;
import javax.swing.event.TableModelEvent;
import javax.swing.table.*;
import java.awt.*;
import java.awt.datatransfer.StringSelection;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.beans.PropertyChangeEvent;
import java.util.List;
import java.util.*;
import static com.intellij.ui.hover.TableHoverListener.getHoveredRow;
import static com.intellij.util.containers.ContainerUtil.getFirstItem;
import static com.intellij.vcs.log.VcsCommitStyleFactory.createStyle;
import static com.intellij.vcs.log.VcsLogHighlighter.TextStyle.BOLD;
import static com.intellij.vcs.log.VcsLogHighlighter.TextStyle.ITALIC;
import static com.intellij.vcs.log.ui.table.column.VcsLogColumnUtilKt.*;
public class VcsLogGraphTable extends TableWithProgress implements DataProvider, CopyProvider, Disposable {
private static final Logger LOG = Logger.getInstance(VcsLogGraphTable.class);
public static final int ROOT_INDICATOR_WHITE_WIDTH = 5;
private static final int ROOT_INDICATOR_WIDTH = ROOT_INDICATOR_WHITE_WIDTH + 8;
private static final int ROOT_NAME_MAX_WIDTH = 300;
private static final int MAX_DEFAULT_DYNAMIC_COLUMN_WIDTH = 300;
private static final int MAX_ROWS_TO_CALC_WIDTH = 1000;
@SuppressWarnings("UseJBColor")
private static final Color DEFAULT_HOVERED_BACKGROUND = new JBColor(ColorUtil.withAlpha(new Color(0xC3D2E3), 0.4),
new Color(0x464A4D));
private static final Color HOVERED_BACKGROUND = JBColor.namedColor("VersionControl.Log.Commit.hoveredBackground",
DEFAULT_HOVERED_BACKGROUND);
private static final Color SELECTION_BACKGROUND = JBColor.namedColor("VersionControl.Log.Commit.selectionBackground",
UIUtil.getListSelectionBackground(true));
private static final Color SELECTION_BACKGROUND_INACTIVE = JBColor.namedColor("VersionControl.Log.Commit.selectionInactiveBackground",
UIUtil.getListSelectionBackground(false));
private static final Color SELECTION_FOREGROUND = JBColor.namedColor("VersionControl.Log.Commit.selectionForeground",
UIUtil.getListSelectionForeground(true));
private static final Color SELECTION_FOREGROUND_INACTIVE = JBColor.namedColor("VersionControl.Log.Commit.selectionInactiveForeground",
UIUtil.getListSelectionForeground(false));
@NotNull private final VcsLogData myLogData;
@NotNull private final String myId;
@NotNull private final VcsLogUiProperties myProperties;
@NotNull private final VcsLogColorManager myColorManager;
@NotNull private final MyDummyTableCellEditor myDummyEditor = new MyDummyTableCellEditor();
@NotNull private final BaseStyleProvider myBaseStyleProvider;
@NotNull private final GraphCommitCellRenderer myGraphCommitCellRenderer;
@NotNull private final MyMouseAdapter myMouseAdapter;
// BasicTableUI.viewIndexForColumn uses reference equality, so we should not change TableColumn during DnD.
@NotNull private final Map<VcsLogColumn<?>, TableColumn> myTableColumns = new HashMap<>();
@NotNull private final Set<VcsLogColumn<?>> myInitializedColumns = new HashSet<>();
@NotNull private final Collection<VcsLogHighlighter> myHighlighters = new LinkedHashSet<>();
@Nullable private Selection mySelection = null;
public VcsLogGraphTable(@NotNull String logId, @NotNull VcsLogData logData,
@NotNull VcsLogUiProperties uiProperties, @NotNull VcsLogColorManager colorManager,
@NotNull Consumer<Runnable> requestMore, @NotNull Disposable disposable) {
super(new GraphTableModel(logData, requestMore, uiProperties));
Disposer.register(disposable, this);
myLogData = logData;
myId = logId;
myProperties = uiProperties;
myColorManager = colorManager;
myBaseStyleProvider = new BaseStyleProvider(this);
getEmptyText().setText(VcsLogBundle.message("vcs.log.default.status"));
myLogData.getProgress().addProgressIndicatorListener(new MyProgressListener(), this);
initColumnModel();
onColumnOrderSettingChanged();
setRootColumnSize();
myGraphCommitCellRenderer = (GraphCommitCellRenderer)myTableColumns.get(Commit.INSTANCE).getCellRenderer();
VcsLogColumnManager.getInstance().addCurrentColumnsListener(this, new MyCurrentColumnsListener());
VcsLogColumnManager.getInstance().addColumnModelListener(this, (column, index) -> {
getModel().fireTableStructureChanged();
});
setShowVerticalLines(false);
setShowHorizontalLines(false);
setIntercellSpacing(JBUI.emptySize());
setTableHeader(new InvisibleResizableHeader() {
@Override
protected boolean canMoveOrResizeColumn(int modelIndex) {
return modelIndex != VcsLogColumnManager.getInstance().getModelIndex(Root.INSTANCE);
}
});
myMouseAdapter = new MyMouseAdapter();
addMouseMotionListener(myMouseAdapter);
addMouseListener(myMouseAdapter);
getSelectionModel().addListSelectionListener(e -> mySelection = null);
getColumnModel().setColumnSelectionAllowed(false);
ScrollingUtil.installActions(this, false);
}
public @NotNull @NonNls String getId() {
return myId;
}
@Override
public void dispose() {
}
private void initColumnModel() {
TableColumnModel columnModel = new MyTableColumnModel(myProperties);
setColumnModel(columnModel);
setAutoCreateColumnsFromModel(false); // otherwise sizes are recalculated after each TableColumn re-initialization
}
protected void updateEmptyText() {
getEmptyText().setText(VcsLogBundle.message("vcs.log.default.status"));
}
protected void setErrorEmptyText(@NotNull Throwable error, @NlsContexts.StatusText @NotNull String defaultText) {
String message = ObjectUtils.chooseNotNull(error.getLocalizedMessage(), defaultText);
String shortenedMessage = StringUtil.shortenTextWithEllipsis(message, 150, 0, true);
getEmptyText().setText(shortenedMessage.replace('\n', ' '));
}
protected void appendActionToEmptyText(@Nls @NotNull String text, @NotNull Runnable action) {
getEmptyText().appendSecondaryText(text, SimpleTextAttributes.LINK_PLAIN_ATTRIBUTES, e -> action.run());
}
public void updateDataPack(@NotNull VisiblePack visiblePack, boolean permGraphChanged) {
boolean filtersChanged = !getModel().getVisiblePack().getFilters().equals(visiblePack.getFilters());
Selection previousSelection = getSelection();
getModel().setVisiblePack(visiblePack);
previousSelection.restore(visiblePack.getVisibleGraph(), true, permGraphChanged);
for (VcsLogHighlighter highlighter : myHighlighters) {
highlighter.update(visiblePack, permGraphChanged);
}
if (!getEmptyText().getText().equals(VcsLogBundle.message("vcs.log.loading.status"))) {
updateEmptyText();
}
setPaintBusy(false);
if (filtersChanged) myInitializedColumns.clear();
reLayout();
}
public void onColumnOrderSettingChanged() {
List<VcsLogColumn<?>> columnOrder = getColumnOrderFromProperties();
if (columnOrder != null) {
TableColumnModel columnModel = getColumnModel();
int columnCount = getVisibleColumnCount();
for (int i = columnCount - 1; i >= 0; i--) {
columnModel.removeColumn(columnModel.getColumn(i));
}
for (VcsLogColumn<?> column : columnOrder) {
myTableColumns.computeIfAbsent(column, (k) -> createTableColumn(column));
columnModel.addColumn(myTableColumns.get(column));
}
}
reLayout();
}
@Nullable
private List<VcsLogColumn<?>> getColumnOrderFromProperties() {
List<VcsLogColumn<?>> columnOrder = getColumnsOrder(myProperties);
if (isValidColumnOrder(columnOrder)) {
return columnOrder;
}
LOG.debug("Incorrect column order was saved in properties " + columnOrder + ", replacing it with default order.");
updateOrder(myProperties, getVisibleColumns());
return null;
}
@NotNull
private List<Integer> getVisibleColumnIndices() {
List<Integer> columnOrder = new ArrayList<>();
for (int i = 0; i < getVisibleColumnCount(); i++) {
columnOrder.add(getColumnModel().getColumn(i).getModelIndex());
}
return columnOrder;
}
@NotNull
public List<VcsLogColumn<?>> getVisibleColumns() {
return ContainerUtil.map2List(getVisibleColumnIndices(),
columnModelIndex -> VcsLogColumnManager.getInstance().getColumn(columnModelIndex));
}
private int getVisibleColumnCount() {
return getColumnModel().getColumnCount();
}
public void onColumnDataChanged(@NotNull VcsLogColumn<?> column) {
if (getRowCount() == 0) return;
TableColumn tableColumn = getTableColumn(column);
if (tableColumn != null) {
reLayout();
getModel().fireTableChanged(new TableModelEvent(getModel(), 0, getRowCount() - 1, tableColumn.getModelIndex()));
}
}
private void reLayout() {
if (getTableHeader().getResizingColumn() == null) {
updateDynamicColumnsWidth();
super.doLayout();
repaint();
}
}
public void forceReLayout(@NotNull VcsLogColumn<?> column) {
myInitializedColumns.remove(column);
reLayout();
}
@Override
public void doLayout() {
if (getTableHeader().getResizingColumn() == null) {
updateDynamicColumnsWidth();
}
super.doLayout();
}
private void resetColumnWidth(@NotNull VcsLogColumn<?> column) {
VcsLogUsageTriggerCollector.triggerColumnReset(myLogData.getProject());
if (VcsLogColumnUtilKt.getWidth(column, myProperties) != -1) {
setWidth(column, myProperties, -1);
}
else {
forceReLayout(column);
}
}
@NotNull
private TableColumn createTableColumn(VcsLogColumn<?> column) {
TableColumn tableColumn = new TableColumn(VcsLogColumnManager.getInstance().getModelIndex(column));
tableColumn.setResizable(column.isResizable());
tableColumn.setCellRenderer(column.createTableCellRenderer(this));
return tableColumn;
}
@NotNull
public VcsLogUiProperties getProperties() {
return myProperties;
}
@NotNull
public VcsLogColorManager getColorManager() {
return myColorManager;
}
@NotNull
public VcsLogData getLogData() {
return myLogData;
}
private void updateDynamicColumnsWidth() {
for (VcsLogColumn<?> logColumn : VcsLogColumnManager.getInstance().getCurrentDynamicColumns()) {
TableColumn column = getTableColumn(logColumn);
if (column == null) continue;
int width = VcsLogColumnUtilKt.getWidth(logColumn, myProperties);
if (width <= 0 || width > getWidth()) {
width = getColumnWidthFromData(column);
}
if (width > 0 && width != column.getPreferredWidth()) {
column.setPreferredWidth(width);
}
}
int size = getWidth();
for (VcsLogColumn<?> logColumn : VcsLogColumnManager.getInstance().getCurrentColumns()) {
if (logColumn == Commit.INSTANCE) continue;
TableColumn column = getTableColumn(logColumn);
if (column != null) size -= column.getPreferredWidth();
}
getCommitColumn().setPreferredWidth(size);
}
private int getColumnWidthFromData(@NotNull TableColumn column) {
int index = column.getModelIndex();
VcsLogColumn<?> logColumn = VcsLogColumnManager.getInstance().getColumn(index);
TableCellRenderer columnRenderer = myTableColumns.get(logColumn).getCellRenderer();
if (columnRenderer instanceof VcsLogCellRenderer) {
Integer width = ((VcsLogCellRenderer)columnRenderer).getPreferredWidth(this);
if (width != null) {
return width;
}
}
if (getModel().getRowCount() <= 0 ||
!(getModel().getValueAt(0, logColumn) instanceof String) ||
myInitializedColumns.contains(logColumn)) {
return column.getPreferredWidth();
}
Font tableFont = getTableFont();
// detect the longest value
int maxRowsToCheck = Math.min(MAX_ROWS_TO_CALC_WIDTH, getRowCount());
int maxValueWidth = 0;
int unloaded = 0;
for (int row = 0; row < maxRowsToCheck; row++) {
String value = getModel().getValueAt(row, logColumn).toString();
if (value.isEmpty()) {
unloaded++;
continue;
}
Font font = tableFont;
VcsLogHighlighter.TextStyle style = getStyle(row, getColumnViewIndex(logColumn), false, false, false).getTextStyle();
if (BOLD.equals(style)) {
font = tableFont.deriveFont(Font.BOLD);
}
else if (ITALIC.equals(style)) {
font = tableFont.deriveFont(Font.ITALIC);
}
maxValueWidth = Math.max(getFontMetrics(font).stringWidth(value + "*"), maxValueWidth);
}
int horizontalPadding = columnRenderer instanceof SimpleColoredComponent ?
VcsLogUiUtil.getHorizontalTextPadding((SimpleColoredComponent)columnRenderer) : 0;
int width = Math.min(maxValueWidth + horizontalPadding, JBUIScale.scale(MAX_DEFAULT_DYNAMIC_COLUMN_WIDTH));
if (unloaded * 2 <= maxRowsToCheck) myInitializedColumns.add(logColumn);
return width;
}
@Nullable
public VcsLogColumn<?> getVcsLogColumn(int viewIndex) {
int modelIndex = convertColumnIndexToModel(viewIndex);
return modelIndex < 0 ? null : VcsLogColumnManager.getInstance().getColumn(modelIndex);
}
public final int getColumnViewIndex(@NotNull VcsLogColumn<?> column) {
return convertColumnIndexToView(VcsLogColumnManager.getInstance().getModelIndex(column));
}
@Nullable
public TableColumn getTableColumn(@NotNull VcsLogColumn<?> column) {
int viewIndex = getColumnViewIndex(column);
return viewIndex != -1 ? getColumnModel().getColumn(viewIndex) : null;
}
@NotNull
public TableColumn getRootColumn() {
return Objects.requireNonNull(getTableColumn(Root.INSTANCE));
}
@NotNull
public TableColumn getCommitColumn() {
return Objects.requireNonNull(getTableColumn(Commit.INSTANCE));
}
@Nullable
private VcsLogCellController getController(@NotNull VcsLogColumn<?> column) {
TableColumn tableColumn = getTableColumn(column);
if (tableColumn == null) return null;
TableCellRenderer renderer = tableColumn.getCellRenderer();
if (!(renderer instanceof VcsLogCellRenderer)) {
return null;
}
return ((VcsLogCellRenderer)renderer).getCellController();
}
@NotNull
Point getPointInCell(@NotNull Point clickPoint, @NotNull VcsLogColumn<?> vcsLogColumn) {
int width = 0;
for (int i = 0; i < getColumnModel().getColumnCount(); i++) {
TableColumn column = getColumnModel().getColumn(i);
if (column.getModelIndex() == VcsLogColumnManager.getInstance().getModelIndex(vcsLogColumn)) break;
width += column.getWidth();
}
return new Point(clickPoint.x - width, PositionUtil.getYInsideRow(clickPoint, getRowHeight()));
}
int getColumnLeftXCoordinate(int viewColumnIndex) {
int x = 0;
for (int i = 0; i < viewColumnIndex; i++) {
x += getColumnModel().getColumn(i).getWidth();
}
return x;
}
private void setRootColumnSize() {
TableColumn column = getRootColumn();
int rootWidth;
if (!myColorManager.hasMultiplePaths()) {
rootWidth = 0;
}
else if (!isShowRootNames()) {
rootWidth = JBUIScale.scale(ROOT_INDICATOR_WIDTH);
}
else {
int width = 0;
for (FilePath file : myColorManager.getPaths()) {
Font tableFont = getTableFont();
width = Math.max(getFontMetrics(tableFont).stringWidth(file.getName() + " "), width);
}
rootWidth = Math.min(width, JBUIScale.scale(ROOT_NAME_MAX_WIDTH));
}
// NB: all further instructions and their order are important, otherwise the minimum size which is less than 15 won't be applied
column.setMinWidth(rootWidth);
column.setMaxWidth(rootWidth);
column.setPreferredWidth(rootWidth);
}
public void rootColumnUpdated() {
setRootColumnSize();
reLayout();
repaint();
}
private boolean isShowRootNames() {
return myProperties.exists(CommonUiProperties.SHOW_ROOT_NAMES) && myProperties.get(CommonUiProperties.SHOW_ROOT_NAMES);
}
public void jumpToRow(int rowIndex, boolean focus) {
if (rowIndex >= 0 && rowIndex <= getRowCount() - 1) {
scrollRectToVisible(getCellRect(rowIndex, 0, false));
setRowSelectionInterval(rowIndex, rowIndex);
if (focus && !hasFocus()) {
IdeFocusManager.getInstance(myLogData.getProject()).requestFocus(this, true);
}
}
}
@Nullable
@Override
public Object getData(@NotNull @NonNls String dataId) {
return ValueKey.match(dataId)
.ifEq(PlatformDataKeys.COPY_PROVIDER).then(this)
.ifEq(VcsDataKeys.VCS).thenGet(() -> {
int[] selectedRows = getSelectedRows();
if (selectedRows.length == 0 || selectedRows.length > VcsLogUtil.MAX_SELECTED_COMMITS) return null;
Set<VirtualFile> roots = ContainerUtil.map2Set(Ints.asList(selectedRows), row -> getModel().getRootAtRow(row));
if (roots.size() == 1) {
return myLogData.getLogProvider(Objects.requireNonNull(getFirstItem(roots))).getSupportedVcs();
}
return null;
})
.ifEq(VcsLogDataKeys.VCS_LOG_BRANCHES).thenGet(() -> {
int[] selectedRows = getSelectedRows();
if (selectedRows.length != 1) return null;
return getModel().getBranchesAtRow(selectedRows[0]);
})
.ifEq(VcsLogDataKeys.VCS_LOG_REFS).thenGet(() -> {
int[] selectedRows = getSelectedRows();
if (selectedRows.length != 1) return null;
return getModel().getRefsAtRow(selectedRows[0]);
})
.ifEq(VcsDataKeys.PRESET_COMMIT_MESSAGE).thenGet(() -> {
int[] selectedRows = getSelectedRows();
if (selectedRows.length == 0) return null;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < Math.min(VcsLogUtil.MAX_SELECTED_COMMITS, selectedRows.length); i++) {
sb.append(getModel().getValueAt(selectedRows[i], Commit.INSTANCE));
if (i != selectedRows.length - 1) sb.append("\n");
}
return sb.toString();
})
.orNull();
}
@Override
public void performCopy(@NotNull DataContext dataContext) {
StringBuilder sb = new StringBuilder();
List<Integer> visibleColumns = getVisibleColumnIndices();
int[] selectedRows = getSelectedRows();
for (int i = 0; i < Math.min(VcsLogUtil.MAX_SELECTED_COMMITS, selectedRows.length); i++) {
int row = selectedRows[i];
sb.append(StringUtil.join(visibleColumns, j -> {
if (j == VcsLogColumnManager.getInstance().getModelIndex(Root.INSTANCE)) {
return "";
}
else {
return getModel().getValueAt(row, j).toString();
}
}, " "));
if (i != selectedRows.length - 1) sb.append("\n");
}
CopyPasteManager.getInstance().setContents(new StringSelection(sb.toString()));
}
@Override
public boolean isCopyEnabled(@NotNull DataContext dataContext) {
return getSelectedRowCount() > 0;
}
@Override
public boolean isCopyVisible(@NotNull DataContext dataContext) {
return true;
}
public void addHighlighter(@NotNull VcsLogHighlighter highlighter) {
myHighlighters.add(highlighter);
highlighter.update(getModel().getVisiblePack(), true);
}
public void removeHighlighter(@NotNull VcsLogHighlighter highlighter) {
myHighlighters.remove(highlighter);
}
public void removeAllHighlighters() {
myHighlighters.clear();
}
@NotNull
public SimpleTextAttributes applyHighlighters(@NotNull Component rendererComponent,
int row,
int column,
boolean hasFocus,
final boolean selected) {
VcsCommitStyle style = getStyle(row, column, hasFocus, selected, row == getHoveredRow(this));
assert style.getBackground() != null && style.getForeground() != null && style.getTextStyle() != null;
rendererComponent.setBackground(style.getBackground());
rendererComponent.setForeground(style.getForeground());
switch (style.getTextStyle()) {
case BOLD:
return SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES;
case ITALIC:
return SimpleTextAttributes.REGULAR_ITALIC_ATTRIBUTES;
default:
}
return SimpleTextAttributes.REGULAR_ATTRIBUTES;
}
@NotNull
public VcsCommitStyle getBaseStyle(int row, int column, boolean hasFocus, boolean selected) {
return myBaseStyleProvider.getBaseStyle(row, column, hasFocus, selected);
}
@NotNull
VcsCommitStyle getStyle(int row, int column, boolean hasFocus, boolean selected, boolean hovered) {
VcsCommitStyle baseStyle = getBaseStyle(row, column, hasFocus, selected);
VisibleGraph<Integer> visibleGraph = getVisibleGraph();
if (row < 0 || row >= visibleGraph.getVisibleCommitCount()) {
LOG.error("Visible graph has " + visibleGraph.getVisibleCommitCount() + " commits, yet we want row " + row);
return baseStyle;
}
RowInfo<Integer> rowInfo = visibleGraph.getRowInfo(row);
VcsCommitStyle style = createStyle(rowInfo.getRowType() == RowType.UNMATCHED ? JBColor.GRAY : baseStyle.getForeground(),
baseStyle.getBackground(), VcsLogHighlighter.TextStyle.NORMAL);
int commitId = rowInfo.getCommit();
VcsShortCommitDetails details = myLogData.getMiniDetailsGetter().getCommitDataIfAvailable(commitId);
if (details != null) {
int columnModelIndex = convertColumnIndexToModel(column);
List<VcsCommitStyle> styles =
ContainerUtil.map(myHighlighters, highlighter -> highlighter.getStyle(commitId, details, columnModelIndex, selected));
style = VcsCommitStyleFactory.combine(ContainerUtil.append(styles, style));
}
if (!selected && hovered) {
Color background = Objects.requireNonNull(style.getBackground());
VcsCommitStyle lightSelectionBgStyle = VcsCommitStyleFactory.background(getHoveredBackgroundColor(background));
style = VcsCommitStyleFactory.combine(Arrays.asList(lightSelectionBgStyle, style));
}
return style;
}
@Override
protected @Nullable Color getHoveredRowBackground() {
return null; // do not overwrite renderer background
}
public void viewportSet(JViewport viewport) {
viewport.addChangeListener(e -> {
if (isShowRootNames()) {
AbstractTableModel model = getModel();
Couple<Integer> visibleRows = ScrollingUtil.getVisibleRows(this);
if (visibleRows.first >= 0) {
TableModelEvent evt = new TableModelEvent(model, visibleRows.first, visibleRows.second,
VcsLogColumnManager.getInstance().getModelIndex(Root.INSTANCE));
model.fireTableChanged(evt);
}
}
mySelection = null;
});
}
@Override
public void setCursor(Cursor cursor) {
super.setCursor(cursor);
Component layeredPane = ComponentUtil.findParentByCondition(this, component -> component instanceof LoadingDecorator.CursorAware);
if (layeredPane != null) {
layeredPane.setCursor(cursor);
}
}
@Override
@NotNull
public GraphTableModel getModel() {
return (GraphTableModel)super.getModel();
}
@NotNull
public Selection getSelection() {
if (mySelection == null) mySelection = new Selection(this);
return mySelection;
}
public void handleAnswer(@NotNull GraphAnswer<Integer> answer) {
GraphCommitCellController controller = (GraphCommitCellController)Objects.requireNonNull(getController(Commit.INSTANCE));
Cursor cursor = controller.handleGraphAnswer(answer, true, null, null);
myMouseAdapter.handleCursor(cursor);
}
public void showTooltip(int row, @NotNull VcsLogColumn<?> column) {
if (column != Commit.INSTANCE) return;
GraphCommitCellController controller = (GraphCommitCellController)Objects.requireNonNull(getController(column));
controller.showTooltip(row);
}
@NotNull
public VisibleGraph<Integer> getVisibleGraph() {
return getModel().getVisiblePack().getVisibleGraph();
}
@Override
public TableCellEditor getCellEditor() {
// this fixes selection problems by prohibiting selection when user clicks on graph (CellEditor does that)
// what is fun about this code is that if you set cell editor in constructor with setCellEditor method it would not work
return myDummyEditor;
}
@Override
public int getRowHeight() {
return myGraphCommitCellRenderer.getPreferredHeight();
}
@Override
protected void paintFooter(@NotNull Graphics g, int x, int y, int width, int height) {
paintTopBottomBorder(g, x, y, width, height, false);
}
private void paintTopBottomBorder(@NotNull Graphics g, int x, int y, int width, int height, boolean isTopBorder) {
int targetRow = isTopBorder ? 0 : getRowCount() - 1;
if (targetRow >= 0 && targetRow < getRowCount()) {
g.setColor(getStyle(targetRow, getColumnViewIndex(Commit.INSTANCE), hasFocus(), false, false).getBackground());
g.fillRect(x, y, width, height);
if (myColorManager.hasMultiplePaths()) {
g.setColor(getPathBackgroundColor(getModel().getValueAt(targetRow, Root.INSTANCE), myColorManager));
int rootWidth = getRootColumn().getWidth();
if (!isShowRootNames()) rootWidth -= JBUIScale.scale(ROOT_INDICATOR_WHITE_WIDTH);
g.fillRect(x, y, rootWidth, height);
}
}
else {
g.setColor(getBaseStyle(targetRow, getColumnViewIndex(Commit.INSTANCE), hasFocus(), false).getBackground());
g.fillRect(x, y, width, height);
}
}
@NotNull
public Border createTopBottomBorder(int top, int bottom) {
return new MyTopBottomBorder(top, bottom);
}
public boolean isResizingColumns() {
return getCursor() == Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR);
}
@NotNull
private static Color getHoveredBackgroundColor(@NotNull Color background) {
int alpha = HOVERED_BACKGROUND.getAlpha();
if (alpha == 255) return HOVERED_BACKGROUND;
if (alpha == 0) return background;
return ColorUtil.mix(new Color(HOVERED_BACKGROUND.getRGB()), background, alpha / 255.0);
}
@NotNull
public static JBColor getRootBackgroundColor(@NotNull VirtualFile root, @NotNull VcsLogColorManager colorManager) {
return VcsLogColorManagerImpl.getBackgroundColor(colorManager.getRootColor(root));
}
@NotNull
public static JBColor getPathBackgroundColor(@NotNull FilePath filePath, @NotNull VcsLogColorManager colorManager) {
return VcsLogColorManagerImpl.getBackgroundColor(colorManager.getPathColor(filePath));
}
static Font getTableFont() {
return UIManager.getFont("Table.font");
}
private static class BaseStyleProvider {
@NotNull private final JTable myTable;
@NotNull private final TableCellRenderer myDummyRenderer = new DefaultTableCellRenderer();
BaseStyleProvider(@NotNull JTable table) {
myTable = table;
}
@NotNull
public VcsCommitStyle getBaseStyle(int row, int column, boolean hasFocus, boolean selected) {
Component dummyRendererComponent = myDummyRenderer.getTableCellRendererComponent(myTable, "", selected, hasFocus, row, column);
Color background = selected ? getSelectionBackground(myTable.hasFocus()) : getBackground();
return createStyle(dummyRendererComponent.getForeground(), background, VcsLogHighlighter.TextStyle.NORMAL);
}
@NotNull
private static Color getBackground() {
return ExperimentalUI.isNewUI() ? JBUI.CurrentTheme.ToolWindow.background() : UIUtil.getListBackground();
}
@NotNull
private static Color getSelectionBackground(boolean hasFocus) {
return hasFocus ? SELECTION_BACKGROUND : SELECTION_BACKGROUND_INACTIVE;
}
}
private class MyMouseAdapter extends MouseAdapter {
private static final int BORDER_THICKNESS = 3;
@NotNull private final TableLinkMouseListener myLinkListener = new MyLinkMouseListener();
@Nullable private Cursor myLastCursor = null;
@Override
public void mouseClicked(MouseEvent e) {
if (myLinkListener.onClick(e, e.getClickCount())) {
return;
}
int c = columnAtPoint(e.getPoint());
VcsLogColumn<?> column = getVcsLogColumn(c);
if (column == null) return;
if (e.getClickCount() == 2) {
// when we reset column width, commit column eats all the remaining space
// (or gives the required space)
// so it is logical that we reset column width by right border if it is on the left of the commit column
// and by the left border otherwise
int commitColumnIndex = getColumnViewIndex(Commit.INSTANCE);
boolean useLeftBorder = c > commitColumnIndex;
if ((useLeftBorder ? isOnLeftBorder(e, c) : isOnRightBorder(e, c)) && column.isDynamic()) {
resetColumnWidth(column);
}
else {
// user may have clicked just outside of the border
// in that case, c is not the column we are looking for
int c2 = columnAtPoint(new Point(e.getPoint().x + (useLeftBorder ? 1 : -1) * JBUIScale.scale(BORDER_THICKNESS),
e.getPoint().y));
VcsLogColumn<?> column2 = getVcsLogColumn(c2);
if (column2 != null && (useLeftBorder ? isOnLeftBorder(e, c2) : isOnRightBorder(e, c2)) && column2.isDynamic()) {
resetColumnWidth(column2);
}
}
}
int row = rowAtPoint(e.getPoint());
if ((row >= 0 && row < getRowCount()) && e.getClickCount() == 1) {
VcsLogCellController controller = getController(column);
if (controller != null) {
Cursor cursor = controller.performMouseClick(row, e);
handleCursor(cursor);
}
}
}
public boolean isOnLeftBorder(@NotNull MouseEvent e, int column) {
return Math.abs(getColumnLeftXCoordinate(column) - e.getPoint().x) <= JBUIScale.scale(BORDER_THICKNESS);
}
public boolean isOnRightBorder(@NotNull MouseEvent e, int column) {
return Math.abs(getColumnLeftXCoordinate(column) +
getColumnModel().getColumn(column).getWidth() - e.getPoint().x) <= JBUIScale.scale(BORDER_THICKNESS);
}
@Override
public void mouseMoved(MouseEvent e) {
if (getRowCount() == 0) return;
if (isResizingColumns()) return;
getExpandableItemsHandler().setEnabled(true);
if (myLinkListener.getTagAt(e) != null) {
swapCursor();
return;
}
int row = rowAtPoint(e.getPoint());
if (row >= 0 && row < getRowCount()) {
VcsLogColumn<?> column = getVcsLogColumn(columnAtPoint(e.getPoint()));
if (column == null) return;
VcsLogCellController controller = getController(column);
if (controller != null) {
Cursor cursor = controller.performMouseMove(row, e);
handleCursor(cursor);
return;
}
}
restoreCursor();
}
private void handleCursor(@Nullable Cursor cursor) {
if (cursor != null) {
if (cursor.getType() == Cursor.DEFAULT_CURSOR) {
restoreCursor();
}
else if (cursor.getType() == Cursor.HAND_CURSOR) {
swapCursor();
}
}
}
private void swapCursor() {
if (getCursor().getType() != Cursor.HAND_CURSOR && myLastCursor == null) {
Cursor newCursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR);
myLastCursor = getCursor();
setCursor(newCursor);
}
}
private void restoreCursor() {
if (getCursor().getType() != Cursor.DEFAULT_CURSOR) {
setCursor(UIUtil.cursorIfNotDefault(myLastCursor));
}
myLastCursor = null;
}
@Override
public void mouseEntered(MouseEvent e) {
// Do nothing
}
@Override
public void mouseExited(MouseEvent e) {
getExpandableItemsHandler().setEnabled(true);
}
private class MyLinkMouseListener extends SimpleColoredComponentLinkMouseListener {
@Nullable
@Override
public Object getTagAt(@NotNull MouseEvent e) {
return ObjectUtils.tryCast(super.getTagAt(e), SimpleColoredComponent.BrowserLauncherTag.class);
}
}
}
private class MyDummyTableCellEditor implements TableCellEditor {
@Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
return null;
}
@Override
public Object getCellEditorValue() {
return null;
}
@Override
public boolean isCellEditable(EventObject anEvent) {
return false;
}
@Override
public boolean shouldSelectCell(EventObject anEvent) {
if (!(anEvent instanceof MouseEvent)) return true;
MouseEvent e = (MouseEvent)anEvent;
int row = rowAtPoint(e.getPoint());
if (row < 0 || row >= getRowCount()) return true;
VcsLogColumn<?> column = getVcsLogColumn(columnAtPoint(e.getPoint()));
if (column == null) return true;
VcsLogCellController controller = getController(column);
if (controller == null) return true;
return controller.shouldSelectCell(row, e);
}
@Override
public boolean stopCellEditing() {
return false;
}
@Override
public void cancelCellEditing() {
}
@Override
public void addCellEditorListener(CellEditorListener l) {
}
@Override
public void removeCellEditorListener(CellEditorListener l) {
}
}
private class MyProgressListener implements VcsLogProgress.ProgressListener {
@Override
public void progressStarted(@NotNull Collection<? extends VcsLogProgress.ProgressKey> keys) {
progressChanged(keys);
}
@Override
public void progressChanged(@NotNull Collection<? extends VcsLogProgress.ProgressKey> keys) {
if (VcsLogUiUtil.isProgressVisible(keys, myId)) {
getEmptyText().setText(VcsLogBundle.message("vcs.log.loading.status"));
}
else {
updateEmptyText();
}
}
@Override
public void progressStopped() {
updateEmptyText();
}
}
private class MyTableColumnModel extends DefaultTableColumnModel {
@NotNull private final VcsLogUiProperties myProperties;
MyTableColumnModel(@NotNull VcsLogUiProperties properties) {
myProperties = properties;
}
@Override
public void propertyChange(PropertyChangeEvent evt) {
// for some reason if I just add a PropertyChangeListener to a column it's not called
// and TableColumnModelListener.columnMarginChanged does not provide any information which column was changed
if (getTableHeader().getResizingColumn() == null) return;
if ("width".equals(evt.getPropertyName())) {
for (VcsLogColumn<?> logColumn : VcsLogColumnManager.getInstance().getCurrentDynamicColumns()) {
TableColumn column = getTableColumn(logColumn);
if (evt.getSource().equals(column)) {
setWidth(logColumn, myProperties, column.getWidth());
}
}
}
super.propertyChange(evt);
}
@Override
public void moveColumn(int columnIndex, int newIndex) {
VcsLogColumn<?> column = getVcsLogColumn(columnIndex);
if (column == null ||
column == Root.INSTANCE || getVcsLogColumn(newIndex) == Root.INSTANCE ||
!supportsColumnsReordering(myProperties)) {
return;
}
super.moveColumn(columnIndex, newIndex);
VcsLogColumnUtilKt.moveColumn(myProperties, column, newIndex);
}
}
private final class MyTopBottomBorder implements Border {
@NotNull private final JBInsets myInsets;
private MyTopBottomBorder(int top, int bottom) {
myInsets = JBUI.insets(top, 0, bottom, 0);
}
@Override
public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
if (myInsets.top > 0) paintTopBottomBorder(g, x, y, width, myInsets.top, true);
if (myInsets.bottom > 0) paintTopBottomBorder(g, x, y + height - myInsets.bottom, width, myInsets.bottom, false);
}
@Override
public Insets getBorderInsets(Component c) {
return myInsets;
}
@Override
public boolean isBorderOpaque() {
return true;
}
}
private class MyCurrentColumnsListener implements VcsLogColumnManager.CurrentColumnsListener {
@Override
public void columnAdded(@NotNull VcsLogColumn<?> column) {
onColumnOrderSettingChanged();
}
@Override
public void columnRemoved(@NotNull VcsLogColumn<?> column) {
myTableColumns.remove(column);
myInitializedColumns.remove(column);
onColumnOrderSettingChanged();
}
}
@NotNull
public static Color getSelectionForeground(boolean hasFocus) {
return hasFocus ? SELECTION_FOREGROUND : SELECTION_FOREGROUND_INACTIVE;
}
}
| {
"content_hash": "b6cf4c3117bdd9485bc7685b1ae9581a",
"timestamp": "",
"source": "github",
"line_count": 1071,
"max_line_length": 136,
"avg_line_length": 37.136321195144724,
"alnum_prop": 0.6965780806074473,
"repo_name": "jwren/intellij-community",
"id": "a01dedfbbc0cf740cc3a366d1e4b9740cf472885",
"size": "39932",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "platform/vcs-log/impl/src/com/intellij/vcs/log/ui/table/VcsLogGraphTable.java",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
import { RequestAuthOptionsInterface } from '.';
/**
* Request options.
* @interface RequestOptionsInterface
*/
interface RequestOptionsInterface {
/**
* Request headers.
* @type {Object}
*/
headers: {};
/**
* Request authentication options.
* @type {RequestAuthOptionsInterface}
*/
auth: RequestAuthOptionsInterface;
/**
* Convert request body to JSON string?
* @type {Boolean}
*/
json: boolean;
}
export { RequestOptionsInterface };
| {
"content_hash": "b5261aab6f72b744eaa769208b03f5bb",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 48,
"avg_line_length": 17.814814814814813,
"alnum_prop": 0.659043659043659,
"repo_name": "gambio/node-gambio-api-client",
"id": "07ca92d74df04f41f8995b7c1fe5855841af1937",
"size": "481",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "source/Interfaces/RequestOptionsInterface.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "89524"
},
{
"name": "TypeScript",
"bytes": "65639"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WSMCTuristic_CentroHistorico.BO
{
public class SitioBO
{
private int _idSitio;
private string _nombreSitio;
private string _descripcionSitio;
private string _historia;
private string _direccion;
private decimal _longitudSitio;
private decimal _latitudSitio;
private byte[] _fotoSitio;
private string _sucesoImportante;
private int _idTipoSitio;
public int IdTipoSitio
{
get { return _idTipoSitio; }
set { _idTipoSitio = value; }
}
public string SucesoImportante
{
get { return _sucesoImportante; }
set { _sucesoImportante = value; }
}
public byte[] FotoSitio
{
get { return _fotoSitio; }
set { _fotoSitio = value; }
}
public decimal LatitudSitio
{
get { return _latitudSitio; }
set { _latitudSitio = value; }
}
public decimal LongitudSitio
{
get { return _longitudSitio; }
set { _longitudSitio = value; }
}
public string Direccion
{
get { return _direccion; }
set { _direccion = value; }
}
public string Historia
{
get { return _historia; }
set { _historia = value; }
}
public string DescripcionSitio
{
get { return _descripcionSitio; }
set { _descripcionSitio = value; }
}
public string NombreSitio
{
get { return _nombreSitio; }
set { _nombreSitio = value; }
}
public int IdSitio
{
get { return _idSitio; }
set { _idSitio = value; }
}
}
} | {
"content_hash": "45aa87277698c7cb478734e2ec587084",
"timestamp": "",
"source": "github",
"line_count": 81,
"max_line_length": 46,
"avg_line_length": 23.691358024691358,
"alnum_prop": 0.5112037519541428,
"repo_name": "JoseLuisPucChan/Proyecto4Cuatrimestre",
"id": "701ce4eea1aba063145b0574b628b9f21936fd37",
"size": "1921",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Proyecto integrador/Web/Proyecto 1.2 proyeco Reparado/MCTuristic_Centro_Historico/WSMCTuristic_CentroHistorico/BO/SitioBO.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "586832"
},
{
"name": "C#",
"bytes": "812479"
},
{
"name": "CSS",
"bytes": "1237225"
},
{
"name": "HTML",
"bytes": "6193174"
},
{
"name": "JavaScript",
"bytes": "3865649"
},
{
"name": "SQLPL",
"bytes": "4339"
}
],
"symlink_target": ""
} |
FOUNDATION_EXPORT double Pods_soca_iOSVersionNumber;
FOUNDATION_EXPORT const unsigned char Pods_soca_iOSVersionString[];
| {
"content_hash": "0101ee2d6c60dd106fb68c0348657e66",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 67,
"avg_line_length": 40.666666666666664,
"alnum_prop": 0.8442622950819673,
"repo_name": "zhuhaow/soca",
"id": "1159ca68f6a2d9a9fe8b8817115d9c84fa176241",
"size": "148",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Pods/Target Support Files/Pods-soca-iOS/Pods-soca-iOS-umbrella.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "275459"
},
{
"name": "Ruby",
"bytes": "320"
},
{
"name": "Swift",
"bytes": "185936"
}
],
"symlink_target": ""
} |
layout: page
title: Dyer Aerospace Executive Retreat
date: 2016-05-24
author: Peter Barr
tags: weekly links, java
status: published
summary: Integer mi ligula, gravida sit amet pellentesque ut.
banner: images/banner/office-01.jpg
booking:
startDate: 10/08/2016
endDate: 10/09/2016
ctyhocn: BUFARHX
groupCode: DAER
published: true
---
Morbi sit amet libero id sem molestie pulvinar in eget diam. Phasellus facilisis nunc a risus scelerisque lobortis. Cras tristique tempus elit quis condimentum. Sed ultrices viverra ipsum sed finibus. Morbi nec arcu sit amet felis varius ultrices eget eget odio. Nulla facilisis erat nec vehicula imperdiet. Praesent in leo a mi tempus iaculis. Integer sollicitudin blandit purus eu pretium. Aenean pulvinar eros id nisl finibus suscipit.
* Praesent porta leo luctus dolor maximus, congue ultricies urna laoreet
* Mauris bibendum velit nec leo placerat, id varius massa ultrices
* Proin at nisi et enim molestie finibus.
Proin pulvinar dolor a neque congue, facilisis posuere mauris fringilla. Cras sodales magna ut eros egestas vehicula. Proin porttitor luctus quam, et porttitor dui pellentesque et. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nunc blandit mi a ex commodo maximus. Vestibulum lacinia, elit varius vestibulum vehicula, enim nulla sollicitudin quam, elementum mattis leo enim eget massa. Pellentesque a orci lobortis lorem eleifend gravida id fermentum libero.
Vivamus cursus, metus nec ornare auctor, est justo cursus eros, ut cursus arcu nibh a libero. Praesent sed lobortis lacus, vel sodales turpis. Nulla dapibus sapien orci. Suspendisse eu diam elit. Ut et suscipit sem. Nullam vel urna mollis, molestie erat sed, feugiat justo. Integer elit ligula, auctor eget eros eget, condimentum iaculis eros. Maecenas volutpat rhoncus massa, vitae vulputate leo. Nam laoreet, velit non volutpat dapibus, dolor ex ullamcorper velit, sed rutrum orci purus non urna. Aenean varius placerat justo. Vivamus ac ullamcorper quam, sit amet volutpat elit. Aliquam erat volutpat. Curabitur congue metus non magna condimentum elementum. Etiam at finibus lorem, id sodales massa. Curabitur mattis magna dui, a vestibulum nisl pharetra ut.
| {
"content_hash": "4c1a0eacedf5d84c360e4a3705a974f0",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 761,
"avg_line_length": 96.78260869565217,
"alnum_prop": 0.8104222821203954,
"repo_name": "KlishGroup/prose-pogs",
"id": "5d099a5f53881b19c30fc5f5f56f5dae0e95ee00",
"size": "2230",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": "pogs/B/BUFARHX/DAER/index.md",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
/**
* @param {import('mongoose').Connection} connection
*/
function validate (connection) {
/**
* @this import('mongoose').MongooseDocument
*/
async function run () {
const feed = await connection.model('feed').findById(this.feed).exec()
if (!feed) {
throw new Error(`FilteredFormat's specified feed ${this.feed} was not found`)
}
const current = await connection.model('filtered_format').findById(this._id).exec()
// If current doesn't exist, then it's a new subscriber
if (current && current.feed !== this.feed) {
throw new Error('Feed cannot be changed')
}
}
return run
}
module.exports = {
validate
}
| {
"content_hash": "f852bbd425d9acf58323ad82af9770ce",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 87,
"avg_line_length": 27.666666666666668,
"alnum_prop": 0.6460843373493976,
"repo_name": "synzen/Discord.RSS",
"id": "a92c3d4862bb3d2248c88a6e3377f9e46081702e",
"size": "664",
"binary": false,
"copies": "1",
"ref": "refs/heads/dev",
"path": "src/models/middleware/FilteredFormat.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "620701"
},
{
"name": "Dockerfile",
"bytes": "356"
},
{
"name": "HTML",
"bytes": "4115"
},
{
"name": "JavaScript",
"bytes": "2185523"
}
],
"symlink_target": ""
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="en-US" xmlns="http://www.w3.org/1999/xhtml" xml:lang=
"en-US">
<head>
<title>Setting Up the Web Site</title><script>var _hmt = _hmt || [];(function() {var hm = document.createElement("script");hm.src = "//hm.baidu.com/hm.js?dd1361ca20a10cc161e72d4bc4fef6df";var s = document.getElementsByTagName("script")[0];s.parentNode.insertBefore(hm, s);})();</script>
<link rel="stylesheet" type="text/css" href="../../../../technotes/css/guide.css" />
</head>
<body>
<!-- STATIC HEADER -->
<!-- header start -->
<div id="javaseheader">
<div id="javaseheaderlogo">
<img src="../../../../images/javalogo.gif"
alt="Java logo" />
</div>
<div id="javaseheaderindex">
<a href=
"../../../../index.html">Documentation Contents</a>
</div>
<div class="clear"></div>
</div>
<!-- header end -->
<p><small><a href="contents.html">< Contents</a></small></p>
<h1>Setting Up the Web Site</h1>
<h2><br />
<a name="intro" id="intro"></a>Introduction</h2>
<p>Java Web Start leverages existing Internet technology, such as
the HTTP protocol and Web servers, so existing infrastructure for
deploying HTML-based contents can be reused to deploy Java
Technology-based applications using Java Web Start.</p>
<p>In order to deploy your application to client machines, you must
make sure that all files containing your application are accessible
through a Web server. This typically amounts to copying one or more
JAR files, along with a JNLP file, into the Web server's
directories. The set-up required for enabling the Web site to
support Java Web Start is very similar to deploying HTML-based
contents. The only caveat is that a new MIME type needs to be
configured for the Web server.</p>
<h2><a name="steps" id="steps"></a>Basic Steps</h2>
<p><b>1. Configure the Web server to use the Java Web Start MIME
type</b></p>
<p>Configure the Web server so that all files with the
<tt>.jnlp</tt> file extension are set to the
<tt>application/x-java-jnlp-file</tt> MIME type.</p>
<p>Most Web browsers use the MIME type returned with the contents
from the Web server to determine how to handle the particular
content. The server must return
<tt>application/x-java-jnlp-file</tt> MIME type for JNLP files in
order for Java Web Start to be invoked.</p>
<p>Each Web server has a specific way in which to add MIME types.
For example, for the Apache Web server you must add the following
line to the <tt>.mime.types</tt> configuration file:</p>
<p><tt>application/x-java-jnlp-file JNLP</tt></p>
<p>Check the documentation for the specifics of your Web
server.</p>
<p><b>2. Create a JNLP file for the application</b></p>
<p>The easiest way to create this file is to modify an existing
JNLP file to your requirements.</p>
<p>The syntax and format for the JNLP file is described in a later
<a href="syntax.html">section</a>.</p>
<p><b>3. Make the application accessible on the Web server</b></p>
<p>Ensure your application's JAR files and the JNLP file are
accessible at the URLs listed in the JNLP file.</p>
<p><b>4. Create the web page that launches the application</b></p>
<p>See the next chapter, <a href="launch.html">Creating the Web
Page that launches the Application</a>, for details on step 4.</p>
<!-- footer start -->
<div id="javasefooter">
<div class="hr">
<hr /></div>
<div id="javasecopyright">
<img id="oraclelogofooter" src=
"../../../../images/oraclelogo.gif" alt="Oracle and/or its affiliates"
border="0" width="100" height="29" name=
"oraclelogofooter" />
<a href="../../../../legal/cpyr.html">Copyright
©</a> 1993, 2015, Oracle and/or its affiliates. All rights
reserved.</div>
<div id="javasecontactus">
<a href=
"http://docs.oracle.com/javase/feedback.html">Contact
Us</a>
</div>
</div>
<!-- footer end -->
<!-- STATIC FOOTER -->
</body>
</html>
| {
"content_hash": "f38072d945be1b1729e65e506ada40df",
"timestamp": "",
"source": "github",
"line_count": 98,
"max_line_length": 286,
"avg_line_length": 39.55102040816327,
"alnum_prop": 0.7102683178534571,
"repo_name": "piterlin/piterlin.github.io",
"id": "847d9d89dad30bc4c76a17c8f76faa2e05fcf272",
"size": "3876",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "doc/technotes/guides/javaws/developersguide/setup.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "479"
},
{
"name": "HTML",
"bytes": "9480869"
},
{
"name": "JavaScript",
"bytes": "246"
}
],
"symlink_target": ""
} |
/* @flow */
'use strict';
import _ from 'underscore';
import Q from 'q';
import {Events} from 'backbone';
import ContigInterval from '../ContigInterval';
import BamFile from '../data/bam';
import RemoteFile from '../RemoteFile';
import type {GenomeRange} from '../types';
import type {Alignment} from '../Alignment';
import type {DataSource} from './DataSource';
// Genome ranges are rounded to multiples of this for fetching.
// This reduces network activity while fetching.
// TODO: tune this value
var BASE_PAIRS_PER_FETCH = 100;
var ZERO_BASED = false;
function createFromBamFile(remoteSource: BamFile): DataSource<Alignment> {
var reads: {[key:string]: Alignment} = {};
// Mapping from contig name to canonical contig name.
var contigNames: {[key:string]: string} = {};
// Ranges for which we have complete information -- no need to hit network.
var coveredRanges: ContigInterval<string>[] = [];
function addRead(read: Alignment) {
var key = read.getKey();
if (!reads[key]) {
reads[key] = read;
}
}
function saveContigMapping(header: Object) {
header.references.forEach(ref => {
var name = ref.name;
contigNames[name] = name;
contigNames['chr' + name] = name;
if (name.slice(0, 3) == 'chr') {
contigNames[name.slice(3)] = name;
}
});
}
function fetch(range: GenomeRange) {
var refsPromise = !_.isEmpty(contigNames) ? Q.when() :
remoteSource.header.then(saveContigMapping);
// For BAMs without index chunks, we need to fetch the entire BAI file
// before we can know how large the BAM header is. If the header is
// pending, it's almost certainly because the BAI file is in flight.
Q.when().then(() => {
if (refsPromise.isPending() && !remoteSource.hasIndexChunks) {
o.trigger('networkprogress', {
status: 'Fetching BAM index -- use index chunks to speed this up'
});
}
}).done();
return refsPromise.then(() => {
var contigName = contigNames[range.contig];
var interval = new ContigInterval(contigName, range.start, range.stop);
// Check if this interval is already in the cache.
// If not, immediately "cover" it to prevent duplicate requests.
if (interval.isCoveredBy(coveredRanges)) {
return Q.when();
}
interval = interval.round(BASE_PAIRS_PER_FETCH, ZERO_BASED);
var newRanges = interval.complementIntervals(coveredRanges);
coveredRanges.push(interval);
coveredRanges = ContigInterval.coalesce(coveredRanges);
return Q.all(newRanges.map(range =>
remoteSource.getFeaturesInRange(range)
.progress(progressEvent => {
o.trigger('networkprogress', progressEvent);
})
.then(reads => {
reads.forEach(read => addRead(read));
o.trigger('networkdone');
o.trigger('newdata', range);
})));
});
}
function getFeaturesInRange(range: ContigInterval<string>): Alignment[] {
if (!range) return [];
if (_.isEmpty(contigNames)) return [];
var canonicalRange = new ContigInterval(contigNames[range.contig],
range.start(), range.stop());
return _.filter(reads, read => read.intersects(canonicalRange));
}
var o = {
rangeChanged: function(newRange: GenomeRange) {
fetch(newRange).done();
},
getFeaturesInRange,
// These are here to make Flow happy.
on: () => {},
once: () => {},
off: () => {},
trigger: (status: string, param: any) => {}
};
_.extend(o, Events); // Make this an event emitter
return o;
}
type BamSpec = {
url: string;
indexUrl: string;
indexChunks?: Object;
}
function create(spec: BamSpec): DataSource<Alignment> {
var url = spec.url;
if (!url) {
throw new Error(`Missing URL from track data: ${JSON.stringify(spec)}`);
}
var indexUrl = spec.indexUrl;
if (!indexUrl) {
throw new Error(`Missing indexURL from track data: ${JSON.stringify(spec)}`);
}
// TODO: this is overly repetitive, see flow issue facebook/flow#437
var bamFile = spec.indexChunks ?
new BamFile(new RemoteFile(url), new RemoteFile(indexUrl), spec.indexChunks) :
new BamFile(new RemoteFile(url), new RemoteFile(indexUrl));
return createFromBamFile(bamFile);
}
module.exports = {
create,
createFromBamFile
};
| {
"content_hash": "2910edb7dfa652734274a8e1113d8c23",
"timestamp": "",
"source": "github",
"line_count": 145,
"max_line_length": 84,
"avg_line_length": 30.455172413793104,
"alnum_prop": 0.6345108695652174,
"repo_name": "piotr-gawron/pileup.js",
"id": "848df9bb46cdb42f83e0785d01ee706d6c7df16d",
"size": "4416",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/main/sources/BamDataSource.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "7079"
},
{
"name": "HTML",
"bytes": "1024"
},
{
"name": "JavaScript",
"bytes": "537573"
},
{
"name": "Python",
"bytes": "2816"
},
{
"name": "Shell",
"bytes": "5947"
}
],
"symlink_target": ""
} |
var Licenses = angular.module('Licenses', []);
| {
"content_hash": "cb0b70f6da9ca7ce881feb35b3fea186",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 46,
"avg_line_length": 47,
"alnum_prop": 0.6808510638297872,
"repo_name": "tsiry95/openshift-strongloop-cartridge",
"id": "9510b137287640352f4012f2cb71643f21fe4bfe",
"size": "47",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "strongloop/node_modules/strong-arc/client/www/scripts/modules/licenses/licenses.module.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "2028852"
},
{
"name": "C++",
"bytes": "569460"
},
{
"name": "Groff",
"bytes": "4748"
},
{
"name": "HTML",
"bytes": "690"
},
{
"name": "JavaScript",
"bytes": "25268"
},
{
"name": "Shell",
"bytes": "13019"
}
],
"symlink_target": ""
} |
module Physiqual
class DataImputer
def initialize(data_service, imputers)
@data_service = data_service
@imputers = [imputers].flatten
end
def steps(from, to)
result = retrieve_data_from_service { |service| service.steps(from, to) }
impute_results(result)
end
def heart_rate(from, to)
result = retrieve_data_from_service { |service| service.heart_rate(from, to) }
impute_results(result)
end
def distance(from, to)
result = retrieve_data_from_service { |service| service.distance(from, to) }
impute_results(result)
end
def sleep(from, to)
result = retrieve_data_from_service { |service| service.sleep(from, to) }
impute_results(result)
end
def calories(from, to)
result = retrieve_data_from_service { |service| service.calories(from, to) }
impute_results(result)
end
def activities(from, to)
result = retrieve_data_from_service { |service| service.activities(from, to) }
impute_results(result)
end
private
def retrieve_data_from_service
raise 'No service defined' if @data_service.nil?
begin
yield(@data_service)
rescue Errors::NotSupportedError => e
Rails.logger.warn e.message
nil
end
end
def valid_result?(result)
!result.compact.blank?
end
def impute_results(results)
result_hash = Hash.new(-1)
return result_hash if results.nil?
# Map the results from an array of objects to a hash
results.each { |result| result_hash[result.end_date] = result.values.first }
@imputers.each do |imputer|
break unless result_hash.values.any? { |x| [nil, -1].include? x }
imputed_values = imputer.impute! result_hash.values.flatten
# key.first because an each on a hash gives an array [key, value]
result_hash.each_with_index { |key_value, index| result_hash[key_value.first] = imputed_values[index] }
end
result_hash
end
end
end
| {
"content_hash": "a3955cc7dea2fa6af1abeb44ec243af7",
"timestamp": "",
"source": "github",
"line_count": 70,
"max_line_length": 111,
"avg_line_length": 28.942857142857143,
"alnum_prop": 0.642152023692004,
"repo_name": "roqua/physiqual",
"id": "9a94ee4ca1da22eac682858c8f5fd7e3ccc9a83f",
"size": "2026",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/physiqual/data_imputer.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1372"
},
{
"name": "HTML",
"bytes": "9087"
},
{
"name": "JavaScript",
"bytes": "1234"
},
{
"name": "Ruby",
"bytes": "160020"
}
],
"symlink_target": ""
} |
FROM balenalib/orange-pi-lite-alpine:3.13-run
ENV GO_VERSION 1.17.7
# set up nsswitch.conf for Go's "netgo" implementation
# - https://github.com/golang/go/blob/go1.9.1/src/net/conf.go#L194-L275
# - docker run --rm debian:stretch grep '^hosts:' /etc/nsswitch.conf
RUN [ ! -e /etc/nsswitch.conf ] && echo 'hosts: files dns' > /etc/nsswitch.conf
# gcc for cgo
RUN apk add --no-cache git gcc ca-certificates
RUN fetchDeps='curl' \
&& set -x \
&& apk add --no-cache $fetchDeps \
&& mkdir -p /usr/local/go \
&& curl -SLO "http://resin-packages.s3.amazonaws.com/golang/v$GO_VERSION/go$GO_VERSION.linux-alpine-armv7hf.tar.gz" \
&& echo "052ef9c11ea2788e3c6c242c4b4a4beb9c461a96bab367315bfef515694633d7 go$GO_VERSION.linux-alpine-armv7hf.tar.gz" | sha256sum -c - \
&& tar -xzf "go$GO_VERSION.linux-alpine-armv7hf.tar.gz" -C /usr/local/go --strip-components=1 \
&& rm -f go$GO_VERSION.linux-alpine-armv7hf.tar.gz
ENV GOROOT /usr/local/go
ENV GOPATH /go
ENV PATH $GOPATH/bin:/usr/local/go/bin:$PATH
RUN mkdir -p "$GOPATH/src" "$GOPATH/bin" && chmod -R 777 "$GOPATH"
WORKDIR $GOPATH
CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"]
RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/613d8e9ca8540f29a43fddf658db56a8d826fffe/scripts/assets/tests/test-stack@golang.sh" \
&& echo "Running test-stack@golang" \
&& chmod +x test-stack@golang.sh \
&& bash test-stack@golang.sh \
&& rm -rf test-stack@golang.sh
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo $'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v7 \nOS: Alpine Linux 3.13 \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nGo v1.17.7 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo $'#!/bin/bash\nbalena-info\nbusybox ln -sf /bin/busybox /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& ln -f /bin/sh /bin/sh.real \
&& ln -f /bin/sh-shim /bin/sh | {
"content_hash": "ad0e542f625aa380ffa1d024155a749b",
"timestamp": "",
"source": "github",
"line_count": 42,
"max_line_length": 677,
"avg_line_length": 58.333333333333336,
"alnum_prop": 0.7179591836734693,
"repo_name": "resin-io-library/base-images",
"id": "5f08babaf0981ff20ed827c33551a07ac5cfe45f",
"size": "2471",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "balena-base-images/golang/orange-pi-lite/alpine/3.13/1.17.7/run/Dockerfile",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "71234697"
},
{
"name": "JavaScript",
"bytes": "13096"
},
{
"name": "Shell",
"bytes": "12051936"
},
{
"name": "Smarty",
"bytes": "59789"
}
],
"symlink_target": ""
} |
package org.apache.camel.processor;
import org.apache.camel.ContextTestSupport;
import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
import org.junit.Test;
public class OnExceptionContinueToRouteTest extends ContextTestSupport {
@Test
public void testOnExceptionContinueToRoute() throws Exception {
getMockEndpoint("mock:a").expectedBodiesReceived("Hello World");
getMockEndpoint("mock:b").expectedBodiesReceived("Hello World");
getMockEndpoint("mock:catch").expectedBodiesReceived("Hello World");
getMockEndpoint("mock:catch").message(0).exchangeProperty(Exchange.EXCEPTION_CAUGHT).isInstanceOf(IllegalArgumentException.class);
getMockEndpoint("mock:c").expectedBodiesReceived("Hello World");
getMockEndpoint("mock:c").message(0).exchangeProperty(Exchange.EXCEPTION_CAUGHT).isInstanceOf(IllegalArgumentException.class);
template.sendBody("direct:a", "Hello World");
assertMockEndpointsSatisfied();
}
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
onException(IllegalArgumentException.class).continued(true).to("mock:catch");
from("direct:a")
.to("mock:a")
.to("direct:b")
.to("direct:c");
from("direct:b")
.to("mock:b")
.throwException(new IllegalArgumentException("Damn"));
from("direct:c")
.to("mock:c");
}
};
}
} | {
"content_hash": "a07aac33e76ed55544a1a1976d77f0c0",
"timestamp": "",
"source": "github",
"line_count": 46,
"max_line_length": 138,
"avg_line_length": 36.608695652173914,
"alnum_prop": 0.6395486935866983,
"repo_name": "punkhorn/camel-upstream",
"id": "8044285f455630136af0a9933fdfb45aabe74e8e",
"size": "2487",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "core/camel-core/src/test/java/org/apache/camel/processor/OnExceptionContinueToRouteTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Apex",
"bytes": "6519"
},
{
"name": "Batchfile",
"bytes": "1518"
},
{
"name": "CSS",
"bytes": "16394"
},
{
"name": "Elm",
"bytes": "10852"
},
{
"name": "FreeMarker",
"bytes": "11410"
},
{
"name": "Groovy",
"bytes": "14490"
},
{
"name": "HTML",
"bytes": "896075"
},
{
"name": "Java",
"bytes": "70312352"
},
{
"name": "JavaScript",
"bytes": "90399"
},
{
"name": "Makefile",
"bytes": "513"
},
{
"name": "Shell",
"bytes": "17108"
},
{
"name": "Tcl",
"bytes": "4974"
},
{
"name": "Thrift",
"bytes": "6979"
},
{
"name": "XQuery",
"bytes": "546"
},
{
"name": "XSLT",
"bytes": "270186"
}
],
"symlink_target": ""
} |
<!DOCTYPE html><html><head><meta charset="utf-8" />
<meta http-equiv="refresh" content="0;url=/place/egypt/emissions/" />
</head></html> | {
"content_hash": "e0e02c7d2b62bf3b5cd8a3d4fac0648b",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 69,
"avg_line_length": 45.333333333333336,
"alnum_prop": 0.6764705882352942,
"repo_name": "okfn/opendataindex-2015",
"id": "ac13cbdda5d1379d92c356acbdb75b6602255899",
"size": "136",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": "country/overview/Egypt/emissions/index.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "277465"
},
{
"name": "HTML",
"bytes": "169425658"
},
{
"name": "JavaScript",
"bytes": "37060"
}
],
"symlink_target": ""
} |
<%_ for (idx in fields) {
if (fields[idx].fieldIsEnum) { _%>
const enum <%= fields[idx].fieldType %> {<%
const enums = fields[idx].fieldValues.split(',');
for (var i = 0; i < enums.length; i++) { %>
'<%= enums[i] %>'<%if (i < enums.length - 1) { %>,<% } } _%>
};
<%_ } } _%>
<%_ if (dto == "no") {
for (var rel of differentRelationships) { _%>
import { <%= rel.otherEntityNameCapitalized %> } from '../<%= rel.otherEntityModulePath %>';
<%_ }
}
var variables = [];
var tsKeyType;
if (pkType == 'String') {
tsKeyType = 'string';
} else {
tsKeyType = 'number';
}
variables.push('id?: ' + tsKeyType);
for (idx in fields) {
var fieldType = fields[idx].fieldType;
var fieldName = fields[idx].fieldName;
var tsType;
if (fields[idx].fieldIsEnum) {
tsType = fieldType;
} else if (fieldType == 'ZonedDateTime') {
tsType = 'any';
} else if (fieldType == 'Boolean') {
tsType = 'boolean';
} else if (fieldType == 'Double' || fieldType == 'Float' || fieldType == 'Long' || fieldType == 'Integer' || fieldType == 'BigDecimal') {
tsType = 'number';
} else if (fieldType == 'String' || fieldType == 'UUID') {
tsType = 'string';
} else { //(fieldType === 'byte[]' || fieldType === 'ByteBuffer') && fieldTypeBlobContent == 'any' || (fieldType === 'byte[]' || fieldType === 'ByteBuffer') && fieldTypeBlobContent == 'image' || fieldType == 'LocalDate'
tsType = 'any';
}
variables.push(fieldName + '?: ' + tsType);
}
for (idx in relationships) {
var fieldType;
var fieldName;
if (dto == "no") {
fieldType = relationships[idx].otherEntityNameCapitalized;
fieldName = relationships[idx].relationshipFieldName;
} else {
fieldType = tsKeyType;
fieldName = relationships[idx].relationshipFieldName + "Id";
}
variables.push(fieldName + '?: ' + fieldType);
}_%>
export class <%= entityAngularName %> {
constructor(<% for (idx in variables) { %>
public <%- variables[idx] %>,<% } %>
) { }
}
| {
"content_hash": "9d90c36763173ce04f2416a993859c5f",
"timestamp": "",
"source": "github",
"line_count": 58,
"max_line_length": 223,
"avg_line_length": 35.63793103448276,
"alnum_prop": 0.5645863570391872,
"repo_name": "baskeboler/generator-jhipster",
"id": "65d2ad352d29555a8c7773ab99424c9403eceb1a",
"size": "2067",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "generators/entity/templates/client/angular/src/main/webapp/app/entities/_entity.model.ts",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "5006"
},
{
"name": "CSS",
"bytes": "41374"
},
{
"name": "Gherkin",
"bytes": "179"
},
{
"name": "Groovy",
"bytes": "7910"
},
{
"name": "HTML",
"bytes": "344245"
},
{
"name": "Java",
"bytes": "563589"
},
{
"name": "JavaScript",
"bytes": "884609"
},
{
"name": "Scala",
"bytes": "6262"
},
{
"name": "Shell",
"bytes": "24832"
},
{
"name": "TypeScript",
"bytes": "253729"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
Index Fungorum
#### Published in
null
#### Original name
Verrucaria papillosa var. thalassina Zahlbr.
### Remarks
null | {
"content_hash": "10ea1e20de71c7a434714403e36b2225",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 44,
"avg_line_length": 11.461538461538462,
"alnum_prop": 0.7248322147651006,
"repo_name": "mdoering/backbone",
"id": "21bfb1b09546c0e6e37ac1333e127d980ad0c835",
"size": "217",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Fungi/Ascomycota/Eurotiomycetes/Verrucariales/Verrucariaceae/Verrucaria/Verrucaria papillosa/Verrucaria papillosa thalassina/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
require File.dirname(__FILE__) + '/../test_helper'
class HTTPAuthTest < Test::Unit::TestCase
context "Creating new instance" do
should "should take user and password" do
twitter = Twitter::HTTPAuth.new('username', 'password')
twitter.username.should == 'username'
twitter.password.should == 'password'
end
should "accept options" do
twitter = Twitter::HTTPAuth.new('username', 'password', :ssl => true)
twitter.options.should == {:ssl => true}
end
should "default ssl to false" do
twitter = Twitter::HTTPAuth.new('username', 'password')
twitter.options[:ssl].should be(false)
end
should "use https if ssl is true" do
Twitter::HTTPAuth.expects(:base_uri).with('https://twitter.com')
twitter = Twitter::HTTPAuth.new('username', 'password', :ssl => true)
end
should "use http if ssl is false" do
Twitter::HTTPAuth.expects(:base_uri).with('http://twitter.com')
twitter = Twitter::HTTPAuth.new('username', 'password', :ssl => false)
end
end
context "Client methods" do
setup do
@twitter = Twitter::HTTPAuth.new('username', 'password')
end
should "not throw error when accessing response message" do
stub_get('http://twitter.com:80/statuses/user_timeline.json', 'user_timeline.json')
response = @twitter.get('/statuses/user_timeline.json')
response.message.should == 'OK'
end
should "be able to get" do
stub_get('http://username:password@twitter.com:80/statuses/user_timeline.json', 'user_timeline.json')
response = @twitter.get('/statuses/user_timeline.json')
response.should == fixture_file('user_timeline.json')
end
should "be able to get with headers" do
@twitter.class.expects(:get).with(
'/statuses/user_timeline.json', {
:basic_auth => {:username => 'username', :password => 'password'},
:headers => {'Foo' => 'Bar'}
}
).returns(fixture_file('user_timeline.json'))
@twitter.get('/statuses/user_timeline.json', {'Foo' => 'Bar'})
end
should "be able to post" do
stub_post('http://username:password@twitter.com:80/statuses/update.json', 'status.json')
response = @twitter.post('/statuses/update.json', :text => 'My update.')
response.should == fixture_file('status.json')
end
should "be able to post with headers" do
@twitter.class.expects(:post).with(
'/statuses/update.json', {
:headers => {'Foo' => 'Bar'},
:body => {:text => 'My update.'},
:basic_auth => {:username => 'username', :password => 'password'}
}
).returns(fixture_file('status.json'))
@twitter.post('/statuses/update.json', {:text => 'My update.'}, {'Foo' => 'Bar'})
end
end
end | {
"content_hash": "072e4426a3ef677c47f806e473b6fd6f",
"timestamp": "",
"source": "github",
"line_count": 76,
"max_line_length": 107,
"avg_line_length": 37.28947368421053,
"alnum_prop": 0.6118560338743825,
"repo_name": "paulsingh/twitter",
"id": "affd8e94247fdf50cc6cca25615e1b463bb4b39e",
"size": "2834",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/twitter/httpauth_test.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "48250"
}
],
"symlink_target": ""
} |
// License: Apache 2.0. See LICENSE file in root directory.
// Copyright(c) 2016 Intel Corporation. All Rights Reserved.
/**
* \file projection_interface.h
* @brief
* Describes the \c rs::core::projection_interface class.
*
* Defines mapping between pixel planes and real world, mapping between color and depth cameras with given calibration parameters.
*/
#pragma once
#include "rs/core/status.h"
#include "rs/core/types.h"
#include "rs/core/image_interface.h"
#ifdef WIN32
#ifdef realsense_projection_EXPORTS
#define DLL_EXPORT __declspec(dllexport)
#else
#define DLL_EXPORT __declspec(dllimport)
#endif /* realsense_projection_EXPORTS */
#else /* defined (WIN32) */
#define DLL_EXPORT
#endif
DLL_EXPORT extern "C" {
void* rs_projection_create_instance_from_intrinsics_extrinsics(rs::core::intrinsics *colorIntrinsics, rs::core::intrinsics *depthIntrinsics, rs::core::extrinsics *extrinsics);
}
namespace rs
{
namespace core
{
/**
* \brief
* Defines mapping between cameras and projection to and unprojection from real world.
*
* The real world coordinate system is the right-handed coordinate system.
* The interface requires calibration data of each sensor intrinsic parameters, which describe the camera model,
* and extrinsic parameters, which describe the transformation between two sensors coordinate systems.
*
* Call the \c rs::core::projection::create_instance() method
* to create an instance of this interface.
*/
class DLL_EXPORT projection_interface : public release_interface
{
public:
/**
* @brief Maps depth coordinates to color coordinates for a few pixels.
*
* Retrieve color coordinates based on provided depth coordinates and the depth value of the pixel.
* This method has optimized performance for a few pixels.
* @param[in] npoints Number of pixels to be mapped
* @param[in] pos_uvz Array of depth coordinates and depth value in the \c Point3DF32 structure
* @param[out] pos_ij Array of color coordinates to be returned
* @return status_no_error Successful execution
* @return status_param_unsupported \c npoints value passed equals 0 or depth value is less than <tt>(float)2e-38 </tt> for a certain point.
* @return status_handle_invalid Invalid in or out array passed as parameter
* @return status_data_unavailable Incorrect depth or color data passed in projection initialization
*/
virtual status map_depth_to_color(int32_t npoints, point3dF32 *pos_uvz, pointF32 *pos_ij) = 0;
/**
* @brief Maps color coordinates to depth coordinates for a few pixels.
*
* Retrieve depth coordinates based on provided color coordinates.
* This method has optimized performance for a few pixels.
* This method creates UV Map to perform the mapping.
* @param[in] depth Depth map image
* @param[in] npoints Number of pixels to be mapped
* @param[in] pos_ij Array of color coordinates
* @param[out] pos_uv Array of depth coordinates to be returned
* @return status_no_error Successful execution
* @return status_param_unsupported \c npoints value passed equals 0 or depth value is less than <tt>(float)2e-38 </tt> for a certain point.
* @return status_handle_invalid Invalid in or out array passed as parameter
* @return status_data_unavailable Incorrect depth or color data passed in projection initialization
*/
virtual status map_color_to_depth(image_interface *depth, int32_t npoints, pointF32 *pos_ij, pointF32 *pos_uv) = 0;
/**
* @brief Maps depth coordinates to world coordinates for a few pixels.
*
* Deproject camera coordinate system (depth image) to real world coordinate system (camera) with the origin at the center of the camera sensor
* for a number of points.
* The real world coordinate system is the right-handed coordinate system.
* This method has optimized performance for a few points.
* @param[in] npoints Number of points to be deprojected.
* @param[in] pos_uvz Array of depth pixel coordinates and depth value in the \c Point3DF32 structure.
* @param[out] pos3d Array of world point coordinates to be returned, in millimeters
* @return status_no_error Successful execution.
* @return status_param_unsupported \c npoints value passed equals 0
* @return status_handle_invalid Invalid in or out array passed as parameter
* @return status_data_unavailable Incorrect depth or color data passed in projection initialization.
*/
virtual status project_depth_to_camera(int32_t npoints, point3dF32 *pos_uvz, point3dF32 *pos3d) = 0;
/**
* @brief Deprojects color image pixels to camera (real world) points.
*
* Deproject camera coordinate system (color image) to real world coordinate system (camera) with the origin at the center of the camera sensor
* for a number of points.
* The real world coordinate system is the right-handed coordinate system.
* This method has optimized performance for a few points.
* @param[in] npoints Number of points to be deprojected
* @param[in] pos_ijz Array of color pixel coordinates and depth value in the \c Point3DF32 structure.
* @param[out] pos3d Array of camera point coordinates to be returned, in millimeters
* @return status_no_error Successful execution
* @return status_param_unsupported \c npoints value passed equals 0
* @return status_handle_invalid Invalid in or out array passed as parameter
* @return status_data_unavailable Incorrect depth or color data passed in projection initialization
*/
virtual status project_color_to_camera(int32_t npoints, point3dF32 *pos_ijz, point3dF32 *pos3d) = 0;
/**
* @brief Projects camera (real world) points to depth image pixels.
*
* Project real world coordinate system (camera) to camera coordinate system (depth image) for a number of points.
* The real world coordinate system is expected to be the right-handed coordinate system.
* This method has optimized performance for a few points.
* @param[in] npoints Number of points to be projected
* @param[in] pos3d Array of world point coordinates, in millimeters
* @param[out] pos_uv Array of depth pixel coordinates to be returned
* @return status_no_error Successful execution
* @return status_param_unsupported \c npoints value passed equals 0 or depth value is less than <tt>(float)2e-38 </tt> for a certain point.
* @return status_handle_invalid Invalid in or out array passed as parameter
* @return status_data_unavailable Incorrect depth or color data passed in projection initialization
*/
virtual status project_camera_to_depth(int32_t npoints, point3dF32 *pos3d, pointF32 *pos_uv) = 0;
/**
* @brief Projects camera (real world) points to corresponding color image pixels.
*
* Project real world coordinate system (camera) to camera coordinate system (color image) for a number of points.
* The real world coordinate system is expected to be the right-handed coordinate system.
* This method has optimized performance for a few points.
* @param[in] npoints Number of points to be mapped
* @param[in] pos3d Array of world point coordinates, in millimeters
* @param[out] pos_ij Array of color pixel coordinates, to be returned
* @return status_no_error Successful execution
* @return status_param_unsupported \c npoints value passed equals 0 or depth value is less than <tt>(float)2e-38 </tt> for a certain point.
* @return status_handle_invalid Invalid in or out array passed as parameter
* @return status_data_unavailable Incorrect depth or color data passed in projection initialization
*/
virtual status project_camera_to_color(int32_t npoints, point3dF32 *pos3d, pointF32 *pos_ij) = 0;
/**
* @brief Retrieves UV map for specific depth image.
*
* Retrieve the UV Map for the specific depth image. The UV Map is a \c PointF32 array of depth size \c width*height.
* Each UV Map pixel contains the corresponding normalized color image pixel coordinates which match the depth image pixel with the same
* image coordinates as the UV map pixel.
* @param[in] depth Depth image instance
* @param[out] uvmap UV map, to be returned
* @return status_no_error Successful execution
* @return status_handle_invalid Invalid depth image or uvmap array passed as parameter
* @return status_data_unavailable Incorrect depth or color data passed in projection initialization
*/
virtual status query_uvmap(image_interface *depth, pointF32 *uvmap) = 0;
/**
* @brief Retrieves Inversed UV map for specific depth image.
*
* The Inversed UV Map is a \c PointF32 array of color size \c width*height.
* Each Inversed UV map pixel contains the corresponding normalized depth image pixel coordinates which match the color image pixel with the same
* image coordinates as the Inversed UV map pixel.
* @param[in] depth Depth image instance
* @param[out] inv_uvmap Inversed UV Map, to be returned
* @return status_no_error Successful execution
* @return status_handle_invalid Invalid depth image or invuvmap array passed as parameter
* @return status_data_unavailable Incorrect depth or color data passed in projection initialization
*/
virtual status query_invuvmap(image_interface *depth, pointF32 *inv_uvmap) = 0;
/**
* @brief Retrieves 3D points array of depth resolution with units in millimeters.
*
* Retrieve the vertices for the specific depth image. The vertices is a \c Point3DF32 array of depth
* size \c width*height. The world coordinates units are in millimeters.
* The points array coordinates are in the real world coordinate system with the origin at the center of the camera sensor.
* The real world coordinate system is the right-handed coordinate system.
* @param[in] depth Depth image instance
* @param[out] vertices 3D vertices (real world points) to be returned, in real world coordinates
* @return status_no_error Successful execution
* @return status_handle_invalid Invalid depth image or vertices array passed as parameter
* @return status_data_unavailable Incorrect depth or color data passed in projection initialization
*/
virtual status query_vertices(image_interface *depth, point3dF32 *vertices) = 0;
/**
* @brief Maps every color pixel for every depth pixel and output \c image_interface instance.
*
* Retrieves every color pixel for every depth pixel using the UV map, and outputs a color image, aligned in space
* and resolution to the depth image.
*
* Returned data is wrapped in \c image_interface with self-releasing mechanism.
* This method creates a UV Map to perform the mapping.
* The holes (if any) are left empty (expect the pixel value to be 0).
* The memory is owned by the user. Wrap an instance in the SDK \c unique_ptr to release the memory using a self-releasing mechanism.
* @param[in] depth Depth image instance
* @param[in] color Color image instance
* @return image_interface* Output image in the depth image resolution
* @return nullptr Invalid depth or color image passed as a parameter or uvmap failed to create.
*/
virtual image_interface* create_color_image_mapped_to_depth(image_interface *depth, image_interface *color) = 0;
/**
* @brief Maps every depth pixel to the color image resolution and outputs a depth image, aligned in space
* and resolution to the color image.
*
* The color image size may be different from original.
* Returned data is wrapped in \c image_interface with self-releasing mechanism.
* This method creates UV Map to perform the mapping.
* The holes (if any) are left empty (expect the pixel value to be 0).
* The memory is owned by the user. Wrap an instance in sdk \c unique_ptr to release the memory using self-releasing mechanism.
* @param[in] depth Depth image instance
* @param[in] color Color image instance
* @return image_interface* Output image in the color image resolution
* @return nullptr Invalid depth or color image passed as parameter or uvmap failed to create
*/
virtual image_interface* create_depth_image_mapped_to_color(image_interface *depth, image_interface *color) = 0;
/**
* @brief Creates an instance and initializes, based on intrinsic and extrinsic parameters.
*
* @param[in] colorIntrinsics Camera color intrinsics
* @param[in] depthIntrinsics Camera depth intrinsics
* @param[in] extrinsics Camera depth to color extrinsics
* @return projection_interface* Instance of projection_interface
* @return nullptr Provided intrisics or extrinsics are not initialized
*/
static __inline projection_interface* create_instance(rs::core::intrinsics *colorIntrinsics, rs::core::intrinsics *depthIntrinsics, rs::core::extrinsics *extrinsics)
{
return (projection_interface*)rs_projection_create_instance_from_intrinsics_extrinsics(colorIntrinsics, depthIntrinsics, extrinsics);
}
protected:
//force deletion using the release function
virtual ~projection_interface() {}
};
}
}
| {
"content_hash": "543b4442d6e2e9e0526a45b9d201a088",
"timestamp": "",
"source": "github",
"line_count": 246,
"max_line_length": 177,
"avg_line_length": 63.69512195121951,
"alnum_prop": 0.6178441508711469,
"repo_name": "IntelRealSense/realsense_sdk",
"id": "d46582e9c90b4803cddeedea9a839b97899e02dd",
"size": "15669",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "sdk/include/rs/core/projection_interface.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "1690"
},
{
"name": "C++",
"bytes": "1144840"
},
{
"name": "CMake",
"bytes": "29445"
},
{
"name": "Python",
"bytes": "10128"
}
],
"symlink_target": ""
} |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>basic_signal_set::get_io_service</title>
<link rel="stylesheet" href="../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.76.1">
<link rel="home" href="../../../boost_asio.html" title="Boost.Asio">
<link rel="up" href="../basic_signal_set.html" title="basic_signal_set">
<link rel="prev" href="get_implementation/overload2.html" title="basic_signal_set::get_implementation (2 of 2 overloads)">
<link rel="next" href="get_service.html" title="basic_signal_set::get_service">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../boost.png"></td>
<td align="center"><a href="../../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../../libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="get_implementation/overload2.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../basic_signal_set.html"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../boost_asio.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="get_service.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="section">
<div class="titlepage"><div><div><h4 class="title">
<a name="boost_asio.reference.basic_signal_set.get_io_service"></a><a class="link" href="get_io_service.html" title="basic_signal_set::get_io_service">basic_signal_set::get_io_service</a>
</h4></div></div></div>
<p>
<span class="emphasis"><em>Inherited from basic_io_object.</em></span>
</p>
<p>
<a class="indexterm" name="idp41651696"></a>
Get the <a class="link" href="../io_service.html" title="io_service"><code class="computeroutput"><span class="identifier">io_service</span></code></a> associated with the
object.
</p>
<pre class="programlisting"><span class="identifier">boost</span><span class="special">::</span><span class="identifier">asio</span><span class="special">::</span><span class="identifier">io_service</span> <span class="special">&</span> <span class="identifier">get_io_service</span><span class="special">();</span>
</pre>
<p>
This function may be used to obtain the <a class="link" href="../io_service.html" title="io_service"><code class="computeroutput"><span class="identifier">io_service</span></code></a> object that the I/O
object uses to dispatch handlers for asynchronous operations.
</p>
<h6>
<a name="boost_asio.reference.basic_signal_set.get_io_service.h0"></a>
<span><a name="boost_asio.reference.basic_signal_set.get_io_service.return_value"></a></span><a class="link" href="get_io_service.html#boost_asio.reference.basic_signal_set.get_io_service.return_value">Return
Value</a>
</h6>
<p>
A reference to the <a class="link" href="../io_service.html" title="io_service"><code class="computeroutput"><span class="identifier">io_service</span></code></a> object that the I/O
object will use to dispatch handlers. Ownership is not transferred to the
caller.
</p>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2003-2012 Christopher M. Kohlhoff<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="get_implementation/overload2.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../basic_signal_set.html"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../boost_asio.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="get_service.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
| {
"content_hash": "236980bab6c4ea07d4e72e55352418c2",
"timestamp": "",
"source": "github",
"line_count": 67,
"max_line_length": 453,
"avg_line_length": 69.76119402985074,
"alnum_prop": 0.6409927257167308,
"repo_name": "hand-iemura/lightpng",
"id": "5ea8e45743e98438d8fe64ead6b366515e12f369",
"size": "4674",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "boost_1_53_0/doc/html/boost_asio/reference/basic_signal_set/get_io_service.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "139512"
},
{
"name": "Batchfile",
"bytes": "43970"
},
{
"name": "C",
"bytes": "2306793"
},
{
"name": "C#",
"bytes": "40804"
},
{
"name": "C++",
"bytes": "139009726"
},
{
"name": "CMake",
"bytes": "1741"
},
{
"name": "CSS",
"bytes": "309758"
},
{
"name": "Cuda",
"bytes": "26749"
},
{
"name": "FORTRAN",
"bytes": "1387"
},
{
"name": "Groff",
"bytes": "8039"
},
{
"name": "HTML",
"bytes": "139153356"
},
{
"name": "IDL",
"bytes": "14"
},
{
"name": "JavaScript",
"bytes": "132031"
},
{
"name": "Lex",
"bytes": "1255"
},
{
"name": "M4",
"bytes": "29689"
},
{
"name": "Makefile",
"bytes": "1074346"
},
{
"name": "Max",
"bytes": "36857"
},
{
"name": "Objective-C",
"bytes": "3745"
},
{
"name": "PHP",
"bytes": "59030"
},
{
"name": "Perl",
"bytes": "29502"
},
{
"name": "Perl6",
"bytes": "2053"
},
{
"name": "Python",
"bytes": "1710815"
},
{
"name": "QML",
"bytes": "593"
},
{
"name": "Rebol",
"bytes": "354"
},
{
"name": "Shell",
"bytes": "376263"
},
{
"name": "Tcl",
"bytes": "1172"
},
{
"name": "TeX",
"bytes": "13404"
},
{
"name": "XSLT",
"bytes": "761090"
},
{
"name": "Yacc",
"bytes": "18910"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>hammer-tactics: Not compatible 👼</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.14.0 / hammer-tactics - 1.3+8.12</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
hammer-tactics
<small>
1.3+8.12
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-06-03 04:13:51 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-06-03 04:13:51 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
conf-findutils 1 Virtual package relying on findutils
conf-gmp 4 Virtual package relying on a GMP lib system installation
coq 8.14.0 Formal proof management system
dune 3.2.0 Fast, portable, and opinionated build system
ocaml 4.10.2 The OCaml compiler (virtual package)
ocaml-base-compiler 4.10.2 Official release 4.10.2
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.3 A library manager for OCaml
zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers
# opam file:
opam-version: "2.0"
maintainer: "palmskog@gmail.com"
homepage: "https://github.com/lukaszcz/coqhammer"
dev-repo: "git+https://github.com/lukaszcz/coqhammer.git"
bug-reports: "https://github.com/lukaszcz/coqhammer/issues"
license: "LGPL-2.1-only"
synopsis: "Reconstruction tactics for the hammer for Coq"
description: """
Collection of tactics that are used by the hammer for Coq
to reconstruct proofs found by automated theorem provers. When the hammer
has been successfully applied to a project, only this package needs
to be installed; the hammer plugin is not required.
"""
build: [make "-j%{jobs}%" {ocaml:version >= "4.06"} "tactics"]
install: [
[make "install-tactics"]
[make "test-tactics"] {with-test}
]
depends: [
"ocaml"
"coq" {>= "8.12" & < "8.13~"}
]
conflicts: [
"coq-hammer" {!= version}
]
tags: [
"keyword:automation"
"keyword:hammer"
"keyword:tactics"
"logpath:Hammer.Tactics"
"date:2020-07-28"
]
authors: [
"Lukasz Czajka <lukaszcz@mimuw.edu.pl>"
]
url {
src: "https://github.com/lukaszcz/coqhammer/archive/refs/tags/v1.3-coq8.12.tar.gz"
checksum: "sha512=666ea825c122319e398efb7287f429ebfb5d35611b4cabe4b88732ffb5c265ef348b53d5046c958831ac0b7a759b44ce1ca04220ca68b1915accfd23435b479c"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-hammer-tactics.1.3+8.12 coq.8.14.0</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.14.0).
The following dependencies couldn't be met:
- coq-hammer-tactics -> coq < 8.13~ -> ocaml < 4.10
base of this switch (use `--unlock-base' to force)
Your request can't be satisfied:
- No available version of coq satisfies the constraints
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-hammer-tactics.1.3+8.12</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| {
"content_hash": "d82f7451edfd70e89b5086adf57c4801",
"timestamp": "",
"source": "github",
"line_count": 181,
"max_line_length": 159,
"avg_line_length": 40.71823204419889,
"alnum_prop": 0.5569877883310719,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "21bc3c3bc2bd7cca7bc49ccb0d15a753f8642186",
"size": "7395",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.10.2-2.0.6/released/8.14.0/hammer-tactics/1.3+8.12.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
require 'spec_helper'
describe FeedbacksController do
subject{ response }
let(:delivery){ ActionMailer::Base.deliveries.last }
describe "GET create" do
before do
post :create, feedback: {email: 'foo@bar.com', message: 'test'}
end
it{ should be_success }
it "should deliver feedback" do
expect(delivery).to_not be_nil
expect(delivery.to).to eq ['foo@bar.com']
expect(delivery.body.raw_source).to include 'test'
end
end
end
| {
"content_hash": "f253856a1b1e6c1cd57bae7cc9b2d09a",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 69,
"avg_line_length": 23.9,
"alnum_prop": 0.6673640167364017,
"repo_name": "valorizeme/valorizeme",
"id": "297644336f65ef47662ff9eac000dc8a4f867a4a",
"size": "478",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "spec/controllers/feedbacks_controller_spec.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "443055"
},
{
"name": "HTML",
"bytes": "229331"
},
{
"name": "JavaScript",
"bytes": "213604"
},
{
"name": "Ruby",
"bytes": "623992"
}
],
"symlink_target": ""
} |
alum
====
A forwarding mail server inspired by @alum.mit.edu
## What's in the package
* A secure Postfix instance that will ONLY forward mail, according to the aliases file
* Full opportunistic TLS support
* Automatic security updates, with reboot, and emails on error to `postmaster@alum.example.com`
* Daily Tarsnap backups of the aliases file
* A Ansible playbook to setup all of this
## Usage
* Create a Tarsnap key and put it in `tarsnap.key`
* Generate a self-signed key+certificate and put it in smtpd.pem
* Start a Ubuntu 14.04 LTS machine
* Make sure you can ssh into the machine, and that sudo is passwordless
* Create a `inventory.ini` file like this
```
[alum]
98.25.536.22
```
* Run
```
ansible-playbook -i inventory.ini \
-e domain=alum.example.com \
playbook.yml
```
Include `-e mirror=alum.example.org` if you want to support multiple domains.
* Set the DNS A record for `alum.example.com` to point to the machine, and the MX record of `alum.example.com` to `alum.example.com`
## Adding aliases
Add them like this
```
postmaster@alum.example.com me@example.com
joe@alum.example.com joe@gmail.com
<alias-email-with-domain> <actual-recipient-email>
```
to `/etc/postfix/virtual` and then run
```sh
# postmap /etc/postfix/virtual
# postfix reload
```
| {
"content_hash": "d00278643e175275aea85826085c3f32",
"timestamp": "",
"source": "github",
"line_count": 52,
"max_line_length": 132,
"avg_line_length": 24.71153846153846,
"alnum_prop": 0.733852140077821,
"repo_name": "FiloSottile/alum",
"id": "6767f6d258062862c570412ed5379b0ecc78857d",
"size": "1285",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Go",
"bytes": "10708"
},
{
"name": "HTML",
"bytes": "1482"
},
{
"name": "Shell",
"bytes": "84"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "e2454c586bbc4d8f10e3bf1825bd2938",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "b4e53aff3315aa86053dd3e93ef36d675b5663e1",
"size": "191",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Lamiales/Orobanchaceae/Castilleja/Castilleja pallida/Castilleja pallida lutescens/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
.class public Landroid/database/SQLException;
.super Ljava/lang/RuntimeException;
.source "SQLException.java"
# direct methods
.method public constructor <init>()V
.locals 0
invoke-direct {p0}, Ljava/lang/RuntimeException;-><init>()V
return-void
.end method
.method public constructor <init>(Ljava/lang/String;)V
.locals 0
invoke-direct {p0, p1}, Ljava/lang/RuntimeException;-><init>(Ljava/lang/String;)V
return-void
.end method
.method public constructor <init>(Ljava/lang/String;Ljava/lang/Throwable;)V
.locals 0
invoke-direct {p0, p1, p2}, Ljava/lang/RuntimeException;-><init>(Ljava/lang/String;Ljava/lang/Throwable;)V
return-void
.end method
| {
"content_hash": "bb3ea50180892ba2f233cd22b0df7361",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 110,
"avg_line_length": 23.862068965517242,
"alnum_prop": 0.7225433526011561,
"repo_name": "BatMan-Rom/ModdedFiles",
"id": "e270f3fa80316ed3be54475b56bd824a664e8258",
"size": "692",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "framework.jar.out/smali/android/database/SQLException.smali",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "GLSL",
"bytes": "15069"
},
{
"name": "HTML",
"bytes": "139176"
},
{
"name": "Smali",
"bytes": "541934400"
}
],
"symlink_target": ""
} |
<resources>
<string-array name="phases">
<item>new moon</item>
<item>waxing crescent</item>
<item>first quarter</item>
<item>waxing gibbous</item>
<item>full moon</item>
<item>waning gibbous</item>
<item>third quarter</item>
<item>waning crescent</item>
</string-array>
</resources> | {
"content_hash": "eadf197c0c24f97e56358f6072351b73",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 36,
"avg_line_length": 26.357142857142858,
"alnum_prop": 0.5609756097560976,
"repo_name": "mridang/dashclock-sunmoon",
"id": "0499c87a7d1666e386ba05eb155dfe2775b9a429",
"size": "369",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/res/values/arrays.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "15275"
}
],
"symlink_target": ""
} |
<?php
require_once 'processorFactory.php';
$processorFactory = new \Magento\Framework\Error\ProcessorFactory();
$processor = $processorFactory->createProcessor();
$response = $processor->process503();
$response->sendResponse();
| {
"content_hash": "c4ce911ce520b28e705e59d32ecfdd8b",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 68,
"avg_line_length": 25.666666666666668,
"alnum_prop": 0.7619047619047619,
"repo_name": "enettolima/magento-training",
"id": "76523c1584b798ecb076a7d97180c29e48ecc34d",
"size": "329",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "magento2ce/pub/errors/503.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "22648"
},
{
"name": "CSS",
"bytes": "3382928"
},
{
"name": "HTML",
"bytes": "8749335"
},
{
"name": "JavaScript",
"bytes": "7355635"
},
{
"name": "PHP",
"bytes": "58607662"
},
{
"name": "Perl",
"bytes": "10258"
},
{
"name": "Shell",
"bytes": "41887"
},
{
"name": "XSLT",
"bytes": "19889"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>: The Table of Contents (toc) Plugin</title>
<!-- guides styles -->
<link rel="stylesheet" type="text/css" href="stylesheets/style.css" />
<link rel="stylesheet" type="text/css" href="stylesheets/print.css" media="print" />
<link rel="stylesheet" type="text/css" href="stylesheets/strobe.css" />
<link rel="stylesheet" type="text/css" href="stylesheets/overrides.style.css" />
<link rel="stylesheet" type="text/css" href="stylesheets/overrides.print.css" media="print" />
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!-- syntax highlighting styles -->
<link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shCore.css" />
<link rel="stylesheet" type="text/css" href="stylesheets/shThemeStrobeGuides.css" />
</head>
<body class="guide">
<header role="banner">
<div class="container">
<h1 id="logo">
<a href="http://aloha-editor.org"><img src="images/header/logo.png" height="50" alt="Aloha Editor" /></a>
</h1>
<nav role="navigation">
<ul>
<li><a href="http://aloha-editor.org/features.php" title="A shortcut for Aloha Editor features" class="new">Features</a></li>
<li><a href="http://aloha-editor.org/plugins.php" title="A list of all known Aloha Editor plugins.">Plugins</a></li>
<li class="active"><a href="http://aloha-editor.org/guides/" title="The Aloha Editor documentation">Guides</a></li>
<li><a href="http://aloha-editor.org/about.php" title="Why Aloha? Why HTML5? Lern more about Aloha Editor">About</a></li>
<li><a href="http://getsatisfaction.com/aloha_editor" title="Get help or help others">Forum</a></li>
<li><a href="http://aloha-editor.org/demos.php" title="Feel the Aloha">Try it</a></li>
</ul>
</nav>
</div>
</header>
<div id="feature">
<div class="wrapper">
<div class="feature_header">
<a href="/"><img src="images/strobe/guides.png"></a>
<h2><a href="/"></a></h2>
<p>These guides help you to make your content editable and to develop Aloha Editor.</p>
</div>
<div class="feature_sidebar">
<a href="index.html" id="guidesMenu">
Guides Index <span id="guidesArrow">▸</span>
</a>
<div id="guides" class="clearfix" style="display: none;">
<a href="index.html" class="guidesMenu">
Guides Index <span class="guidesArrow">▾</span>
</a>
<hr style="clear:both;">
<dl class="L">
<dt>Start Here</dt>
<dd><a href="using_aloha.html">Use</a></dd>
<dd><a href="develop_aloha.html">Develop</a></dd>
<dd><a href="dependencies.html">Dependencies</a></dd>
<dt>The Core</dt>
<dd><a href="events.html">Events</a></dd>
<dd><a href="using_commands.html">Commands</a></dd>
<dd><a href="repository.html">Repositories</a></dd>
<dd><a href="functional_description.html">Functional Description</a></dd>
<dd><a href="internals.html">Internals</a></dd>
</dl>
<dl class="R">
<dt>UI</dt>
<dd><a href="ui.html">Aloha Editor UI</a></dd>
<dd><a href="core_hotkey.html">Hotkeys</a></dd>
<dt>Plugins</dt>
<dd><a href="plugins.html">Available Plugins</a></dd>
<dd><a href="writing_plugins.html">Writing Plugins</a></dd>
<dt>Contributing to Aloha Editor</dt>
<dd><a href="releasing.html">Releasing</a></dd>
<dd><a href="style_guide.html">Javascript Style Guide</a></dd>
<dd><a href="documentation_guidelines.html">Documentation Guidelines</a></dd>
<dd><a href="translations.html">Translations</a></dd>
</dl>
</div>
</div>
</div>
</div>
<div id="container">
<div class="wrapper">
<div id="mainCol">
<div class="headerSection">
<h2>The Table of Contents (toc) Plugin</h2>
<p>With this plugin the editor has the possibility to insert a table of contents (<span class="caps">TOC</span>).</p>
<p>All H1 – H6 elements will be extracted and presented as a table of contents. There are also anchor links from the <span class="caps">TOC</span> entries to the sections available.</p>
</div>
<h3 id="plugin-settings">1 Plugin Settings</h3>
<div class="code_container">
<pre class="brush: javascript; gutter: false; toolbar: false">
Aloha.settings.plugins.toc: {
minEntries: 5, // minimum TOC entries to display; default: 0 (show always all)
updateInterval: 5000, // update interval for the TOC in milliseconds; default: 5000 (5 seconds)
editables: {
'#my-editable': [] // disable toc plugin for editable with ID my-editable
}
}
</pre></div>
</div>
<div id="subCol">
<h3 class="chapter"><img src="images/strobe/chapters.png" alt="" />Chapters</h3>
<ol class="chapters">
<li><a href="#plugin-settings"><p>Plugin Settings</p>
</a></li>
</ol>
</div>
</div>
</div>
<hr class="hide" />
<footer>
<div class="container">
<div class="col">
<a href="index.html"><img src="images/footer/logo.png" alt="Aloha Editor" /></a>
<p>
Templates based on <a href="https://github.com/sproutcore/sproutguides">SproutCore guides</a>.
</p>
</div>
<a href="#feature" class="top">Back To Top</a>
</div>
</footer>
<script src="http://code.jquery.com/jquery-1.6.min.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript" src="javascripts/alohaEditorGuides.js"></script>
<script type="text/javascript" src="javascripts/syntaxhighlighter/shCore.js"></script>
<script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushRuby.js"></script>
<script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushJScript.js"></script>
<script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushCss.js"></script>
<script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushXml.js"></script>
<script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushSql.js"></script>
<script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushPlain.js"></script>
<script type="text/javascript">
SyntaxHighlighter.all()
</script>
</body>
</html>
| {
"content_hash": "49ae0afd138339635514ae95dde20dfd",
"timestamp": "",
"source": "github",
"line_count": 148,
"max_line_length": 191,
"avg_line_length": 43.08783783783784,
"alnum_prop": 0.6321154147718363,
"repo_name": "aehparta/edb-online",
"id": "fcd6f6de69c7ae49fbd0c437983b8cc3ca5090a1",
"size": "6377",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "web/js/aloha/doc/guides/plugin_toc.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "52028"
},
{
"name": "CoffeeScript",
"bytes": "5845"
},
{
"name": "HTML",
"bytes": "111094"
},
{
"name": "JavaScript",
"bytes": "322955"
},
{
"name": "PHP",
"bytes": "165366"
},
{
"name": "Shell",
"bytes": "360"
}
],
"symlink_target": ""
} |
/**
* DataModel table section node.
*
* @class
* @extends ve.dm.BranchNode
* @constructor
* @param {ve.dm.BranchNode[]} [children] Child nodes to attach
* @param {Object} [element] Reference to element in linear model
*/
ve.dm.TableSectionNode = function VeDmTableSectionNode( children, element ) {
// Parent constructor
ve.dm.BranchNode.call( this, children, element );
};
/* Inheritance */
OO.inheritClass( ve.dm.TableSectionNode, ve.dm.BranchNode );
/* Static Properties */
ve.dm.TableSectionNode.static.name = 'tableSection';
ve.dm.TableSectionNode.static.childNodeTypes = [ 'tableRow' ];
ve.dm.TableSectionNode.static.parentNodeTypes = [ 'table' ];
ve.dm.TableSectionNode.static.defaultAttributes = {
'style': 'body'
};
ve.dm.TableSectionNode.static.matchTagNames = [ 'thead', 'tbody', 'tfoot' ];
ve.dm.TableSectionNode.static.toDataElement = function ( domElements ) {
var styles = {
'thead': 'header',
'tbody': 'body',
'tfoot': 'footer'
},
style = styles[domElements[0].nodeName.toLowerCase()] || 'body';
return { 'type': 'tableSection', 'attributes': { 'style': style } };
};
ve.dm.TableSectionNode.static.toDomElements = function ( dataElement, doc ) {
var tags = {
'header': 'thead',
'body': 'tbody',
'footer': 'tfoot'
},
tag = tags[dataElement.attributes && dataElement.attributes.style || 'body'];
return [ doc.createElement( tag ) ];
};
/* Registration */
ve.dm.modelRegistry.register( ve.dm.TableSectionNode );
| {
"content_hash": "cda83e249e7a480620ffb69d6af84bd4",
"timestamp": "",
"source": "github",
"line_count": 56,
"max_line_length": 79,
"avg_line_length": 26.410714285714285,
"alnum_prop": 0.6862745098039216,
"repo_name": "BRL-CAD/web",
"id": "1abfdedd5f77c25d52ae7b8c3a68b20f8d9f23b1",
"size": "1662",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "wiki/extensions/VisualEditor/modules/ve/dm/nodes/ve.dm.TableSectionNode.js",
"mode": "33261",
"license": "bsd-2-clause",
"language": [
{
"name": "Batchfile",
"bytes": "46"
},
{
"name": "CSS",
"bytes": "2791896"
},
{
"name": "Gherkin",
"bytes": "8953"
},
{
"name": "HTML",
"bytes": "3386533"
},
{
"name": "Hack",
"bytes": "8554"
},
{
"name": "JavaScript",
"bytes": "6034530"
},
{
"name": "Less",
"bytes": "228870"
},
{
"name": "Makefile",
"bytes": "7564"
},
{
"name": "PHP",
"bytes": "85649990"
},
{
"name": "PLSQL",
"bytes": "47123"
},
{
"name": "PLpgSQL",
"bytes": "31942"
},
{
"name": "Perl",
"bytes": "28087"
},
{
"name": "Pug",
"bytes": "1857"
},
{
"name": "Python",
"bytes": "54812"
},
{
"name": "Ruby",
"bytes": "30411"
},
{
"name": "SCSS",
"bytes": "27565"
},
{
"name": "Shell",
"bytes": "8990"
},
{
"name": "Smarty",
"bytes": "9612"
}
],
"symlink_target": ""
} |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jctools.jmh.throughput.spsc;
import org.jctools.queues.alt.ConcurrentQueue;
import org.jctools.queues.alt.ConcurrentQueueByTypeFactory;
import org.jctools.queues.alt.ConcurrentQueueConsumer;
import org.jctools.queues.alt.ConcurrentQueueProducer;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.infra.Control;
import java.util.concurrent.TimeUnit;
@State(Scope.Group)
@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
@Threads(2)
@Warmup(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 5, time = 3, timeUnit = TimeUnit.SECONDS)
public class ConcurrentQueueThroughputYield {
private final ConcurrentQueue<Integer> q = ConcurrentQueueByTypeFactory.createQueue();
private final ConcurrentQueueProducer<Integer> producer = q.producer();
private final ConcurrentQueueConsumer<Integer> consumer = q.consumer();
private final static Integer ONE = 777;
@Benchmark
@Group("tpt")
public void offer(Control cnt) {
while (!producer.offer(ONE) && !cnt.stopMeasurement) {
Thread.yield();
}
}
@Benchmark
@Group("tpt")
public void poll(Control cnt, ConsumerMarker cm) {
while (consumer.poll() == null && !cnt.stopMeasurement) {
Thread.yield();
}
}
private static ThreadLocal<Object> marker = new ThreadLocal<Object>();
@State(Scope.Thread)
public static class ConsumerMarker {
public ConsumerMarker() {
marker.set(this);
}
}
@TearDown(Level.Iteration)
public void emptyQ() {
if(marker.get() == null)
return;
// sadly the iteration tear down is performed from each participating thread, so we need to guess
// which is which (can't have concurrent access to poll).
while (consumer.poll() != null)
;
}
}
| {
"content_hash": "0d7c2c056eab5b96fcd40c1b5cab8e82",
"timestamp": "",
"source": "github",
"line_count": 69,
"max_line_length": 105,
"avg_line_length": 35.42028985507246,
"alnum_prop": 0.6996726677577741,
"repo_name": "mackstone/JCTools",
"id": "e5efe3a08e98de2810071d44fe25ac4f3912f580",
"size": "2444",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "jctools-benchmarks/src/main/java/org/jctools/jmh/throughput/spsc/ConcurrentQueueThroughputYield.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "557472"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "844452a2025c561b79d3ca4a3f9a523f",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "a8bb1cb1f6245a7c9f1e2e40473e5746cf7e06f8",
"size": "181",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Celastrales/Celastraceae/Gymnosporia/Gymnosporia acuminata/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
@property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
@property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;
- (void)saveContext;
- (NSURL *)applicationDocumentsDirectory;
@end
| {
"content_hash": "6633bdb8d7b8d2b5c297e1b9368df45c",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 97,
"avg_line_length": 32.07142857142857,
"alnum_prop": 0.8195991091314031,
"repo_name": "rogergzou/localpost",
"id": "7b8bdb8838d9c9fd000b770de458d74e0c1afbc6",
"size": "652",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "localpost/AppDelegate.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "1090"
},
{
"name": "Objective-C",
"bytes": "272235"
}
],
"symlink_target": ""
} |
//This file will likely change a lot! Very experimental!
/*global Matcher, Properties, ValidationTypes, ValidationError, PropertyValueIterator */
/*exported Validation */
var Validation = {
validate: function(property, value){
//normalize name
var name = property.toString().toLowerCase(),
expression = new PropertyValueIterator(value),
spec = Properties[name],
part;
if (!spec) {
if (name.indexOf("-") !== 0){ //vendor prefixed are ok
throw new ValidationError("Unknown property '" + property + "'.", property.line, property.col);
}
} else if (typeof spec !== "number"){
// All properties accept some CSS-wide values.
// https://drafts.csswg.org/css-values-3/#common-keywords
if (ValidationTypes.isAny(expression, "inherit | initial | unset")){
if (expression.hasNext()) {
part = expression.next();
throw new ValidationError("Expected end of value but found '" + part + "'.", part.line, part.col);
}
return;
}
// Property-specific validation.
this.singleProperty(spec, expression);
}
},
singleProperty: function(types, expression) {
var result = false,
value = expression.value,
part;
result = Matcher.parse(types).match(expression);
if (!result) {
if (expression.hasNext() && !expression.isFirst()) {
part = expression.peek();
throw new ValidationError("Expected end of value but found '" + part + "'.", part.line, part.col);
} else {
throw new ValidationError("Expected (" + ValidationTypes.describe(types) + ") but found '" + value + "'.", value.line, value.col);
}
} else if (expression.hasNext()) {
part = expression.next();
throw new ValidationError("Expected end of value but found '" + part + "'.", part.line, part.col);
}
}
};
| {
"content_hash": "c26f84a9e70bd1e45d5fc5cf778848f0",
"timestamp": "",
"source": "github",
"line_count": 59,
"max_line_length": 146,
"avg_line_length": 36.32203389830509,
"alnum_prop": 0.54129724685021,
"repo_name": "cscott/parser-lib",
"id": "117c33f9ab85df36ab61e3dac301c9ba313ad141",
"size": "2143",
"binary": false,
"copies": "1",
"ref": "refs/heads/domino",
"path": "src/css/Validation.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "136001"
},
{
"name": "JavaScript",
"bytes": "1480997"
}
],
"symlink_target": ""
} |
import java.awt.*;
import java.awt.peer.*;
import sun.awt.*;
import java.lang.reflect.*;
import java.net.*;
import java.io.*;
import java.util.*;
public final class DirectRobot
{
public DirectRobot() throws AWTException
{
this(null);
}
public DirectRobot(GraphicsDevice device) throws AWTException
{
if (device == null)
device = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
this.device = device;
Toolkit toolkit = Toolkit.getDefaultToolkit();
peer = ((ComponentFactory) toolkit).createRobot(null, device);
Class<?> peerClass = peer.getClass();
Method method = null;
int methodType = -1;
Object methodParam = null;
try
{
method = peerClass.getDeclaredMethod("getRGBPixels", new Class<?>[] { Integer.TYPE, Integer.TYPE, Integer.TYPE, Integer.TYPE, int[].class });
methodType = 0;
}
catch (Exception ex) { }
if (methodType < 0)
try
{
method = peerClass.getDeclaredMethod("getScreenPixels", new Class<?>[] { Rectangle.class, int[].class });
methodType = 1;
}
catch (Exception ex) { }
if (methodType < 0)
try
{
method = peerClass.getDeclaredMethod("getScreenPixels", new Class<?>[] { Integer.TYPE, Rectangle.class, int[].class });
methodType = 2;
GraphicsDevice[] devices = GraphicsEnvironment.getLocalGraphicsEnvironment().
getScreenDevices();
int count = devices.length;
for (int i = 0; i != count; ++i)
if (device.equals(devices[i]))
{
methodParam = Integer.valueOf(i);
break;
}
}
catch (Exception ex) { }
if (methodType < 0)
try
{
method = peerClass.getDeclaredMethod("getRGBPixelsImpl", new Class<?>[] { Class.forName("sun.awt.X11GraphicsConfig"), Integer.TYPE, Integer.TYPE, Integer.TYPE, Integer.TYPE, int[].class });
methodType = 3;
Field field = peerClass.getDeclaredField("xgc");
try
{
field.setAccessible(true);
methodParam = field.get(peer);
}
finally
{
field.setAccessible(false);
}
}
catch (Exception ex) { }
if (methodType >= 0 && method != null && (methodType <= 1 || methodParam != null))
{
getRGBPixelsMethod = method;
getRGBPixelsMethodType = methodType;
getRGBPixelsMethodParam = methodParam;
}
else
{
System.out.println("WARNING: Failed to acquire direct method for grabbing pixels, please post this on the main thread!");
System.out.println();
System.out.println(peer.getClass().getName());
System.out.println();
try
{
Method[] methods = peer.getClass().getDeclaredMethods();
for (Method method1 : methods)
System.out.println(method1);
}
catch (Exception ex) { }
System.out.println();
}
}
public static GraphicsDevice getMouseInfo(Point point)
{
if (!hasMouseInfoPeer)
{
hasMouseInfoPeer = true;
try
{
Toolkit toolkit = Toolkit.getDefaultToolkit();
Method method = toolkit.getClass().getDeclaredMethod("getMouseInfoPeer", new Class<?>[0]);
try
{
method.setAccessible(true);
mouseInfoPeer = (MouseInfoPeer) method.invoke(toolkit, new Object[0]);
}
finally
{
method.setAccessible(false);
}
}
catch (Exception ex) { }
}
if (mouseInfoPeer != null)
{
int device = mouseInfoPeer.fillPointWithCoords(point != null ? point:new Point());
GraphicsDevice[] devices = GraphicsEnvironment.getLocalGraphicsEnvironment().
getScreenDevices();
return devices[device];
}
PointerInfo info = MouseInfo.getPointerInfo();
if (point != null)
{
Point location = info.getLocation();
point.x = location.x;
point.y = location.y;
}
return info.getDevice();
}
public static int getNumberOfMouseButtons()
{
return MouseInfo.getNumberOfButtons();
}
public static GraphicsDevice getDefaultScreenDevice()
{
return GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
}
public static GraphicsDevice getScreenDevice()
{
return getMouseInfo(null);
}
public void mouseMove(int x, int y)
{
peer.mouseMove(x, y);
}
public void mousePress(int buttons)
{
peer.mousePress(buttons);
}
public void mouseRelease(int buttons)
{
peer.mouseRelease(buttons);
}
public void mouseWheel(int wheelAmt)
{
peer.mouseWheel(wheelAmt);
}
public void keyPress(int keycode)
{
peer.keyPress(keycode);
}
public void keyRelease(int keycode)
{
peer.keyRelease(keycode);
}
public int getRGBPixel(int x, int y)
{
return peer.getRGBPixel(x, y);
}
public int[] getRGBPixels(Rectangle bounds)
{
return peer.getRGBPixels(bounds);
}
public boolean getRGBPixels(int x, int y, int width, int height, int[] pixels)
{
if (getRGBPixelsMethod != null)
try
{
if (getRGBPixelsMethodType == 0)
getRGBPixelsMethod.invoke(peer, new Object[] { Integer.valueOf(x), Integer.valueOf(y), Integer.valueOf(width), Integer.valueOf(height), pixels });
else if (getRGBPixelsMethodType == 1)
getRGBPixelsMethod.invoke(peer, new Object[] { new Rectangle(x, y, width, height), pixels });
else if (getRGBPixelsMethodType == 2)
getRGBPixelsMethod.invoke(peer, new Object[] { getRGBPixelsMethodParam, new Rectangle(x, y, width, height), pixels });
else
getRGBPixelsMethod.invoke(peer, new Object[] { getRGBPixelsMethodParam, Integer.valueOf(x), Integer.valueOf(y), Integer.valueOf(width), Integer.valueOf(height), pixels });
return true;
}
catch (Exception ex) { }
int[] tmp = getRGBPixels(new Rectangle(x, y, width, height));
System.arraycopy(tmp, 0, pixels, 0, width * height);
return false;
}
public void dispose()
{
getRGBPixelsMethodParam = null;
Method method = getRGBPixelsMethod;
if (method != null)
{
getRGBPixelsMethod = null;
try
{
method.setAccessible(false);
}
catch (Exception ex) { }
}
//Using reflection now because of some peers not having ANY support at all (1.5)
try
{
peer.getClass().getDeclaredMethod("dispose", new Class<?>[0]).invoke(peer, new Class<?>[0]);
}
catch (Exception ex) { }
}
protected void finalize() throws Throwable
{
try
{
dispose();
}
finally
{
super.finalize();
}
}
private Object getRGBPixelsMethodParam;
public int getRGBPixelsMethodType;
public final GraphicsDevice device;
private Method getRGBPixelsMethod;
private final RobotPeer peer;
private static boolean hasMouseInfoPeer;
private static MouseInfoPeer mouseInfoPeer;
} | {
"content_hash": "984ac45a675b8b9f11a7df2e73dfa7ec",
"timestamp": "",
"source": "github",
"line_count": 258,
"max_line_length": 197,
"avg_line_length": 26.972868217054263,
"alnum_prop": 0.6282511855151602,
"repo_name": "DrBrainlove/DBL_LEDcontrol",
"id": "79498b4ee5c44ea6ae2386fd75dd419e522f894d",
"size": "6959",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "DBLX/build-tmp/source/DirectRobot.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Arduino",
"bytes": "24321"
},
{
"name": "CSS",
"bytes": "11139"
},
{
"name": "GLSL",
"bytes": "285"
},
{
"name": "HTML",
"bytes": "327926"
},
{
"name": "Java",
"bytes": "284035"
},
{
"name": "Processing",
"bytes": "233096"
},
{
"name": "Shell",
"bytes": "112"
}
],
"symlink_target": ""
} |
<?php
use Illuminate\Database\Schema\Blueprint;
use ErpNET\App\Repositories\BaseMigration;
class CreateUsersTable extends BaseMigration {
protected $table = 'users';
/**
* Run the migrations.
*
* @return void
*/
public function upMigration()
{
$this->createTable(function(Blueprint $table)
{
$table->increments('id');
$table->timestamps();
$table->softDeletes();
$table->integer('role_id')->unsigned()->index()->nullable();
// $table->foreign('role_id')
// ->references('id')
// ->on('roles')
// ->onDelete('restrict')
// ->onUpdate('cascade');
$table->string('mandante')->index();
$table->string('name');
$table->string('avatar')->nullable();
// $table->string('email')->unique();
$table->string('password')->nullable();
$table->string('username')->nullable();
$table->string('email')->unique()->default(time() . '-no-reply@ilhanet.com');
// $table->string('email')->unique()->default(time() . '-no-reply@EasyAuthenticator.com')->change();
// $table->string('avatar');
$table->string('provider')->default('laravel');
$table->string('provider_id')->unique()->nullable();
$table->string('activation_code')->nullable();
$table->integer('active')->nullable();
$table->rememberToken();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function downMigration()
{
$this->dropTable();
}
}
| {
"content_hash": "ab0e60bc3e57b4b68e70ea249cb84cf7",
"timestamp": "",
"source": "github",
"line_count": 61,
"max_line_length": 111,
"avg_line_length": 25.704918032786885,
"alnum_prop": 0.5529336734693877,
"repo_name": "lucianobapo/erpnet-core",
"id": "ca8a592495fc6114ca1cd22e9ed3629801a2c79e",
"size": "1568",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "database/migrations/2014_10_12_000000_create_users_table.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "551831"
}
],
"symlink_target": ""
} |
using System;
using System.Text;
using System.Security.Permissions;
using System.Runtime.Serialization;
using OpenADK.Library;
using OpenADK.Library.Global;
using OpenADK.Library.au.Common;
namespace OpenADK.Library.au.School{
/// <summary>A ResourceUsage</summary>
/// <remarks>
///
/// <para>Author: Generated by adkgen</para>
/// <para>Version: 2.6</para>
/// <para>Since: 2.5</para>
/// </remarks>
[Serializable]
public class ResourceUsage : SifDataObject
{
/// <summary>
/// Creates an instance of a ResourceUsage
/// </summary>
public ResourceUsage() : base( Adk.SifVersion, SchoolDTD.RESOURCEUSAGE ){}
/// <summary>
/// Constructor that accepts values for all mandatory fields
/// </summary>
///<param name="refId">A RefId</param>
///<param name="schoolInfoRefId">A SchoolInfoRefId</param>
///<param name="resourceUsageContentType">A ResourceUsageContentType</param>
///<param name="resourceReportColumnList">A ResourceReportColumnList</param>
///<param name="resourceReportLineList">A ResourceReportLineList</param>
///
public ResourceUsage( string refId, string schoolInfoRefId, ResourceUsageContentType resourceUsageContentType, ResourceReportColumn resourceReportColumnList, ResourceReportLine resourceReportLineList ) : base( Adk.SifVersion, SchoolDTD.RESOURCEUSAGE )
{
this.RefId = refId;
this.SchoolInfoRefId = schoolInfoRefId;
this.ResourceUsageContentType = resourceUsageContentType;
this.ResourceReportColumnList = new ResourceReportColumnList( resourceReportColumnList );
this.ResourceReportLineList = new ResourceReportLineList( resourceReportLineList );
}
/// <summary>
/// Constructor used by the .Net Serialization formatter
/// </summary>
[SecurityPermission( SecurityAction.Demand, SerializationFormatter=true )]
protected ResourceUsage( SerializationInfo info, StreamingContext context ) : base( info, context ) {}
/// <summary>
/// Gets the metadata fields that make up the key of this object
/// </summary>
/// <value>
/// an array of metadata fields that make up the object's key
/// </value>
public override IElementDef[] KeyFields {
get { return new IElementDef[] { SchoolDTD.RESOURCEUSAGE_REFID }; }
}
/// <summary>
/// Gets or sets the value of the <c>RefId</c> attribute.
/// </summary>
/// <value> The <c>RefId</c> attribute of this object.</value>
/// <remarks>
/// <para>Version: 2.6</para>
/// <para>Since: 2.5</para>
/// </remarks>
public override string RefId
{
get
{
return (string) GetSifSimpleFieldValue( SchoolDTD.RESOURCEUSAGE_REFID ) ;
}
set
{
SetFieldValue( SchoolDTD.RESOURCEUSAGE_REFID, new SifString( value ), value );
}
}
/// <summary>
/// Gets or sets the value of the <c><SchoolInfoRefId></c> element.
/// </summary>
/// <value> The <c>SchoolInfoRefId</c> element of this object.</value>
/// <remarks>
/// <para>Version: 2.6</para>
/// <para>Since: 2.5</para>
/// </remarks>
public string SchoolInfoRefId
{
get
{
return (string) GetSifSimpleFieldValue( SchoolDTD.RESOURCEUSAGE_SCHOOLINFOREFID ) ;
}
set
{
SetFieldValue( SchoolDTD.RESOURCEUSAGE_SCHOOLINFOREFID, new SifString( value ), value );
}
}
///<summary>Sets the value of the <c><ResourceUsageContentType></c> element.</summary>
/// <param name="Code">A Code</param>
///<remarks>
/// <para>This form of <c>setResourceUsageContentType</c> is provided as a convenience method
/// that is functionally equivalent to the <c>ResourceUsageContentType</c></para>
/// <para>Version: 2.6</para>
/// <para>Since: 2.5</para>
/// </remarks>
public void SetResourceUsageContentType( AUCodeSetsResourceUsageContentTypeType Code ) {
RemoveChild( SchoolDTD.RESOURCEUSAGE_RESOURCEUSAGECONTENTTYPE);
AddChild( SchoolDTD.RESOURCEUSAGE_RESOURCEUSAGECONTENTTYPE, new ResourceUsageContentType( Code ) );
}
/// <summary>
/// Gets or sets the value of the <c><ResourceUsageContentType></c> element.
/// </summary>
/// <value> A ResourceUsageContentType </value>
/// <remarks>
/// <para>To remove the <c>ResourceUsageContentType</c>, set <c>ResourceUsageContentType</c> to <c>null</c></para>
/// <para>Version: 2.6</para>
/// <para>Since: 2.5</para>
/// </remarks>
public ResourceUsageContentType ResourceUsageContentType
{
get
{
return (ResourceUsageContentType)GetChild( SchoolDTD.RESOURCEUSAGE_RESOURCEUSAGECONTENTTYPE);
}
set
{
RemoveChild( SchoolDTD.RESOURCEUSAGE_RESOURCEUSAGECONTENTTYPE);
if( value != null)
{
AddChild( SchoolDTD.RESOURCEUSAGE_RESOURCEUSAGECONTENTTYPE, value );
}
}
}
///<summary>Sets the value of the <c><ResourceReportColumnList></c> element.</summary>
/// <param name="ResourceReportColumn">A ResourceReportColumn</param>
///<remarks>
/// <para>This form of <c>setResourceReportColumnList</c> is provided as a convenience method
/// that is functionally equivalent to the <c>ResourceReportColumnList</c></para>
/// <para>Version: 2.6</para>
/// <para>Since: 2.5</para>
/// </remarks>
public void SetResourceReportColumnList( ResourceReportColumn ResourceReportColumn ) {
RemoveChild( SchoolDTD.RESOURCEUSAGE_RESOURCEREPORTCOLUMNLIST);
AddChild( SchoolDTD.RESOURCEUSAGE_RESOURCEREPORTCOLUMNLIST, new ResourceReportColumnList( ResourceReportColumn ) );
}
/// <summary>
/// Gets or sets the value of the <c><ResourceReportColumnList></c> element.
/// </summary>
/// <value> A ResourceReportColumnList </value>
/// <remarks>
/// <para>To remove the <c>ResourceReportColumnList</c>, set <c>ResourceReportColumnList</c> to <c>null</c></para>
/// <para>Version: 2.6</para>
/// <para>Since: 2.5</para>
/// </remarks>
public ResourceReportColumnList ResourceReportColumnList
{
get
{
return (ResourceReportColumnList)GetChild( SchoolDTD.RESOURCEUSAGE_RESOURCEREPORTCOLUMNLIST);
}
set
{
RemoveChild( SchoolDTD.RESOURCEUSAGE_RESOURCEREPORTCOLUMNLIST);
if( value != null)
{
AddChild( SchoolDTD.RESOURCEUSAGE_RESOURCEREPORTCOLUMNLIST, value );
}
}
}
///<summary>Sets the value of the <c><ResourceReportLineList></c> element.</summary>
/// <param name="ResourceReportLine">A ResourceReportLine</param>
///<remarks>
/// <para>This form of <c>setResourceReportLineList</c> is provided as a convenience method
/// that is functionally equivalent to the <c>ResourceReportLineList</c></para>
/// <para>Version: 2.6</para>
/// <para>Since: 2.5</para>
/// </remarks>
public void SetResourceReportLineList( ResourceReportLine ResourceReportLine ) {
RemoveChild( SchoolDTD.RESOURCEUSAGE_RESOURCEREPORTLINELIST);
AddChild( SchoolDTD.RESOURCEUSAGE_RESOURCEREPORTLINELIST, new ResourceReportLineList( ResourceReportLine ) );
}
/// <summary>
/// Gets or sets the value of the <c><ResourceReportLineList></c> element.
/// </summary>
/// <value> A ResourceReportLineList </value>
/// <remarks>
/// <para>To remove the <c>ResourceReportLineList</c>, set <c>ResourceReportLineList</c> to <c>null</c></para>
/// <para>Version: 2.6</para>
/// <para>Since: 2.5</para>
/// </remarks>
public ResourceReportLineList ResourceReportLineList
{
get
{
return (ResourceReportLineList)GetChild( SchoolDTD.RESOURCEUSAGE_RESOURCEREPORTLINELIST);
}
set
{
RemoveChild( SchoolDTD.RESOURCEUSAGE_RESOURCEREPORTLINELIST);
if( value != null)
{
AddChild( SchoolDTD.RESOURCEUSAGE_RESOURCEREPORTLINELIST, value );
}
}
}
}}
| {
"content_hash": "52e20e5d959b335eebd7691c7929d5e1",
"timestamp": "",
"source": "github",
"line_count": 213,
"max_line_length": 252,
"avg_line_length": 34.76525821596244,
"alnum_prop": 0.7199189736664416,
"repo_name": "open-adk/OpenADK-csharp",
"id": "f741264f7e48209a99c0beb519b2243072e4c3e7",
"size": "7568",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/au/sdo/School/ResourceUsage.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "16903092"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "486300c4ebb3a8d4efc4772508b158f3",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.307692307692308,
"alnum_prop": 0.6940298507462687,
"repo_name": "mdoering/backbone",
"id": "df3026cf7fd83ea960d60ec6c71a7db1dfbafde3",
"size": "195",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Chromista/Ochrophyta/Phaeophyceae/Laminariales/Laminariaceae/Laminaria/Laminaria hyperborea/Laminaria hyperborea compressa/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
body {
padding-top: 60px; /* 60px to make the container go all the way to the bottom of the topbar */
}
.post-current {
border-left: 6px solid #636ee7;
}
.post-inner {
margin-left: 10px;
word-wrap: break-word;
}
.post-other {
margin-top: 10px;
margin-bottom: 10px;
border-left: 6px solid #c3b8b8;
} | {
"content_hash": "758860a2d9c1c493c4317ec799253e76",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 95,
"avg_line_length": 16.31578947368421,
"alnum_prop": 0.6774193548387096,
"repo_name": "mlakkadshaw/SImple-Chat-Server",
"id": "fb23075e1905444c48991fd6d56c1a91c0716153",
"size": "310",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "public/stylesheets/style.css",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "395"
},
{
"name": "HTML",
"bytes": "22113"
},
{
"name": "JavaScript",
"bytes": "3855"
}
],
"symlink_target": ""
} |
[live demo](https://bees.github.io/yikyuk/#!/)
> yikyak clone to demo a more involved Vue project
## Build Setup
``` bash
# install dependencies
npm install
# serve with hot reload at localhost:8080
npm run dev
# build for production with minification
npm run build
# run unit tests
npm run unit
# run e2e tests
npm run e2e
# run all tests
npm test
```
For detailed explanation on how things work, checkout the [guide](https://github.com/vuejs-templates/webpack#vue-webpack-boilerplate) and [docs for vue-loader](http://vuejs.github.io/vue-loader).
| {
"content_hash": "f54d584b66c5b124cfc8df8e1aa99c28",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 195,
"avg_line_length": 19.310344827586206,
"alnum_prop": 0.7410714285714286,
"repo_name": "bees/yikyuk",
"id": "eb2ad1c2b8af0c2cf4d088cbab007fa0e139c6d5",
"size": "570",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "6148"
},
{
"name": "HTML",
"bytes": "437"
},
{
"name": "JavaScript",
"bytes": "18942"
},
{
"name": "Vue",
"bytes": "10698"
}
],
"symlink_target": ""
} |
/* Underline From Left */
.hvr-underline-from-left {
display: inline-block;
vertical-align: middle;
-webkit-transform: translateZ(0);
transform: translateZ(0);
box-shadow: 0 0 1px rgba(0, 0, 0, 0);
-webkit-backface-visibility: hidden;
backface-visibility: hidden;
-moz-osx-font-smoothing: grayscale;
position: relative;
overflow: hidden;
}
.hvr-underline-from-left:before {
content: "";
position: absolute;
z-index: -1;
left: 0;
right: 100%;
bottom: 0;
background: #666;
height: 2px;
-webkit-transition-property: right;
transition-property: right;
-webkit-transition-duration: 0.2s;
transition-duration: 0.2s;
-webkit-transition-timing-function: ease-out;
transition-timing-function: ease-out;
}
.hvr-underline-from-left:hover:before, .hvr-underline-from-left:focus:before, .hvr-underline-from-left:active:before {
right: 0;
} | {
"content_hash": "393c56ed66605378079b49fbfff94ae4",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 118,
"avg_line_length": 27.375,
"alnum_prop": 0.7077625570776256,
"repo_name": "ptatters/budgetgame-open",
"id": "2d2aef400943d8bdbedf7500b649c56a2ecdd6bb",
"size": "876",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ui/site/css/effects.css",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "39909"
},
{
"name": "HTML",
"bytes": "140074"
},
{
"name": "JavaScript",
"bytes": "347055"
},
{
"name": "PHP",
"bytes": "4959"
}
],
"symlink_target": ""
} |
package org.jkiss.dbeaver.ui.controls.lightgrid;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.widgets.Event;
/**
* Used by Grid to externalize the scrollbars from the table itself.
*
* @author chris.gross@us.ibm.com
* @version 1.0.0
*/
public interface IGridScrollBar
{
public int getWidth();
public boolean getVisible();
public void setVisible(boolean visible);
public int getSelection();
public void setSelection(int selection);
/**
* Sets the receiver's selection, minimum value, maximum value, thumb,
* increment and page increment all at once.
*
* @param selection selection
* @param min minimum
* @param max maximum
* @param thumb thumb
* @param increment increment
* @param pageIncrement page increment
*/
public void setValues(int selection, int min, int max, int thumb, int increment, int pageIncrement);
public void handleMouseWheel(Event e);
public void setMinimum(int min);
public int getMinimum();
public void setMaximum(int max);
public int getMaximum();
public void setThumb(int thumb);
public int getThumb();
public void setIncrement(int increment);
public int getIncrement();
public void setPageIncrement(int page);
public int getPageIncrement();
public void addSelectionListener(SelectionListener listener);
public void removeSelectionListener(SelectionListener listener);
}
| {
"content_hash": "1e21ca307de29938076f108258377451",
"timestamp": "",
"source": "github",
"line_count": 65,
"max_line_length": 104,
"avg_line_length": 24.50769230769231,
"alnum_prop": 0.6528562460765851,
"repo_name": "ruspl-afed/dbeaver",
"id": "5012b9696a5e9bce8754024a11f8d010a01f100a",
"size": "2269",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "plugins/org.jkiss.dbeaver.core/src/org/jkiss/dbeaver/ui/controls/lightgrid/IGridScrollBar.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "690"
},
{
"name": "C++",
"bytes": "65328"
},
{
"name": "CSS",
"bytes": "4214"
},
{
"name": "HTML",
"bytes": "2368"
},
{
"name": "Java",
"bytes": "12750447"
},
{
"name": "Shell",
"bytes": "32"
},
{
"name": "XSLT",
"bytes": "7361"
}
],
"symlink_target": ""
} |
import EventEmitter from '../sync/EventEmitter';
export default {
activate() {
EventEmitter.getInstance()
.synced.entities(':user:selected')
.cancelProduction(0);
},
};
| {
"content_hash": "696b91d40191bdd8eeea5e2b1bc3275e",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 48,
"avg_line_length": 21.11111111111111,
"alnum_prop": 0.6578947368421053,
"repo_name": "vbence86/fivenations",
"id": "3ee1fda78b2c1b18467e8c1f16ca3787af8d7905",
"size": "190",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/js/gui/CancelProductionButton.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1116"
},
{
"name": "Dockerfile",
"bytes": "666"
},
{
"name": "HTML",
"bytes": "8858"
},
{
"name": "JavaScript",
"bytes": "26660266"
},
{
"name": "Shell",
"bytes": "3728"
}
],
"symlink_target": ""
} |
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/*
| -------------------------------------------------------------------
| AUTO-LOADER
| -------------------------------------------------------------------
| This file specifies which systems should be loaded by default.
|
| In order to keep the framework as light-weight as possible only the
| absolute minimal resources are loaded by default. For example,
| the database is not connected to automatically since no assumption
| is made regarding whether you intend to use it. This file lets
| you globally define which systems you would like loaded with every
| request.
|
| -------------------------------------------------------------------
| Instructions
| -------------------------------------------------------------------
|
| These are the things you can load automatically:
|
| 1. Packages
| 2. Libraries
| 3. Drivers
| 4. Helper files
| 5. Custom config files
| 6. Language files
| 7. Models
|
*/
/*
| -------------------------------------------------------------------
| Auto-load Packages
| -------------------------------------------------------------------
| Prototype:
|
| $autoload['packages'] = array(APPPATH.'third_party', '/usr/local/shared');
|
*/
$autoload['packages'] = array();
/*
| -------------------------------------------------------------------
| Auto-load Libraries
| -------------------------------------------------------------------
| These are the classes located in system/libraries/ or your
| application/libraries/ directory, with the addition of the
| 'database' library, which is somewhat of a special case.
|
| Prototype:
|
| $autoload['libraries'] = array('database', 'email', 'session');
|
| You can also supply an alternative library name to be assigned
| in the controller:
|
| $autoload['libraries'] = array('user_agent' => 'ua');
*/
$autoload['libraries'] = array('database', 'session', 'form_validation', 'user_agent');
/*
| -------------------------------------------------------------------
| Auto-load Drivers
| -------------------------------------------------------------------
| These classes are located in system/libraries/ or in your
| application/libraries/ directory, but are also placed inside their
| own subdirectory and they extend the CI_Driver_Library class. They
| offer multiple interchangeable driver options.
|
| Prototype:
|
| $autoload['drivers'] = array('cache');
|
| You can also supply an alternative property name to be assigned in
| the controller:
|
| $autoload['drivers'] = array('cache' => 'cch');
|
*/
$autoload['drivers'] = array();
/*
| -------------------------------------------------------------------
| Auto-load Helper Files
| -------------------------------------------------------------------
| Prototype:
|
| $autoload['helper'] = array('url', 'file');
*/
$autoload['helper'] = array("form", "url", "security");
/*
| -------------------------------------------------------------------
| Auto-load Config files
| -------------------------------------------------------------------
| Prototype:
|
| $autoload['config'] = array('config1', 'config2');
|
| NOTE: This item is intended for use ONLY if you have created custom
| config files. Otherwise, leave it blank.
|
*/
$autoload['config'] = array();
/*
| -------------------------------------------------------------------
| Auto-load Language files
| -------------------------------------------------------------------
| Prototype:
|
| $autoload['language'] = array('lang1', 'lang2');
|
| NOTE: Do not include the "_lang" part of your file. For example
| "codeigniter_lang.php" would be referenced as array('codeigniter');
|
*/
$autoload['language'] = array();
/*
| -------------------------------------------------------------------
| Auto-load Models
| -------------------------------------------------------------------
| Prototype:
|
| $autoload['model'] = array('first_model', 'second_model');
|
| You can also supply an alternative model name to be assigned
| in the controller:
|
| $autoload['model'] = array('first_model' => 'first');
*/
$autoload['model'] = array();
| {
"content_hash": "5c7ab980428b7e4d80db7c20ae1ebc76",
"timestamp": "",
"source": "github",
"line_count": 135,
"max_line_length": 87,
"avg_line_length": 30.4,
"alnum_prop": 0.4788011695906433,
"repo_name": "kewei/newdeisgn_personal_website",
"id": "81768d5271cd04612c1385d453bd5ab52f18823d",
"size": "4104",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "application/config/autoload.php",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "351"
},
{
"name": "CSS",
"bytes": "2344"
},
{
"name": "HTML",
"bytes": "5633"
},
{
"name": "JavaScript",
"bytes": "39773"
},
{
"name": "PHP",
"bytes": "1815340"
}
],
"symlink_target": ""
} |
<!-- Logo -->
<p align="center">
<img alt="Terra Logo" height="128" width="128" src="https://github.com/cerner/terra-clinical/raw/main/terra.png" />
</p>
<!-- Name -->
<h1 align="center">
Terra Clinical
</h1>
[](http://engineering.cerner.com/2014/01/cerner-and-open-source/)
[](https://github.com/cerner/terra-clinical/blob/main/LICENSE)
[](https://travis-ci.com/cerner/terra-clinical)
[](https://david-dm.org/cerner/terra-clinical?type=dev)
[](https://lerna.js.org/)
- [Supported Browsers](https://github.com/cerner/terra-ui/blob/main/src/terra-dev-site/about/ComponentStandards.e.contributing.md#cross-browser-support)
- [Packages](#packages)
- [Status](#status)
- [Internationalization (I18n)](#internationalization-i18n)
- [Contributing](#contributing)
- [Local Development](#local-development)
- [LICENSE](#license)
<h2 id="packages">
Packages
</h2>
<h3 id="status">
Status
</h3>



<!-- AUTO-GENERATED-CONTENT:START (SUBPACKAGELIST) -->
| Terra Package | Version | Status | Dependencies |
|--------------------|---------|--------|--------------|
| [terra-clinical-data-grid](https://github.com/cerner/terra-clinical/tree/main/packages/terra-clinical-data-grid) | [](https://www.npmjs.org/package/terra-clinical-data-grid) |  | [](https://david-dm.org/cerner/terra-clinical?path=packages/terra-clinical-data-grid) |
| [terra-clinical-detail-view](https://github.com/cerner/terra-clinical/tree/main/packages/terra-clinical-detail-view) | [](https://www.npmjs.org/package/terra-clinical-detail-view) |  | [](https://david-dm.org/cerner/terra-clinical?path=packages/terra-clinical-detail-view) |
| [terra-clinical-header](https://github.com/cerner/terra-clinical/tree/main/packages/terra-clinical-header) | [](https://www.npmjs.org/package/terra-clinical-header) |  | [](https://david-dm.org/cerner/terra-clinical?path=packages/terra-clinical-header) |
| [terra-clinical-item-collection](https://github.com/cerner/terra-clinical/tree/main/packages/terra-clinical-item-collection) | [](https://www.npmjs.org/package/terra-clinical-item-collection) |  | [](https://david-dm.org/cerner/terra-clinical?path=packages/terra-clinical-item-collection) |
| [terra-clinical-item-display](https://github.com/cerner/terra-clinical/tree/main/packages/terra-clinical-item-display) | [](https://www.npmjs.org/package/terra-clinical-item-display) |  | [](https://david-dm.org/cerner/terra-clinical?path=packages/terra-clinical-item-display) |
| [terra-clinical-item-view](https://github.com/cerner/terra-clinical/tree/main/packages/terra-clinical-item-view) | [](https://www.npmjs.org/package/terra-clinical-item-view) |  | [](https://david-dm.org/cerner/terra-clinical?path=packages/terra-clinical-item-view) |
| [terra-clinical-label-value-view](https://github.com/cerner/terra-clinical/tree/main/packages/terra-clinical-label-value-view) | [](https://www.npmjs.org/package/terra-clinical-label-value-view) |  | [](https://david-dm.org/cerner/terra-clinical?path=packages/terra-clinical-label-value-view) |
| [terra-clinical-onset-picker](https://github.com/cerner/terra-clinical/tree/main/packages/terra-clinical-onset-picker) | [](https://www.npmjs.org/package/terra-clinical-onset-picker) |  | [](https://david-dm.org/cerner/terra-clinical?path=packages/terra-clinical-onset-picker) |
<!-- AUTO-GENERATED-CONTENT:END *-->
### Deprecated
| Terra Package | Version | Status |
|--------------------|---------|--------|
| terra-clinical-action-header | [](https://www.npmjs.org/package/terra-clinical-action-header) | |
| terra-clinical-app-delegate |[](https://www.npmjs.org/package/terra-clinical-app-delegate) | |
| terra-clinical-error-view | [](https://www.npmjs.org/package/terra-clinical-error-view) | |
| terra-clinical-modal-manager |[](https://www.npmjs.org/package/terra-clinical-modal-manager) | |
| terra-clinical-no-data-view | [](https://www.npmjs.org/package/terra-clinical-no-data-view) | |
| terra-clinical-site |[](https://www.npmjs.org/package/terra-clinical-site) | |
| terra-clinical-slide-group |[](https://www.npmjs.org/package/terra-clinical-slide-group) | |
<h2 id="internationalization-i18n">
Internationalization (I18n)
</h2>
Please review [Terra's Internationalization documentation](https://engineering.cerner.com/terra-ui/#/getting-started/terra-ui/internationalization) for more information. Included are directions on consumption and how internationalization is setup.
<h2 id="contributing">
Contributing
</h2>
Please read through our [contributing guidelines](CONTRIBUTING.md). Included are directions for issue reporting and pull requests.
<h2 id="local-development">
Local Development
</h2>
1. Install docker https://www.docker.com/ to run browser tests.
2. Install dependencies and run tests.
```sh
npm install
npm run test
```
<h2 id="license">
LICENSE
</h2>
Copyright 2017 - 2020 Cerner Innovation, Inc.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
| {
"content_hash": "c1f28c475b9f14a62f4f1ac477193cb6",
"timestamp": "",
"source": "github",
"line_count": 95,
"max_line_length": 550,
"avg_line_length": 91.9578947368421,
"alnum_prop": 0.7503434065934066,
"repo_name": "cerner/terra-clinical",
"id": "48fed980cea648714007a0081a290b63b1d29d7a",
"size": "8736",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "62"
},
{
"name": "JavaScript",
"bytes": "558154"
},
{
"name": "Procfile",
"bytes": "26"
},
{
"name": "SCSS",
"bytes": "107800"
}
],
"symlink_target": ""
} |
using System.ComponentModel.DataAnnotations;
namespace $safeprojectname$.Data.ApiModels
{
public class LoginApiModel
{
[Required]
public string Email { get; set; }
[Required]
public string Password { get; set; }
}
} | {
"content_hash": "23b853b698f3e41c7c115401929a9d5b",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 45,
"avg_line_length": 20.153846153846153,
"alnum_prop": 0.6335877862595419,
"repo_name": "miseeger/VisualStudio.Templates",
"id": "75bd962fd1ca464a0b79cde0d0a5979bdb9a4ccd",
"size": "264",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Sources/AspDotNet Core JWTAuth WebApi VueClient EF/NetCoreApi.Core/Data/ApiModels/LoginApiModel.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "641932"
},
{
"name": "CSS",
"bytes": "3740"
},
{
"name": "HTML",
"bytes": "18315"
},
{
"name": "JavaScript",
"bytes": "17700"
},
{
"name": "TypeScript",
"bytes": "75139"
},
{
"name": "VBA",
"bytes": "16407"
},
{
"name": "Vue",
"bytes": "70164"
}
],
"symlink_target": ""
} |
<?php
namespace yii\db;
use yii\base\InvalidParamException;
use yii\base\NotSupportedException;
use yii\helpers\ArrayHelper;
/**
* QueryBuilder builds a SELECT SQL statement based on the specification given as a [[Query]] object.
*
* SQL statements are created from [[Query]] objects using the [[build()]]-method.
*
* QueryBuilder is also used by [[Command]] to build SQL statements such as INSERT, UPDATE, DELETE, CREATE TABLE.
*
* For more details and usage information on QueryBuilder, see the [guide article on query builders](guide:db-query-builder).
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class QueryBuilder extends \yii\base\Object
{
/**
* The prefix for automatically generated query binding parameters.
*/
const PARAM_PREFIX = ':qp';
/**
* @var Connection the database connection.
*/
public $db;
/**
* @var string the separator between different fragments of a SQL statement.
* Defaults to an empty space. This is mainly used by [[build()]] when generating a SQL statement.
*/
public $separator = ' ';
/**
* @var array the abstract column types mapped to physical column types.
* This is mainly used to support creating/modifying tables using DB-independent data type specifications.
* Child classes should override this property to declare supported type mappings.
*/
public $typeMap = [];
/**
* @var array map of query condition to builder methods.
* These methods are used by [[buildCondition]] to build SQL conditions from array syntax.
*/
protected $conditionBuilders = [
'NOT' => 'buildNotCondition',
'AND' => 'buildAndCondition',
'OR' => 'buildAndCondition',
'BETWEEN' => 'buildBetweenCondition',
'NOT BETWEEN' => 'buildBetweenCondition',
'IN' => 'buildInCondition',
'NOT IN' => 'buildInCondition',
'LIKE' => 'buildLikeCondition',
'NOT LIKE' => 'buildLikeCondition',
'OR LIKE' => 'buildLikeCondition',
'OR NOT LIKE' => 'buildLikeCondition',
'EXISTS' => 'buildExistsCondition',
'NOT EXISTS' => 'buildExistsCondition',
];
/**
* @var array map of chars to their replacements in LIKE conditions.
* By default it's configured to escape `%`, `_` and `\` with `\`.
* @since 2.0.12.
*/
protected $likeEscapingReplacements = [
'%' => '\%',
'_' => '\_',
'\\' => '\\\\',
];
/**
* @var string|null character used to escape special characters in LIKE conditions.
* By default it's assumed to be `\`.
* @since 2.0.12
*/
protected $likeEscapeCharacter;
/**
* Constructor.
* @param Connection $connection the database connection.
* @param array $config name-value pairs that will be used to initialize the object properties
*/
public function __construct($connection, $config = [])
{
$this->db = $connection;
parent::__construct($config);
}
/**
* Generates a SELECT SQL statement from a [[Query]] object.
* @param Query $query the [[Query]] object from which the SQL statement will be generated.
* @param array $params the parameters to be bound to the generated SQL statement. These parameters will
* be included in the result with the additional parameters generated during the query building process.
* @return array the generated SQL statement (the first array element) and the corresponding
* parameters to be bound to the SQL statement (the second array element). The parameters returned
* include those provided in `$params`.
*/
public function build($query, $params = [])
{
$query = $query->prepare($this);
$params = empty($params) ? $query->params : array_merge($params, $query->params);
$clauses = [
$this->buildSelect($query->select, $params, $query->distinct, $query->selectOption),
$this->buildFrom($query->from, $params),
$this->buildJoin($query->join, $params),
$this->buildWhere($query->where, $params),
$this->buildGroupBy($query->groupBy),
$this->buildHaving($query->having, $params),
];
$sql = implode($this->separator, array_filter($clauses));
$sql = $this->buildOrderByAndLimit($sql, $query->orderBy, $query->limit, $query->offset);
if (!empty($query->orderBy)) {
foreach ($query->orderBy as $expression) {
if ($expression instanceof Expression) {
$params = array_merge($params, $expression->params);
}
}
}
if (!empty($query->groupBy)) {
foreach ($query->groupBy as $expression) {
if ($expression instanceof Expression) {
$params = array_merge($params, $expression->params);
}
}
}
$union = $this->buildUnion($query->union, $params);
if ($union !== '') {
$sql = "($sql){$this->separator}$union";
}
return [$sql, $params];
}
/**
* Creates an INSERT SQL statement.
* For example,
*
* ```php
* $sql = $queryBuilder->insert('user', [
* 'name' => 'Sam',
* 'age' => 30,
* ], $params);
* ```
*
* The method will properly escape the table and column names.
*
* @param string $table the table that new rows will be inserted into.
* @param array|\yii\db\Query $columns the column data (name => value) to be inserted into the table or instance
* of [[yii\db\Query|Query]] to perform INSERT INTO ... SELECT SQL statement.
* Passing of [[yii\db\Query|Query]] is available since version 2.0.11.
* @param array $params the binding parameters that will be generated by this method.
* They should be bound to the DB command later.
* @return string the INSERT SQL
*/
public function insert($table, $columns, &$params)
{
$schema = $this->db->getSchema();
if (($tableSchema = $schema->getTableSchema($table)) !== null) {
$columnSchemas = $tableSchema->columns;
} else {
$columnSchemas = [];
}
$names = [];
$placeholders = [];
$values = ' DEFAULT VALUES';
if ($columns instanceof \yii\db\Query) {
list($names, $values, $params) = $this->prepareInsertSelectSubQuery($columns, $schema);
} else {
foreach ($columns as $name => $value) {
$names[] = $schema->quoteColumnName($name);
if ($value instanceof Expression) {
$placeholders[] = $value->expression;
foreach ($value->params as $n => $v) {
$params[$n] = $v;
}
} elseif ($value instanceof \yii\db\Query) {
list($sql, $params) = $this->build($value, $params);
$placeholders[] = "($sql)";
} else {
$phName = self::PARAM_PREFIX . count($params);
$placeholders[] = $phName;
$params[$phName] = !is_array($value) && isset($columnSchemas[$name]) ? $columnSchemas[$name]->dbTypecast($value) : $value;
}
}
}
return 'INSERT INTO ' . $schema->quoteTableName($table)
. (!empty($names) ? ' (' . implode(', ', $names) . ')' : '')
. (!empty($placeholders) ? ' VALUES (' . implode(', ', $placeholders) . ')' : $values);
}
/**
* Prepare select-subquery and field names for INSERT INTO ... SELECT SQL statement.
*
* @param \yii\db\Query $columns Object, which represents select query.
* @param \yii\db\Schema $schema Schema object to quote column name.
* @param array $params the parameters to be bound to the generated SQL statement. These parameters will
* be included in the result with the additional parameters generated during the query building process.
* @return array
* @throws InvalidParamException if query's select does not contain named parameters only.
* @since 2.0.11
*/
protected function prepareInsertSelectSubQuery($columns, $schema, $params = [])
{
if (!is_array($columns->select) || empty($columns->select) || in_array('*', $columns->select)) {
throw new InvalidParamException('Expected select query object with enumerated (named) parameters');
}
list($values, $params) = $this->build($columns, $params);
$names = [];
$values = ' ' . $values;
foreach ($columns->select as $title => $field) {
if (is_string($title)) {
$names[] = $schema->quoteColumnName($title);
} else if (preg_match('/^(.*?)(?i:\s+as\s+|\s+)([\w\-_\.]+)$/', $field, $matches)) {
$names[] = $schema->quoteColumnName($matches[2]);
} else {
$names[] = $schema->quoteColumnName($field);
}
}
return [$names, $values, $params];
}
/**
* Generates a batch INSERT SQL statement.
* For example,
*
* ```php
* $sql = $queryBuilder->batchInsert('user', ['name', 'age'], [
* ['Tom', 30],
* ['Jane', 20],
* ['Linda', 25],
* ]);
* ```
*
* Note that the values in each row must match the corresponding column names.
*
* The method will properly escape the column names, and quote the values to be inserted.
*
* @param string $table the table that new rows will be inserted into.
* @param array $columns the column names
* @param array $rows the rows to be batch inserted into the table
* @return string the batch INSERT SQL statement
*/
public function batchInsert($table, $columns, $rows)
{
if (empty($rows)) {
return '';
}
$schema = $this->db->getSchema();
if (($tableSchema = $schema->getTableSchema($table)) !== null) {
$columnSchemas = $tableSchema->columns;
} else {
$columnSchemas = [];
}
$values = [];
foreach ($rows as $row) {
$vs = [];
foreach ($row as $i => $value) {
if (isset($columns[$i], $columnSchemas[$columns[$i]]) && !is_array($value)) {
$value = $columnSchemas[$columns[$i]]->dbTypecast($value);
}
if (is_string($value)) {
$value = $schema->quoteValue($value);
} elseif ($value === false) {
$value = 0;
} elseif ($value === null) {
$value = 'NULL';
}
$vs[] = $value;
}
$values[] = '(' . implode(', ', $vs) . ')';
}
if (empty($values)) {
return '';
}
foreach ($columns as $i => $name) {
$columns[$i] = $schema->quoteColumnName($name);
}
return 'INSERT INTO ' . $schema->quoteTableName($table)
. ' (' . implode(', ', $columns) . ') VALUES ' . implode(', ', $values);
}
/**
* Creates an UPDATE SQL statement.
* For example,
*
* ```php
* $params = [];
* $sql = $queryBuilder->update('user', ['status' => 1], 'age > 30', $params);
* ```
*
* The method will properly escape the table and column names.
*
* @param string $table the table to be updated.
* @param array $columns the column data (name => value) to be updated.
* @param array|string $condition the condition that will be put in the WHERE part. Please
* refer to [[Query::where()]] on how to specify condition.
* @param array $params the binding parameters that will be modified by this method
* so that they can be bound to the DB command later.
* @return string the UPDATE SQL
*/
public function update($table, $columns, $condition, &$params)
{
if (($tableSchema = $this->db->getTableSchema($table)) !== null) {
$columnSchemas = $tableSchema->columns;
} else {
$columnSchemas = [];
}
$lines = [];
foreach ($columns as $name => $value) {
if ($value instanceof Expression) {
$lines[] = $this->db->quoteColumnName($name) . '=' . $value->expression;
foreach ($value->params as $n => $v) {
$params[$n] = $v;
}
} else {
$phName = self::PARAM_PREFIX . count($params);
$lines[] = $this->db->quoteColumnName($name) . '=' . $phName;
$params[$phName] = !is_array($value) && isset($columnSchemas[$name]) ? $columnSchemas[$name]->dbTypecast($value) : $value;
}
}
$sql = 'UPDATE ' . $this->db->quoteTableName($table) . ' SET ' . implode(', ', $lines);
$where = $this->buildWhere($condition, $params);
return $where === '' ? $sql : $sql . ' ' . $where;
}
/**
* Creates a DELETE SQL statement.
* For example,
*
* ```php
* $sql = $queryBuilder->delete('user', 'status = 0');
* ```
*
* The method will properly escape the table and column names.
*
* @param string $table the table where the data will be deleted from.
* @param array|string $condition the condition that will be put in the WHERE part. Please
* refer to [[Query::where()]] on how to specify condition.
* @param array $params the binding parameters that will be modified by this method
* so that they can be bound to the DB command later.
* @return string the DELETE SQL
*/
public function delete($table, $condition, &$params)
{
$sql = 'DELETE FROM ' . $this->db->quoteTableName($table);
$where = $this->buildWhere($condition, $params);
return $where === '' ? $sql : $sql . ' ' . $where;
}
/**
* Builds a SQL statement for creating a new DB table.
*
* The columns in the new table should be specified as name-definition pairs (e.g. 'name' => 'string'),
* where name stands for a column name which will be properly quoted by the method, and definition
* stands for the column type which can contain an abstract DB type.
* The [[getColumnType()]] method will be invoked to convert any abstract type into a physical one.
*
* If a column is specified with definition only (e.g. 'PRIMARY KEY (name, type)'), it will be directly
* inserted into the generated SQL.
*
* For example,
*
* ```php
* $sql = $queryBuilder->createTable('user', [
* 'id' => 'pk',
* 'name' => 'string',
* 'age' => 'integer',
* ]);
* ```
*
* @param string $table the name of the table to be created. The name will be properly quoted by the method.
* @param array $columns the columns (name => definition) in the new table.
* @param string $options additional SQL fragment that will be appended to the generated SQL.
* @return string the SQL statement for creating a new DB table.
*/
public function createTable($table, $columns, $options = null)
{
$cols = [];
foreach ($columns as $name => $type) {
if (is_string($name)) {
$cols[] = "\t" . $this->db->quoteColumnName($name) . ' ' . $this->getColumnType($type);
} else {
$cols[] = "\t" . $type;
}
}
$sql = 'CREATE TABLE ' . $this->db->quoteTableName($table) . " (\n" . implode(",\n", $cols) . "\n)";
return $options === null ? $sql : $sql . ' ' . $options;
}
/**
* Builds a SQL statement for renaming a DB table.
* @param string $oldName the table to be renamed. The name will be properly quoted by the method.
* @param string $newName the new table name. The name will be properly quoted by the method.
* @return string the SQL statement for renaming a DB table.
*/
public function renameTable($oldName, $newName)
{
return 'RENAME TABLE ' . $this->db->quoteTableName($oldName) . ' TO ' . $this->db->quoteTableName($newName);
}
/**
* Builds a SQL statement for dropping a DB table.
* @param string $table the table to be dropped. The name will be properly quoted by the method.
* @return string the SQL statement for dropping a DB table.
*/
public function dropTable($table)
{
return 'DROP TABLE ' . $this->db->quoteTableName($table);
}
/**
* Builds a SQL statement for adding a primary key constraint to an existing table.
* @param string $name the name of the primary key constraint.
* @param string $table the table that the primary key constraint will be added to.
* @param string|array $columns comma separated string or array of columns that the primary key will consist of.
* @return string the SQL statement for adding a primary key constraint to an existing table.
*/
public function addPrimaryKey($name, $table, $columns)
{
if (is_string($columns)) {
$columns = preg_split('/\s*,\s*/', $columns, -1, PREG_SPLIT_NO_EMPTY);
}
foreach ($columns as $i => $col) {
$columns[$i] = $this->db->quoteColumnName($col);
}
return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' ADD CONSTRAINT '
. $this->db->quoteColumnName($name) . ' PRIMARY KEY ('
. implode(', ', $columns). ' )';
}
/**
* Builds a SQL statement for removing a primary key constraint to an existing table.
* @param string $name the name of the primary key constraint to be removed.
* @param string $table the table that the primary key constraint will be removed from.
* @return string the SQL statement for removing a primary key constraint from an existing table.
*/
public function dropPrimaryKey($name, $table)
{
return 'ALTER TABLE ' . $this->db->quoteTableName($table)
. ' DROP CONSTRAINT ' . $this->db->quoteColumnName($name);
}
/**
* Builds a SQL statement for truncating a DB table.
* @param string $table the table to be truncated. The name will be properly quoted by the method.
* @return string the SQL statement for truncating a DB table.
*/
public function truncateTable($table)
{
return 'TRUNCATE TABLE ' . $this->db->quoteTableName($table);
}
/**
* Builds a SQL statement for adding a new DB column.
* @param string $table the table that the new column will be added to. The table name will be properly quoted by the method.
* @param string $column the name of the new column. The name will be properly quoted by the method.
* @param string $type the column type. The [[getColumnType()]] method will be invoked to convert abstract column type (if any)
* into the physical one. Anything that is not recognized as abstract type will be kept in the generated SQL.
* For example, 'string' will be turned into 'varchar(255)', while 'string not null' will become 'varchar(255) not null'.
* @return string the SQL statement for adding a new column.
*/
public function addColumn($table, $column, $type)
{
return 'ALTER TABLE ' . $this->db->quoteTableName($table)
. ' ADD ' . $this->db->quoteColumnName($column) . ' '
. $this->getColumnType($type);
}
/**
* Builds a SQL statement for dropping a DB column.
* @param string $table the table whose column is to be dropped. The name will be properly quoted by the method.
* @param string $column the name of the column to be dropped. The name will be properly quoted by the method.
* @return string the SQL statement for dropping a DB column.
*/
public function dropColumn($table, $column)
{
return 'ALTER TABLE ' . $this->db->quoteTableName($table)
. ' DROP COLUMN ' . $this->db->quoteColumnName($column);
}
/**
* Builds a SQL statement for renaming a column.
* @param string $table the table whose column is to be renamed. The name will be properly quoted by the method.
* @param string $oldName the old name of the column. The name will be properly quoted by the method.
* @param string $newName the new name of the column. The name will be properly quoted by the method.
* @return string the SQL statement for renaming a DB column.
*/
public function renameColumn($table, $oldName, $newName)
{
return 'ALTER TABLE ' . $this->db->quoteTableName($table)
. ' RENAME COLUMN ' . $this->db->quoteColumnName($oldName)
. ' TO ' . $this->db->quoteColumnName($newName);
}
/**
* Builds a SQL statement for changing the definition of a column.
* @param string $table the table whose column is to be changed. The table name will be properly quoted by the method.
* @param string $column the name of the column to be changed. The name will be properly quoted by the method.
* @param string $type the new column type. The [[getColumnType()]] method will be invoked to convert abstract
* column type (if any) into the physical one. Anything that is not recognized as abstract type will be kept
* in the generated SQL. For example, 'string' will be turned into 'varchar(255)', while 'string not null'
* will become 'varchar(255) not null'.
* @return string the SQL statement for changing the definition of a column.
*/
public function alterColumn($table, $column, $type)
{
return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' CHANGE '
. $this->db->quoteColumnName($column) . ' '
. $this->db->quoteColumnName($column) . ' '
. $this->getColumnType($type);
}
/**
* Builds a SQL statement for adding a foreign key constraint to an existing table.
* The method will properly quote the table and column names.
* @param string $name the name of the foreign key constraint.
* @param string $table the table that the foreign key constraint will be added to.
* @param string|array $columns the name of the column to that the constraint will be added on.
* If there are multiple columns, separate them with commas or use an array to represent them.
* @param string $refTable the table that the foreign key references to.
* @param string|array $refColumns the name of the column that the foreign key references to.
* If there are multiple columns, separate them with commas or use an array to represent them.
* @param string $delete the ON DELETE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL
* @param string $update the ON UPDATE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL
* @return string the SQL statement for adding a foreign key constraint to an existing table.
*/
public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete = null, $update = null)
{
$sql = 'ALTER TABLE ' . $this->db->quoteTableName($table)
. ' ADD CONSTRAINT ' . $this->db->quoteColumnName($name)
. ' FOREIGN KEY (' . $this->buildColumns($columns) . ')'
. ' REFERENCES ' . $this->db->quoteTableName($refTable)
. ' (' . $this->buildColumns($refColumns) . ')';
if ($delete !== null) {
$sql .= ' ON DELETE ' . $delete;
}
if ($update !== null) {
$sql .= ' ON UPDATE ' . $update;
}
return $sql;
}
/**
* Builds a SQL statement for dropping a foreign key constraint.
* @param string $name the name of the foreign key constraint to be dropped. The name will be properly quoted by the method.
* @param string $table the table whose foreign is to be dropped. The name will be properly quoted by the method.
* @return string the SQL statement for dropping a foreign key constraint.
*/
public function dropForeignKey($name, $table)
{
return 'ALTER TABLE ' . $this->db->quoteTableName($table)
. ' DROP CONSTRAINT ' . $this->db->quoteColumnName($name);
}
/**
* Builds a SQL statement for creating a new index.
* @param string $name the name of the index. The name will be properly quoted by the method.
* @param string $table the table that the new index will be created for. The table name will be properly quoted by the method.
* @param string|array $columns the column(s) that should be included in the index. If there are multiple columns,
* separate them with commas or use an array to represent them. Each column name will be properly quoted
* by the method, unless a parenthesis is found in the name.
* @param bool $unique whether to add UNIQUE constraint on the created index.
* @return string the SQL statement for creating a new index.
*/
public function createIndex($name, $table, $columns, $unique = false)
{
return ($unique ? 'CREATE UNIQUE INDEX ' : 'CREATE INDEX ')
. $this->db->quoteTableName($name) . ' ON '
. $this->db->quoteTableName($table)
. ' (' . $this->buildColumns($columns) . ')';
}
/**
* Builds a SQL statement for dropping an index.
* @param string $name the name of the index to be dropped. The name will be properly quoted by the method.
* @param string $table the table whose index is to be dropped. The name will be properly quoted by the method.
* @return string the SQL statement for dropping an index.
*/
public function dropIndex($name, $table)
{
return 'DROP INDEX ' . $this->db->quoteTableName($name) . ' ON ' . $this->db->quoteTableName($table);
}
/**
* Creates a SQL statement for resetting the sequence value of a table's primary key.
* The sequence will be reset such that the primary key of the next new row inserted
* will have the specified value or 1.
* @param string $table the name of the table whose primary key sequence will be reset
* @param array|string $value the value for the primary key of the next new row inserted. If this is not set,
* the next new row's primary key will have a value 1.
* @return string the SQL statement for resetting sequence
* @throws NotSupportedException if this is not supported by the underlying DBMS
*/
public function resetSequence($table, $value = null)
{
throw new NotSupportedException($this->db->getDriverName() . ' does not support resetting sequence.');
}
/**
* Builds a SQL statement for enabling or disabling integrity check.
* @param bool $check whether to turn on or off the integrity check.
* @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema.
* @param string $table the table name. Defaults to empty string, meaning that no table will be changed.
* @return string the SQL statement for checking integrity
* @throws NotSupportedException if this is not supported by the underlying DBMS
*/
public function checkIntegrity($check = true, $schema = '', $table = '')
{
throw new NotSupportedException($this->db->getDriverName() . ' does not support enabling/disabling integrity check.');
}
/**
* Builds a SQL command for adding comment to column
*
* @param string $table the table whose column is to be commented. The table name will be properly quoted by the method.
* @param string $column the name of the column to be commented. The column name will be properly quoted by the method.
* @param string $comment the text of the comment to be added. The comment will be properly quoted by the method.
* @return string the SQL statement for adding comment on column
* @since 2.0.8
*/
public function addCommentOnColumn($table, $column, $comment)
{
return 'COMMENT ON COLUMN ' . $this->db->quoteTableName($table) . '.' . $this->db->quoteColumnName($column) . ' IS ' . $this->db->quoteValue($comment);
}
/**
* Builds a SQL command for adding comment to table
*
* @param string $table the table whose column is to be commented. The table name will be properly quoted by the method.
* @param string $comment the text of the comment to be added. The comment will be properly quoted by the method.
* @return string the SQL statement for adding comment on table
* @since 2.0.8
*/
public function addCommentOnTable($table, $comment)
{
return 'COMMENT ON TABLE ' . $this->db->quoteTableName($table) . ' IS ' . $this->db->quoteValue($comment);
}
/**
* Builds a SQL command for adding comment to column
*
* @param string $table the table whose column is to be commented. The table name will be properly quoted by the method.
* @param string $column the name of the column to be commented. The column name will be properly quoted by the method.
* @return string the SQL statement for adding comment on column
* @since 2.0.8
*/
public function dropCommentFromColumn($table, $column)
{
return 'COMMENT ON COLUMN ' . $this->db->quoteTableName($table) . '.' . $this->db->quoteColumnName($column) . ' IS NULL';
}
/**
* Builds a SQL command for adding comment to table
*
* @param string $table the table whose column is to be commented. The table name will be properly quoted by the method.
* @return string the SQL statement for adding comment on column
* @since 2.0.8
*/
public function dropCommentFromTable($table)
{
return 'COMMENT ON TABLE ' . $this->db->quoteTableName($table) . ' IS NULL';
}
/**
* Converts an abstract column type into a physical column type.
* The conversion is done using the type map specified in [[typeMap]].
* The following abstract column types are supported (using MySQL as an example to explain the corresponding
* physical types):
*
* - `pk`: an auto-incremental primary key type, will be converted into "int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY"
* - `bigpk`: an auto-incremental primary key type, will be converted into "bigint(20) NOT NULL AUTO_INCREMENT PRIMARY KEY"
* - `unsignedpk`: an unsigned auto-incremental primary key type, will be converted into "int(11) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY"
* - `char`: char type, will be converted into "char(1)"
* - `string`: string type, will be converted into "varchar(255)"
* - `text`: a long string type, will be converted into "text"
* - `smallint`: a small integer type, will be converted into "smallint(6)"
* - `integer`: integer type, will be converted into "int(11)"
* - `bigint`: a big integer type, will be converted into "bigint(20)"
* - `boolean`: boolean type, will be converted into "tinyint(1)"
* - `float``: float number type, will be converted into "float"
* - `decimal`: decimal number type, will be converted into "decimal"
* - `datetime`: datetime type, will be converted into "datetime"
* - `timestamp`: timestamp type, will be converted into "timestamp"
* - `time`: time type, will be converted into "time"
* - `date`: date type, will be converted into "date"
* - `money`: money type, will be converted into "decimal(19,4)"
* - `binary`: binary data type, will be converted into "blob"
*
* If the abstract type contains two or more parts separated by spaces (e.g. "string NOT NULL"), then only
* the first part will be converted, and the rest of the parts will be appended to the converted result.
* For example, 'string NOT NULL' is converted to 'varchar(255) NOT NULL'.
*
* For some of the abstract types you can also specify a length or precision constraint
* by appending it in round brackets directly to the type.
* For example `string(32)` will be converted into "varchar(32)" on a MySQL database.
* If the underlying DBMS does not support these kind of constraints for a type it will
* be ignored.
*
* If a type cannot be found in [[typeMap]], it will be returned without any change.
* @param string|ColumnSchemaBuilder $type abstract column type
* @return string physical column type.
*/
public function getColumnType($type)
{
if ($type instanceof ColumnSchemaBuilder) {
$type = $type->__toString();
}
if (isset($this->typeMap[$type])) {
return $this->typeMap[$type];
} elseif (preg_match('/^(\w+)\((.+?)\)(.*)$/', $type, $matches)) {
if (isset($this->typeMap[$matches[1]])) {
return preg_replace('/\(.+\)/', '(' . $matches[2] . ')', $this->typeMap[$matches[1]]) . $matches[3];
}
} elseif (preg_match('/^(\w+)\s+/', $type, $matches)) {
if (isset($this->typeMap[$matches[1]])) {
return preg_replace('/^\w+/', $this->typeMap[$matches[1]], $type);
}
}
return $type;
}
/**
* @param array $columns
* @param array $params the binding parameters to be populated
* @param bool $distinct
* @param string $selectOption
* @return string the SELECT clause built from [[Query::$select]].
*/
public function buildSelect($columns, &$params, $distinct = false, $selectOption = null)
{
$select = $distinct ? 'SELECT DISTINCT' : 'SELECT';
if ($selectOption !== null) {
$select .= ' ' . $selectOption;
}
if (empty($columns)) {
return $select . ' *';
}
foreach ($columns as $i => $column) {
if ($column instanceof Expression) {
if (is_int($i)) {
$columns[$i] = $column->expression;
} else {
$columns[$i] = $column->expression . ' AS ' . $this->db->quoteColumnName($i);
}
$params = array_merge($params, $column->params);
} elseif ($column instanceof Query) {
list($sql, $params) = $this->build($column, $params);
$columns[$i] = "($sql) AS " . $this->db->quoteColumnName($i);
} elseif (is_string($i)) {
if (strpos($column, '(') === false) {
$column = $this->db->quoteColumnName($column);
}
$columns[$i] = "$column AS " . $this->db->quoteColumnName($i);
} elseif (strpos($column, '(') === false) {
if (preg_match('/^(.*?)(?i:\s+as\s+|\s+)([\w\-_\.]+)$/', $column, $matches)) {
$columns[$i] = $this->db->quoteColumnName($matches[1]) . ' AS ' . $this->db->quoteColumnName($matches[2]);
} else {
$columns[$i] = $this->db->quoteColumnName($column);
}
}
}
return $select . ' ' . implode(', ', $columns);
}
/**
* @param array $tables
* @param array $params the binding parameters to be populated
* @return string the FROM clause built from [[Query::$from]].
*/
public function buildFrom($tables, &$params)
{
if (empty($tables)) {
return '';
}
$tables = $this->quoteTableNames($tables, $params);
return 'FROM ' . implode(', ', $tables);
}
/**
* @param array $joins
* @param array $params the binding parameters to be populated
* @return string the JOIN clause built from [[Query::$join]].
* @throws Exception if the $joins parameter is not in proper format
*/
public function buildJoin($joins, &$params)
{
if (empty($joins)) {
return '';
}
foreach ($joins as $i => $join) {
if (!is_array($join) || !isset($join[0], $join[1])) {
throw new Exception('A join clause must be specified as an array of join type, join table, and optionally join condition.');
}
// 0:join type, 1:join table, 2:on-condition (optional)
list ($joinType, $table) = $join;
$tables = $this->quoteTableNames((array) $table, $params);
$table = reset($tables);
$joins[$i] = "$joinType $table";
if (isset($join[2])) {
$condition = $this->buildCondition($join[2], $params);
if ($condition !== '') {
$joins[$i] .= ' ON ' . $condition;
}
}
}
return implode($this->separator, $joins);
}
/**
* Quotes table names passed
*
* @param array $tables
* @param array $params
* @return array
*/
private function quoteTableNames($tables, &$params)
{
foreach ($tables as $i => $table) {
if ($table instanceof Query) {
list($sql, $params) = $this->build($table, $params);
$tables[$i] = "($sql) " . $this->db->quoteTableName($i);
} elseif (is_string($i)) {
if (strpos($table, '(') === false) {
$table = $this->db->quoteTableName($table);
}
$tables[$i] = "$table " . $this->db->quoteTableName($i);
} elseif (strpos($table, '(') === false) {
if (preg_match('/^(.*?)(?i:\s+as|)\s+([^ ]+)$/', $table, $matches)) { // with alias
$tables[$i] = $this->db->quoteTableName($matches[1]) . ' ' . $this->db->quoteTableName($matches[2]);
} else {
$tables[$i] = $this->db->quoteTableName($table);
}
}
}
return $tables;
}
/**
* @param string|array $condition
* @param array $params the binding parameters to be populated
* @return string the WHERE clause built from [[Query::$where]].
*/
public function buildWhere($condition, &$params)
{
$where = $this->buildCondition($condition, $params);
return $where === '' ? '' : 'WHERE ' . $where;
}
/**
* @param array $columns
* @return string the GROUP BY clause
*/
public function buildGroupBy($columns)
{
if (empty($columns)) {
return '';
}
foreach ($columns as $i => $column) {
if ($column instanceof Expression) {
$columns[$i] = $column->expression;
} elseif (strpos($column, '(') === false) {
$columns[$i] = $this->db->quoteColumnName($column);
}
}
return 'GROUP BY ' . implode(', ', $columns);
}
/**
* @param string|array $condition
* @param array $params the binding parameters to be populated
* @return string the HAVING clause built from [[Query::$having]].
*/
public function buildHaving($condition, &$params)
{
$having = $this->buildCondition($condition, $params);
return $having === '' ? '' : 'HAVING ' . $having;
}
/**
* Builds the ORDER BY and LIMIT/OFFSET clauses and appends them to the given SQL.
* @param string $sql the existing SQL (without ORDER BY/LIMIT/OFFSET)
* @param array $orderBy the order by columns. See [[Query::orderBy]] for more details on how to specify this parameter.
* @param int $limit the limit number. See [[Query::limit]] for more details.
* @param int $offset the offset number. See [[Query::offset]] for more details.
* @return string the SQL completed with ORDER BY/LIMIT/OFFSET (if any)
*/
public function buildOrderByAndLimit($sql, $orderBy, $limit, $offset)
{
$orderBy = $this->buildOrderBy($orderBy);
if ($orderBy !== '') {
$sql .= $this->separator . $orderBy;
}
$limit = $this->buildLimit($limit, $offset);
if ($limit !== '') {
$sql .= $this->separator . $limit;
}
return $sql;
}
/**
* @param array $columns
* @return string the ORDER BY clause built from [[Query::$orderBy]].
*/
public function buildOrderBy($columns)
{
if (empty($columns)) {
return '';
}
$orders = [];
foreach ($columns as $name => $direction) {
if ($direction instanceof Expression) {
$orders[] = $direction->expression;
} else {
$orders[] = $this->db->quoteColumnName($name) . ($direction === SORT_DESC ? ' DESC' : '');
}
}
return 'ORDER BY ' . implode(', ', $orders);
}
/**
* @param int $limit
* @param int $offset
* @return string the LIMIT and OFFSET clauses
*/
public function buildLimit($limit, $offset)
{
$sql = '';
if ($this->hasLimit($limit)) {
$sql = 'LIMIT ' . $limit;
}
if ($this->hasOffset($offset)) {
$sql .= ' OFFSET ' . $offset;
}
return ltrim($sql);
}
/**
* Checks to see if the given limit is effective.
* @param mixed $limit the given limit
* @return bool whether the limit is effective
*/
protected function hasLimit($limit)
{
return ($limit instanceof Expression) || ctype_digit((string) $limit);
}
/**
* Checks to see if the given offset is effective.
* @param mixed $offset the given offset
* @return bool whether the offset is effective
*/
protected function hasOffset($offset)
{
return ($offset instanceof Expression) || ctype_digit((string) $offset) && (string) $offset !== '0';
}
/**
* @param array $unions
* @param array $params the binding parameters to be populated
* @return string the UNION clause built from [[Query::$union]].
*/
public function buildUnion($unions, &$params)
{
if (empty($unions)) {
return '';
}
$result = '';
foreach ($unions as $i => $union) {
$query = $union['query'];
if ($query instanceof Query) {
list($unions[$i]['query'], $params) = $this->build($query, $params);
}
$result .= 'UNION ' . ($union['all'] ? 'ALL ' : '') . '( ' . $unions[$i]['query'] . ' ) ';
}
return trim($result);
}
/**
* Processes columns and properly quotes them if necessary.
* It will join all columns into a string with comma as separators.
* @param string|array $columns the columns to be processed
* @return string the processing result
*/
public function buildColumns($columns)
{
if (!is_array($columns)) {
if (strpos($columns, '(') !== false) {
return $columns;
} else {
$columns = preg_split('/\s*,\s*/', $columns, -1, PREG_SPLIT_NO_EMPTY);
}
}
foreach ($columns as $i => $column) {
if ($column instanceof Expression) {
$columns[$i] = $column->expression;
} elseif (strpos($column, '(') === false) {
$columns[$i] = $this->db->quoteColumnName($column);
}
}
return is_array($columns) ? implode(', ', $columns) : $columns;
}
/**
* Parses the condition specification and generates the corresponding SQL expression.
* @param string|array|Expression $condition the condition specification. Please refer to [[Query::where()]]
* on how to specify a condition.
* @param array $params the binding parameters to be populated
* @return string the generated SQL expression
*/
public function buildCondition($condition, &$params)
{
if ($condition instanceof Expression) {
foreach ($condition->params as $n => $v) {
$params[$n] = $v;
}
return $condition->expression;
} elseif (!is_array($condition)) {
return (string) $condition;
} elseif (empty($condition)) {
return '';
}
if (isset($condition[0])) { // operator format: operator, operand 1, operand 2, ...
$operator = strtoupper($condition[0]);
if (isset($this->conditionBuilders[$operator])) {
$method = $this->conditionBuilders[$operator];
} else {
$method = 'buildSimpleCondition';
}
array_shift($condition);
return $this->$method($operator, $condition, $params);
} else { // hash format: 'column1' => 'value1', 'column2' => 'value2', ...
return $this->buildHashCondition($condition, $params);
}
}
/**
* Creates a condition based on column-value pairs.
* @param array $condition the condition specification.
* @param array $params the binding parameters to be populated
* @return string the generated SQL expression
*/
public function buildHashCondition($condition, &$params)
{
$parts = [];
foreach ($condition as $column => $value) {
if (ArrayHelper::isTraversable($value) || $value instanceof Query) {
// IN condition
$parts[] = $this->buildInCondition('IN', [$column, $value], $params);
} else {
if (strpos($column, '(') === false) {
$column = $this->db->quoteColumnName($column);
}
if ($value === null) {
$parts[] = "$column IS NULL";
} elseif ($value instanceof Expression) {
$parts[] = "$column=" . $value->expression;
foreach ($value->params as $n => $v) {
$params[$n] = $v;
}
} else {
$phName = self::PARAM_PREFIX . count($params);
$parts[] = "$column=$phName";
$params[$phName] = $value;
}
}
}
return count($parts) === 1 ? $parts[0] : '(' . implode(') AND (', $parts) . ')';
}
/**
* Connects two or more SQL expressions with the `AND` or `OR` operator.
* @param string $operator the operator to use for connecting the given operands
* @param array $operands the SQL expressions to connect.
* @param array $params the binding parameters to be populated
* @return string the generated SQL expression
*/
public function buildAndCondition($operator, $operands, &$params)
{
$parts = [];
foreach ($operands as $operand) {
if (is_array($operand)) {
$operand = $this->buildCondition($operand, $params);
}
if ($operand instanceof Expression) {
foreach ($operand->params as $n => $v) {
$params[$n] = $v;
}
$operand = $operand->expression;
}
if ($operand !== '') {
$parts[] = $operand;
}
}
if (!empty($parts)) {
return '(' . implode(") $operator (", $parts) . ')';
} else {
return '';
}
}
/**
* Inverts an SQL expressions with `NOT` operator.
* @param string $operator the operator to use for connecting the given operands
* @param array $operands the SQL expressions to connect.
* @param array $params the binding parameters to be populated
* @return string the generated SQL expression
* @throws InvalidParamException if wrong number of operands have been given.
*/
public function buildNotCondition($operator, $operands, &$params)
{
if (count($operands) !== 1) {
throw new InvalidParamException("Operator '$operator' requires exactly one operand.");
}
$operand = reset($operands);
if (is_array($operand)) {
$operand = $this->buildCondition($operand, $params);
}
if ($operand === '') {
return '';
}
return "$operator ($operand)";
}
/**
* Creates an SQL expressions with the `BETWEEN` operator.
* @param string $operator the operator to use (e.g. `BETWEEN` or `NOT BETWEEN`)
* @param array $operands the first operand is the column name. The second and third operands
* describe the interval that column value should be in.
* @param array $params the binding parameters to be populated
* @return string the generated SQL expression
* @throws InvalidParamException if wrong number of operands have been given.
*/
public function buildBetweenCondition($operator, $operands, &$params)
{
if (!isset($operands[0], $operands[1], $operands[2])) {
throw new InvalidParamException("Operator '$operator' requires three operands.");
}
list($column, $value1, $value2) = $operands;
if (strpos($column, '(') === false) {
$column = $this->db->quoteColumnName($column);
}
if ($value1 instanceof Expression) {
foreach ($value1->params as $n => $v) {
$params[$n] = $v;
}
$phName1 = $value1->expression;
} else {
$phName1 = self::PARAM_PREFIX . count($params);
$params[$phName1] = $value1;
}
if ($value2 instanceof Expression) {
foreach ($value2->params as $n => $v) {
$params[$n] = $v;
}
$phName2 = $value2->expression;
} else {
$phName2 = self::PARAM_PREFIX . count($params);
$params[$phName2] = $value2;
}
return "$column $operator $phName1 AND $phName2";
}
/**
* Creates an SQL expressions with the `IN` operator.
* @param string $operator the operator to use (e.g. `IN` or `NOT IN`)
* @param array $operands the first operand is the column name. If it is an array
* a composite IN condition will be generated.
* The second operand is an array of values that column value should be among.
* If it is an empty array the generated expression will be a `false` value if
* operator is `IN` and empty if operator is `NOT IN`.
* @param array $params the binding parameters to be populated
* @return string the generated SQL expression
* @throws Exception if wrong number of operands have been given.
*/
public function buildInCondition($operator, $operands, &$params)
{
if (!isset($operands[0], $operands[1])) {
throw new Exception("Operator '$operator' requires two operands.");
}
list($column, $values) = $operands;
if ($column === []) {
// no columns to test against
return $operator === 'IN' ? '0=1' : '';
}
if ($values instanceof Query) {
return $this->buildSubqueryInCondition($operator, $column, $values, $params);
}
if (!is_array($values) && !$values instanceof \Traversable) {
// ensure values is an array
$values = (array) $values;
}
if ($column instanceof \Traversable || count($column) > 1) {
return $this->buildCompositeInCondition($operator, $column, $values, $params);
} elseif (is_array($column)) {
$column = reset($column);
}
$sqlValues = [];
foreach ($values as $i => $value) {
if (is_array($value) || $value instanceof \ArrayAccess) {
$value = isset($value[$column]) ? $value[$column] : null;
}
if ($value === null) {
$sqlValues[$i] = 'NULL';
} elseif ($value instanceof Expression) {
$sqlValues[$i] = $value->expression;
foreach ($value->params as $n => $v) {
$params[$n] = $v;
}
} else {
$phName = self::PARAM_PREFIX . count($params);
$params[$phName] = $value;
$sqlValues[$i] = $phName;
}
}
if (empty($sqlValues)) {
return $operator === 'IN' ? '0=1' : '';
}
if (strpos($column, '(') === false) {
$column = $this->db->quoteColumnName($column);
}
if (count($sqlValues) > 1) {
return "$column $operator (" . implode(', ', $sqlValues) . ')';
} else {
$operator = $operator === 'IN' ? '=' : '<>';
return $column . $operator . reset($sqlValues);
}
}
/**
* Builds SQL for IN condition
*
* @param string $operator
* @param array $columns
* @param Query $values
* @param array $params
* @return string SQL
*/
protected function buildSubqueryInCondition($operator, $columns, $values, &$params)
{
list($sql, $params) = $this->build($values, $params);
if (is_array($columns)) {
foreach ($columns as $i => $col) {
if (strpos($col, '(') === false) {
$columns[$i] = $this->db->quoteColumnName($col);
}
}
return '(' . implode(', ', $columns) . ") $operator ($sql)";
} else {
if (strpos($columns, '(') === false) {
$columns = $this->db->quoteColumnName($columns);
}
return "$columns $operator ($sql)";
}
}
/**
* Builds SQL for IN condition
*
* @param string $operator
* @param array|\Traversable $columns
* @param array $values
* @param array $params
* @return string SQL
*/
protected function buildCompositeInCondition($operator, $columns, $values, &$params)
{
$vss = [];
foreach ($values as $value) {
$vs = [];
foreach ($columns as $column) {
if (isset($value[$column])) {
$phName = self::PARAM_PREFIX . count($params);
$params[$phName] = $value[$column];
$vs[] = $phName;
} else {
$vs[] = 'NULL';
}
}
$vss[] = '(' . implode(', ', $vs) . ')';
}
if (empty($vss)) {
return $operator === 'IN' ? '0=1' : '';
}
$sqlColumns = [];
foreach ($columns as $i => $column) {
$sqlColumns[] = strpos($column, '(') === false ? $this->db->quoteColumnName($column) : $column;
}
return '(' . implode(', ', $sqlColumns) . ") $operator (" . implode(', ', $vss) . ')';
}
/**
* Creates an SQL expressions with the `LIKE` operator.
* @param string $operator the operator to use (e.g. `LIKE`, `NOT LIKE`, `OR LIKE` or `OR NOT LIKE`)
* @param array $operands an array of two or three operands
*
* - The first operand is the column name.
* - The second operand is a single value or an array of values that column value
* should be compared with. If it is an empty array the generated expression will
* be a `false` value if operator is `LIKE` or `OR LIKE`, and empty if operator
* is `NOT LIKE` or `OR NOT LIKE`.
* - An optional third operand can also be provided to specify how to escape special characters
* in the value(s). The operand should be an array of mappings from the special characters to their
* escaped counterparts. If this operand is not provided, a default escape mapping will be used.
* You may use `false` or an empty array to indicate the values are already escaped and no escape
* should be applied. Note that when using an escape mapping (or the third operand is not provided),
* the values will be automatically enclosed within a pair of percentage characters.
* @param array $params the binding parameters to be populated
* @return string the generated SQL expression
* @throws InvalidParamException if wrong number of operands have been given.
*/
public function buildLikeCondition($operator, $operands, &$params)
{
if (!isset($operands[0], $operands[1])) {
throw new InvalidParamException("Operator '$operator' requires two operands.");
}
$escape = isset($operands[2]) ? $operands[2] : $this->likeEscapingReplacements;
unset($operands[2]);
if (!preg_match('/^(AND |OR |)(((NOT |))I?LIKE)/', $operator, $matches)) {
throw new InvalidParamException("Invalid operator '$operator'.");
}
$andor = ' ' . (!empty($matches[1]) ? $matches[1] : 'AND ');
$not = !empty($matches[3]);
$operator = $matches[2];
list($column, $values) = $operands;
if (!is_array($values)) {
$values = [$values];
}
if (empty($values)) {
return $not ? '' : '0=1';
}
if (strpos($column, '(') === false) {
$column = $this->db->quoteColumnName($column);
}
$parts = [];
foreach ($values as $value) {
if ($value instanceof Expression) {
foreach ($value->params as $n => $v) {
$params[$n] = $v;
}
$phName = $value->expression;
} else {
$phName = self::PARAM_PREFIX . count($params);
$params[$phName] = empty($escape) ? $value : ('%' . strtr($value, $escape) . '%');
}
$escapeSql = '';
if ($this->likeEscapeCharacter !== null) {
$escapeSql = " ESCAPE '{$this->likeEscapeCharacter}'";
}
$parts[] = "{$column} {$operator} {$phName}{$escapeSql}";
}
return implode($andor, $parts);
}
/**
* Creates an SQL expressions with the `EXISTS` operator.
* @param string $operator the operator to use (e.g. `EXISTS` or `NOT EXISTS`)
* @param array $operands contains only one element which is a [[Query]] object representing the sub-query.
* @param array $params the binding parameters to be populated
* @return string the generated SQL expression
* @throws InvalidParamException if the operand is not a [[Query]] object.
*/
public function buildExistsCondition($operator, $operands, &$params)
{
if ($operands[0] instanceof Query) {
list($sql, $params) = $this->build($operands[0], $params);
return "$operator ($sql)";
} else {
throw new InvalidParamException('Subquery for EXISTS operator must be a Query object.');
}
}
/**
* Creates an SQL expressions like `"column" operator value`.
* @param string $operator the operator to use. Anything could be used e.g. `>`, `<=`, etc.
* @param array $operands contains two column names.
* @param array $params the binding parameters to be populated
* @return string the generated SQL expression
* @throws InvalidParamException if wrong number of operands have been given.
*/
public function buildSimpleCondition($operator, $operands, &$params)
{
if (count($operands) !== 2) {
throw new InvalidParamException("Operator '$operator' requires two operands.");
}
list($column, $value) = $operands;
if (strpos($column, '(') === false) {
$column = $this->db->quoteColumnName($column);
}
if ($value === null) {
return "$column $operator NULL";
} elseif ($value instanceof Expression) {
foreach ($value->params as $n => $v) {
$params[$n] = $v;
}
return "$column $operator {$value->expression}";
} elseif ($value instanceof Query) {
list($sql, $params) = $this->build($value, $params);
return "$column $operator ($sql)";
} else {
$phName = self::PARAM_PREFIX . count($params);
$params[$phName] = $value;
return "$column $operator $phName";
}
}
/**
* Creates a SELECT EXISTS() SQL statement.
* @param string $rawSql the subquery in a raw form to select from.
* @return string the SELECT EXISTS() SQL statement.
* @since 2.0.8
*/
public function selectExists($rawSql)
{
return 'SELECT EXISTS(' . $rawSql . ')';
}
}
| {
"content_hash": "8c4a8aa4f2c785ede5e1535bb7b588ba",
"timestamp": "",
"source": "github",
"line_count": 1486,
"max_line_length": 159,
"avg_line_length": 40.802826379542395,
"alnum_prop": 0.5671663945376281,
"repo_name": "johnkind49/yii2",
"id": "ae4ec26cfaa42464599f168435869b37df712f44",
"size": "60777",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "framework/db/QueryBuilder.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ApacheConf",
"bytes": "28"
},
{
"name": "Batchfile",
"bytes": "1085"
},
{
"name": "JavaScript",
"bytes": "69628"
},
{
"name": "PHP",
"bytes": "4658338"
},
{
"name": "PLSQL",
"bytes": "15246"
},
{
"name": "Ruby",
"bytes": "207"
},
{
"name": "Shell",
"bytes": "2978"
}
],
"symlink_target": ""
} |
module Azure::Compute::Mgmt::V2017_12_01
module Models
#
# The status of the latest virtual machine scale set rolling upgrade.
#
class RollingUpgradeStatusInfo < Resource
include MsRestAzure
# @return [RollingUpgradePolicy] The rolling upgrade policies applied for
# this upgrade.
attr_accessor :policy
# @return [RollingUpgradeRunningStatus] Information about the current
# running state of the overall upgrade.
attr_accessor :running_status
# @return [RollingUpgradeProgressInfo] Information about the number of
# virtual machine instances in each upgrade state.
attr_accessor :progress
# @return [ApiError] Error details for this upgrade, if there are any.
attr_accessor :error
#
# Mapper for RollingUpgradeStatusInfo class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'RollingUpgradeStatusInfo',
type: {
name: 'Composite',
class_name: 'RollingUpgradeStatusInfo',
model_properties: {
id: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'id',
type: {
name: 'String'
}
},
name: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'name',
type: {
name: 'String'
}
},
type: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'type',
type: {
name: 'String'
}
},
location: {
client_side_validation: true,
required: true,
serialized_name: 'location',
type: {
name: 'String'
}
},
tags: {
client_side_validation: true,
required: false,
serialized_name: 'tags',
type: {
name: 'Dictionary',
value: {
client_side_validation: true,
required: false,
serialized_name: 'StringElementType',
type: {
name: 'String'
}
}
}
},
policy: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'properties.policy',
type: {
name: 'Composite',
class_name: 'RollingUpgradePolicy'
}
},
running_status: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'properties.runningStatus',
type: {
name: 'Composite',
class_name: 'RollingUpgradeRunningStatus'
}
},
progress: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'properties.progress',
type: {
name: 'Composite',
class_name: 'RollingUpgradeProgressInfo'
}
},
error: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'properties.error',
type: {
name: 'Composite',
class_name: 'ApiError'
}
}
}
}
}
end
end
end
end
| {
"content_hash": "b525d284b7f9cffdbdee69a2bfda592c",
"timestamp": "",
"source": "github",
"line_count": 136,
"max_line_length": 79,
"avg_line_length": 30.977941176470587,
"alnum_prop": 0.4374554948967482,
"repo_name": "Azure/azure-sdk-for-ruby",
"id": "e7330fce0a779c5229da5f5cdccb65d29503dded",
"size": "4377",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "management/azure_mgmt_compute/lib/2017-12-01/generated/azure_mgmt_compute/models/rolling_upgrade_status_info.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "345216400"
},
{
"name": "Shell",
"bytes": "305"
}
],
"symlink_target": ""
} |
require 'test_helper'
class CrackTest < Test::Unit::TestCase
context "to_xml_attributes" do
setup do
@hash = { :one => "ONE", "two" => "TWO", :three => "it \"should\" work" }
end
should "turn the hash into xml attributes" do
attrs = Crack::Util.to_xml_attributes(@hash)
attrs.should =~ /one="ONE"/m
attrs.should =~ /two="TWO"/m
attrs.should =~ /three="it "should" work"/m
end
should 'preserve _ in hash keys' do
attrs = Crack::Util.to_xml_attributes({
:some_long_attribute => "with short value",
:crash => :burn,
:merb => "uses extlib"
})
attrs.should =~ /some_long_attribute="with short value"/
attrs.should =~ /merb="uses extlib"/
attrs.should =~ /crash="burn"/
end
end
end
| {
"content_hash": "30fbc51eed58264d9f2f0e7e28e1b998",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 79,
"avg_line_length": 29.678571428571427,
"alnum_prop": 0.5583634175691937,
"repo_name": "spookandpuff/spooky-core",
"id": "673060be855ff71b2873a5cf9699b401ca26cffa",
"size": "831",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": ".bundle/gems/crack-0.3.1/test/hash_test.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "189872"
},
{
"name": "CMake",
"bytes": "314"
},
{
"name": "CSS",
"bytes": "2285"
},
{
"name": "Gherkin",
"bytes": "161113"
},
{
"name": "HTML",
"bytes": "107027"
},
{
"name": "Makefile",
"bytes": "32273"
},
{
"name": "PowerShell",
"bytes": "318"
},
{
"name": "REXX",
"bytes": "1931"
},
{
"name": "Ruby",
"bytes": "3398913"
},
{
"name": "Shell",
"bytes": "5885"
},
{
"name": "XSLT",
"bytes": "1868"
},
{
"name": "Yacc",
"bytes": "7381"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="de">
<head>
<!-- Generated by javadoc -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Package org.apache.commons.lang3.tuple (Apache Commons Lang 3.5 API)</title>
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Package org.apache.commons.lang3.tuple (Apache Commons Lang 3.5 API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li class="navBarCell1Rev">Use</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/apache/commons/lang3/tuple/package-use.html" target="_top">Frames</a></li>
<li><a href="package-use.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h1 title="Uses of Package org.apache.commons.lang3.tuple" class="title">Uses of Package<br>org.apache.commons.lang3.tuple</h1>
</div>
<div class="contentContainer">
<ul class="blockList">
<li class="blockList">
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../org/apache/commons/lang3/tuple/package-summary.html">org.apache.commons.lang3.tuple</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#org.apache.commons.lang3.builder">org.apache.commons.lang3.builder</a></td>
<td class="colLast">
<div class="block">Assists in creating consistent <code>equals(Object)</code>, <code>toString()</code>, <code>hashCode()</code>, and <code>compareTo(Object)</code> methods.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="#org.apache.commons.lang3.exception">org.apache.commons.lang3.exception</a></td>
<td class="colLast">
<div class="block">Provides functionality for Exceptions.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="#org.apache.commons.lang3.tuple">org.apache.commons.lang3.tuple</a></td>
<td class="colLast">
<div class="block">Tuple classes, starting with a Pair class in version 3.0.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="org.apache.commons.lang3.builder">
<!-- -->
</a>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation">
<caption><span>Classes in <a href="../../../../../org/apache/commons/lang3/tuple/package-summary.html">org.apache.commons.lang3.tuple</a> used by <a href="../../../../../org/apache/commons/lang3/builder/package-summary.html">org.apache.commons.lang3.builder</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colOne"><a href="../../../../../org/apache/commons/lang3/tuple/class-use/Pair.html#org.apache.commons.lang3.builder">Pair</a>
<div class="block">A pair consisting of two elements.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="org.apache.commons.lang3.exception">
<!-- -->
</a>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation">
<caption><span>Classes in <a href="../../../../../org/apache/commons/lang3/tuple/package-summary.html">org.apache.commons.lang3.tuple</a> used by <a href="../../../../../org/apache/commons/lang3/exception/package-summary.html">org.apache.commons.lang3.exception</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colOne"><a href="../../../../../org/apache/commons/lang3/tuple/class-use/Pair.html#org.apache.commons.lang3.exception">Pair</a>
<div class="block">A pair consisting of two elements.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="org.apache.commons.lang3.tuple">
<!-- -->
</a>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation">
<caption><span>Classes in <a href="../../../../../org/apache/commons/lang3/tuple/package-summary.html">org.apache.commons.lang3.tuple</a> used by <a href="../../../../../org/apache/commons/lang3/tuple/package-summary.html">org.apache.commons.lang3.tuple</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colOne"><a href="../../../../../org/apache/commons/lang3/tuple/class-use/ImmutablePair.html#org.apache.commons.lang3.tuple">ImmutablePair</a>
<div class="block">An immutable pair consisting of two <code>Object</code> elements.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="../../../../../org/apache/commons/lang3/tuple/class-use/ImmutableTriple.html#org.apache.commons.lang3.tuple">ImmutableTriple</a>
<div class="block">An immutable triple consisting of three <code>Object</code> elements.</div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><a href="../../../../../org/apache/commons/lang3/tuple/class-use/MutablePair.html#org.apache.commons.lang3.tuple">MutablePair</a>
<div class="block">A mutable pair consisting of two <code>Object</code> elements.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="../../../../../org/apache/commons/lang3/tuple/class-use/MutableTriple.html#org.apache.commons.lang3.tuple">MutableTriple</a>
<div class="block">A mutable triple consisting of three <code>Object</code> elements.</div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><a href="../../../../../org/apache/commons/lang3/tuple/class-use/Pair.html#org.apache.commons.lang3.tuple">Pair</a>
<div class="block">A pair consisting of two elements.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="../../../../../org/apache/commons/lang3/tuple/class-use/Triple.html#org.apache.commons.lang3.tuple">Triple</a>
<div class="block">A triple consisting of three elements.</div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li class="navBarCell1Rev">Use</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/apache/commons/lang3/tuple/package-use.html" target="_top">Frames</a></li>
<li><a href="package-use.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2001–2016 <a href="https://www.apache.org/">The Apache Software Foundation</a>. All rights reserved.</small></p>
</body>
</html>
| {
"content_hash": "62eba314e7ac2639236f7599a7b8fdbe",
"timestamp": "",
"source": "github",
"line_count": 233,
"max_line_length": 316,
"avg_line_length": 40.75107296137339,
"alnum_prop": 0.6542390731964192,
"repo_name": "VeberAxel/Extract-Component",
"id": "3f191974f95752606415ab1576541ca79f064229",
"size": "9495",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "vendor/commons-lang3-3.5/apidocs/org/apache/commons/lang3/tuple/package-use.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "38065"
}
],
"symlink_target": ""
} |
GitLink
==========
[](https://gitter.im/GitTools/GitLink?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)







GitLink let's users step through your code hosted on GitHub! **Help make .NET open source projects more accessible by enabling this for your .NET projects, it's just a single additional step in your build**. See the list of [projects using GitLink](#projects-using-gitlink).
<a href="https://pledgie.com/campaigns/26957"><img alt="Click here to lend your support to: GitLink and make a donation at pledgie.com !" src="https://pledgie.com/campaigns/26957.png?skin_name=chrome" border="0" /></a>
--
**Important note**
*GitLink* was formerly named *GitHubLink*. By adding support to more Git hosting services the name seemed not covering the whole package. The old GitHubLink packages on NuGet and Chocolatey will no longer be updated or maintained.
--
GitLink makes symbol servers obsolete which saves you both time with uploading source files with symbols and the user no longer has to specify custom symbol servers (such as symbolsource.org).

The advantage of GitLink is that it is fully customized for Git. It also works with GitHub or BitBucket urls so it **does not require a local git repository to work**. This makes it perfectly usable in continuous integration servers such as <a href="http://www.finalbuilder.com/Continua-CI" target="_blank">Continua CI</a>.
Updating all the pdb files is very fast. A solution with over 85 projects will be handled in less than 30 seconds.
When using GitLink, the user no longer has to specify symbol servers. The only requirement is to ensure the check the `Enable source server support` option in Visual Studio as shown below:

# Troubleshooting
## Source Stepping isn't working
* Visual Studio 2012 needs to run elevated in order to download the source server files
* Specify a value for Visual Studio -> Options -> Debugging -> Symbols -> `Cache Symbols in this directory`

## Source Stepping returns HTML
If your repository is private, you are likely seeing the logon HTML from your git host.
* Log onto your git host in Internet Explorer
* Purge your local symbol cache
# Supported git providers
GitLink supports the following providers out of the box (will auto-detect based on the url):
* <a href="https://bitbucket.org/" target="_blank">BitBucket</a>
* <a href="https://github.com/" target="_blank">GitHub</a>
* Custom Provider (custom urls)
Providers currently being worked on:
* <a href="https://www.assembla.com/home" target="_blank">Assembla</a>
* <a href="http://beanstalkapp.com/" target="_blank">Beanstalk</a>
* <a href="http://www.cloudforge.com/" target="_blank">CloudForge</a>
* <a href="https://www.codebasehq.com/" target="_blank">Codebase</a>
* <a href="https://www.fogcreek.com/kiln/" target="_blank">FogCreek</a>
* <a href="https://plan.io/" target="_blank">Planio</a>
* <a href="http://projectlocker.com/" target="_blank">ProjectLocker</a>
* <a href="https://rhodecode.com/" target="_blank">RhodeCode</a>
* <a href="https://unfuddle.com/" target="_blank">Unfuddle</a>
It is also possible to specify a custom url provider.
# Using GitLink as command line tool
Using GitLink via the command line is very simple:
1. Build the solution - in release mode with pdb files enabled
2. Run the console application with the right command line parameters
3. Include the PDB in your nuget package
See [Oren Novotony's blog post](https://oren.codes/2015/09/23/enabling-source-code-debugging-for-your-nuget-packages-with-gitlink/) for even more detail and examples on build integration.
## Most simple usage
This is the most simple usage available **starting from 2.2.0**. It will automatically determine the url and commit based on a local *.git* directory.
GitLink.exe c:\source\catel
## Running for the default branch
GitLink.exe c:\source\catel -u https://github.com/catel/catel
This will use the default branch (which is in most cases **master**). You can find out the default branch by checking what branch is loaded by default on the GitHub page.
## Running for a specific branch
GitLink.exe c:\source\catel -u https://github.com/catel/catel -b develop
This will use the develop branch.
## Running for a specific branch and configuration
GitLink.exe c:\source\catel -u https://github.com/catel/catel -b develop -c debug
This will use the develop branch and the debug configuration.
## Running for a specific solution only
Sometimes a repository contains more than 1 solution file. By default, all solutions will be processed. To only process a single solution file, use the *-f* option:
GitLink.exe c:\source\catel -u https://github.com/catel/catel -f Catel.sln
## Ignoring projects and explicitly including them
When specific projects should be ignored, use the *-ignore* option. This option accepts a comma separated list of patterns to ignore. Each pattern is either a literal project name (case-insensitive) or a regex enclosed in slashes. For example:
GitLink.exe c:\source\catel -u https://github.com/catel/catel -f Catel.sln -ignore Catel.Core.WP80,Catel.MVVM.WP80
GitLink.exe c:\source\catel -u https://github.com/catel/catel -f Catel.sln -ignore /^.+\.WP80$/,Catel.Core
In case you want to ignore most of your projects, you can explicitly *-include* only the projects you need - others will be ignored automatically. Same as *-ignore* it accepts list of patterns. For example:
GitLink.exe c:\source\catel -u https://github.com/catel/catel -f Catel.sln -include Catel.Core
GitLink.exe c:\source\catel -u https://github.com/catel/catel -f Catel.sln -include /Catel\..*$/,SomeOtherProject
Finally, you can set both *-ignore* and *-include* options. In this case only projects matching one of *-include* patterns will be taken, but if and only if they don't match one of *-ignore*s. For example, the following command line will include only Catel.* projects, except "Catel.Core":
GitLink.exe c:\source\catel -u https://github.com/catel/catel -f Catel.sln -include /Catel\..*$/ -ignore Catel.Core
## Running for an uncommon / customized URL
When working with a repository using uncommon URL you can use placeholders to specifiy where the filename and revision hash should be, use `-u` parameter with the custom URL
GitLink.exe c:\source\catel -u "https://host/projects/catel/repos/catel/browse/{filename}?at={revision}&raw"
The custom url will be used to fill the placeholders with the relative file path and the revision hash.
## Running for a custom raw content URL
When working with a content proxy or an alternative git VCS system that supports direct HTTP access to specific file revisions use the `-u` parameter with the custom raw content root URL
GitLink.exe c:\source\catel -u https://raw.githubusercontent.com/catel/catel
The custom url will be used to fill in the following pattern `{customUrl}/{revision}/{relativeFilePath}` when generating the source mapping.
## Getting help
When you need help about GitLink, use the following command line:
GitLink.exe -help
## Logging to a file
When you need to log the information to a file, use the following command line:
GitLink.exe c:\source\catel -u https://github.com/catel/catel -b develop -l GitLinkLog.log
# Using GitLink in code
GitLink is built with 2 usages in mind: command line and code reference. Though most people will use the command line version, it is possible to reference the executable and use the logic in code.
The command line implementation uses the same available API.
## Creating a context
To link files to a Git project, a context must be created. The command line version does this by using the *ArgumentParser* class. It is also possible to create a context from scratch as shown in the example below:
var context = new GitLink.Context(new ProviderManager());
context.SolutionDirectory = @"c:\source\catel";
context.TargetUrl = "https://github.com/catel/catel";
context.TargetBranch = "develop";
It is possible to create a context based on command line arguments:
var context = ArgumentParser.Parse(@"c:\source\catel -u https://github.com/catel/catel -b develop");
## Linking a context
Once a context is created, the *Linker* class can be used to actually link the files:
Linker.Link(context);
# How to get
There are three general ways to get GitLink:
## Get it from GitHub
The releases will be available as separate executable download on the [releases tab](https://github.com/GitTools/GitLink/releases) of the project.
## Get it via Chocolatey
If you want to install the tool on your (build) computer, the package is available via <a href="https://chocolatey.org/" target="_blank">Chocolatey</a>. To install, use the following command:
choco install gitlink
## Get it via NuGet
If you want to reference the assembly to use it in code, the recommended way to get it is via <a href="http://www.nuget.org/" target="_blank">NuGet</a>.
**Note that getting GitLink via NuGet will add it as a reference to the project**
# How does it work
The SrcSrv tool (Srcsrv.dll) enables a client to retrieve the exact version of the source files that were used to build an application. Because the source code for a module can change between versions and over the course of years, it is important to look at the source code as it existed when the version of the module in question was built.
For more information, see the <a href="http://msdn.microsoft.com/en-us/library/windows/hardware/ff558791(v=vs.85).aspx" target="_blank">official documentation of SrcSrv</a>.
GitLink creates a source index file and updates the PDB file so it will retrieve the files from the Git host file handler.
<a name="projects-using-gitlink"></a>
# Projects using GitLink
Below is a list of projects already using GitLink (alphabetically ordered).
- <a href="http://www.catelproject.com" target="_blank">Catel</a>
- <a href="http://www.expandframework.com/" target="_blank">eXpand</a>
- <a href="https://github.com/fluentribbon/Fluent.Ribbon" target="_blank">Fluent.Ribbon</a>
- <a href="https://github.com/GitTools/GitLink" target="_blank">GitLink</a>
- <a href="https://github.com/MahApps/MahApps.Metro" target="_blank">MahApps.Metro</a>
- <a href="https://github.com/elasticsearch/elasticsearch-net" target="_blank">NEST and Elasticsearch.NET</a>
- <a href="https://github.com/orcomp/Orc.Analytics" target="_blank">Orc.Analytics</a>
- <a href="https://github.com/orcomp/Orc.AutomaticSupport" target="_blank">Orc.AutomaticSupport</a>
- <a href="https://github.com/orcomp/Orc.CommandLine" target="_blank">Orc.CommandLine</a>
- <a href="https://github.com/orcomp/Orc.Controls" target="_blank">Orc.Controls</a>
- <a href="https://github.com/orcomp/Orc.CrashReporting" target="_blank">Orc.CrashReporting</a>
- <a href="https://github.com/orcomp/Orc.CsvHelper" target="_blank">Orc.CsvHelper</a>
- <a href="https://github.com/orcomp/Orc.Feedback" target="_blank">Orc.Feedback</a>
- <a href="https://github.com/orcomp/Orc.FileAssociation" target="_blank">Orc.FileAssociation</a>
- <a href="https://github.com/orcomp/Orc.FilterBuilder" target="_blank">Orc.FilterBuilder</a>
- <a href="https://github.com/orcomp/Orc.LicenseManager" target="_blank">Orc.LicenseManager</a>
- <a href="https://github.com/orcomp/Orc.Metadata" target="_blank">Orc.Metadata</a>
- <a href="https://github.com/orcomp/Orc.Notifications" target="_blank">Orc.Notifications</a>
- <a href="https://github.com/orcomp/Orc.NuGetExplorer" target="_blank">Orc.NuGetExplorer</a>
- <a href="https://github.com/orcomp/Orc.ProjectManagement" target="_blank">Orc.ProjectManagement</a>
- <a href="https://github.com/orcomp/Orc.Search" target="_blank">Orc.Search</a>
- <a href="https://github.com/orcomp/Orc.Sort" target="_blank">Orc.Sort</a>
- <a href="https://github.com/orcomp/Orc.Squirrel" target="_blank">Orc.Squirrel</a>
- <a href="https://github.com/orcomp/Orc.SupportPackage" target="_blank">Orc.SupportPackage</a>
- <a href="https://github.com/orcomp/Orc.SystemInfo" target="_blank">Orc.SystemInfo</a>
- <a href="https://github.com/orcomp/Orc.WorkspaceManagement" target="_blank">Orc.WorkspaceManagement</a>
- <a href="https://github.com/orcomp/Orc.Wizard" target="_blank">Orc.Wizard</a>
- <a href="https://github.com/orcomp/Orchestra" target="_blank">Orchestra</a>
- <a href="https://github.com/oxyplot/oxyplot" target="_blank">OxyPlot</a>
- <a href="http://romanticweb.net" target="_blank">Romantic Web</a>
- <a href="https://github.com/xunit/xunit" target="_blank">xUnit.net</a>
- <a href="https://github.com/xunit/visualstudio.xunit" target="_blank">xUnit.net Visual Studio Runner</a>
Are you using GitLink in your projects? Let us know and we will add your project to the list.
*Note that you can also create a pull request on this document and add it yourself.*
# Icon
Link by Dominic Whittle from The Noun Project
| {
"content_hash": "287f763409d9cce4113679ffd3d569aa",
"timestamp": "",
"source": "github",
"line_count": 259,
"max_line_length": 341,
"avg_line_length": 52.78378378378378,
"alnum_prop": 0.7485919098822325,
"repo_name": "distantcam/GitLink",
"id": "0ba8c4173b98d5faffd1ddb071ee1c4bb7e05bf5",
"size": "13671",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "1464"
},
{
"name": "C#",
"bytes": "126985"
}
],
"symlink_target": ""
} |
package org.kuali.kra.irb.noteattachment;
import org.kuali.kra.irb.Protocol;
import org.kuali.kra.protocol.noteattachment.ProtocolAttachmentProtocolBase;
/**
* This class represents the Protocol Attachment Protocol.
*/
public class ProtocolAttachmentProtocol extends ProtocolAttachmentProtocolBase {
private static final long serialVersionUID = -7115904344245464654L;
private static final String GROUP_CODE = "1";
public static final String INCOMPLETE_STATUS_CODE = "1";
public static final String COMPLETE_STATUS_CODE = "2";
/**
* empty ctor to satisfy JavaBean convention.
*/
public ProtocolAttachmentProtocol() {
super();
}
/**
* Convenience ctor to add the protocol as an owner.
*
* <p>
* This ctor does not validate any of the properties.
* </p>
*
* @param protocol the protocol.
*/
public ProtocolAttachmentProtocol(final Protocol protocol) {
super(protocol);
}
@Override
public String getGroupCode() {
return GROUP_CODE;
}
@Override
public String getAttachmentDescription() {
return "Protocol Attachment";
}
public boolean isDraft() {
return ProtocolAttachmentStatus.DRAFT.equals(documentStatusCode);
}
public void setDraft() {
documentStatusCode = ProtocolAttachmentStatus.DRAFT;
}
public boolean isFinal() {
return ProtocolAttachmentStatus.FINALIZED.equals(documentStatusCode);
}
public void setFinal() {
documentStatusCode = ProtocolAttachmentStatus.FINALIZED;
}
public boolean isDeleted() {
return ProtocolAttachmentStatus.DELETED.equals(documentStatusCode);
}
public void setDeleted() {
documentStatusCode = ProtocolAttachmentStatus.DELETED;
}
}
| {
"content_hash": "1a2c633521b082496829623cee541fac",
"timestamp": "",
"source": "github",
"line_count": 72,
"max_line_length": 80,
"avg_line_length": 25.666666666666668,
"alnum_prop": 0.6715367965367965,
"repo_name": "blackcathacker/kc.preclean",
"id": "29964984b0591d2cffbd0c4a67e5ca9c109ac8ce",
"size": "2471",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "coeus-code/src/main/java/org/kuali/kra/irb/noteattachment/ProtocolAttachmentProtocol.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "96034"
},
{
"name": "Java",
"bytes": "27623677"
},
{
"name": "JavaScript",
"bytes": "749782"
},
{
"name": "Perl",
"bytes": "1278"
},
{
"name": "Scheme",
"bytes": "8283377"
},
{
"name": "Shell",
"bytes": "69314"
},
{
"name": "XSLT",
"bytes": "20298494"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "//www.w3.org/TR/html4/strict.dtd">
<HTML style="overflow:auto;">
<HEAD>
<meta name="generator" content="JDiff v1.1.0">
<!-- Generated by the JDiff Javadoc doclet -->
<!-- (http://www.jdiff.org) -->
<meta name="description" content="JDiff is a Javadoc doclet which generates an HTML report of all the packages, classes, constructors, methods, and fields which have been removed, added or changed in any way, including their documentation, when two APIs are compared.">
<meta name="keywords" content="diff, jdiff, javadiff, java diff, java difference, API difference, difference between two APIs, API diff, Javadoc, doclet">
<TITLE>
android.media.MediaRecorder
</TITLE>
<link href="../../../../assets/android-developer-docs.css" rel="stylesheet" type="text/css" />
<link href="../stylesheet-jdiff.css" rel="stylesheet" type="text/css" />
<noscript>
<style type="text/css">
body{overflow:auto;}
#body-content{position:relative; top:0;}
#doc-content{overflow:visible;border-left:3px solid #666;}
#side-nav{padding:0;}
#side-nav .toggle-list ul {display:block;}
#resize-packages-nav{border-bottom:3px solid #666;}
</style>
</noscript>
<style type="text/css">
</style>
</HEAD>
<BODY>
<!-- Start of nav bar -->
<a name="top"></a>
<div id="header" style="margin-bottom:0;padding-bottom:0;">
<div id="headerLeft">
<a href="../../../../index.html" tabindex="-1" target="_top"><img src="../../../../assets/images/bg_logo.png" alt="Android Developers" /></a>
</div>
<div id="headerRight">
<div id="headerLinks">
<!-- <img src="/assets/images/icon_world.jpg" alt="" /> -->
<span class="text">
<!-- <a href="#">English</a> | -->
<nobr><a href="//developer.android.com" target="_top">Android Developers</a> | <a href="//www.android.com" target="_top">Android.com</a></nobr>
</span>
</div>
<div class="and-diff-id" style="margin-top:6px;margin-right:8px;">
<table class="diffspectable">
<tr>
<td colspan="2" class="diffspechead">API Diff Specification</td>
</tr>
<tr>
<td class="diffspec" style="padding-top:.25em">To Level:</td>
<td class="diffvaluenew" style="padding-top:.25em">24</td>
</tr>
<tr>
<td class="diffspec">From Level:</td>
<td class="diffvalueold">23</td>
</tr>
<tr>
<td class="diffspec">Generated</td>
<td class="diffvalue">2016.06.13 13:31</td>
</tr>
</table>
</div><!-- End and-diff-id -->
<div class="and-diff-id" style="margin-right:8px;">
<table class="diffspectable">
<tr>
<td class="diffspec" colspan="2"><a href="jdiff_statistics.html">Statistics</a>
</tr>
</table>
</div> <!-- End and-diff-id -->
</div> <!-- End headerRight -->
</div> <!-- End header -->
<div id="body-content" xstyle="padding:12px;padding-right:18px;">
<div id="doc-content" style="position:relative;">
<div id="mainBodyFluid">
<H2>
Class android.media.<A HREF="../../../../reference/android/media/MediaRecorder.html" target="_top"><font size="+2"><code>MediaRecorder</code></font></A>
</H2>
<a NAME="constructors"></a>
<a NAME="methods"></a>
<p>
<a NAME="Added"></a>
<TABLE summary="Added Methods" WIDTH="100%">
<TR>
<TH VALIGN="TOP" COLSPAN=2>Added Methods</FONT></TD>
</TH>
<TR BGCOLOR="#FFFFFF" CLASS="TableRowColor">
<TD VALIGN="TOP" WIDTH="25%">
<A NAME="android.media.MediaRecorder.pause_added()"></A>
<nobr><code>void</code> <A HREF="../../../../reference/android/media/MediaRecorder.html#pause()" target="_top"><code>pause</code></A>()</nobr>
</TD>
<TD> </TD>
</TR>
<TR BGCOLOR="#FFFFFF" CLASS="TableRowColor">
<TD VALIGN="TOP" WIDTH="25%">
<A NAME="android.media.MediaRecorder.resume_added()"></A>
<nobr><code>void</code> <A HREF="../../../../reference/android/media/MediaRecorder.html#resume()" target="_top"><code>resume</code></A>()</nobr>
</TD>
<TD> </TD>
</TR>
</TABLE>
<a NAME="fields"></a>
</div>
<div id="footer">
<div id="copyright">
Except as noted, this content is licensed under
<a href="//creativecommons.org/licenses/by/2.5/"> Creative Commons Attribution 2.5</a>.
For details and restrictions, see the <a href="/license.html">Content License</a>.
</div>
<div id="footerlinks">
<p>
<a href="//www.android.com/terms.html">Site Terms of Service</a> -
<a href="//www.android.com/privacy.html">Privacy Policy</a> -
<a href="//www.android.com/branding.html">Brand Guidelines</a>
</p>
</div>
</div> <!-- end footer -->
</div><!-- end doc-content -->
</div> <!-- end body-content -->
<script src="//www.google-analytics.com/ga.js" type="text/javascript">
</script>
<script type="text/javascript">
try {
var pageTracker = _gat._getTracker("UA-5831155-1");
pageTracker._setAllowAnchor(true);
pageTracker._initData();
pageTracker._trackPageview();
} catch(e) {}
</script>
</BODY>
</HTML>
| {
"content_hash": "11a08add7fd058f401c2da5550080467",
"timestamp": "",
"source": "github",
"line_count": 129,
"max_line_length": 269,
"avg_line_length": 38.58139534883721,
"alnum_prop": 0.6276873618645771,
"repo_name": "xorware/android_frameworks_base",
"id": "684afb335439846383549361f1e4d3dcde31d182",
"size": "4977",
"binary": false,
"copies": "1",
"ref": "refs/heads/n",
"path": "docs/html/sdk/api_diff/24/changes/android.media.MediaRecorder.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "167132"
},
{
"name": "C++",
"bytes": "7092455"
},
{
"name": "GLSL",
"bytes": "20654"
},
{
"name": "HTML",
"bytes": "224185"
},
{
"name": "Java",
"bytes": "78926513"
},
{
"name": "Makefile",
"bytes": "420231"
},
{
"name": "Python",
"bytes": "42309"
},
{
"name": "RenderScript",
"bytes": "153826"
},
{
"name": "Shell",
"bytes": "21079"
}
],
"symlink_target": ""
} |
* {
padding: 0;
margin: 0;
}
html {
height: 100%;
/* Font size is needed to make the activity bar the correct size. */
font-size: 10px;
}
body {
height: 100%;
/*background-color: #404040;
background-image: url(../images/texture.png);*/
}
body.full-screen {
overflow: hidden;
}
body,
input,
button,
select {
font: message-box;
outline: none;
}
.hidden {
display: none !important;
}
[hidden] {
display: none !important;
}
#viewerContainer:-webkit-full-screen {
top: 0px;
border-top: 2px solid transparent;
background-color: #000;
/*width: 100%;
height: 100%;*/
width: 60%;
height: 80%;
overflow: hidden;
cursor: none;
}
#viewerContainer:-moz-full-screen {
top: 0px;
border-top: 2px solid transparent;
background-color: #000;
/*width: 100%;
height: 100%;*/
width: 60%;
height: 80%;
overflow: hidden;
cursor: none;
}
#viewerContainer:-ms-fullscreen {
top: 0px !important;
border-top: 2px solid transparent;
/*width: 100%;
height: 100%;*/
width: 60%;
height: 80%;
overflow: hidden !important;
cursor: none;
}
#viewerContainer:-ms-fullscreen::-ms-backdrop {
background-color: #000;
}
#viewerContainer:fullscreen {
top: 0px;
border-top: 2px solid transparent;
background-color: #000;
/*width: 100%;
height: 100%;*/
width: 60%;
height: 80%;
overflow: hidden;
cursor: none;
}
:-webkit-full-screen .page {
margin-bottom: 100%;
border: 0;
}
:-moz-full-screen .page {
margin-bottom: 100%;
border: 0;
}
:-ms-fullscreen .page {
margin-bottom: 100% !important;
border: 0;
}
:fullscreen .page {
margin-bottom: 100%;
border: 0;
}
:-webkit-full-screen a:not(.internalLink) {
display: none;
}
:-moz-full-screen a:not(.internalLink) {
display: none;
}
:-ms-fullscreen a:not(.internalLink) {
display: none !important;
}
:fullscreen a:not(.internalLink) {
display: none;
}
:-webkit-full-screen .textLayer > div {
cursor: none;
}
:-moz-full-screen .textLayer > div {
cursor: none;
}
:fullscreen .textLayer > div {
cursor: none;
}
#viewerContainer.presentationControls,
#viewerContainer.presentationControls .textLayer > div {
cursor: default;
}
/* outer/inner center provides horizontal center */
.outerCenter {
pointer-events: none;
position: relative;
}
html[dir='ltr'] .outerCenter {
float: right;
right: 40%;
}
html[dir='rtl'] .outerCenter {
float: left;
left: 40%;
}
.innerCenter {
pointer-events: auto;
position: relative;
}
html[dir='ltr'] .innerCenter {
float: right;
right: -50%;
}
html[dir='rtl'] .innerCenter {
float: left;
left: -50%;
}
#outerContainer {
width: 10%;/*100%;*/
height: 50%;/*100%;*/
position: absolute;
}
#sidebarContainer {
position: absolute;
top: 0;
bottom: 0;
/* Modified by DCS
width: 200px;
*/
width: 100px;
visibility: hidden;
-webkit-transition-duration: 200ms;
-webkit-transition-timing-function: ease;
transition-duration: 200ms;
transition-timing-function: ease;
}
html[dir='ltr'] #sidebarContainer {
-webkit-transition-property: left;
transition-property: left;
left: -200px;
}
html[dir='rtl'] #sidebarContainer {
-webkit-transition-property: right;
transition-property: right;
right: -200px;
}
#outerContainer.sidebarMoving > #sidebarContainer,
#outerContainer.sidebarOpen > #sidebarContainer {
visibility: visible;
}
html[dir='ltr'] #outerContainer.sidebarOpen > #sidebarContainer {
left: 0px;
}
html[dir='rtl'] #outerContainer.sidebarOpen > #sidebarContainer {
right: 0px;
}
#mainContainer {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
min-width: 320px;
-webkit-transition-duration: 200ms;
-webkit-transition-timing-function: ease;
transition-duration: 200ms;
transition-timing-function: ease;
}
html[dir='ltr'] #outerContainer.sidebarOpen > #mainContainer {
-webkit-transition-property: left;
transition-property: left;
}
html[dir='rtl'] #outerContainer.sidebarOpen > #mainContainer {
-webkit-transition-property: right;
transition-property: right;
right: 200px;
}
#sidebarContent {
top: 32px;
bottom: 0;
overflow: auto;
-webkit-overflow-scrolling: touch;
position: absolute;
/*width: 200px;*/
width: 160px;
background-color: hsla(0,0%,0%,.2);
z-index:999;
}
html[dir='ltr'] #sidebarContent {
left: 0;
box-shadow: inset -1px 0 0 hsla(0,0%,0%,.25);
}
html[dir='rtl'] #sidebarContent {
right: 0;
box-shadow: inset 1px 0 0 hsla(0,0%,0%,.25);
}
#viewerContainer {
overflow: auto;
-webkit-overflow-scrolling: touch;
position: absolute;
top: 32px;
right: 0;
bottom: 0;
left: 0;
outline: none;
}
html[dir='ltr'] #viewerContainer {
box-shadow: inset 1px 0 0 hsla(0,0%,100%,.05);
}
html[dir='rtl'] #viewerContainer {
box-shadow: inset -1px 0 0 hsla(0,0%,100%,.05);
}
.toolbar {
position: relative;
left: 0;
right: 0;
z-index: 9999;
cursor: default;
width:345px;
}
#toolbarContainer {
width: 100%;
}
#toolbarSidebar {
width: 200px;
height: 32px;
background-color: #424242; /* fallback */
background-image: url(../images/texture.png),
linear-gradient(hsla(0,0%,30%,.99), hsla(0,0%,25%,.95));
}
html[dir='ltr'] #toolbarSidebar {
box-shadow: inset -1px 0 0 rgba(0, 0, 0, 0.25),
inset 0 -1px 0 hsla(0,0%,100%,.05),
0 1px 0 hsla(0,0%,0%,.15),
0 0 1px hsla(0,0%,0%,.1);
}
html[dir='rtl'] #toolbarSidebar {
box-shadow: inset 1px 0 0 rgba(0, 0, 0, 0.25),
inset 0 1px 0 hsla(0,0%,100%,.05),
0 1px 0 hsla(0,0%,0%,.15),
0 0 1px hsla(0,0%,0%,.1);
}
#toolbarContainer, .findbar, .secondaryToolbar {
position: relative;
height: 32px;
background-color: #474747; /* fallback */
background-image: url(../images/texture.png),
linear-gradient(hsla(0,0%,32%,.99), hsla(0,0%,27%,.95));
}
html[dir='ltr'] #toolbarContainer, .findbar, .secondaryToolbar {
box-shadow: inset 1px 0 0 hsla(0,0%,100%,.08),
inset 0 1px 1px hsla(0,0%,0%,.15),
inset 0 -1px 0 hsla(0,0%,100%,.05),
0 1px 0 hsla(0,0%,0%,.15),
0 1px 1px hsla(0,0%,0%,.1);
}
html[dir='rtl'] #toolbarContainer, .findbar, .secondaryToolbar {
box-shadow: inset -1px 0 0 hsla(0,0%,100%,.08),
inset 0 1px 1px hsla(0,0%,0%,.15),
inset 0 -1px 0 hsla(0,0%,100%,.05),
0 1px 0 hsla(0,0%,0%,.15),
0 1px 1px hsla(0,0%,0%,.1);
}
#toolbarViewer {
height: 32px;
}
#loadingBar {
position: relative;
width: 100%;
height: 6px;
background-color: #333;
border-bottom: 1px solid #333;
}
#loadingBar .progress {
position: absolute;
top: 0;
left: 0;
width: 0%;
height: 100%;
background-color: #ddd;
overflow: hidden;
-webkit-transition: width 200ms;
transition: width 200ms;
}
@-webkit-keyframes progressIndeterminate {
0% { left: 0%; }
50% { left: 100%; }
100% { left: 100%; }
}
@keyframes progressIndeterminate {
0% { left: 0%; }
50% { left: 100%; }
100% { left: 100%; }
}
#loadingBar .progress.indeterminate {
background-color: #999;
-webkit-transition: none;
transition: none;
}
#loadingBar .indeterminate .glimmer {
position: absolute;
top: 0;
left: 0;
height: 100%;
width: 50px;
background-image: linear-gradient(to right, #999 0%, #fff 50%, #999 100%);
background-size: 100% 100%;
background-repeat: no-repeat;
-webkit-animation: progressIndeterminate 2s linear infinite;
animation: progressIndeterminate 2s linear infinite;
}
.findbar, .secondaryToolbar {
top: 32px;
position: absolute;
z-index: 10000;
height: 32px;
min-width: 16px;
padding: 0px 6px 0px 6px;
margin: 4px 2px 4px 2px;
color: hsl(0,0%,85%);
font-size: 12px;
line-height: 14px;
text-align: left;
cursor: default;
}
html[dir='ltr'] .findbar {
left: 68px;
}
html[dir='rtl'] .findbar {
right: 68px;
}
.findbar label {
-webkit-user-select: none;
-moz-user-select: none;
}
#findInput[data-status="pending"] {
background-image: url(../images/loading-small.png);
background-repeat: no-repeat;
background-position: right;
}
.secondaryToolbar {
padding: 6px;
height: auto;
z-index: 30000;
}
html[dir='ltr'] .secondaryToolbar {
right: 4px;
}
html[dir='rtl'] .secondaryToolbar {
left: 4px;
}
#secondaryToolbarButtonContainer {
max-width: 200px;
max-height: 400px;
overflow-y: auto;
-webkit-overflow-scrolling: touch;
margin-bottom: -4px;
}
.doorHanger,
.doorHangerRight {
border: 1px solid hsla(0,0%,0%,.5);
border-radius: 2px;
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.3);
}
.doorHanger:after, .doorHanger:before,
.doorHangerRight:after, .doorHangerRight:before {
bottom: 100%;
border: solid transparent;
content: " ";
height: 0;
width: 0;
position: absolute;
pointer-events: none;
}
.doorHanger:after,
.doorHangerRight:after {
border-bottom-color: hsla(0,0%,32%,.99);
border-width: 8px;
}
.doorHanger:before,
.doorHangerRight:before {
border-bottom-color: hsla(0,0%,0%,.5);
border-width: 9px;
}
html[dir='ltr'] .doorHanger:after,
html[dir='rtl'] .doorHangerRight:after {
left: 13px;
margin-left: -8px;
}
html[dir='ltr'] .doorHanger:before,
html[dir='rtl'] .doorHangerRight:before {
left: 13px;
margin-left: -9px;
}
html[dir='rtl'] .doorHanger:after,
html[dir='ltr'] .doorHangerRight:after {
right: 13px;
margin-right: -8px;
}
html[dir='rtl'] .doorHanger:before,
html[dir='ltr'] .doorHangerRight:before {
right: 13px;
margin-right: -9px;
}
#findMsg {
font-style: italic;
color: #A6B7D0;
}
.notFound {
background-color: rgb(255, 137, 153);
}
html[dir='ltr'] #toolbarViewerLeft {
margin-left: -1px;
}
html[dir='rtl'] #toolbarViewerRight {
margin-right: -1px;
}
html[dir='ltr'] #toolbarViewerLeft,
html[dir='rtl'] #toolbarViewerRight {
position: absolute;
top: 0;
left: 0;
}
html[dir='ltr'] #toolbarViewerRight,
html[dir='rtl'] #toolbarViewerLeft {
position: absolute;
top: 0;
right: 0;
}
html[dir='ltr'] #toolbarViewerLeft > *,
html[dir='ltr'] #toolbarViewerMiddle > *,
html[dir='ltr'] #toolbarViewerRight > *,
html[dir='ltr'] .findbar > * {
position: relative;
float: left;
}
html[dir='rtl'] #toolbarViewerLeft > *,
html[dir='rtl'] #toolbarViewerMiddle > *,
html[dir='rtl'] #toolbarViewerRight > *,
html[dir='rtl'] .findbar > * {
position: relative;
float: right;
}
html[dir='ltr'] .splitToolbarButton {
margin: 3px 2px 4px 0;
display: inline-block;
}
html[dir='rtl'] .splitToolbarButton {
margin: 3px 0 4px 2px;
display: inline-block;
}
html[dir='ltr'] .splitToolbarButton > .toolbarButton {
border-radius: 0;
float: left;
}
html[dir='rtl'] .splitToolbarButton > .toolbarButton {
border-radius: 0;
float: right;
}
.toolbarButton,
.secondaryToolbarButton {
border: 0 none;
background-color: rgba(0, 0, 0, 0);
width: 32px;
height: 25px;
}
.toolbarButton > span {
display: inline-block;
width: 0;
height: 0;
overflow: hidden;
}
.toolbarButton[disabled],
.secondaryToolbarButton[disabled] {
opacity: .5;
}
.toolbarButton.group {
margin-right: 0;
}
.splitToolbarButton.toggled .toolbarButton {
margin: 0;
}
.splitToolbarButton:hover > .toolbarButton,
.splitToolbarButton:focus > .toolbarButton,
.splitToolbarButton.toggled > .toolbarButton,
.toolbarButton.textButton {
background-color: hsla(0,0%,0%,.12);
background-image: linear-gradient(hsla(0,0%,100%,.05), hsla(0,0%,100%,0));
background-clip: padding-box;
border: 1px solid hsla(0,0%,0%,.35);
border-color: hsla(0,0%,0%,.32) hsla(0,0%,0%,.38) hsla(0,0%,0%,.42);
box-shadow: 0 1px 0 hsla(0,0%,100%,.05) inset,
0 0 1px hsla(0,0%,100%,.15) inset,
0 1px 0 hsla(0,0%,100%,.05);
-webkit-transition-property: background-color, border-color, box-shadow;
-webkit-transition-duration: 150ms;
-webkit-transition-timing-function: ease;
transition-property: background-color, border-color, box-shadow;
transition-duration: 150ms;
transition-timing-function: ease;
}
.splitToolbarButton > .toolbarButton:hover,
.splitToolbarButton > .toolbarButton:focus,
.dropdownToolbarButton:hover,
.overlayButton:hover,
.toolbarButton.textButton:hover,
.toolbarButton.textButton:focus {
background-color: hsla(0,0%,0%,.2);
box-shadow: 0 1px 0 hsla(0,0%,100%,.05) inset,
0 0 1px hsla(0,0%,100%,.15) inset,
0 0 1px hsla(0,0%,0%,.05);
z-index: 199;
}
.splitToolbarButton > .toolbarButton {
position: relative;
}
html[dir='ltr'] .splitToolbarButton > .toolbarButton:first-child,
html[dir='rtl'] .splitToolbarButton > .toolbarButton:last-child {
position: relative;
margin: 0;
margin-right: -1px;
border-top-left-radius: 2px;
border-bottom-left-radius: 2px;
border-right-color: transparent;
}
html[dir='ltr'] .splitToolbarButton > .toolbarButton:last-child,
html[dir='rtl'] .splitToolbarButton > .toolbarButton:first-child {
position: relative;
margin: 0;
margin-left: -1px;
border-top-right-radius: 2px;
border-bottom-right-radius: 2px;
border-left-color: transparent;
}
.splitToolbarButtonSeparator {
padding: 8px 0;
width: 1px;
background-color: hsla(0,0%,0%,.5);
z-index: 99;
box-shadow: 0 0 0 1px hsla(0,0%,100%,.08);
display: inline-block;
margin: 5px 0;
}
html[dir='ltr'] .splitToolbarButtonSeparator {
float: left;
}
html[dir='rtl'] .splitToolbarButtonSeparator {
float: right;
}
.splitToolbarButton:hover > .splitToolbarButtonSeparator,
.splitToolbarButton.toggled > .splitToolbarButtonSeparator {
padding: 12px 0;
margin: 1px 0;
box-shadow: 0 0 0 1px hsla(0,0%,100%,.03);
-webkit-transition-property: padding;
-webkit-transition-duration: 10ms;
-webkit-transition-timing-function: ease;
transition-property: padding;
transition-duration: 10ms;
transition-timing-function: ease;
}
.toolbarButton,
.dropdownToolbarButton,
.overlayButton,
.secondaryToolbarButton {
min-width: 16px;
padding: 2px 6px 0;
border: 1px solid transparent;
border-radius: 2px;
color: hsla(0,0%,100%,.8);
font-size: 12px;
line-height: 14px;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
/* Opera does not support user-select, use <... unselectable="on"> instead */
cursor: default;
-webkit-transition-property: background-color, border-color, box-shadow;
-webkit-transition-duration: 150ms;
-webkit-transition-timing-function: ease;
transition-property: background-color, border-color, box-shadow;
transition-duration: 150ms;
transition-timing-function: ease;
}
html[dir='ltr'] .toolbarButton,
html[dir='ltr'] .overlayButton,
html[dir='ltr'] .dropdownToolbarButton {
margin: 3px 2px 4px 0;
}
html[dir='rtl'] .toolbarButton,
html[dir='rtl'] .overlayButton,
html[dir='rtl'] .dropdownToolbarButton {
margin: 3px 0 4px 2px;
}
.toolbarButton:hover,
.toolbarButton:focus,
.dropdownToolbarButton,
.overlayButton,
.secondaryToolbarButton:hover,
.secondaryToolbarButton:focus {
background-color: hsla(0,0%,0%,.12);
background-image: linear-gradient(hsla(0,0%,100%,.05), hsla(0,0%,100%,0));
background-clip: padding-box;
border: 1px solid hsla(0,0%,0%,.35);
border-color: hsla(0,0%,0%,.32) hsla(0,0%,0%,.38) hsla(0,0%,0%,.42);
box-shadow: 0 1px 0 hsla(0,0%,100%,.05) inset,
0 0 1px hsla(0,0%,100%,.15) inset,
0 1px 0 hsla(0,0%,100%,.05);
}
.toolbarButton:hover:active,
.overlayButton:hover:active,
.dropdownToolbarButton:hover:active,
.secondaryToolbarButton:hover:active {
background-color: hsla(0,0%,0%,.2);
background-image: linear-gradient(hsla(0,0%,100%,.05), hsla(0,0%,100%,0));
border-color: hsla(0,0%,0%,.35) hsla(0,0%,0%,.4) hsla(0,0%,0%,.45);
box-shadow: 0 1px 1px hsla(0,0%,0%,.1) inset,
0 0 1px hsla(0,0%,0%,.2) inset,
0 1px 0 hsla(0,0%,100%,.05);
-webkit-transition-property: background-color, border-color, box-shadow;
-webkit-transition-duration: 10ms;
-webkit-transition-timing-function: linear;
transition-property: background-color, border-color, box-shadow;
transition-duration: 10ms;
transition-timing-function: linear;
}
.toolbarButton.toggled,
.splitToolbarButton.toggled > .toolbarButton.toggled,
.secondaryToolbarButton.toggled {
background-color: hsla(0,0%,0%,.3);
background-image: linear-gradient(hsla(0,0%,100%,.05), hsla(0,0%,100%,0));
border-color: hsla(0,0%,0%,.4) hsla(0,0%,0%,.45) hsla(0,0%,0%,.5);
box-shadow: 0 1px 1px hsla(0,0%,0%,.1) inset,
0 0 1px hsla(0,0%,0%,.2) inset,
0 1px 0 hsla(0,0%,100%,.05);
-webkit-transition-property: background-color, border-color, box-shadow;
-webkit-transition-duration: 10ms;
-webkit-transition-timing-function: linear;
transition-property: background-color, border-color, box-shadow;
transition-duration: 10ms;
transition-timing-function: linear;
}
.toolbarButton.toggled:hover:active,
.splitToolbarButton.toggled > .toolbarButton.toggled:hover:active,
.secondaryToolbarButton.toggled:hover:active {
background-color: hsla(0,0%,0%,.4);
border-color: hsla(0,0%,0%,.4) hsla(0,0%,0%,.5) hsla(0,0%,0%,.55);
box-shadow: 0 1px 1px hsla(0,0%,0%,.2) inset,
0 0 1px hsla(0,0%,0%,.3) inset,
0 1px 0 hsla(0,0%,100%,.05);
}
.dropdownToolbarButton {
width: 120px;
max-width: 120px;
padding: 3px 2px 2px;
overflow: hidden;
background: url(../images/toolbarButton-menuArrows.png) no-repeat;
}
html[dir='ltr'] .dropdownToolbarButton {
background-position: 95%;
}
html[dir='rtl'] .dropdownToolbarButton {
background-position: 5%;
}
.dropdownToolbarButton > select {
-webkit-appearance: none;
-moz-appearance: none; /* in the future this might matter, see bugzilla bug #649849 */
min-width: 140px;
font-size: 12px;
color: hsl(0,0%,95%);
margin: 0;
padding: 0;
border: none;
background: rgba(0,0,0,0); /* Opera does not support 'transparent' <select> background */
}
.dropdownToolbarButton > select > option {
background: hsl(0,0%,24%);
}
.overlayButton {
margin: 3px 2px 4px 5px !important;
line-height: 16px;
padding: 2px 6px 3px 6px;
}
#customScaleOption {
display: none;
}
#pageWidthOption {
border-bottom: 1px rgba(255, 255, 255, .5) solid;
}
html[dir='ltr'] .splitToolbarButton:first-child,
html[dir='ltr'] .toolbarButton:first-child,
html[dir='rtl'] .splitToolbarButton:last-child,
html[dir='rtl'] .toolbarButton:last-child {
margin-left: 4px;
}
html[dir='ltr'] .splitToolbarButton:last-child,
html[dir='ltr'] .toolbarButton:last-child,
html[dir='rtl'] .splitToolbarButton:first-child,
html[dir='rtl'] .toolbarButton:first-child {
margin-right: 4px;
}
.toolbarButtonSpacer {
width: 30px;
display: inline-block;
height: 1px;
}
.toolbarButtonFlexibleSpacer {
-webkit-box-flex: 1;
-moz-box-flex: 1;
min-width: 30px;
}
html[dir='ltr'] #findPrevious {
margin-left: 3px;
}
html[dir='ltr'] #findNext {
margin-right: 3px;
}
html[dir='rtl'] #findPrevious {
margin-right: 3px;
}
html[dir='rtl'] #findNext {
margin-left: 3px;
}
.toolbarButton::before,
.secondaryToolbarButton::before {
/* All matching images have a size of 16x16
* All relevant containers have a size of 32x25 */
position: absolute;
display: inline-block;
top: 4px;
left: 7px;
}
html[dir="ltr"] .secondaryToolbarButton::before {
left: 4px;
}
html[dir="rtl"] .secondaryToolbarButton::before {
right: 4px;
}
html[dir='ltr'] .toolbarButton#sidebarToggle::before {
content: url(../images/toolbarButton-sidebarToggle.png);
}
html[dir='rtl'] .toolbarButton#sidebarToggle::before {
content: url(../images/toolbarButton-sidebarToggle-rtl.png);
}
html[dir='ltr'] .toolbarButton#secondaryToolbarToggle::before {
content: url(../images/toolbarButton-secondaryToolbarToggle.png);
}
html[dir='rtl'] .toolbarButton#secondaryToolbarToggle::before {
content: url(../images/toolbarButton-secondaryToolbarToggle-rtl.png);
}
html[dir='ltr'] .toolbarButton.findPrevious::before {
content: url(../images/findbarButton-previous.png);
}
html[dir='rtl'] .toolbarButton.findPrevious::before {
content: url(../images/findbarButton-previous-rtl.png);
}
html[dir='ltr'] .toolbarButton.findNext::before {
content: url(../images/findbarButton-next.png);
}
html[dir='rtl'] .toolbarButton.findNext::before {
content: url(../images/findbarButton-next-rtl.png);
}
html[dir='ltr'] .toolbarButton.pageUp::before {
content: url(../images/toolbarButton-pageUp.png);
}
html[dir='rtl'] .toolbarButton.pageUp::before {
content: url(../images/toolbarButton-pageUp-rtl.png);
}
html[dir='ltr'] .toolbarButton.pageDown::before {
content: url(../images/toolbarButton-pageDown.png);
}
html[dir='rtl'] .toolbarButton.pageDown::before {
content: url(../images/toolbarButton-pageDown-rtl.png);
}
.toolbarButton.zoomOut::before {
content: url(../images/toolbarButton-zoomOut.png);
}
.toolbarButton.zoomIn::before {
content: url(../images/toolbarButton-zoomIn.png);
}
.toolbarButton.presentationMode::before,
.secondaryToolbarButton.presentationMode::before {
content: url(../images/toolbarButton-presentationMode.png);
}
.toolbarButton.print::before,
.secondaryToolbarButton.print::before {
content: url(../images/toolbarButton-print.png);
}
.toolbarButton.openFile::before,
.secondaryToolbarButton.openFile::before {
content: url(../images/toolbarButton-openFile.png);
}
.toolbarButton.download::before,
.secondaryToolbarButton.download::before {
content: url(../images/toolbarButton-download.png);
}
.toolbarButton.bookmark,
.secondaryToolbarButton.bookmark {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
outline: none;
padding-top: 4px;
text-decoration: none;
}
.secondaryToolbarButton.bookmark {
padding-top: 5px;
}
.bookmark[href='#'] {
opacity: .5;
pointer-events: none;
}
.toolbarButton.bookmark::before,
.secondaryToolbarButton.bookmark::before {
content: url(../images/toolbarButton-bookmark.png);
}
#viewThumbnail.toolbarButton::before {
content: url(../images/toolbarButton-viewThumbnail.png);
}
html[dir="ltr"] #viewOutline.toolbarButton::before {
content: url(../images/toolbarButton-viewOutline.png);
}
html[dir="rtl"] #viewOutline.toolbarButton::before {
content: url(../images/toolbarButton-viewOutline-rtl.png);
}
#viewAttachments.toolbarButton::before {
content: url(../images/toolbarButton-viewAttachments.png);
}
#viewFind.toolbarButton::before {
content: url(../images/toolbarButton-search.png);
}
.secondaryToolbarButton {
position: relative;
margin: 0 0 4px 0;
padding: 3px 0 1px 0;
height: auto;
min-height: 25px;
width: auto;
min-width: 100%;
white-space: normal;
}
html[dir="ltr"] .secondaryToolbarButton {
padding-left: 24px;
text-align: left;
}
html[dir="rtl"] .secondaryToolbarButton {
padding-right: 24px;
text-align: right;
}
html[dir="ltr"] .secondaryToolbarButton.bookmark {
padding-left: 27px;
}
html[dir="rtl"] .secondaryToolbarButton.bookmark {
padding-right: 27px;
}
html[dir="ltr"] .secondaryToolbarButton > span {
padding-right: 4px;
}
html[dir="rtl"] .secondaryToolbarButton > span {
padding-left: 4px;
}
.secondaryToolbarButton.firstPage::before {
content: url(../images/secondaryToolbarButton-firstPage.png);
}
.secondaryToolbarButton.lastPage::before {
content: url(../images/secondaryToolbarButton-lastPage.png);
}
.secondaryToolbarButton.rotateCcw::before {
content: url(../images/secondaryToolbarButton-rotateCcw.png);
}
.secondaryToolbarButton.rotateCw::before {
content: url(../images/secondaryToolbarButton-rotateCw.png);
}
.secondaryToolbarButton.handTool::before {
content: url(../images/secondaryToolbarButton-handTool.png);
}
.secondaryToolbarButton.documentProperties::before {
content: url(../images/secondaryToolbarButton-documentProperties.png);
}
.verticalToolbarSeparator {
display: block;
padding: 8px 0;
margin: 8px 4px;
width: 1px;
background-color: hsla(0,0%,0%,.5);
box-shadow: 0 0 0 1px hsla(0,0%,100%,.08);
}
html[dir='ltr'] .verticalToolbarSeparator {
margin-left: 2px;
}
html[dir='rtl'] .verticalToolbarSeparator {
margin-right: 2px;
}
.horizontalToolbarSeparator {
display: block;
margin: 0 0 4px 0;
height: 1px;
width: 100%;
background-color: hsla(0,0%,0%,.5);
box-shadow: 0 0 0 1px hsla(0,0%,100%,.08);
}
.toolbarField {
padding: 3px 6px;
margin: 4px 0 4px 0;
border: 1px solid transparent;
border-radius: 2px;
background-color: hsla(0,0%,100%,.09);
background-image: linear-gradient(hsla(0,0%,100%,.05), hsla(0,0%,100%,0));
background-clip: padding-box;
border: 1px solid hsla(0,0%,0%,.35);
border-color: hsla(0,0%,0%,.32) hsla(0,0%,0%,.38) hsla(0,0%,0%,.42);
box-shadow: 0 1px 0 hsla(0,0%,0%,.05) inset,
0 1px 0 hsla(0,0%,100%,.05);
color: hsl(0,0%,95%);
font-size: 12px;
line-height: 14px;
outline-style: none;
transition-property: background-color, border-color, box-shadow;
transition-duration: 150ms;
transition-timing-function: ease;
}
.toolbarField[type=checkbox] {
display: inline-block;
margin: 8px 0px;
}
.toolbarField.pageNumber {
-moz-appearance: textfield; /* hides the spinner in moz */
min-width: 16px;
text-align: right;
width: 40px;
}
.toolbarField.pageNumber::-webkit-inner-spin-button,
.toolbarField.pageNumber::-webkit-outer-spin-button {
-webkit-appearance: none;
margin: 0;
}
.toolbarField:hover {
background-color: hsla(0,0%,100%,.11);
border-color: hsla(0,0%,0%,.4) hsla(0,0%,0%,.43) hsla(0,0%,0%,.45);
}
.toolbarField:focus {
background-color: hsla(0,0%,100%,.15);
border-color: hsla(204,100%,65%,.8) hsla(204,100%,65%,.85) hsla(204,100%,65%,.9);
}
.toolbarLabel {
min-width: 16px;
padding: 3px 6px 3px 2px;
margin: 4px 2px 4px 0;
border: 1px solid transparent;
border-radius: 2px;
color: hsl(0,0%,85%);
font-size: 12px;
line-height: 14px;
text-align: left;
-webkit-user-select: none;
-moz-user-select: none;
cursor: default;
}
#thumbnailView {
position: absolute;
/*width: 120px;*/
width: 100px;
top: 0;
bottom: 0;
padding: 10px 40px 0;
overflow: auto;
-webkit-overflow-scrolling: touch;
}
.thumbnail {
float: left;
margin-bottom: 5px;
}
#thumbnailView > a:last-of-type > .thumbnail {
margin-bottom: 10px;
}
.thumbnail:not([data-loaded]) {
border: 1px dashed rgba(255, 255, 255, 0.5);
margin-bottom: 10px;
}
.thumbnailImage {
transition-duration: 150ms;
border: 1px solid transparent;
box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.5), 0 2px 8px rgba(0, 0, 0, 0.3);
opacity: 0.8;
z-index: 99;
}
.thumbnailSelectionRing {
border-radius: 2px;
padding: 7px;
transition-duration: 150ms;
}
a:focus > .thumbnail > .thumbnailSelectionRing > .thumbnailImage,
.thumbnail:hover > .thumbnailSelectionRing > .thumbnailImage {
opacity: .9;
}
a:focus > .thumbnail > .thumbnailSelectionRing,
.thumbnail:hover > .thumbnailSelectionRing {
background-color: hsla(0,0%,100%,.15);
background-image: linear-gradient(hsla(0,0%,100%,.05), hsla(0,0%,100%,0));
background-clip: padding-box;
box-shadow: 0 1px 0 hsla(0,0%,100%,.05) inset,
0 0 1px hsla(0,0%,100%,.2) inset,
0 0 1px hsla(0,0%,0%,.2);
color: hsla(0,0%,100%,.9);
}
.thumbnail.selected > .thumbnailSelectionRing > .thumbnailImage {
box-shadow: 0 0 0 1px hsla(0,0%,0%,.5);
opacity: 1;
}
.thumbnail.selected > .thumbnailSelectionRing {
background-color: hsla(0,0%,100%,.3);
background-image: linear-gradient(hsla(0,0%,100%,.05), hsla(0,0%,100%,0));
background-clip: padding-box;
box-shadow: 0 1px 0 hsla(0,0%,100%,.05) inset,
0 0 1px hsla(0,0%,100%,.1) inset,
0 0 1px hsla(0,0%,0%,.2);
color: hsla(0,0%,100%,1);
}
#outlineView,
#attachmentsView {
position: absolute;
width: 192px;
top: 0;
bottom: 0;
overflow: auto;
-webkit-overflow-scrolling: touch;
-webkit-user-select: none;
-moz-user-select: none;
}
#outlineView {
padding: 4px 4px 0;
}
#attachmentsView {
padding: 3px 4px 0;
}
html[dir='ltr'] .outlineItem > .outlineItems {
margin-left: 20px;
}
html[dir='rtl'] .outlineItem > .outlineItems {
margin-right: 20px;
}
.outlineItem > a,
.attachmentsItem > button {
text-decoration: none;
display: inline-block;
min-width: 95%;
height: auto;
margin-bottom: 1px;
border-radius: 2px;
color: hsla(0,0%,100%,.8);
font-size: 13px;
line-height: 15px;
-moz-user-select: none;
white-space: normal;
}
.attachmentsItem > button {
border: 0 none;
background: none;
cursor: pointer;
width: 100%;
}
html[dir='ltr'] .outlineItem > a {
padding: 2px 0 5px 10px;
}
html[dir='ltr'] .attachmentsItem > button {
padding: 2px 0 3px 7px;
text-align: left;
}
html[dir='rtl'] .outlineItem > a {
padding: 2px 10px 5px 0;
}
html[dir='rtl'] .attachmentsItem > button {
padding: 2px 7px 3px 0;
text-align: right;
}
.outlineItem > a:hover,
.attachmentsItem > button:hover {
background-color: hsla(0,0%,100%,.02);
background-image: linear-gradient(hsla(0,0%,100%,.05), hsla(0,0%,100%,0));
background-clip: padding-box;
box-shadow: 0 1px 0 hsla(0,0%,100%,.05) inset,
0 0 1px hsla(0,0%,100%,.2) inset,
0 0 1px hsla(0,0%,0%,.2);
color: hsla(0,0%,100%,.9);
}
.outlineItem.selected {
background-color: hsla(0,0%,100%,.08);
background-image: linear-gradient(hsla(0,0%,100%,.05), hsla(0,0%,100%,0));
background-clip: padding-box;
box-shadow: 0 1px 0 hsla(0,0%,100%,.05) inset,
0 0 1px hsla(0,0%,100%,.1) inset,
0 0 1px hsla(0,0%,0%,.2);
color: hsla(0,0%,100%,1);
}
.noResults {
font-size: 12px;
color: hsla(0,0%,100%,.8);
font-style: italic;
cursor: default;
}
.canvasWrapper {
overflow: hidden;
}
canvas {
margin: 0;
display: block;
}
.page {
direction: ltr;
width: 816px;
height: 1056px;
margin: 1px auto -8px auto;
position: relative;
overflow: visible;
border: 9px solid transparent;
background-clip: content-box;
border-image: url(../images/shadow.png) 9 9 repeat;
background-color: white;
}
.annotLink > a:hover {
opacity: 0.2;
background: #ff0;
box-shadow: 0px 2px 10px #ff0;
}
.loadingIcon {
position: absolute;
display: block;
left: 0;
top: 0;
right: 0;
bottom: 0;
background: url('../images/loading-icon.gif') center no-repeat;
}
.textLayer {
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
color: #000;
font-family: sans-serif;
overflow: hidden;
}
.textLayer > div {
color: transparent;
position: absolute;
white-space: pre;
cursor: text;
}
.textLayer .highlight {
margin: -1px;
padding: 1px;
background-color: rgba(180, 0, 170, 0.2);
border-radius: 4px;
}
.textLayer .highlight.begin {
border-radius: 4px 0px 0px 4px;
}
.textLayer .highlight.end {
border-radius: 0px 4px 4px 0px;
}
.textLayer .highlight.middle {
border-radius: 0px;
}
.textLayer .highlight.selected {
background-color: rgba(0, 100, 0, 0.2);
}
/* TODO: file FF bug to support ::-moz-selection:window-inactive
so we can override the opaque grey background when the window is inactive;
see https://bugzilla.mozilla.org/show_bug.cgi?id=706209 */
::selection { background:rgba(0,0,255,0.3); }
::-moz-selection { background:rgba(0,0,255,0.3); }
.annotationHighlight {
position: absolute;
border: 2px #FFFF99 solid;
}
.annotText > img {
position: absolute;
cursor: pointer;
}
.annotTextContentWrapper {
position: absolute;
width: 20em;
}
.annotTextContent {
z-index: 200;
float: left;
max-width: 20em;
background-color: #FFFF99;
box-shadow: 0px 2px 5px #333;
border-radius: 2px;
padding: 0.6em;
cursor: pointer;
}
.annotTextContent > h1 {
font-size: 1em;
border-bottom: 1px solid #000000;
padding-bottom: 0.2em;
}
.annotTextContent > p {
padding-top: 0.2em;
}
.annotLink > a {
position: absolute;
font-size: 1em;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
#errorWrapper {
background: none repeat scroll 0 0 #FF5555;
color: white;
left: 0;
position: absolute;
right: 0;
z-index: 1000;
padding: 3px;
font-size: 0.8em;
}
.loadingInProgress #errorWrapper {
top: 39px;
}
#errorMessageLeft {
float: left;
}
#errorMessageRight {
float: right;
}
#errorMoreInfo {
background-color: #FFFFFF;
color: black;
padding: 3px;
margin: 3px;
width: 98%;
}
#overlayContainer {
display: table;
position: absolute;
width: 100%;
height: 100%;
background-color: hsla(0,0%,0%,.2);
z-index: 10000;
}
#overlayContainer > * {
overflow: auto;
-webkit-overflow-scrolling: touch;
}
#promptContainer {
display: table-cell;
vertical-align: middle;
text-align: center;
}
#promptContainer > * {
display: inline-block;
}
.prompt {
display: table;
padding: 15px;
border-spacing: 4px;
color: hsl(0,0%,85%);
line-height: 14px;
text-align: center;
background-color: #474747; /* fallback */
background-image: url(../images/texture.png),
linear-gradient(hsla(0,0%,32%,.99), hsla(0,0%,27%,.95));
box-shadow: inset 1px 0 0 hsla(0,0%,100%,.08),
inset 0 1px 1px hsla(0,0%,0%,.15),
inset 0 -1px 0 hsla(0,0%,100%,.05),
0 1px 0 hsla(0,0%,0%,.15),
0 1px 1px hsla(0,0%,0%,.1);
}
.prompt > .row {
display: table-row;
}
.prompt > .row > * {
display: table-cell;
}
.prompt .toolbarField {
margin: 5px 0;
width: 200px;
}
.prompt .toolbarField:hover,
.prompt .toolbarField:focus {
border-color: hsla(0,0%,0%,.32) hsla(0,0%,0%,.38) hsla(0,0%,0%,.42);
}
#documentPropertiesContainer {
display: table-cell;
vertical-align: middle;
text-align: center;
}
#documentPropertiesContainer > * {
display: inline-block;
padding: 15px;
border-spacing: 4px;
max-width: 350px;
max-height: 350px;
color: hsl(0,0%,85%);
font-size: 12px;
line-height: 14px;
text-align: left;
cursor: default;
background-color: #474747; /* fallback */
background-image: url(../images/texture.png),
linear-gradient(hsla(0,0%,32%,.99), hsla(0,0%,27%,.95));
box-shadow: inset 1px 0 0 hsla(0,0%,100%,.08),
inset 0 1px 1px hsla(0,0%,0%,.15),
inset 0 -1px 0 hsla(0,0%,100%,.05),
0 1px 0 hsla(0,0%,0%,.15),
0 1px 1px hsla(0,0%,0%,.1);
}
#documentPropertiesContainer .separator {
display: block;
margin: 4px 0 4px 0;
height: 1px;
width: 100%;
background-color: hsla(0,0%,0%,.5);
box-shadow: 0 0 0 1px hsla(0,0%,100%,.08);
}
#documentPropertiesContainer .row {
display: table-row;
}
html[dir='ltr'] #documentPropertiesContainer .row > * {
display: table-cell;
min-width: 100px;
}
html[dir='rtl'] #documentPropertiesContainer .row > * {
display: table-cell;
min-width: 100px;
text-align: right;
}
#documentPropertiesContainer .row span {
width: 125px;
word-wrap: break-word;
}
#documentPropertiesContainer .row p {
max-width: 225px;
word-wrap: break-word;
}
#documentPropertiesContainer .buttonRow {
margin-top: 10px;
text-align: center;
vertical-align: middle;
}
.clearBoth {
clear: both;
}
.fileInput {
background: white;
color: black;
margin-top: 5px;
visibility: hidden;
position: fixed;
right: 0;
top: 0;
}
#PDFBug {
background: none repeat scroll 0 0 white;
border: 1px solid #666666;
position: fixed;
top: 32px;
right: 0;
bottom: 0;
font-size: 10px;
padding: 0;
width: 300px;
}
#PDFBug .controls {
background:#EEEEEE;
border-bottom: 1px solid #666666;
padding: 3px;
}
#PDFBug .panels {
bottom: 0;
left: 0;
overflow: auto;
-webkit-overflow-scrolling: touch;
position: absolute;
right: 0;
top: 27px;
}
#PDFBug button.active {
font-weight: bold;
}
.debuggerShowText {
background: none repeat scroll 0 0 yellow;
color: blue;
opacity: 0.3;
}
.debuggerHideText:hover {
background: none repeat scroll 0 0 yellow;
opacity: 0.3;
}
#PDFBug .stats {
font-family: courier;
font-size: 10px;
white-space: pre;
}
#PDFBug .stats .title {
font-weight: bold;
}
#PDFBug table {
font-size: 10px;
}
#viewer.textLayer-visible .textLayer > div,
#viewer.textLayer-hover .textLayer > div:hover {
background-color: white;
color: black;
}
#viewer.textLayer-shadow .textLayer > div {
background-color: rgba(255,255,255, .6);
color: black;
}
.grab-to-pan-grab {
cursor: url("../images/grab.cur"), move !important;
cursor: -webkit-grab !important;
cursor: -moz-grab !important;
cursor: grab !important;
}
.grab-to-pan-grab *:not(input):not(textarea):not(button):not(select):not(:link) {
cursor: inherit !important;
}
.grab-to-pan-grab:active,
.grab-to-pan-grabbing {
cursor: url("../images/grabbing.cur"), move !important;
cursor: -webkit-grabbing !important;
cursor: -moz-grabbing !important;
cursor: grabbing !important;
position: fixed;
background: transparent;
display: block;
top: 0;
left: 0;
right: 0;
bottom: 0;
overflow: hidden;
z-index: 50000; /* should be higher than anything else in PDF.js! */
}
@page {
margin: 0;
}
#printContainer {
display: none;
}
@media screen and (min-resolution: 2dppx) {
/* Rules for Retina screens */
.toolbarButton::before {
-webkit-transform: scale(0.5);
transform: scale(0.5);
top: -5px;
}
.secondaryToolbarButton::before {
-webkit-transform: scale(0.5);
transform: scale(0.5);
top: -4px;
}
html[dir='ltr'] .toolbarButton::before,
html[dir='rtl'] .toolbarButton::before {
left: -1px;
}
html[dir='ltr'] .secondaryToolbarButton::before {
left: -2px;
}
html[dir='rtl'] .secondaryToolbarButton::before {
left: 186px;
}
.dropdownToolbarButton {
background: url(../images/toolbarButton-menuArrows@2x.png) no-repeat;
background-size: 7px 16px;
}
html[dir='ltr'] .toolbarButton#sidebarToggle::before {
content: url(../images/toolbarButton-sidebarToggle@2x.png);
}
html[dir='rtl'] .toolbarButton#sidebarToggle::before {
content: url(../images/toolbarButton-sidebarToggle-rtl@2x.png);
}
html[dir='ltr'] .toolbarButton#secondaryToolbarToggle::before {
content: url(../images/toolbarButton-secondaryToolbarToggle@2x.png);
}
html[dir='rtl'] .toolbarButton#secondaryToolbarToggle::before {
content: url(../images/toolbarButton-secondaryToolbarToggle-rtl@2x.png);
}
html[dir='ltr'] .toolbarButton.findPrevious::before {
content: url(../images/findbarButton-previous@2x.png);
}
html[dir='rtl'] .toolbarButton.findPrevious::before {
content: url(../images/findbarButton-previous-rtl@2x.png);
}
html[dir='ltr'] .toolbarButton.findNext::before {
content: url(../images/findbarButton-next@2x.png);
}
html[dir='rtl'] .toolbarButton.findNext::before {
content: url(../images/findbarButton-next-rtl@2x.png);
}
html[dir='ltr'] .toolbarButton.pageUp::before {
content: url(../images/toolbarButton-pageUp@2x.png);
}
html[dir='rtl'] .toolbarButton.pageUp::before {
content: url(../images/toolbarButton-pageUp-rtl@2x.png);
}
html[dir='ltr'] .toolbarButton.pageDown::before {
content: url(../images/toolbarButton-pageDown@2x.png);
}
html[dir='rtl'] .toolbarButton.pageDown::before {
content: url(../images/toolbarButton-pageDown-rtl@2x.png);
}
.toolbarButton.zoomIn::before {
content: url(../images/toolbarButton-zoomIn@2x.png);
}
.toolbarButton.zoomOut::before {
content: url(../images/toolbarButton-zoomOut@2x.png);
}
.toolbarButton.presentationMode::before,
.secondaryToolbarButton.presentationMode::before {
content: url(../images/toolbarButton-presentationMode@2x.png);
}
.toolbarButton.print::before,
.secondaryToolbarButton.print::before {
content: url(../images/toolbarButton-print@2x.png);
}
.toolbarButton.openFile::before,
.secondaryToolbarButton.openFile::before {
content: url(../images/toolbarButton-openFile@2x.png);
}
.toolbarButton.download::before,
.secondaryToolbarButton.download::before {
content: url(../images/toolbarButton-download@2x.png);
}
.toolbarButton.bookmark::before,
.secondaryToolbarButton.bookmark::before {
content: url(../images/toolbarButton-bookmark@2x.png);
}
#viewThumbnail.toolbarButton::before {
content: url(../images/toolbarButton-viewThumbnail@2x.png);
}
html[dir="ltr"] #viewOutline.toolbarButton::before {
content: url(../images/toolbarButton-viewOutline@2x.png);
}
html[dir="rtl"] #viewOutline.toolbarButton::before {
content: url(../images/toolbarButton-viewOutline-rtl@2x.png);
}
#viewAttachments.toolbarButton::before {
content: url(../images/toolbarButton-viewAttachments@2x.png);
}
#viewFind.toolbarButton::before {
content: url(../images/toolbarButton-search@2x.png);
}
.secondaryToolbarButton.firstPage::before {
content: url(../images/secondaryToolbarButton-firstPage@2x.png);
}
.secondaryToolbarButton.lastPage::before {
content: url(../images/secondaryToolbarButton-lastPage@2x.png);
}
.secondaryToolbarButton.rotateCcw::before {
content: url(../images/secondaryToolbarButton-rotateCcw@2x.png);
}
.secondaryToolbarButton.rotateCw::before {
content: url(../images/secondaryToolbarButton-rotateCw@2x.png);
}
.secondaryToolbarButton.handTool::before {
content: url(../images/secondaryToolbarButton-handTool@2x.png);
}
.secondaryToolbarButton.documentProperties::before {
content: url(../images/secondaryToolbarButton-documentProperties@2x.png);
}
}
@media print {
/* General rules for printing. */
body {
background: transparent none;
}
/* Rules for browsers that don't support mozPrintCallback. */
#sidebarContainer, #secondaryToolbar, .toolbar, #loadingBox, #errorWrapper, .textLayer {
display: none;
}
#viewerContainer {
overflow: visible;
}
#mainContainer, #viewerContainer, .page, .page canvas {
position: static;
padding: 0;
margin: 0;
}
.page {
float: left;
display: none;
border: none;
box-shadow: none;
}
.page[data-loaded] {
display: block;
}
.fileInput {
display: none;
}
/* Rules for browsers that support mozPrintCallback */
body[data-mozPrintCallback] #outerContainer {
display: none;
}
body[data-mozPrintCallback] #printContainer {
display: block;
}
#printContainer canvas {
position: relative;
top: 0;
left: 0;
}
}
.visibleLargeView,
.visibleMediumView,
.visibleSmallView {
display: none;
}
/*
@media all and (max-width: 860px) {
html[dir='ltr'] #outerContainer.sidebarMoving .outerCenter,
html[dir='ltr'] #outerContainer.sidebarOpen .outerCenter {
float: left;
left: 205px;
}
html[dir='rtl'] #outerContainer.sidebarMoving .outerCenter,
html[dir='rtl'] #outerContainer.sidebarOpen .outerCenter {
float: right;
right: 205px;
}
}
@media all and (max-width: 800px) {
.sidebarOpen .hiddenLargeView {
display: none;
}
.sidebarOpen .visibleLargeView {
display: inherit;
}
}
@media all and (max-width: 760px) {
.sidebarOpen .hiddenMediumView {
display: none;
}
.sidebarOpen .visibleMediumView {
display: inherit;
}
}
@media all and (max-width: 670px) {
#sidebarContainer {
top: 32px;
z-index: 100;
}
.loadingInProgress #sidebarContainer {
top: 39px;
}
#sidebarContent {
top: 32px;
background-color: hsla(0,0%,0%,.7);
}
html[dir='ltr'] #outerContainer.sidebarOpen > #mainContainer {
left: 0px;
}
html[dir='rtl'] #outerContainer.sidebarOpen > #mainContainer {
right: 0px;
}
html[dir='ltr'] .outerCenter {
float: left;
left: 205px;
}
html[dir='rtl'] .outerCenter {
float: right;
right: 205px;
}
#outerContainer .hiddenLargeView,
#outerContainer .hiddenMediumView {
display: inherit;
}
#outerContainer .visibleLargeView,
#outerContainer .visibleMediumView {
display: none;
}
}
@media all and (max-width: 700px) {
#outerContainer .hiddenLargeView {
display: none;
}
#outerContainer .visibleLargeView {
display: inherit;
}
}
@media all and (max-width: 660px) {
#outerContainer .hiddenMediumView {
display: none;
}
#outerContainer .visibleMediumView {
display: inherit;
}
}
@media all and (max-width: 600px) {
.hiddenSmallView {
display: none;
}
.visibleSmallView {
display: inherit;
}
html[dir='ltr'] #outerContainer.sidebarMoving .outerCenter,
html[dir='ltr'] #outerContainer.sidebarOpen .outerCenter,
html[dir='ltr'] .outerCenter {
left: 156px;
}
html[dir='rtl'] #outerContainer.sidebarMoving .outerCenter,
html[dir='rtl'] #outerContainer.sidebarOpen .outerCenter,
html[dir='rtl'] .outerCenter {
right: 156px;
}
.toolbarButtonSpacer {
width: 0;
}
}
@media all and (max-width: 510px) {
#scaleSelectContainer, #pageNumberLabel {
display: none;
}
}*/
| {
"content_hash": "dcd418cf392213d0b6f60dd006aa1ee0",
"timestamp": "",
"source": "github",
"line_count": 1987,
"max_line_length": 91,
"avg_line_length": 22.563663814796175,
"alnum_prop": 0.6688673774367667,
"repo_name": "SimpleECM/invoicevalidation",
"id": "28143c1f976936773475d5109b1fc4e85d660c15",
"size": "45432",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "web/css/viewer.css",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
layout: article
title: Данные из таблицы
---
Чтобы вывести данные из таблицы используют ключевое слово `FROM`, после которого указывается имя таблицы.
SELECT cities.name
FROM cities
выведет значения поля `name` из таблицы `cities`.
Для таблицы может быть указана **схема**, к которой принадлежит эта таблица:
SELECT cities.name
FROM geo.cities
таблица `cities`, которая находится в схеме `geo`.
Перед именем поля можно не указывать название таблицы,
если поле с таким именем существует только в одной таблице, используемой в запросе:
SELECT name
FROM cities
К таблицам тоже можно применять псевдонимы:
SELECT "Города".name
FROM cities "Города"
И так тоже можно:
SELECT "Города".name "Название"
FROM cities "Города"
И так:
SELECT a.name
FROM cities a
Конечно, можно перечислить несколько таблиц:
SELECT cities.name, countries.name, countries.code
FROM cities, countries
выведет названия городов, названия и коды стран. Видите, поле `name` есть как в таблице `cities`, так и в `countries`.
Поэтому мы должны явно указывать название таблицы для этих полей.
Но в таком виде запрос не рекомендую запускать.
Как выводить данные из нескольких таблиц рассмотрим дальше.
SELECT cities.*
FROM cities
выведет все поля из таблицы `cities`
SELECT cities.*, countries.*
FROM cities, countries
выведет все поля из таблиц `cities` и `countries`
SELECT *
FROM cities, countries
также выведет все поля этих таблиц
| {
"content_hash": "954dd7229e3d39e243336f06793c41a8",
"timestamp": "",
"source": "github",
"line_count": 63,
"max_line_length": 118,
"avg_line_length": 23.825396825396826,
"alnum_prop": 0.7401732178547635,
"repo_name": "prosql/prosql.github.io",
"id": "f7094063adb1898560ecb878bb012e26adb2d93a",
"size": "2250",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "_book/01-04-from.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "63814"
},
{
"name": "HTML",
"bytes": "8904"
}
],
"symlink_target": ""
} |
package docker
import (
"context"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"strings"
"github.com/containerd/containerd/errdefs"
"github.com/containerd/containerd/images"
"github.com/containerd/containerd/log"
"github.com/docker/distribution/registry/api/errcode"
ocispec "github.com/opencontainers/image-spec/specs-go/v1"
"github.com/pkg/errors"
)
type dockerFetcher struct {
*dockerBase
}
func (r dockerFetcher) Fetch(ctx context.Context, desc ocispec.Descriptor) (io.ReadCloser, error) {
ctx = log.WithLogger(ctx, log.G(ctx).WithField("digest", desc.Digest))
hosts := r.filterHosts(HostCapabilityPull)
if len(hosts) == 0 {
return nil, errors.Wrap(errdefs.ErrNotFound, "no pull hosts")
}
ctx, err := contextWithRepositoryScope(ctx, r.refspec, false)
if err != nil {
return nil, err
}
return newHTTPReadSeeker(desc.Size, func(offset int64) (io.ReadCloser, error) {
// firstly try fetch via external urls
for _, us := range desc.URLs {
ctx = log.WithLogger(ctx, log.G(ctx).WithField("url", us))
u, err := url.Parse(us)
if err != nil {
log.G(ctx).WithError(err).Debug("failed to parse")
continue
}
log.G(ctx).Debug("trying alternative url")
// Try this first, parse it
host := RegistryHost{
Client: http.DefaultClient,
Host: u.Host,
Scheme: u.Scheme,
Path: u.Path,
Capabilities: HostCapabilityPull,
}
req := r.request(host, http.MethodGet)
// Strip namespace from base
req.path = u.Path
if u.RawQuery != "" {
req.path = req.path + "?" + u.RawQuery
}
rc, err := r.open(ctx, req, desc.MediaType, offset)
if err != nil {
if errdefs.IsNotFound(err) {
continue // try one of the other urls.
}
return nil, err
}
return rc, nil
}
// Try manifests endpoints for manifests types
switch desc.MediaType {
case images.MediaTypeDockerSchema2Manifest, images.MediaTypeDockerSchema2ManifestList,
images.MediaTypeDockerSchema1Manifest,
ocispec.MediaTypeImageManifest, ocispec.MediaTypeImageIndex:
for _, host := range r.hosts {
req := r.request(host, http.MethodGet, "manifests", desc.Digest.String())
rc, err := r.open(ctx, req, desc.MediaType, offset)
if err != nil {
if errdefs.IsNotFound(err) {
continue // try another host
}
return nil, err
}
return rc, nil
}
}
// Finally use blobs endpoints
for _, host := range r.hosts {
req := r.request(host, http.MethodGet, "blobs", desc.Digest.String())
rc, err := r.open(ctx, req, desc.MediaType, offset)
if err != nil {
if errdefs.IsNotFound(err) {
continue // try another host
}
return nil, err
}
return rc, nil
}
return nil, errors.Wrapf(errdefs.ErrNotFound,
"could not fetch content descriptor %v (%v) from remote",
desc.Digest, desc.MediaType)
})
}
func (r dockerFetcher) open(ctx context.Context, req *request, mediatype string, offset int64) (io.ReadCloser, error) {
req.header.Set("Accept", strings.Join([]string{mediatype, `*/*`}, ", "))
if offset > 0 {
// Note: "Accept-Ranges: bytes" cannot be trusted as some endpoints
// will return the header without supporting the range. The content
// range must always be checked.
req.header.Set("Range", fmt.Sprintf("bytes=%d-", offset))
}
resp, err := req.doWithRetries(ctx, nil)
if err != nil {
return nil, err
}
if resp.StatusCode > 299 {
// TODO(stevvooe): When doing a offset specific request, we should
// really distinguish between a 206 and a 200. In the case of 200, we
// can discard the bytes, hiding the seek behavior from the
// implementation.
defer resp.Body.Close()
if resp.StatusCode == http.StatusNotFound {
return nil, errors.Wrapf(errdefs.ErrNotFound, "content at %v not found", req.String())
}
var registryErr errcode.Errors
if err := json.NewDecoder(resp.Body).Decode(®istryErr); err != nil || registryErr.Len() < 1 {
return nil, errors.Errorf("unexpected status code %v: %v", req.String(), resp.Status)
}
return nil, errors.Errorf("unexpected status code %v: %s - Server message: %s", req.String(), resp.Status, registryErr.Error())
}
if offset > 0 {
cr := resp.Header.Get("content-range")
if cr != "" {
if !strings.HasPrefix(cr, fmt.Sprintf("bytes %d-", offset)) {
return nil, errors.Errorf("unhandled content range in response: %v", cr)
}
} else {
// TODO: Should any cases where use of content range
// without the proper header be considered?
// 206 responses?
// Discard up to offset
// Could use buffer pool here but this case should be rare
n, err := io.Copy(ioutil.Discard, io.LimitReader(resp.Body, offset))
if err != nil {
return nil, errors.Wrap(err, "failed to discard to offset")
}
if n != offset {
return nil, errors.Errorf("unable to discard to offset")
}
}
}
return resp.Body, nil
}
| {
"content_hash": "d53745c758b5ed165dc1516466ffc835",
"timestamp": "",
"source": "github",
"line_count": 181,
"max_line_length": 129,
"avg_line_length": 27.248618784530386,
"alnum_prop": 0.6632197891321979,
"repo_name": "yongtang/docker",
"id": "ad8482fa392142c0ff32e0ba8c90424fc937e1ab",
"size": "5526",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "vendor/github.com/containerd/containerd/remotes/docker/fetcher.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "81"
},
{
"name": "C",
"bytes": "4815"
},
{
"name": "Dockerfile",
"bytes": "17543"
},
{
"name": "Go",
"bytes": "7450671"
},
{
"name": "Makefile",
"bytes": "10469"
},
{
"name": "PowerShell",
"bytes": "82163"
},
{
"name": "Shell",
"bytes": "136964"
},
{
"name": "Vim script",
"bytes": "1369"
}
],
"symlink_target": ""
} |
import numpy as np, numpy, sys, os, scipy.linalg
from six import print_
#add the parent directory, so we find our iisignature build if it was built --inplace
sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))
import iisignature
#the following 3 functions for interpreting basis strings
#are copied from the tests
#text, index -> (either number or [res, res]), newIndex
def parseBracketedExpression(text,index):
if(text[index]=='['):
left, m = parseBracketedExpression(text,index+1)
right, n = parseBracketedExpression(text,m+1)
return [left,right],n+1
else:
n = 0
while(n<len(text) and text[index+n] in ['1','2','3','4','5','6','7','8','9']): #this should always just happen once if input is a bracketed expression of letters
n = n + 1
return int(text[index:index+n]), index+n
#print (parseBracketedExpression("[23,[2,[[22,1],2]]]",0))
#bracketed expression, dim -> numpy array of its value, depth
def multiplyOut(expn, dim):
if isinstance(expn,list):
left, leftDepth = multiplyOut(expn[0],dim)
right,rightDepth = multiplyOut(expn[1],dim)
a = numpy.outer(left,right).flatten()
b = numpy.outer(right,left).flatten()
return a-b, leftDepth+rightDepth
else:
a = numpy.zeros(dim)
a[expn-1]=1
return a,1
#string of bracketed expression, dim -> numpy array of its value, depth
#for example:
#valueOfBracket("[1,2]",2) is ([0,1,-1,0],2)
def valueOfBracket(text,dim):
return multiplyOut(parseBracketedExpression(text,0)[0],dim)
def getMatrices(s):
info=iisignature.info(s)
m=info["level"]
d=info["dimension"]
values=[[] for i in range(m)]
for exp in iisignature.basis(s):
vec,level = valueOfBracket(exp,d)
values[level-1].append(vec)
out=[]
for v in values:
def f(x,y): return numpy.inner(v[x],v[y])
out.append(numpy.fromfunction(
numpy.vectorize(f),(len(v),len(v)),dtype=int))
# store=[]
# for x1 in v:
# store.append([])
# for x2 in v:
# store[-1].append(numpy.inner(x1,x2))
# out.append(numpy.array(store))
return out
def demo():
#1. generate some dummy data
d=3
m=6
path1=np.random.uniform(size=(20,d))
path2=np.random.uniform(size=(20,d))
paths = (path1,path2)
s=iisignature.prepare(d,m)
#2. print the dot product of the log signatures in tensor space
#(The "x" means that the log signature is returned in tensor space.)
expandedLogSig1,expandedLogSig2=(iisignature.logsig(i,s,"x") for i in paths)
target = np.inner(expandedLogSig1,expandedLogSig2)
print_ ("Target:", float(target))
#3. use getMatrices to act on the log signatures expressed in a basis
# and get the same answer.
matrices=getMatrices(s)
logsig1,logsig2=(iisignature.logsig(i,s) for i in paths)
adjustment=scipy.linalg.block_diag(*matrices)
#print(np.dot(adjustment,logsig2).shape)
print_ ("We get:", float(np.inner(logsig1,np.dot(adjustment,logsig2))))
if __name__=="__main__":
demo()
| {
"content_hash": "5dae1a9034886dcaf2a1f282ef883642",
"timestamp": "",
"source": "github",
"line_count": 89,
"max_line_length": 169,
"avg_line_length": 35.449438202247194,
"alnum_prop": 0.6380348652931854,
"repo_name": "bottler/iisignature",
"id": "418cfe97c10f2108440b5a51245130bfe7bee7bf",
"size": "3618",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "examples/innerProductLogSig.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "250026"
},
{
"name": "Python",
"bytes": "50245"
},
{
"name": "Shell",
"bytes": "1428"
}
],
"symlink_target": ""
} |
package uk.co.thisishillman.ui;
import uk.co.thisishillman.vis.PieChart;
import uk.co.thisishillman.vis.Map;
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.JComboBox;
import javax.swing.text.AttributeSet;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
import org.openstreetmap.gui.jmapviewer.interfaces.TileSource;
import org.openstreetmap.gui.jmapviewer.tilesources.BingAerialTileSource;
import org.openstreetmap.gui.jmapviewer.tilesources.MapQuestOpenAerialTileSource;
import org.openstreetmap.gui.jmapviewer.tilesources.MapQuestOsmTileSource;
import org.openstreetmap.gui.jmapviewer.tilesources.OsmTileSource;
import uk.co.thisishillman.model.OpenSSHProcessor;
/**
*
* @author M Hillman
*/
public class MainPanel extends javax.swing.JPanel {
// SSH log processor
private OpenSSHProcessor processor;
//
private Map mapPanel;
//
private final JComboBox<TileSource> tileBox;
/**
*
*/
public MainPanel() {
initComponents();
tileBox = new JComboBox<>(new TileSource[] {
new OsmTileSource.Mapnik(),
new OsmTileSource.CycleMap(),
new BingAerialTileSource(),
new MapQuestOsmTileSource(),
new MapQuestOpenAerialTileSource()
});
boxContainer.add(tileBox, BorderLayout.CENTER);
}
/**
*
*/
public void stopMonitoring() {
if(processor != null) {
processor.stopRunning();
appendToPane("", Color.GRAY);
appendToPane("SSH log monitoring successfully terminated!", Color.GRAY);
}
}
/**
*
* @param processor
*/
public void startMonitoring(OpenSSHProcessor processor) {
// this.mapPanel = new Map(scaleLabel, tileBox);
//
// this.processor = processor;
// this.processor.setTextDestination(terminal);
// this.processor.addMapPanel(mapPanel);
//
// this.centerPanel.removeAll();
// this.centerPanel.add(mapPanel, BorderLayout.CENTER);
// this.centerPanel.revalidate();
// this.centerPanel.repaint();
//
// this.terminal.setText("");
// appendToPane("Beginning live SSH log monitoring...", Color.BLACK);
//
// this.processor.start();
}
/**
*
* @param showTerminal
* @param showSettings
* @param showMap
* @param showPie
*/
public void updateUI(boolean showTerminal, boolean showSettings, boolean showMap, boolean showPie) {
// removeAll();
//
// if(showPie) {
// add(new PieChart(processor.getAttempts()), BorderLayout.CENTER);
//
// if(showTerminal) add(scrollPane, BorderLayout.SOUTH);
//
// revalidate();
// repaint();
// return;
// }
//
// if(showMap) {
// add(centerPanel, BorderLayout.CENTER);
// if(showTerminal) {
// add(scrollPane, BorderLayout.SOUTH);
// }
//
// } else if(showTerminal && !showMap) {
// add(scrollPane, BorderLayout.CENTER);
//
// } else if(!showTerminal && !showMap) {
// add(noMapLabel, BorderLayout.CENTER);
// }
//
// if(showSettings) {
// add(settingsPanel, BorderLayout.WEST);
// }
//
// if(!showTerminal && ! showSettings && !showMap) {
// add(emptyLabel, BorderLayout.CENTER);
// }
//
// revalidate();
// repaint();
}
/**
*
* @param msg
* @param c
*/
private void appendToPane(String msg, Color c) {
StyleContext sc = StyleContext.getDefaultStyleContext();
AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, c);
aset = sc.addAttribute(aset, StyleConstants.Alignment, StyleConstants.ALIGN_LEFT);
int len = terminal.getDocument().getLength();
terminal.setCaretPosition(len);
terminal.setCharacterAttributes(aset, false);
terminal.replaceSelection(msg + "\n");
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
emptyLabel = new javax.swing.JLabel();
noMapLabel = new javax.swing.JLabel();
centerPanel = new javax.swing.JPanel();
loadingLabel = new javax.swing.JLabel();
settingsPanel = new javax.swing.JPanel();
scaleLabel = new javax.swing.JLabel();
boxContainer = new javax.swing.JPanel();
tileTitle = new javax.swing.JLabel();
descLabel = new javax.swing.JLabel();
approvedCheck = new javax.swing.JCheckBox();
deniedCheck = new javax.swing.JCheckBox();
scaleTitle = new javax.swing.JLabel();
scrollPane = new javax.swing.JScrollPane();
terminal = new javax.swing.JTextPane();
emptyLabel.setBackground(new java.awt.Color(204, 204, 204));
emptyLabel.setFont(LaFHandler.GULIM);
emptyLabel.setForeground(new java.awt.Color(102, 102, 102));
emptyLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
emptyLabel.setText("Use the 'View' menu in the toolbar to see details on SSH tracking.");
emptyLabel.setOpaque(true);
noMapLabel.setBackground(new java.awt.Color(204, 204, 204));
noMapLabel.setFont(LaFHandler.GULIM);
noMapLabel.setForeground(new java.awt.Color(102, 102, 102));
noMapLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
noMapLabel.setText("Use the 'View' menu in the toolbar to see SSH tracking visualisations.");
noMapLabel.setOpaque(true);
setBackground(new java.awt.Color(255, 255, 255));
setLayout(new java.awt.BorderLayout());
centerPanel.setBackground(new java.awt.Color(204, 255, 255));
centerPanel.setMaximumSize(new java.awt.Dimension(999, 999));
centerPanel.setMinimumSize(new java.awt.Dimension(100, 100));
centerPanel.setPreferredSize(new java.awt.Dimension(400, 400));
centerPanel.setLayout(new java.awt.BorderLayout());
loadingLabel.setBackground(new java.awt.Color(204, 204, 204));
loadingLabel.setFont(LaFHandler.GULIM);
loadingLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
loadingLabel.setText("Loading...");
loadingLabel.setOpaque(true);
centerPanel.add(loadingLabel, java.awt.BorderLayout.CENTER);
add(centerPanel, java.awt.BorderLayout.CENTER);
settingsPanel.setBackground(new java.awt.Color(255, 255, 255));
settingsPanel.setBorder(javax.swing.BorderFactory.createMatteBorder(0, 0, 0, 1, new java.awt.Color(153, 153, 153)));
settingsPanel.setMaximumSize(new java.awt.Dimension(150, 999));
settingsPanel.setMinimumSize(new java.awt.Dimension(150, 100));
settingsPanel.setPreferredSize(new java.awt.Dimension(150, 504));
scaleLabel.setFont(LaFHandler.GULIM);
scaleLabel.setForeground(new java.awt.Color(102, 102, 102));
scaleLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
scaleLabel.setText("0.0");
scaleLabel.setToolTipText(null);
scaleLabel.setMaximumSize(new java.awt.Dimension(140, 25));
scaleLabel.setMinimumSize(new java.awt.Dimension(140, 25));
scaleLabel.setPreferredSize(new java.awt.Dimension(140, 25));
boxContainer.setForeground(new java.awt.Color(102, 102, 102));
boxContainer.setToolTipText(null);
boxContainer.setMaximumSize(new java.awt.Dimension(140, 25));
boxContainer.setMinimumSize(new java.awt.Dimension(140, 25));
boxContainer.setOpaque(false);
boxContainer.setPreferredSize(new java.awt.Dimension(140, 25));
boxContainer.setLayout(new java.awt.BorderLayout());
tileTitle.setFont(LaFHandler.GULIM);
tileTitle.setForeground(new java.awt.Color(102, 102, 102));
tileTitle.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
tileTitle.setText("Map Source");
tileTitle.setToolTipText(null);
tileTitle.setBorder(javax.swing.BorderFactory.createMatteBorder(0, 0, 1, 0, new java.awt.Color(153, 153, 153)));
tileTitle.setMaximumSize(new java.awt.Dimension(140, 25));
tileTitle.setMinimumSize(new java.awt.Dimension(140, 25));
tileTitle.setPreferredSize(new java.awt.Dimension(140, 25));
descLabel.setFont(LaFHandler.GULIM);
descLabel.setForeground(new java.awt.Color(102, 102, 102));
descLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
descLabel.setText("<html><p align=\"center\">Use the right mouse button to move, left double click or mouse wheel to zoom.</p></html>");
descLabel.setToolTipText(null);
descLabel.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 5, 0, 5));
descLabel.setMaximumSize(new java.awt.Dimension(140, 150));
descLabel.setMinimumSize(new java.awt.Dimension(140, 150));
descLabel.setPreferredSize(new java.awt.Dimension(140, 150));
approvedCheck.setFont(LaFHandler.GULIM);
approvedCheck.setForeground(new java.awt.Color(102, 102, 102));
approvedCheck.setSelected(true);
approvedCheck.setText("Approved Attempts");
approvedCheck.setToolTipText(null);
approvedCheck.setMaximumSize(new java.awt.Dimension(140, 25));
approvedCheck.setMinimumSize(new java.awt.Dimension(140, 25));
approvedCheck.setOpaque(false);
approvedCheck.setPreferredSize(new java.awt.Dimension(140, 25));
approvedCheck.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
approvedCheckActionPerformed(evt);
}
});
deniedCheck.setFont(LaFHandler.GULIM);
deniedCheck.setForeground(new java.awt.Color(102, 102, 102));
deniedCheck.setSelected(true);
deniedCheck.setText("Denied Attempts");
deniedCheck.setToolTipText(null);
deniedCheck.setMaximumSize(new java.awt.Dimension(140, 25));
deniedCheck.setMinimumSize(new java.awt.Dimension(140, 25));
deniedCheck.setOpaque(false);
deniedCheck.setPreferredSize(new java.awt.Dimension(140, 25));
scaleTitle.setFont(LaFHandler.GULIM);
scaleTitle.setForeground(new java.awt.Color(102, 102, 102));
scaleTitle.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
scaleTitle.setText("Metres per Pixel");
scaleTitle.setToolTipText(null);
scaleTitle.setBorder(javax.swing.BorderFactory.createMatteBorder(0, 0, 1, 0, new java.awt.Color(153, 153, 153)));
scaleTitle.setMaximumSize(new java.awt.Dimension(140, 25));
scaleTitle.setMinimumSize(new java.awt.Dimension(140, 25));
scaleTitle.setPreferredSize(new java.awt.Dimension(140, 25));
javax.swing.GroupLayout settingsPanelLayout = new javax.swing.GroupLayout(settingsPanel);
settingsPanel.setLayout(settingsPanelLayout);
settingsPanelLayout.setHorizontalGroup(
settingsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(settingsPanelLayout.createSequentialGroup()
.addGroup(settingsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(settingsPanelLayout.createSequentialGroup()
.addGap(5, 5, 5)
.addGroup(settingsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(settingsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(boxContainer, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(tileTitle, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(scaleTitle, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(scaleLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(descLabel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(settingsPanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(approvedCheck, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(settingsPanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(deniedCheck, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
settingsPanelLayout.setVerticalGroup(
settingsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, settingsPanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(descLabel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15)
.addComponent(tileTitle, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(boxContainer, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(scaleTitle, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(scaleLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(approvedCheck, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(10, 10, 10)
.addComponent(deniedCheck, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(120, 120, 120))
);
add(settingsPanel, java.awt.BorderLayout.WEST);
scrollPane.setMaximumSize(new java.awt.Dimension(32767, 100));
scrollPane.setMinimumSize(new java.awt.Dimension(23, 100));
scrollPane.setPreferredSize(new java.awt.Dimension(8, 100));
terminal.setFont(LaFHandler.GULIM);
scrollPane.setViewportView(terminal);
add(scrollPane, java.awt.BorderLayout.SOUTH);
}// </editor-fold>//GEN-END:initComponents
private void approvedCheckActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_approvedCheckActionPerformed
if(mapPanel != null) mapPanel.showLayers(approvedCheck.isSelected(), deniedCheck.isSelected());
}//GEN-LAST:event_approvedCheckActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JCheckBox approvedCheck;
private javax.swing.JPanel boxContainer;
private javax.swing.JPanel centerPanel;
private javax.swing.JCheckBox deniedCheck;
private javax.swing.JLabel descLabel;
private javax.swing.JLabel emptyLabel;
private javax.swing.JLabel loadingLabel;
private javax.swing.JLabel noMapLabel;
private javax.swing.JLabel scaleLabel;
private javax.swing.JLabel scaleTitle;
private javax.swing.JScrollPane scrollPane;
private javax.swing.JPanel settingsPanel;
private javax.swing.JTextPane terminal;
private javax.swing.JLabel tileTitle;
// End of variables declaration//GEN-END:variables
}
// End of class. | {
"content_hash": "02d8904638aa46716ace514930b71f03",
"timestamp": "",
"source": "github",
"line_count": 352,
"max_line_length": 218,
"avg_line_length": 48.12784090909091,
"alnum_prop": 0.6729236762882946,
"repo_name": "CaptainHillman/sabertooth",
"id": "fe6e05232db9a3267ee8abb707604160635d379f",
"size": "18094",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "src/main/java/uk/co/thisishillman/ui/MainPanel.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "115302"
}
],
"symlink_target": ""
} |
<?php
declare(strict_types=1);
namespace Yansongda\Pay\Plugin\Wechat\Marketing\Coupon;
use Yansongda\Pay\Exception\Exception;
use Yansongda\Pay\Exception\InvalidParamsException;
use Yansongda\Pay\Plugin\Wechat\GeneralPlugin;
use Yansongda\Pay\Rocket;
/**
* @see https://pay.weixin.qq.com/wiki/doc/apiv3/apis/chapter9_1_10.shtml
*/
class QueryStockUseFlowPlugin extends GeneralPlugin
{
protected function getMethod(): string
{
return 'GET';
}
protected function doSomething(Rocket $rocket): void
{
$rocket->setPayload(null);
}
/**
* @throws \Yansongda\Pay\Exception\InvalidParamsException
*/
protected function getUri(Rocket $rocket): string
{
$payload = $rocket->getPayload();
if (is_null($payload->get('stock_id'))) {
throw new InvalidParamsException(Exception::MISSING_NECESSARY_PARAMS);
}
return 'vv3/marketing/favor/stocks/'.
$payload->get('stock_id').
'/use-flow';
}
}
| {
"content_hash": "fd583063060273765e5792b15e3efbe6",
"timestamp": "",
"source": "github",
"line_count": 42,
"max_line_length": 82,
"avg_line_length": 24.238095238095237,
"alnum_prop": 0.6571709233791748,
"repo_name": "yansongda/pay",
"id": "5afc44805acf27d96ad286a446deade7a131bbc6",
"size": "1018",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Plugin/Wechat/Marketing/Coupon/QueryStockUseFlowPlugin.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "5916"
},
{
"name": "PHP",
"bytes": "608087"
},
{
"name": "SCSS",
"bytes": "253"
},
{
"name": "TypeScript",
"bytes": "2542"
},
{
"name": "Vue",
"bytes": "2297"
}
],
"symlink_target": ""
} |
shared_examples_for "ActiveModel" do
include ActiveModel::Lint::Tests
# to_s is to support ruby-1.9
ActiveModel::Lint::Tests.public_instance_methods.map{|m| m.to_s}.grep(/^test/).each do |m|
example m.sub('_',' ') do
send m
end
end
def model
subject
end
end
| {
"content_hash": "3a8df8c3d25727777ecbecbea440af42",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 92,
"avg_line_length": 20.714285714285715,
"alnum_prop": 0.6413793103448275,
"repo_name": "apigee/usergrid_ironhorse",
"id": "491e030f6dd136258215a20644bdf27f537ebb5d",
"size": "445",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "spec/support/active_model_lint.rb",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/types.h>
#include <linux/sched.h>
#include <linux/pci.h>
#include <linux/spinlock.h>
#include <linux/slab.h>
#include <linux/completion.h>
#include <linux/blkdev.h>
#include <linux/delay.h>
#include <linux/kthread.h>
#include <linux/interrupt.h>
#include <linux/semaphore.h>
#include <scsi/scsi.h>
#include <scsi/scsi_host.h>
#include <scsi/scsi_device.h>
#include <scsi/scsi_cmnd.h>
#include "aacraid.h"
/**
* fib_map_alloc - allocate the fib objects
* @dev: Adapter to allocate for
*
* Allocate and map the shared PCI space for the FIB blocks used to
* talk to the Adaptec firmware.
*/
static int fib_map_alloc(struct aac_dev *dev)
{
dprintk((KERN_INFO
"allocate hardware fibs pci_alloc_consistent(%p, %d * (%d + %d), %p)\n",
dev->pdev, dev->max_fib_size, dev->scsi_host_ptr->can_queue,
AAC_NUM_MGT_FIB, &dev->hw_fib_pa));
dev->hw_fib_va = pci_alloc_consistent(dev->pdev,
(dev->max_fib_size + sizeof(struct aac_fib_xporthdr))
* (dev->scsi_host_ptr->can_queue + AAC_NUM_MGT_FIB) + (ALIGN32 - 1),
&dev->hw_fib_pa);
if (dev->hw_fib_va == NULL)
return -ENOMEM;
return 0;
}
/**
* aac_fib_map_free - free the fib objects
* @dev: Adapter to free
*
* Free the PCI mappings and the memory allocated for FIB blocks
* on this adapter.
*/
void aac_fib_map_free(struct aac_dev *dev)
{
pci_free_consistent(dev->pdev,
dev->max_fib_size * (dev->scsi_host_ptr->can_queue + AAC_NUM_MGT_FIB),
dev->hw_fib_va, dev->hw_fib_pa);
dev->hw_fib_va = NULL;
dev->hw_fib_pa = 0;
}
/**
* aac_fib_setup - setup the fibs
* @dev: Adapter to set up
*
* Allocate the PCI space for the fibs, map it and then initialise the
* fib area, the unmapped fib data and also the free list
*/
int aac_fib_setup(struct aac_dev * dev)
{
struct fib *fibptr;
struct hw_fib *hw_fib;
dma_addr_t hw_fib_pa;
int i;
while (((i = fib_map_alloc(dev)) == -ENOMEM)
&& (dev->scsi_host_ptr->can_queue > (64 - AAC_NUM_MGT_FIB))) {
dev->init->MaxIoCommands = cpu_to_le32((dev->scsi_host_ptr->can_queue + AAC_NUM_MGT_FIB) >> 1);
dev->scsi_host_ptr->can_queue = le32_to_cpu(dev->init->MaxIoCommands) - AAC_NUM_MGT_FIB;
}
if (i<0)
return -ENOMEM;
/* 32 byte alignment for PMC */
hw_fib_pa = (dev->hw_fib_pa + (ALIGN32 - 1)) & ~(ALIGN32 - 1);
dev->hw_fib_va = (struct hw_fib *)((unsigned char *)dev->hw_fib_va +
(hw_fib_pa - dev->hw_fib_pa));
dev->hw_fib_pa = hw_fib_pa;
memset(dev->hw_fib_va, 0,
(dev->max_fib_size + sizeof(struct aac_fib_xporthdr)) *
(dev->scsi_host_ptr->can_queue + AAC_NUM_MGT_FIB));
/* add Xport header */
dev->hw_fib_va = (struct hw_fib *)((unsigned char *)dev->hw_fib_va +
sizeof(struct aac_fib_xporthdr));
dev->hw_fib_pa += sizeof(struct aac_fib_xporthdr);
hw_fib = dev->hw_fib_va;
hw_fib_pa = dev->hw_fib_pa;
/*
* Initialise the fibs
*/
for (i = 0, fibptr = &dev->fibs[i];
i < (dev->scsi_host_ptr->can_queue + AAC_NUM_MGT_FIB);
i++, fibptr++)
{
fibptr->dev = dev;
fibptr->hw_fib_va = hw_fib;
fibptr->data = (void *) fibptr->hw_fib_va->data;
fibptr->next = fibptr+1; /* Forward chain the fibs */
sema_init(&fibptr->event_wait, 0);
spin_lock_init(&fibptr->event_lock);
hw_fib->header.XferState = cpu_to_le32(0xffffffff);
hw_fib->header.SenderSize = cpu_to_le16(dev->max_fib_size);
fibptr->hw_fib_pa = hw_fib_pa;
hw_fib = (struct hw_fib *)((unsigned char *)hw_fib +
dev->max_fib_size + sizeof(struct aac_fib_xporthdr));
hw_fib_pa = hw_fib_pa +
dev->max_fib_size + sizeof(struct aac_fib_xporthdr);
}
/*
* Add the fib chain to the free list
*/
dev->fibs[dev->scsi_host_ptr->can_queue + AAC_NUM_MGT_FIB - 1].next = NULL;
/*
* Enable this to debug out of queue space
*/
dev->free_fib = &dev->fibs[0];
return 0;
}
/**
* aac_fib_alloc - allocate a fib
* @dev: Adapter to allocate the fib for
*
* Allocate a fib from the adapter fib pool. If the pool is empty we
* return NULL.
*/
struct fib *aac_fib_alloc(struct aac_dev *dev)
{
struct fib * fibptr;
unsigned long flags;
spin_lock_irqsave(&dev->fib_lock, flags);
fibptr = dev->free_fib;
if(!fibptr){
spin_unlock_irqrestore(&dev->fib_lock, flags);
return fibptr;
}
dev->free_fib = fibptr->next;
spin_unlock_irqrestore(&dev->fib_lock, flags);
/*
* Set the proper node type code and node byte size
*/
fibptr->type = FSAFS_NTC_FIB_CONTEXT;
fibptr->size = sizeof(struct fib);
/*
* Null out fields that depend on being zero at the start of
* each I/O
*/
fibptr->hw_fib_va->header.XferState = 0;
fibptr->flags = 0;
fibptr->callback = NULL;
fibptr->callback_data = NULL;
return fibptr;
}
/**
* aac_fib_free - free a fib
* @fibptr: fib to free up
*
* Frees up a fib and places it on the appropriate queue
*/
void aac_fib_free(struct fib *fibptr)
{
unsigned long flags, flagsv;
spin_lock_irqsave(&fibptr->event_lock, flagsv);
if (fibptr->done == 2) {
spin_unlock_irqrestore(&fibptr->event_lock, flagsv);
return;
}
spin_unlock_irqrestore(&fibptr->event_lock, flagsv);
spin_lock_irqsave(&fibptr->dev->fib_lock, flags);
if (unlikely(fibptr->flags & FIB_CONTEXT_FLAG_TIMED_OUT))
aac_config.fib_timeouts++;
if (fibptr->hw_fib_va->header.XferState != 0) {
printk(KERN_WARNING "aac_fib_free, XferState != 0, fibptr = 0x%p, XferState = 0x%x\n",
(void*)fibptr,
le32_to_cpu(fibptr->hw_fib_va->header.XferState));
}
fibptr->next = fibptr->dev->free_fib;
fibptr->dev->free_fib = fibptr;
spin_unlock_irqrestore(&fibptr->dev->fib_lock, flags);
}
/**
* aac_fib_init - initialise a fib
* @fibptr: The fib to initialize
*
* Set up the generic fib fields ready for use
*/
void aac_fib_init(struct fib *fibptr)
{
struct hw_fib *hw_fib = fibptr->hw_fib_va;
hw_fib->header.StructType = FIB_MAGIC;
hw_fib->header.Size = cpu_to_le16(fibptr->dev->max_fib_size);
hw_fib->header.XferState = cpu_to_le32(HostOwned | FibInitialized | FibEmpty | FastResponseCapable);
hw_fib->header.SenderFibAddress = 0; /* Filled in later if needed */
hw_fib->header.ReceiverFibAddress = cpu_to_le32(fibptr->hw_fib_pa);
hw_fib->header.SenderSize = cpu_to_le16(fibptr->dev->max_fib_size);
}
/**
* fib_deallocate - deallocate a fib
* @fibptr: fib to deallocate
*
* Will deallocate and return to the free pool the FIB pointed to by the
* caller.
*/
static void fib_dealloc(struct fib * fibptr)
{
struct hw_fib *hw_fib = fibptr->hw_fib_va;
BUG_ON(hw_fib->header.StructType != FIB_MAGIC);
hw_fib->header.XferState = 0;
}
/*
* Commuication primitives define and support the queuing method we use to
* support host to adapter commuication. All queue accesses happen through
* these routines and are the only routines which have a knowledge of the
* how these queues are implemented.
*/
/**
* aac_get_entry - get a queue entry
* @dev: Adapter
* @qid: Queue Number
* @entry: Entry return
* @index: Index return
* @nonotify: notification control
*
* With a priority the routine returns a queue entry if the queue has free entries. If the queue
* is full(no free entries) than no entry is returned and the function returns 0 otherwise 1 is
* returned.
*/
static int aac_get_entry (struct aac_dev * dev, u32 qid, struct aac_entry **entry, u32 * index, unsigned long *nonotify)
{
struct aac_queue * q;
unsigned long idx;
/*
* All of the queues wrap when they reach the end, so we check
* to see if they have reached the end and if they have we just
* set the index back to zero. This is a wrap. You could or off
* the high bits in all updates but this is a bit faster I think.
*/
q = &dev->queues->queue[qid];
idx = *index = le32_to_cpu(*(q->headers.producer));
/* Interrupt Moderation, only interrupt for first two entries */
if (idx != le32_to_cpu(*(q->headers.consumer))) {
if (--idx == 0) {
if (qid == AdapNormCmdQueue)
idx = ADAP_NORM_CMD_ENTRIES;
else
idx = ADAP_NORM_RESP_ENTRIES;
}
if (idx != le32_to_cpu(*(q->headers.consumer)))
*nonotify = 1;
}
if (qid == AdapNormCmdQueue) {
if (*index >= ADAP_NORM_CMD_ENTRIES)
*index = 0; /* Wrap to front of the Producer Queue. */
} else {
if (*index >= ADAP_NORM_RESP_ENTRIES)
*index = 0; /* Wrap to front of the Producer Queue. */
}
/* Queue is full */
if ((*index + 1) == le32_to_cpu(*(q->headers.consumer))) {
printk(KERN_WARNING "Queue %d full, %u outstanding.\n",
qid, q->numpending);
return 0;
} else {
*entry = q->base + *index;
return 1;
}
}
/**
* aac_queue_get - get the next free QE
* @dev: Adapter
* @index: Returned index
* @priority: Priority of fib
* @fib: Fib to associate with the queue entry
* @wait: Wait if queue full
* @fibptr: Driver fib object to go with fib
* @nonotify: Don't notify the adapter
*
* Gets the next free QE off the requested priorty adapter command
* queue and associates the Fib with the QE. The QE represented by
* index is ready to insert on the queue when this routine returns
* success.
*/
int aac_queue_get(struct aac_dev * dev, u32 * index, u32 qid, struct hw_fib * hw_fib, int wait, struct fib * fibptr, unsigned long *nonotify)
{
struct aac_entry * entry = NULL;
int map = 0;
if (qid == AdapNormCmdQueue) {
/* if no entries wait for some if caller wants to */
while (!aac_get_entry(dev, qid, &entry, index, nonotify)) {
printk(KERN_ERR "GetEntries failed\n");
}
/*
* Setup queue entry with a command, status and fib mapped
*/
entry->size = cpu_to_le32(le16_to_cpu(hw_fib->header.Size));
map = 1;
} else {
while (!aac_get_entry(dev, qid, &entry, index, nonotify)) {
/* if no entries wait for some if caller wants to */
}
/*
* Setup queue entry with command, status and fib mapped
*/
entry->size = cpu_to_le32(le16_to_cpu(hw_fib->header.Size));
entry->addr = hw_fib->header.SenderFibAddress;
/* Restore adapters pointer to the FIB */
hw_fib->header.ReceiverFibAddress = hw_fib->header.SenderFibAddress; /* Let the adapter now where to find its data */
map = 0;
}
/*
* If MapFib is true than we need to map the Fib and put pointers
* in the queue entry.
*/
if (map)
entry->addr = cpu_to_le32(fibptr->hw_fib_pa);
return 0;
}
/*
* Define the highest level of host to adapter communication routines.
* These routines will support host to adapter FS commuication. These
* routines have no knowledge of the commuication method used. This level
* sends and receives FIBs. This level has no knowledge of how these FIBs
* get passed back and forth.
*/
/**
* aac_fib_send - send a fib to the adapter
* @command: Command to send
* @fibptr: The fib
* @size: Size of fib data area
* @priority: Priority of Fib
* @wait: Async/sync select
* @reply: True if a reply is wanted
* @callback: Called with reply
* @callback_data: Passed to callback
*
* Sends the requested FIB to the adapter and optionally will wait for a
* response FIB. If the caller does not wish to wait for a response than
* an event to wait on must be supplied. This event will be set when a
* response FIB is received from the adapter.
*/
int aac_fib_send(u16 command, struct fib *fibptr, unsigned long size,
int priority, int wait, int reply, fib_callback callback,
void *callback_data)
{
struct aac_dev * dev = fibptr->dev;
struct hw_fib * hw_fib = fibptr->hw_fib_va;
unsigned long flags = 0;
unsigned long qflags;
unsigned long mflags = 0;
if (!(hw_fib->header.XferState & cpu_to_le32(HostOwned)))
return -EBUSY;
/*
* There are 5 cases with the wait and response requested flags.
* The only invalid cases are if the caller requests to wait and
* does not request a response and if the caller does not want a
* response and the Fib is not allocated from pool. If a response
* is not requesed the Fib will just be deallocaed by the DPC
* routine when the response comes back from the adapter. No
* further processing will be done besides deleting the Fib. We
* will have a debug mode where the adapter can notify the host
* it had a problem and the host can log that fact.
*/
fibptr->flags = 0;
if (wait && !reply) {
return -EINVAL;
} else if (!wait && reply) {
hw_fib->header.XferState |= cpu_to_le32(Async | ResponseExpected);
FIB_COUNTER_INCREMENT(aac_config.AsyncSent);
} else if (!wait && !reply) {
hw_fib->header.XferState |= cpu_to_le32(NoResponseExpected);
FIB_COUNTER_INCREMENT(aac_config.NoResponseSent);
} else if (wait && reply) {
hw_fib->header.XferState |= cpu_to_le32(ResponseExpected);
FIB_COUNTER_INCREMENT(aac_config.NormalSent);
}
/*
* Map the fib into 32bits by using the fib number
*/
hw_fib->header.SenderFibAddress = cpu_to_le32(((u32)(fibptr - dev->fibs)) << 2);
hw_fib->header.SenderData = (u32)(fibptr - dev->fibs);
/*
* Set FIB state to indicate where it came from and if we want a
* response from the adapter. Also load the command from the
* caller.
*
* Map the hw fib pointer as a 32bit value
*/
hw_fib->header.Command = cpu_to_le16(command);
hw_fib->header.XferState |= cpu_to_le32(SentFromHost);
fibptr->hw_fib_va->header.Flags = 0; /* 0 the flags field - internal only*/
/*
* Set the size of the Fib we want to send to the adapter
*/
hw_fib->header.Size = cpu_to_le16(sizeof(struct aac_fibhdr) + size);
if (le16_to_cpu(hw_fib->header.Size) > le16_to_cpu(hw_fib->header.SenderSize)) {
return -EMSGSIZE;
}
/*
* Get a queue entry connect the FIB to it and send an notify
* the adapter a command is ready.
*/
hw_fib->header.XferState |= cpu_to_le32(NormalPriority);
/*
* Fill in the Callback and CallbackContext if we are not
* going to wait.
*/
if (!wait) {
fibptr->callback = callback;
fibptr->callback_data = callback_data;
fibptr->flags = FIB_CONTEXT_FLAG;
}
fibptr->done = 0;
FIB_COUNTER_INCREMENT(aac_config.FibsSent);
dprintk((KERN_DEBUG "Fib contents:.\n"));
dprintk((KERN_DEBUG " Command = %d.\n", le32_to_cpu(hw_fib->header.Command)));
dprintk((KERN_DEBUG " SubCommand = %d.\n", le32_to_cpu(((struct aac_query_mount *)fib_data(fibptr))->command)));
dprintk((KERN_DEBUG " XferState = %x.\n", le32_to_cpu(hw_fib->header.XferState)));
dprintk((KERN_DEBUG " hw_fib va being sent=%p\n",fibptr->hw_fib_va));
dprintk((KERN_DEBUG " hw_fib pa being sent=%lx\n",(ulong)fibptr->hw_fib_pa));
dprintk((KERN_DEBUG " fib being sent=%p\n",fibptr));
if (!dev->queues)
return -EBUSY;
if (wait) {
spin_lock_irqsave(&dev->manage_lock, mflags);
if (dev->management_fib_count >= AAC_NUM_MGT_FIB) {
printk(KERN_INFO "No management Fibs Available:%d\n",
dev->management_fib_count);
spin_unlock_irqrestore(&dev->manage_lock, mflags);
return -EBUSY;
}
dev->management_fib_count++;
spin_unlock_irqrestore(&dev->manage_lock, mflags);
spin_lock_irqsave(&fibptr->event_lock, flags);
}
if (aac_adapter_deliver(fibptr) != 0) {
printk(KERN_ERR "aac_fib_send: returned -EBUSY\n");
if (wait) {
spin_unlock_irqrestore(&fibptr->event_lock, flags);
spin_lock_irqsave(&dev->manage_lock, mflags);
dev->management_fib_count--;
spin_unlock_irqrestore(&dev->manage_lock, mflags);
}
return -EBUSY;
}
/*
* If the caller wanted us to wait for response wait now.
*/
if (wait) {
spin_unlock_irqrestore(&fibptr->event_lock, flags);
/* Only set for first known interruptable command */
if (wait < 0) {
/*
* *VERY* Dangerous to time out a command, the
* assumption is made that we have no hope of
* functioning because an interrupt routing or other
* hardware failure has occurred.
*/
unsigned long count = 36000000L; /* 3 minutes */
while (down_trylock(&fibptr->event_wait)) {
int blink;
if (--count == 0) {
struct aac_queue * q = &dev->queues->queue[AdapNormCmdQueue];
spin_lock_irqsave(q->lock, qflags);
q->numpending--;
spin_unlock_irqrestore(q->lock, qflags);
if (wait == -1) {
printk(KERN_ERR "aacraid: aac_fib_send: first asynchronous command timed out.\n"
"Usually a result of a PCI interrupt routing problem;\n"
"update mother board BIOS or consider utilizing one of\n"
"the SAFE mode kernel options (acpi, apic etc)\n");
}
return -ETIMEDOUT;
}
if ((blink = aac_adapter_check_health(dev)) > 0) {
if (wait == -1) {
printk(KERN_ERR "aacraid: aac_fib_send: adapter blinkLED 0x%x.\n"
"Usually a result of a serious unrecoverable hardware problem\n",
blink);
}
return -EFAULT;
}
udelay(5);
}
} else if (down_interruptible(&fibptr->event_wait)) {
/* Do nothing ... satisfy
* down_interruptible must_check */
}
spin_lock_irqsave(&fibptr->event_lock, flags);
if (fibptr->done == 0) {
fibptr->done = 2; /* Tell interrupt we aborted */
spin_unlock_irqrestore(&fibptr->event_lock, flags);
return -ERESTARTSYS;
}
spin_unlock_irqrestore(&fibptr->event_lock, flags);
BUG_ON(fibptr->done == 0);
if(unlikely(fibptr->flags & FIB_CONTEXT_FLAG_TIMED_OUT))
return -ETIMEDOUT;
return 0;
}
/*
* If the user does not want a response than return success otherwise
* return pending
*/
if (reply)
return -EINPROGRESS;
else
return 0;
}
/**
* aac_consumer_get - get the top of the queue
* @dev: Adapter
* @q: Queue
* @entry: Return entry
*
* Will return a pointer to the entry on the top of the queue requested that
* we are a consumer of, and return the address of the queue entry. It does
* not change the state of the queue.
*/
int aac_consumer_get(struct aac_dev * dev, struct aac_queue * q, struct aac_entry **entry)
{
u32 index;
int status;
if (le32_to_cpu(*q->headers.producer) == le32_to_cpu(*q->headers.consumer)) {
status = 0;
} else {
/*
* The consumer index must be wrapped if we have reached
* the end of the queue, else we just use the entry
* pointed to by the header index
*/
if (le32_to_cpu(*q->headers.consumer) >= q->entries)
index = 0;
else
index = le32_to_cpu(*q->headers.consumer);
*entry = q->base + index;
status = 1;
}
return(status);
}
/**
* aac_consumer_free - free consumer entry
* @dev: Adapter
* @q: Queue
* @qid: Queue ident
*
* Frees up the current top of the queue we are a consumer of. If the
* queue was full notify the producer that the queue is no longer full.
*/
void aac_consumer_free(struct aac_dev * dev, struct aac_queue *q, u32 qid)
{
int wasfull = 0;
u32 notify;
if ((le32_to_cpu(*q->headers.producer)+1) == le32_to_cpu(*q->headers.consumer))
wasfull = 1;
if (le32_to_cpu(*q->headers.consumer) >= q->entries)
*q->headers.consumer = cpu_to_le32(1);
else
le32_add_cpu(q->headers.consumer, 1);
if (wasfull) {
switch (qid) {
case HostNormCmdQueue:
notify = HostNormCmdNotFull;
break;
case HostNormRespQueue:
notify = HostNormRespNotFull;
break;
default:
BUG();
return;
}
aac_adapter_notify(dev, notify);
}
}
/**
* aac_fib_adapter_complete - complete adapter issued fib
* @fibptr: fib to complete
* @size: size of fib
*
* Will do all necessary work to complete a FIB that was sent from
* the adapter.
*/
int aac_fib_adapter_complete(struct fib *fibptr, unsigned short size)
{
struct hw_fib * hw_fib = fibptr->hw_fib_va;
struct aac_dev * dev = fibptr->dev;
struct aac_queue * q;
unsigned long nointr = 0;
unsigned long qflags;
if (dev->comm_interface == AAC_COMM_MESSAGE_TYPE1) {
kfree(hw_fib);
return 0;
}
if (hw_fib->header.XferState == 0) {
if (dev->comm_interface == AAC_COMM_MESSAGE)
kfree(hw_fib);
return 0;
}
/*
* If we plan to do anything check the structure type first.
*/
if (hw_fib->header.StructType != FIB_MAGIC) {
if (dev->comm_interface == AAC_COMM_MESSAGE)
kfree(hw_fib);
return -EINVAL;
}
/*
* This block handles the case where the adapter had sent us a
* command and we have finished processing the command. We
* call completeFib when we are done processing the command
* and want to send a response back to the adapter. This will
* send the completed cdb to the adapter.
*/
if (hw_fib->header.XferState & cpu_to_le32(SentFromAdapter)) {
if (dev->comm_interface == AAC_COMM_MESSAGE) {
kfree (hw_fib);
} else {
u32 index;
hw_fib->header.XferState |= cpu_to_le32(HostProcessed);
if (size) {
size += sizeof(struct aac_fibhdr);
if (size > le16_to_cpu(hw_fib->header.SenderSize))
return -EMSGSIZE;
hw_fib->header.Size = cpu_to_le16(size);
}
q = &dev->queues->queue[AdapNormRespQueue];
spin_lock_irqsave(q->lock, qflags);
aac_queue_get(dev, &index, AdapNormRespQueue, hw_fib, 1, NULL, &nointr);
*(q->headers.producer) = cpu_to_le32(index + 1);
spin_unlock_irqrestore(q->lock, qflags);
if (!(nointr & (int)aac_config.irq_mod))
aac_adapter_notify(dev, AdapNormRespQueue);
}
} else {
printk(KERN_WARNING "aac_fib_adapter_complete: "
"Unknown xferstate detected.\n");
BUG();
}
return 0;
}
/**
* aac_fib_complete - fib completion handler
* @fib: FIB to complete
*
* Will do all necessary work to complete a FIB.
*/
int aac_fib_complete(struct fib *fibptr)
{
unsigned long flags;
struct hw_fib * hw_fib = fibptr->hw_fib_va;
/*
* Check for a fib which has already been completed
*/
if (hw_fib->header.XferState == 0)
return 0;
/*
* If we plan to do anything check the structure type first.
*/
if (hw_fib->header.StructType != FIB_MAGIC)
return -EINVAL;
/*
* This block completes a cdb which orginated on the host and we
* just need to deallocate the cdb or reinit it. At this point the
* command is complete that we had sent to the adapter and this
* cdb could be reused.
*/
spin_lock_irqsave(&fibptr->event_lock, flags);
if (fibptr->done == 2) {
spin_unlock_irqrestore(&fibptr->event_lock, flags);
return 0;
}
spin_unlock_irqrestore(&fibptr->event_lock, flags);
if((hw_fib->header.XferState & cpu_to_le32(SentFromHost)) &&
(hw_fib->header.XferState & cpu_to_le32(AdapterProcessed)))
{
fib_dealloc(fibptr);
}
else if(hw_fib->header.XferState & cpu_to_le32(SentFromHost))
{
/*
* This handles the case when the host has aborted the I/O
* to the adapter because the adapter is not responding
*/
fib_dealloc(fibptr);
} else if(hw_fib->header.XferState & cpu_to_le32(HostOwned)) {
fib_dealloc(fibptr);
} else {
BUG();
}
return 0;
}
/**
* aac_printf - handle printf from firmware
* @dev: Adapter
* @val: Message info
*
* Print a message passed to us by the controller firmware on the
* Adaptec board
*/
void aac_printf(struct aac_dev *dev, u32 val)
{
char *cp = dev->printfbuf;
if (dev->printf_enabled)
{
int length = val & 0xffff;
int level = (val >> 16) & 0xffff;
/*
* The size of the printfbuf is set in port.c
* There is no variable or define for it
*/
if (length > 255)
length = 255;
if (cp[length] != 0)
cp[length] = 0;
if (level == LOG_AAC_HIGH_ERROR)
printk(KERN_WARNING "%s:%s", dev->name, cp);
else
printk(KERN_INFO "%s:%s", dev->name, cp);
}
memset(cp, 0, 256);
}
/**
* aac_handle_aif - Handle a message from the firmware
* @dev: Which adapter this fib is from
* @fibptr: Pointer to fibptr from adapter
*
* This routine handles a driver notify fib from the adapter and
* dispatches it to the appropriate routine for handling.
*/
#define AIF_SNIFF_TIMEOUT (30*HZ)
static void aac_handle_aif(struct aac_dev * dev, struct fib * fibptr)
{
struct hw_fib * hw_fib = fibptr->hw_fib_va;
struct aac_aifcmd * aifcmd = (struct aac_aifcmd *)hw_fib->data;
u32 channel, id, lun, container;
struct scsi_device *device;
enum {
NOTHING,
DELETE,
ADD,
CHANGE
} device_config_needed = NOTHING;
/* Sniff for container changes */
if (!dev || !dev->fsa_dev)
return;
container = channel = id = lun = (u32)-1;
/*
* We have set this up to try and minimize the number of
* re-configures that take place. As a result of this when
* certain AIF's come in we will set a flag waiting for another
* type of AIF before setting the re-config flag.
*/
switch (le32_to_cpu(aifcmd->command)) {
case AifCmdDriverNotify:
switch (le32_to_cpu(((__le32 *)aifcmd->data)[0])) {
/*
* Morph or Expand complete
*/
case AifDenMorphComplete:
case AifDenVolumeExtendComplete:
container = le32_to_cpu(((__le32 *)aifcmd->data)[1]);
if (container >= dev->maximum_num_containers)
break;
/*
* Find the scsi_device associated with the SCSI
* address. Make sure we have the right array, and if
* so set the flag to initiate a new re-config once we
* see an AifEnConfigChange AIF come through.
*/
if ((dev != NULL) && (dev->scsi_host_ptr != NULL)) {
device = scsi_device_lookup(dev->scsi_host_ptr,
CONTAINER_TO_CHANNEL(container),
CONTAINER_TO_ID(container),
CONTAINER_TO_LUN(container));
if (device) {
dev->fsa_dev[container].config_needed = CHANGE;
dev->fsa_dev[container].config_waiting_on = AifEnConfigChange;
dev->fsa_dev[container].config_waiting_stamp = jiffies;
scsi_device_put(device);
}
}
}
/*
* If we are waiting on something and this happens to be
* that thing then set the re-configure flag.
*/
if (container != (u32)-1) {
if (container >= dev->maximum_num_containers)
break;
if ((dev->fsa_dev[container].config_waiting_on ==
le32_to_cpu(*(__le32 *)aifcmd->data)) &&
time_before(jiffies, dev->fsa_dev[container].config_waiting_stamp + AIF_SNIFF_TIMEOUT))
dev->fsa_dev[container].config_waiting_on = 0;
} else for (container = 0;
container < dev->maximum_num_containers; ++container) {
if ((dev->fsa_dev[container].config_waiting_on ==
le32_to_cpu(*(__le32 *)aifcmd->data)) &&
time_before(jiffies, dev->fsa_dev[container].config_waiting_stamp + AIF_SNIFF_TIMEOUT))
dev->fsa_dev[container].config_waiting_on = 0;
}
break;
case AifCmdEventNotify:
switch (le32_to_cpu(((__le32 *)aifcmd->data)[0])) {
case AifEnBatteryEvent:
dev->cache_protected =
(((__le32 *)aifcmd->data)[1] == cpu_to_le32(3));
break;
/*
* Add an Array.
*/
case AifEnAddContainer:
container = le32_to_cpu(((__le32 *)aifcmd->data)[1]);
if (container >= dev->maximum_num_containers)
break;
dev->fsa_dev[container].config_needed = ADD;
dev->fsa_dev[container].config_waiting_on =
AifEnConfigChange;
dev->fsa_dev[container].config_waiting_stamp = jiffies;
break;
/*
* Delete an Array.
*/
case AifEnDeleteContainer:
container = le32_to_cpu(((__le32 *)aifcmd->data)[1]);
if (container >= dev->maximum_num_containers)
break;
dev->fsa_dev[container].config_needed = DELETE;
dev->fsa_dev[container].config_waiting_on =
AifEnConfigChange;
dev->fsa_dev[container].config_waiting_stamp = jiffies;
break;
/*
* Container change detected. If we currently are not
* waiting on something else, setup to wait on a Config Change.
*/
case AifEnContainerChange:
container = le32_to_cpu(((__le32 *)aifcmd->data)[1]);
if (container >= dev->maximum_num_containers)
break;
if (dev->fsa_dev[container].config_waiting_on &&
time_before(jiffies, dev->fsa_dev[container].config_waiting_stamp + AIF_SNIFF_TIMEOUT))
break;
dev->fsa_dev[container].config_needed = CHANGE;
dev->fsa_dev[container].config_waiting_on =
AifEnConfigChange;
dev->fsa_dev[container].config_waiting_stamp = jiffies;
break;
case AifEnConfigChange:
break;
case AifEnAddJBOD:
case AifEnDeleteJBOD:
container = le32_to_cpu(((__le32 *)aifcmd->data)[1]);
if ((container >> 28)) {
container = (u32)-1;
break;
}
channel = (container >> 24) & 0xF;
if (channel >= dev->maximum_num_channels) {
container = (u32)-1;
break;
}
id = container & 0xFFFF;
if (id >= dev->maximum_num_physicals) {
container = (u32)-1;
break;
}
lun = (container >> 16) & 0xFF;
container = (u32)-1;
channel = aac_phys_to_logical(channel);
device_config_needed =
(((__le32 *)aifcmd->data)[0] ==
cpu_to_le32(AifEnAddJBOD)) ? ADD : DELETE;
if (device_config_needed == ADD) {
device = scsi_device_lookup(dev->scsi_host_ptr,
channel,
id,
lun);
if (device) {
scsi_remove_device(device);
scsi_device_put(device);
}
}
break;
case AifEnEnclosureManagement:
/*
* If in JBOD mode, automatic exposure of new
* physical target to be suppressed until configured.
*/
if (dev->jbod)
break;
switch (le32_to_cpu(((__le32 *)aifcmd->data)[3])) {
case EM_DRIVE_INSERTION:
case EM_DRIVE_REMOVAL:
container = le32_to_cpu(
((__le32 *)aifcmd->data)[2]);
if ((container >> 28)) {
container = (u32)-1;
break;
}
channel = (container >> 24) & 0xF;
if (channel >= dev->maximum_num_channels) {
container = (u32)-1;
break;
}
id = container & 0xFFFF;
lun = (container >> 16) & 0xFF;
container = (u32)-1;
if (id >= dev->maximum_num_physicals) {
/* legacy dev_t ? */
if ((0x2000 <= id) || lun || channel ||
((channel = (id >> 7) & 0x3F) >=
dev->maximum_num_channels))
break;
lun = (id >> 4) & 7;
id &= 0xF;
}
channel = aac_phys_to_logical(channel);
device_config_needed =
(((__le32 *)aifcmd->data)[3]
== cpu_to_le32(EM_DRIVE_INSERTION)) ?
ADD : DELETE;
break;
}
break;
}
/*
* If we are waiting on something and this happens to be
* that thing then set the re-configure flag.
*/
if (container != (u32)-1) {
if (container >= dev->maximum_num_containers)
break;
if ((dev->fsa_dev[container].config_waiting_on ==
le32_to_cpu(*(__le32 *)aifcmd->data)) &&
time_before(jiffies, dev->fsa_dev[container].config_waiting_stamp + AIF_SNIFF_TIMEOUT))
dev->fsa_dev[container].config_waiting_on = 0;
} else for (container = 0;
container < dev->maximum_num_containers; ++container) {
if ((dev->fsa_dev[container].config_waiting_on ==
le32_to_cpu(*(__le32 *)aifcmd->data)) &&
time_before(jiffies, dev->fsa_dev[container].config_waiting_stamp + AIF_SNIFF_TIMEOUT))
dev->fsa_dev[container].config_waiting_on = 0;
}
break;
case AifCmdJobProgress:
/*
* These are job progress AIF's. When a Clear is being
* done on a container it is initially created then hidden from
* the OS. When the clear completes we don't get a config
* change so we monitor the job status complete on a clear then
* wait for a container change.
*/
if (((__le32 *)aifcmd->data)[1] == cpu_to_le32(AifJobCtrZero) &&
(((__le32 *)aifcmd->data)[6] == ((__le32 *)aifcmd->data)[5] ||
((__le32 *)aifcmd->data)[4] == cpu_to_le32(AifJobStsSuccess))) {
for (container = 0;
container < dev->maximum_num_containers;
++container) {
/*
* Stomp on all config sequencing for all
* containers?
*/
dev->fsa_dev[container].config_waiting_on =
AifEnContainerChange;
dev->fsa_dev[container].config_needed = ADD;
dev->fsa_dev[container].config_waiting_stamp =
jiffies;
}
}
if (((__le32 *)aifcmd->data)[1] == cpu_to_le32(AifJobCtrZero) &&
((__le32 *)aifcmd->data)[6] == 0 &&
((__le32 *)aifcmd->data)[4] == cpu_to_le32(AifJobStsRunning)) {
for (container = 0;
container < dev->maximum_num_containers;
++container) {
/*
* Stomp on all config sequencing for all
* containers?
*/
dev->fsa_dev[container].config_waiting_on =
AifEnContainerChange;
dev->fsa_dev[container].config_needed = DELETE;
dev->fsa_dev[container].config_waiting_stamp =
jiffies;
}
}
break;
}
container = 0;
retry_next:
if (device_config_needed == NOTHING)
for (; container < dev->maximum_num_containers; ++container) {
if ((dev->fsa_dev[container].config_waiting_on == 0) &&
(dev->fsa_dev[container].config_needed != NOTHING) &&
time_before(jiffies, dev->fsa_dev[container].config_waiting_stamp + AIF_SNIFF_TIMEOUT)) {
device_config_needed =
dev->fsa_dev[container].config_needed;
dev->fsa_dev[container].config_needed = NOTHING;
channel = CONTAINER_TO_CHANNEL(container);
id = CONTAINER_TO_ID(container);
lun = CONTAINER_TO_LUN(container);
break;
}
}
if (device_config_needed == NOTHING)
return;
/*
* If we decided that a re-configuration needs to be done,
* schedule it here on the way out the door, please close the door
* behind you.
*/
/*
* Find the scsi_device associated with the SCSI address,
* and mark it as changed, invalidating the cache. This deals
* with changes to existing device IDs.
*/
if (!dev || !dev->scsi_host_ptr)
return;
/*
* force reload of disk info via aac_probe_container
*/
if ((channel == CONTAINER_CHANNEL) &&
(device_config_needed != NOTHING)) {
if (dev->fsa_dev[container].valid == 1)
dev->fsa_dev[container].valid = 2;
aac_probe_container(dev, container);
}
device = scsi_device_lookup(dev->scsi_host_ptr, channel, id, lun);
if (device) {
switch (device_config_needed) {
case DELETE:
#if (defined(AAC_DEBUG_INSTRUMENT_AIF_DELETE))
scsi_remove_device(device);
#else
if (scsi_device_online(device)) {
scsi_device_set_state(device, SDEV_OFFLINE);
sdev_printk(KERN_INFO, device,
"Device offlined - %s\n",
(channel == CONTAINER_CHANNEL) ?
"array deleted" :
"enclosure services event");
}
#endif
break;
case ADD:
if (!scsi_device_online(device)) {
sdev_printk(KERN_INFO, device,
"Device online - %s\n",
(channel == CONTAINER_CHANNEL) ?
"array created" :
"enclosure services event");
scsi_device_set_state(device, SDEV_RUNNING);
}
/* FALLTHRU */
case CHANGE:
if ((channel == CONTAINER_CHANNEL)
&& (!dev->fsa_dev[container].valid)) {
#if (defined(AAC_DEBUG_INSTRUMENT_AIF_DELETE))
scsi_remove_device(device);
#else
if (!scsi_device_online(device))
break;
scsi_device_set_state(device, SDEV_OFFLINE);
sdev_printk(KERN_INFO, device,
"Device offlined - %s\n",
"array failed");
#endif
break;
}
scsi_rescan_device(&device->sdev_gendev);
default:
break;
}
scsi_device_put(device);
device_config_needed = NOTHING;
}
if (device_config_needed == ADD)
scsi_add_device(dev->scsi_host_ptr, channel, id, lun);
if (channel == CONTAINER_CHANNEL) {
container++;
device_config_needed = NOTHING;
goto retry_next;
}
}
static int _aac_reset_adapter(struct aac_dev *aac, int forced)
{
int index, quirks;
int retval;
struct Scsi_Host *host;
struct scsi_device *dev;
struct scsi_cmnd *command;
struct scsi_cmnd *command_list;
int jafo = 0;
/*
* Assumptions:
* - host is locked, unless called by the aacraid thread.
* (a matter of convenience, due to legacy issues surrounding
* eh_host_adapter_reset).
* - in_reset is asserted, so no new i/o is getting to the
* card.
* - The card is dead, or will be very shortly ;-/ so no new
* commands are completing in the interrupt service.
*/
host = aac->scsi_host_ptr;
scsi_block_requests(host);
aac_adapter_disable_int(aac);
if (aac->thread->pid != current->pid) {
spin_unlock_irq(host->host_lock);
kthread_stop(aac->thread);
jafo = 1;
}
/*
* If a positive health, means in a known DEAD PANIC
* state and the adapter could be reset to `try again'.
*/
retval = aac_adapter_restart(aac, forced ? 0 : aac_adapter_check_health(aac));
if (retval)
goto out;
/*
* Loop through the fibs, close the synchronous FIBS
*/
for (retval = 1, index = 0; index < (aac->scsi_host_ptr->can_queue + AAC_NUM_MGT_FIB); index++) {
struct fib *fib = &aac->fibs[index];
if (!(fib->hw_fib_va->header.XferState & cpu_to_le32(NoResponseExpected | Async)) &&
(fib->hw_fib_va->header.XferState & cpu_to_le32(ResponseExpected))) {
unsigned long flagv;
spin_lock_irqsave(&fib->event_lock, flagv);
up(&fib->event_wait);
spin_unlock_irqrestore(&fib->event_lock, flagv);
schedule();
retval = 0;
}
}
/* Give some extra time for ioctls to complete. */
if (retval == 0)
ssleep(2);
index = aac->cardtype;
/*
* Re-initialize the adapter, first free resources, then carefully
* apply the initialization sequence to come back again. Only risk
* is a change in Firmware dropping cache, it is assumed the caller
* will ensure that i/o is queisced and the card is flushed in that
* case.
*/
aac_fib_map_free(aac);
pci_free_consistent(aac->pdev, aac->comm_size, aac->comm_addr, aac->comm_phys);
aac->comm_addr = NULL;
aac->comm_phys = 0;
kfree(aac->queues);
aac->queues = NULL;
free_irq(aac->pdev->irq, aac);
if (aac->msi)
pci_disable_msi(aac->pdev);
kfree(aac->fsa_dev);
aac->fsa_dev = NULL;
quirks = aac_get_driver_ident(index)->quirks;
if (quirks & AAC_QUIRK_31BIT) {
if (((retval = pci_set_dma_mask(aac->pdev, DMA_BIT_MASK(31)))) ||
((retval = pci_set_consistent_dma_mask(aac->pdev, DMA_BIT_MASK(31)))))
goto out;
} else {
if (((retval = pci_set_dma_mask(aac->pdev, DMA_BIT_MASK(32)))) ||
((retval = pci_set_consistent_dma_mask(aac->pdev, DMA_BIT_MASK(32)))))
goto out;
}
if ((retval = (*(aac_get_driver_ident(index)->init))(aac)))
goto out;
if (quirks & AAC_QUIRK_31BIT)
if ((retval = pci_set_dma_mask(aac->pdev, DMA_BIT_MASK(32))))
goto out;
if (jafo) {
aac->thread = kthread_run(aac_command_thread, aac, aac->name);
if (IS_ERR(aac->thread)) {
retval = PTR_ERR(aac->thread);
goto out;
}
}
(void)aac_get_adapter_info(aac);
if ((quirks & AAC_QUIRK_34SG) && (host->sg_tablesize > 34)) {
host->sg_tablesize = 34;
host->max_sectors = (host->sg_tablesize * 8) + 112;
}
if ((quirks & AAC_QUIRK_17SG) && (host->sg_tablesize > 17)) {
host->sg_tablesize = 17;
host->max_sectors = (host->sg_tablesize * 8) + 112;
}
aac_get_config_status(aac, 1);
aac_get_containers(aac);
/*
* This is where the assumption that the Adapter is quiesced
* is important.
*/
command_list = NULL;
__shost_for_each_device(dev, host) {
unsigned long flags;
spin_lock_irqsave(&dev->list_lock, flags);
list_for_each_entry(command, &dev->cmd_list, list)
if (command->SCp.phase == AAC_OWNER_FIRMWARE) {
command->SCp.buffer = (struct scatterlist *)command_list;
command_list = command;
}
spin_unlock_irqrestore(&dev->list_lock, flags);
}
while ((command = command_list)) {
command_list = (struct scsi_cmnd *)command->SCp.buffer;
command->SCp.buffer = NULL;
command->result = DID_OK << 16
| COMMAND_COMPLETE << 8
| SAM_STAT_TASK_SET_FULL;
command->SCp.phase = AAC_OWNER_ERROR_HANDLER;
command->scsi_done(command);
}
retval = 0;
out:
aac->in_reset = 0;
scsi_unblock_requests(host);
if (jafo) {
spin_lock_irq(host->host_lock);
}
return retval;
}
int aac_reset_adapter(struct aac_dev * aac, int forced)
{
unsigned long flagv = 0;
int retval;
struct Scsi_Host * host;
if (spin_trylock_irqsave(&aac->fib_lock, flagv) == 0)
return -EBUSY;
if (aac->in_reset) {
spin_unlock_irqrestore(&aac->fib_lock, flagv);
return -EBUSY;
}
aac->in_reset = 1;
spin_unlock_irqrestore(&aac->fib_lock, flagv);
/*
* Wait for all commands to complete to this specific
* target (block maximum 60 seconds). Although not necessary,
* it does make us a good storage citizen.
*/
host = aac->scsi_host_ptr;
scsi_block_requests(host);
if (forced < 2) for (retval = 60; retval; --retval) {
struct scsi_device * dev;
struct scsi_cmnd * command;
int active = 0;
__shost_for_each_device(dev, host) {
spin_lock_irqsave(&dev->list_lock, flagv);
list_for_each_entry(command, &dev->cmd_list, list) {
if (command->SCp.phase == AAC_OWNER_FIRMWARE) {
active++;
break;
}
}
spin_unlock_irqrestore(&dev->list_lock, flagv);
if (active)
break;
}
/*
* We can exit If all the commands are complete
*/
if (active == 0)
break;
ssleep(1);
}
/* Quiesce build, flush cache, write through mode */
if (forced < 2)
aac_send_shutdown(aac);
spin_lock_irqsave(host->host_lock, flagv);
retval = _aac_reset_adapter(aac, forced ? forced : ((aac_check_reset != 0) && (aac_check_reset != 1)));
spin_unlock_irqrestore(host->host_lock, flagv);
if ((forced < 2) && (retval == -ENODEV)) {
/* Unwind aac_send_shutdown() IOP_RESET unsupported/disabled */
struct fib * fibctx = aac_fib_alloc(aac);
if (fibctx) {
struct aac_pause *cmd;
int status;
aac_fib_init(fibctx);
cmd = (struct aac_pause *) fib_data(fibctx);
cmd->command = cpu_to_le32(VM_ContainerConfig);
cmd->type = cpu_to_le32(CT_PAUSE_IO);
cmd->timeout = cpu_to_le32(1);
cmd->min = cpu_to_le32(1);
cmd->noRescan = cpu_to_le32(1);
cmd->count = cpu_to_le32(0);
status = aac_fib_send(ContainerCommand,
fibctx,
sizeof(struct aac_pause),
FsaNormal,
-2 /* Timeout silently */, 1,
NULL, NULL);
if (status >= 0)
aac_fib_complete(fibctx);
/* FIB should be freed only after getting
* the response from the F/W */
if (status != -ERESTARTSYS)
aac_fib_free(fibctx);
}
}
return retval;
}
int aac_check_health(struct aac_dev * aac)
{
int BlinkLED;
unsigned long time_now, flagv = 0;
struct list_head * entry;
struct Scsi_Host * host;
/* Extending the scope of fib_lock slightly to protect aac->in_reset */
if (spin_trylock_irqsave(&aac->fib_lock, flagv) == 0)
return 0;
if (aac->in_reset || !(BlinkLED = aac_adapter_check_health(aac))) {
spin_unlock_irqrestore(&aac->fib_lock, flagv);
return 0; /* OK */
}
aac->in_reset = 1;
/* Fake up an AIF:
* aac_aifcmd.command = AifCmdEventNotify = 1
* aac_aifcmd.seqnum = 0xFFFFFFFF
* aac_aifcmd.data[0] = AifEnExpEvent = 23
* aac_aifcmd.data[1] = AifExeFirmwarePanic = 3
* aac.aifcmd.data[2] = AifHighPriority = 3
* aac.aifcmd.data[3] = BlinkLED
*/
time_now = jiffies/HZ;
entry = aac->fib_list.next;
/*
* For each Context that is on the
* fibctxList, make a copy of the
* fib, and then set the event to wake up the
* thread that is waiting for it.
*/
while (entry != &aac->fib_list) {
/*
* Extract the fibctx
*/
struct aac_fib_context *fibctx = list_entry(entry, struct aac_fib_context, next);
struct hw_fib * hw_fib;
struct fib * fib;
/*
* Check if the queue is getting
* backlogged
*/
if (fibctx->count > 20) {
/*
* It's *not* jiffies folks,
* but jiffies / HZ, so do not
* panic ...
*/
u32 time_last = fibctx->jiffies;
/*
* Has it been > 2 minutes
* since the last read off
* the queue?
*/
if ((time_now - time_last) > aif_timeout) {
entry = entry->next;
aac_close_fib_context(aac, fibctx);
continue;
}
}
/*
* Warning: no sleep allowed while
* holding spinlock
*/
hw_fib = kzalloc(sizeof(struct hw_fib), GFP_ATOMIC);
fib = kzalloc(sizeof(struct fib), GFP_ATOMIC);
if (fib && hw_fib) {
struct aac_aifcmd * aif;
fib->hw_fib_va = hw_fib;
fib->dev = aac;
aac_fib_init(fib);
fib->type = FSAFS_NTC_FIB_CONTEXT;
fib->size = sizeof (struct fib);
fib->data = hw_fib->data;
aif = (struct aac_aifcmd *)hw_fib->data;
aif->command = cpu_to_le32(AifCmdEventNotify);
aif->seqnum = cpu_to_le32(0xFFFFFFFF);
((__le32 *)aif->data)[0] = cpu_to_le32(AifEnExpEvent);
((__le32 *)aif->data)[1] = cpu_to_le32(AifExeFirmwarePanic);
((__le32 *)aif->data)[2] = cpu_to_le32(AifHighPriority);
((__le32 *)aif->data)[3] = cpu_to_le32(BlinkLED);
/*
* Put the FIB onto the
* fibctx's fibs
*/
list_add_tail(&fib->fiblink, &fibctx->fib_list);
fibctx->count++;
/*
* Set the event to wake up the
* thread that will waiting.
*/
up(&fibctx->wait_sem);
} else {
printk(KERN_WARNING "aifd: didn't allocate NewFib.\n");
kfree(fib);
kfree(hw_fib);
}
entry = entry->next;
}
spin_unlock_irqrestore(&aac->fib_lock, flagv);
if (BlinkLED < 0) {
printk(KERN_ERR "%s: Host adapter dead %d\n", aac->name, BlinkLED);
goto out;
}
printk(KERN_ERR "%s: Host adapter BLINK LED 0x%x\n", aac->name, BlinkLED);
if (!aac_check_reset || ((aac_check_reset == 1) &&
(aac->supplement_adapter_info.SupportedOptions2 &
AAC_OPTION_IGNORE_RESET)))
goto out;
host = aac->scsi_host_ptr;
if (aac->thread->pid != current->pid)
spin_lock_irqsave(host->host_lock, flagv);
BlinkLED = _aac_reset_adapter(aac, aac_check_reset != 1);
if (aac->thread->pid != current->pid)
spin_unlock_irqrestore(host->host_lock, flagv);
return BlinkLED;
out:
aac->in_reset = 0;
return BlinkLED;
}
/**
* aac_command_thread - command processing thread
* @dev: Adapter to monitor
*
* Waits on the commandready event in it's queue. When the event gets set
* it will pull FIBs off it's queue. It will continue to pull FIBs off
* until the queue is empty. When the queue is empty it will wait for
* more FIBs.
*/
int aac_command_thread(void *data)
{
struct aac_dev *dev = data;
struct hw_fib *hw_fib, *hw_newfib;
struct fib *fib, *newfib;
struct aac_fib_context *fibctx;
unsigned long flags;
DECLARE_WAITQUEUE(wait, current);
unsigned long next_jiffies = jiffies + HZ;
unsigned long next_check_jiffies = next_jiffies;
long difference = HZ;
/*
* We can only have one thread per adapter for AIF's.
*/
if (dev->aif_thread)
return -EINVAL;
/*
* Let the DPC know it has a place to send the AIF's to.
*/
dev->aif_thread = 1;
add_wait_queue(&dev->queues->queue[HostNormCmdQueue].cmdready, &wait);
set_current_state(TASK_INTERRUPTIBLE);
dprintk ((KERN_INFO "aac_command_thread start\n"));
while (1) {
spin_lock_irqsave(dev->queues->queue[HostNormCmdQueue].lock, flags);
while(!list_empty(&(dev->queues->queue[HostNormCmdQueue].cmdq))) {
struct list_head *entry;
struct aac_aifcmd * aifcmd;
set_current_state(TASK_RUNNING);
entry = dev->queues->queue[HostNormCmdQueue].cmdq.next;
list_del(entry);
spin_unlock_irqrestore(dev->queues->queue[HostNormCmdQueue].lock, flags);
fib = list_entry(entry, struct fib, fiblink);
/*
* We will process the FIB here or pass it to a
* worker thread that is TBD. We Really can't
* do anything at this point since we don't have
* anything defined for this thread to do.
*/
hw_fib = fib->hw_fib_va;
memset(fib, 0, sizeof(struct fib));
fib->type = FSAFS_NTC_FIB_CONTEXT;
fib->size = sizeof(struct fib);
fib->hw_fib_va = hw_fib;
fib->data = hw_fib->data;
fib->dev = dev;
/*
* We only handle AifRequest fibs from the adapter.
*/
aifcmd = (struct aac_aifcmd *) hw_fib->data;
if (aifcmd->command == cpu_to_le32(AifCmdDriverNotify)) {
/* Handle Driver Notify Events */
aac_handle_aif(dev, fib);
*(__le32 *)hw_fib->data = cpu_to_le32(ST_OK);
aac_fib_adapter_complete(fib, (u16)sizeof(u32));
} else {
/* The u32 here is important and intended. We are using
32bit wrapping time to fit the adapter field */
u32 time_now, time_last;
unsigned long flagv;
unsigned num;
struct hw_fib ** hw_fib_pool, ** hw_fib_p;
struct fib ** fib_pool, ** fib_p;
/* Sniff events */
if ((aifcmd->command ==
cpu_to_le32(AifCmdEventNotify)) ||
(aifcmd->command ==
cpu_to_le32(AifCmdJobProgress))) {
aac_handle_aif(dev, fib);
}
time_now = jiffies/HZ;
/*
* Warning: no sleep allowed while
* holding spinlock. We take the estimate
* and pre-allocate a set of fibs outside the
* lock.
*/
num = le32_to_cpu(dev->init->AdapterFibsSize)
/ sizeof(struct hw_fib); /* some extra */
spin_lock_irqsave(&dev->fib_lock, flagv);
entry = dev->fib_list.next;
while (entry != &dev->fib_list) {
entry = entry->next;
++num;
}
spin_unlock_irqrestore(&dev->fib_lock, flagv);
hw_fib_pool = NULL;
fib_pool = NULL;
if (num
&& ((hw_fib_pool = kmalloc(sizeof(struct hw_fib *) * num, GFP_KERNEL)))
&& ((fib_pool = kmalloc(sizeof(struct fib *) * num, GFP_KERNEL)))) {
hw_fib_p = hw_fib_pool;
fib_p = fib_pool;
while (hw_fib_p < &hw_fib_pool[num]) {
if (!(*(hw_fib_p++) = kmalloc(sizeof(struct hw_fib), GFP_KERNEL))) {
--hw_fib_p;
break;
}
if (!(*(fib_p++) = kmalloc(sizeof(struct fib), GFP_KERNEL))) {
kfree(*(--hw_fib_p));
break;
}
}
if ((num = hw_fib_p - hw_fib_pool) == 0) {
kfree(fib_pool);
fib_pool = NULL;
kfree(hw_fib_pool);
hw_fib_pool = NULL;
}
} else {
kfree(hw_fib_pool);
hw_fib_pool = NULL;
}
spin_lock_irqsave(&dev->fib_lock, flagv);
entry = dev->fib_list.next;
/*
* For each Context that is on the
* fibctxList, make a copy of the
* fib, and then set the event to wake up the
* thread that is waiting for it.
*/
hw_fib_p = hw_fib_pool;
fib_p = fib_pool;
while (entry != &dev->fib_list) {
/*
* Extract the fibctx
*/
fibctx = list_entry(entry, struct aac_fib_context, next);
/*
* Check if the queue is getting
* backlogged
*/
if (fibctx->count > 20)
{
/*
* It's *not* jiffies folks,
* but jiffies / HZ so do not
* panic ...
*/
time_last = fibctx->jiffies;
/*
* Has it been > 2 minutes
* since the last read off
* the queue?
*/
if ((time_now - time_last) > aif_timeout) {
entry = entry->next;
aac_close_fib_context(dev, fibctx);
continue;
}
}
/*
* Warning: no sleep allowed while
* holding spinlock
*/
if (hw_fib_p < &hw_fib_pool[num]) {
hw_newfib = *hw_fib_p;
*(hw_fib_p++) = NULL;
newfib = *fib_p;
*(fib_p++) = NULL;
/*
* Make the copy of the FIB
*/
memcpy(hw_newfib, hw_fib, sizeof(struct hw_fib));
memcpy(newfib, fib, sizeof(struct fib));
newfib->hw_fib_va = hw_newfib;
/*
* Put the FIB onto the
* fibctx's fibs
*/
list_add_tail(&newfib->fiblink, &fibctx->fib_list);
fibctx->count++;
/*
* Set the event to wake up the
* thread that is waiting.
*/
up(&fibctx->wait_sem);
} else {
printk(KERN_WARNING "aifd: didn't allocate NewFib.\n");
}
entry = entry->next;
}
/*
* Set the status of this FIB
*/
*(__le32 *)hw_fib->data = cpu_to_le32(ST_OK);
aac_fib_adapter_complete(fib, sizeof(u32));
spin_unlock_irqrestore(&dev->fib_lock, flagv);
/* Free up the remaining resources */
hw_fib_p = hw_fib_pool;
fib_p = fib_pool;
while (hw_fib_p < &hw_fib_pool[num]) {
kfree(*hw_fib_p);
kfree(*fib_p);
++fib_p;
++hw_fib_p;
}
kfree(hw_fib_pool);
kfree(fib_pool);
}
kfree(fib);
spin_lock_irqsave(dev->queues->queue[HostNormCmdQueue].lock, flags);
}
/*
* There are no more AIF's
*/
spin_unlock_irqrestore(dev->queues->queue[HostNormCmdQueue].lock, flags);
/*
* Background activity
*/
if ((time_before(next_check_jiffies,next_jiffies))
&& ((difference = next_check_jiffies - jiffies) <= 0)) {
next_check_jiffies = next_jiffies;
if (aac_check_health(dev) == 0) {
difference = ((long)(unsigned)check_interval)
* HZ;
next_check_jiffies = jiffies + difference;
} else if (!dev->queues)
break;
}
if (!time_before(next_check_jiffies,next_jiffies)
&& ((difference = next_jiffies - jiffies) <= 0)) {
struct timeval now;
int ret;
/* Don't even try to talk to adapter if its sick */
ret = aac_check_health(dev);
if (!ret && !dev->queues)
break;
next_check_jiffies = jiffies
+ ((long)(unsigned)check_interval)
* HZ;
do_gettimeofday(&now);
/* Synchronize our watches */
if (((1000000 - (1000000 / HZ)) > now.tv_usec)
&& (now.tv_usec > (1000000 / HZ)))
difference = (((1000000 - now.tv_usec) * HZ)
+ 500000) / 1000000;
else if (ret == 0) {
struct fib *fibptr;
if ((fibptr = aac_fib_alloc(dev))) {
int status;
__le32 *info;
aac_fib_init(fibptr);
info = (__le32 *) fib_data(fibptr);
if (now.tv_usec > 500000)
++now.tv_sec;
*info = cpu_to_le32(now.tv_sec);
status = aac_fib_send(SendHostTime,
fibptr,
sizeof(*info),
FsaNormal,
1, 1,
NULL,
NULL);
/* Do not set XferState to zero unless
* receives a response from F/W */
if (status >= 0)
aac_fib_complete(fibptr);
/* FIB should be freed only after
* getting the response from the F/W */
if (status != -ERESTARTSYS)
aac_fib_free(fibptr);
}
difference = (long)(unsigned)update_interval*HZ;
} else {
/* retry shortly */
difference = 10 * HZ;
}
next_jiffies = jiffies + difference;
if (time_before(next_check_jiffies,next_jiffies))
difference = next_check_jiffies - jiffies;
}
if (difference <= 0)
difference = 1;
set_current_state(TASK_INTERRUPTIBLE);
schedule_timeout(difference);
if (kthread_should_stop())
break;
}
if (dev->queues)
remove_wait_queue(&dev->queues->queue[HostNormCmdQueue].cmdready, &wait);
dev->aif_thread = 0;
return 0;
}
| {
"content_hash": "f1948395b30fdb831564389de145d278",
"timestamp": "",
"source": "github",
"line_count": 1866,
"max_line_length": 141,
"avg_line_length": 28.5010718113612,
"alnum_prop": 0.6364627794596017,
"repo_name": "WhiteBearSolutions/WBSAirback",
"id": "e5f2d7d9002ec4df139d9db4260069d58d2fcfce",
"size": "54304",
"binary": false,
"copies": "2984",
"ref": "refs/heads/master",
"path": "packages/wbsairback-kernel-image/wbsairback-kernel-image-3.2.43/drivers/scsi/aacraid/commsup.c",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "4780982"
}
],
"symlink_target": ""
} |
import constant
import smtplib
from email import MIMEMultipart
from email import MIMEText
from email import MIMEBase
from email import encoders
def send_mail(fromaddr, toaddr, subject, mail_body, send_mail_server,
send_mail_port=587, send_file_name_as=None, send_file_path=None):
"""
simple send mail with body and attachment
:param fromaddr: str|sender email address
:param toaddr: list of str| list of receiver email address
:param subject: str| subject of email
:param mail_body: str|email body
:param send_mail_server: str|
:param send_mail_port: int|
:param send_file_name_as: str|filename of the attachment
:param send_file_path: str|path to the attachment
"""
msg = MIMEMultipart.MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = ", ".join(toaddr["To"])
msg['CC'] = ", ".join(toaddr["CC"])
msg['BCC'] = ", ".join(toaddr["BCC"])
msg['Subject'] = subject
msg.attach(MIMEText.MIMEText(mail_body, 'plain'))
if send_file_name_as and send_file_path:
attachment = open(send_file_path, "rb")
part = MIMEBase.MIMEBase('application', 'octet-stream')
part.set_payload(attachment.read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= %s" % send_file_name_as)
msg.attach(part)
server = smtplib.SMTP(send_mail_server, send_mail_port)
server.starttls()
server.login(fromaddr, constant.ps)
text = msg.as_string()
server.sendmail(fromaddr, toaddr["To"], text)
server.quit()
if __name__=="__main__":
"""
please define all constants in the constant.py file
"""
from constant import *
send_mail(sender_address, to_address_dict, subject, mail_body, send_mail_server,
send_mail_port=send_mail_port, send_file_name_as=send_file_name_as,
send_file_path=send_file_path) | {
"content_hash": "43469e19eb32ea1dcbb0d2f270d0f417",
"timestamp": "",
"source": "github",
"line_count": 53,
"max_line_length": 94,
"avg_line_length": 36.094339622641506,
"alnum_prop": 0.658128593831678,
"repo_name": "WenchenLi/util",
"id": "79b1af4f6cfa2a8cafcef1bd44ef22404d80654e",
"size": "1913",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "python/python2/mail.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "4799"
},
{
"name": "Shell",
"bytes": "3526"
}
],
"symlink_target": ""
} |
import gdsfactory as gf
from gdsfactory.component import Component
from gdsfactory.components.pad import pad as pad_function
from gdsfactory.components.rectangle import rectangle
from gdsfactory.types import ComponentSpec, LayerSpec
@gf.cell
def pads_shorted(
pad: ComponentSpec = pad_function,
columns: int = 8,
pad_spacing: float = 150.0,
layer_metal: LayerSpec = "M3",
metal_width: float = 10,
) -> Component:
"""Returns a 1D array of shorted_pads.
Args:
pad: pad spec.
columns: number of columns.
pad_spacing: in um
layer_metal: for the short.
metal_width: for the short.
"""
c = Component()
pad = gf.get_component(pad)
for i in range(columns):
pad_ref = c.add_ref(pad)
pad_ref.movex(i * pad_spacing - columns / 2 * pad_spacing + pad_spacing / 2)
short = rectangle(
size=(pad_spacing * (columns - 1), metal_width),
layer=layer_metal,
centered=True,
)
c.add_ref(short)
return c
if __name__ == "__main__":
c = pads_shorted(metal_width=20)
c.show(show_ports=True)
| {
"content_hash": "8f45fdef45eacb2dcc4a9e5c93ce2326",
"timestamp": "",
"source": "github",
"line_count": 43,
"max_line_length": 84,
"avg_line_length": 26.046511627906977,
"alnum_prop": 0.6294642857142857,
"repo_name": "gdsfactory/gdsfactory",
"id": "5b78c2e02a7375b3ba9a8cb20308d52cd9c77703",
"size": "1120",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "gdsfactory/components/pads_shorted.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "605"
},
{
"name": "Dockerfile",
"bytes": "31"
},
{
"name": "Makefile",
"bytes": "4572"
},
{
"name": "Python",
"bytes": "2471982"
},
{
"name": "Shell",
"bytes": "671"
},
{
"name": "XS",
"bytes": "10045"
}
],
"symlink_target": ""
} |
package test.configuration;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Arrays;
import org.testng.Assert;
import org.testng.TestNG;
import org.testng.annotations.Test;
import org.testng.xml.XmlSuite;
import test.configuration.issue2726.TestClassSample;
import test.configuration.issue2743.SuiteRunnerIssueTestSample;
import test.configuration.sample.ConfigurationTestSample;
import test.configuration.sample.ExternalConfigurationClassSample;
import test.configuration.sample.MethodCallOrderTestSample;
import test.configuration.sample.SuiteTestSample;
/**
* Test @Configuration
*
* @author cbeust
*/
public class ConfigurationTest extends ConfigurationBaseTest {
@Test
public void testConfiguration() {
testConfiguration(ConfigurationTestSample.class);
}
@Test
public void testMethodCallOrder() {
testConfiguration(MethodCallOrderTestSample.class, ExternalConfigurationClassSample.class);
}
@Test
public void testSuite() {
testConfiguration(SuiteTestSample.class);
Assert.assertEquals(Arrays.asList(1, 2, 3, 4, 5), SuiteTestSample.m_order);
}
@Test
public void testSuiteRunnerWithDefaultConfiguration() {
TestNG testNG = create(SuiteRunnerIssueTestSample.class);
testNG.run();
Assert.assertEquals(testNG.getStatus(), 0);
}
@Test(description = "GITHUB-2726")
public void testAfterClassCalledOnlyOnceForParallelTestMethods() {
TestNG testng = create(TestClassSample.class);
testng.setParallel(XmlSuite.ParallelMode.METHODS);
testng.setVerbose(2);
testng.run();
assertThat(TestClassSample.beforeLogs).hasSize(1);
assertThat(TestClassSample.afterLogs).hasSize(1);
}
}
| {
"content_hash": "8694f621a818cf43ad9844cd4ee28576",
"timestamp": "",
"source": "github",
"line_count": 56,
"max_line_length": 95,
"avg_line_length": 30.160714285714285,
"alnum_prop": 0.7838957963291888,
"repo_name": "cbeust/testng",
"id": "c40b54c1e8a84d388abd48ecb0969f7b53bbc43b",
"size": "1689",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "testng-core/src/test/java/test/configuration/ConfigurationTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "711"
},
{
"name": "CSS",
"bytes": "12708"
},
{
"name": "Groovy",
"bytes": "3285"
},
{
"name": "HTML",
"bytes": "9063"
},
{
"name": "Java",
"bytes": "3961736"
},
{
"name": "JavaScript",
"bytes": "7230"
},
{
"name": "Kotlin",
"bytes": "75929"
},
{
"name": "Shell",
"bytes": "1458"
}
],
"symlink_target": ""
} |
package com.badlogic.gdx.tests;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.tests.utils.GdxTest;
/** A simple test to demonstrate the life cycle of an application.
*
* @author mzechner */
public class LifeCycleTest extends GdxTest {
@Override
public void dispose () {
Gdx.app.log("Test", "app destroyed");
}
@Override
public void pause () {
Gdx.app.log("Test", "app paused");
}
@Override
public void resume () {
Gdx.app.log("Test", "app resumed");
}
@Override
public void render () {
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
}
@Override
public void create () {
Gdx.app.log("Test", "app created: " + Gdx.graphics.getWidth() + "x" + Gdx.graphics.getHeight());
}
@Override
public void resize (int width, int height) {
Gdx.app.log("Test", "app resized: " + width + "x" + height + ", Graphics says: " + Gdx.graphics.getWidth() + "x"
+ Gdx.graphics.getHeight());
}
@Override
public boolean needsGL20 () {
return false;
}
}
| {
"content_hash": "7e03b0cb182698479c8d51d491ad614b",
"timestamp": "",
"source": "github",
"line_count": 50,
"max_line_length": 114,
"avg_line_length": 21.38,
"alnum_prop": 0.6314312441534145,
"repo_name": "ryoenji/libgdx",
"id": "5ddbbf0771064038c8054458bdab30a319d4dbd2",
"size": "1839",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "tests/gdx-tests/src/com/badlogic/gdx/tests/LifeCycleTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "299963"
},
{
"name": "Awk",
"bytes": "3965"
},
{
"name": "Batchfile",
"bytes": "1697"
},
{
"name": "C",
"bytes": "10463213"
},
{
"name": "C++",
"bytes": "10070654"
},
{
"name": "CMake",
"bytes": "26649"
},
{
"name": "CSS",
"bytes": "65738"
},
{
"name": "DIGITAL Command Language",
"bytes": "35819"
},
{
"name": "GLSL",
"bytes": "79085"
},
{
"name": "Groff",
"bytes": "35050"
},
{
"name": "HTML",
"bytes": "1081320"
},
{
"name": "Java",
"bytes": "12339136"
},
{
"name": "JavaScript",
"bytes": "24"
},
{
"name": "Lua",
"bytes": "63243"
},
{
"name": "Makefile",
"bytes": "247693"
},
{
"name": "Module Management System",
"bytes": "13694"
},
{
"name": "Objective-C",
"bytes": "65828"
},
{
"name": "Objective-C++",
"bytes": "58296"
},
{
"name": "OpenEdge ABL",
"bytes": "8244"
},
{
"name": "Pascal",
"bytes": "17677"
},
{
"name": "Python",
"bytes": "172284"
},
{
"name": "Ragel in Ruby Host",
"bytes": "27319"
},
{
"name": "SAS",
"bytes": "14198"
},
{
"name": "Shell",
"bytes": "996502"
},
{
"name": "Smalltalk",
"bytes": "1252"
}
],
"symlink_target": ""
} |
[](https://landscape.io/github/chachi/MirrorMirror/master)
MirrorMirror
============
An art project.
This will become an interactive video exhibit which reacts to the
viewers facial expressions with different sorts of video actions.
Dependencies
-------------
Python: MirrorMirror is written using Python 2.7 which is installed by
default on Mac OSX, but can be found at http://python.org
opencv is currently the only library dependency. It can be installed
with a tool like homebrew from http://brew.sh or from
http://opencv.org
Running
--------
After installing OpenCV, you'll have to modify mirror.py so that the
FACE_CASCADE_XML string points to the correct
haarcascade_frontalface_default.xml file. This is necessary for the face detection.
In a terminal, run:
python mirror.py
It should open a new window to your computer's webcam and show you a bounding box around any faces in the image.
To-Do
-------
- [X] Image capture
- [X] Facial detection
- [X] Add facial expression learning
- [X] Add hooks for emotion reactions
- [X] Distributed node communication
RPi Setup
---------
- ssh-copy-id to each RPi
- sudo raspi-config
1. Expand filesystem
3. Enable boot to desktop
- /etc/network/interfaces needs "wireless-power off" to disable wireless power saving
- Add restart, fix_network scripts to cron
- Add /etc/init.d script
- Install unclutter package to hide cursor
- Rebuild/install zmq with pip
- Copy virtualenv
| {
"content_hash": "a7453825d001258fdf5c54d41ffe7215",
"timestamp": "",
"source": "github",
"line_count": 55,
"max_line_length": 142,
"avg_line_length": 27.90909090909091,
"alnum_prop": 0.7478827361563518,
"repo_name": "chachi/MirrorMirror",
"id": "a44ec28ee2929b01661c8d937b05811615a91dac",
"size": "1535",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "22124"
},
{
"name": "Shell",
"bytes": "43"
}
],
"symlink_target": ""
} |
/**********************************************************************************************
* File Name : InputView.java
* Purpose : provides the interface by which the user enters and views their TODOs
* Creation Date : Sat Apr 09 21:10:46 CDT 2016
* Last Modified : Sun Apr 10 13:54:09 CDT 2016
* Author : Ivan Guerra <Ivan.E.Guerra-1@ou.edu>
*********************************************************************************************/
package com.ou.cs.client;
import com.google.gwt.core.shared.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DockPanel;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
public class InputView {
private final Button jbtCreate = new Button("Create TODO"); /* button used to create new TODOs */
private final Button jbtRemove = new Button("Clear Complete TODOs"); /* button used to remove all TODOs marked as completed */
private final Label jlCounter = new Label(); /* label used to display a count of how TODOs are active in the system globally (total count of this user and all other users' active TODOs) */
private final Label jlInstructions = new Label(
"Use the buttons below to add and remove TODOs."); /* label used to provide the user instructions on how to create and remove TODOs */
private final Label jlPageTitle = new Label("TODO Tracker"); /* the page header label or title */
private final DockPanel jplButtons = new DockPanel(); /* panel used to group interface buttons */
private final VerticalPanel jplRoot = new VerticalPanel(); /* panel used to group all interface widgets */
private RootPanel rootPanel; /* panel used to display all widgets on the interface */
private final TodoCountServiceAsync todoCountSvc = GWT
.create(TodoCountService.class); /* service class used to retrieve global TODO count */
private final FlexTable todoTable = new FlexTable(); /* table used to display TODOs to the user */
/**********************************************************************************************
* Name : InputView Purpose : default constructor Parameters :
*
* @param: none Return :
* @return: none
*********************************************************************************************/
public InputView() {
}
/**********************************************************************************************
* Name : InputView Purpose : non-default constructor used to initialize the
* primary input view Parameters :
*
* @rootPaneL: the root panel used by this GWT application Return :
* @return: none
*********************************************************************************************/
public InputView(final RootPanel rootPanel) {
this.rootPanel = rootPanel;
init();
}
/**********************************************************************************************
* Name : getGlobalTodoCount Purpose : set @jlCounter to display the number
* of TODOs currently being tracked by the system factoring in all users'
* TODOs Parameters :
*
* @param: none Return :
* @return: none
*********************************************************************************************/
private void getGlobalTodoCount() {
final AsyncCallback<Integer> callBack = new AsyncCallback<Integer>() {
public void onFailure(final Throwable caught) {
}
public void onSuccess(final Integer result) {
setJlCounterText(result);
}
};
todoCountSvc.getCurrentGlobalTodoCount(callBack);
}
/**********************************************************************************************
* Name : getJbtCreate Purpose : returns the @jbtCreate button Parameters :
*
* @param: none Return :
* @return: the @jbtCreate button
*********************************************************************************************/
public Button getJbtCreate() {
return jbtCreate;
}
/**********************************************************************************************
* Name : getJbtRemove Purpose : returns the @jbtRemove button Parameters :
*
* @param: none Return :
* @return: the @jbtRemove button
*********************************************************************************************/
public Button getJbtRemove() {
return jbtRemove;
}
/**********************************************************************************************
* Name : getJlCounter Purpose : returns the @jlCounter label Parameters :
*
* @param: none Return :
* @return: the @jlCounter label
*********************************************************************************************/
public Label getJlCounter() {
return jlCounter;
}
/**********************************************************************************************
* Name : getTodoTable Purpose : returns the @todoTable FlexTable Parameters
* :
*
* @param: none Return :
* @return: the @todoTable FlexTable
*********************************************************************************************/
public FlexTable getTodoTable() {
return todoTable;
}
/**********************************************************************************************
* Name : init Purpose : initialize interface widgets and set their layout
* Parameters :
*
* @param: none Return :
* @return: none
*********************************************************************************************/
private void init() {
/* initialize the first row or header of @todoTable */
todoTable.setHTML(0, 0, "<b>Description</b>");
todoTable.addCell(0);
todoTable.setHTML(0, 1, "<b>Creation Date</b>");
todoTable.addCell(0);
todoTable.setHTML(0, 2, "<b>Due Date</b>");
todoTable.addCell(0);
todoTable.setHTML(0, 3, "<b>Status</b>");
for (int i = 0; i < 4; i++) {
todoTable.getColumnFormatter().setWidth(i, "300px");
}
jplButtons.add(jbtCreate, DockPanel.WEST);
jplButtons.add(jbtRemove, DockPanel.EAST);
jplRoot.add(jlPageTitle);
jplRoot.add(todoTable);
jplRoot.add(jplButtons);
jplRoot.setStyleName("center");
/* set the style of each widget using CSS style names */
jlPageTitle.addStyleName("todoHeaderLabel");
jlInstructions.addStyleName("todoInstructionLabel");
jlCounter.addStyleName("todoCounterLabel");
todoTable.getRowFormatter().addStyleName(0, "todoTableHeader");
todoTable.addStyleName("todoTable");
rootPanel.setStyleName("backgroundColor");
getGlobalTodoCount();
rootPanel.add(jlPageTitle);
rootPanel.add(jlCounter);
rootPanel.add(jlInstructions);
rootPanel.add(jplRoot);
}
/**********************************************************************************************
* Name : setJlCounterText Purpose : update the count displayed by @jlCounter
* to display the parameter value, @count Parameters :
*
* @count: the global count of TODOs Return :
* @return: none
*********************************************************************************************/
public void setJlCounterText(final int count) {
final String globalCount = "Global System TODO Count: "
+ Integer.toString(count);
jlCounter.setText(globalCount);
}
}
| {
"content_hash": "53856d976d8a855d192fbc2295d7d50a",
"timestamp": "",
"source": "github",
"line_count": 171,
"max_line_length": 195,
"avg_line_length": 44.25730994152047,
"alnum_prop": 0.513477801268499,
"repo_name": "ivan-guerra/university_projects",
"id": "137410df8686a5876bc1a9b406f4871d9fcd57b7",
"size": "7568",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "human_computer_interaction/todo_tracker/client/InputView.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "100998"
},
{
"name": "C++",
"bytes": "232277"
},
{
"name": "CSS",
"bytes": "1163"
},
{
"name": "HTML",
"bytes": "2233"
},
{
"name": "Java",
"bytes": "146676"
},
{
"name": "Python",
"bytes": "34786"
},
{
"name": "Racket",
"bytes": "2505"
},
{
"name": "Scheme",
"bytes": "1258"
}
],
"symlink_target": ""
} |
package io.permazen.kv;
import com.google.common.base.Preconditions;
import io.permazen.util.ByteUtil;
import java.util.Arrays;
import java.util.Map;
/**
* A key/value pair.
*
* <p>
* Note: the internal byte arrays are not copied; therefore, values passed to the constructor
* or returned from the accessor methods must not be modified if instances are to remain immutable.
* To ensure safety, use {@link #clone}.
*/
public class KVPair implements Cloneable {
private /*final*/ byte[] key;
private /*final*/ byte[] value;
/**
* Constructor. The given arrays are copied.
*
* @param key key
* @param value value
* @throws IllegalArgumentException if {@code key} or {@code value} is null
*/
public KVPair(byte[] key, byte[] value) {
Preconditions.checkArgument(key != null, "null key");
Preconditions.checkArgument(value != null, "null value");
this.key = key;
this.value = value;
}
/**
* Constructor. The given key and value arrays are copied.
*
* @param entry map entry
* @throws IllegalArgumentException if {@code entry} or its key or value is null
*/
public KVPair(Map.Entry<byte[], byte[]> entry) {
Preconditions.checkArgument(entry != null, "null entry");
this.key = entry.getKey();
this.value = entry.getValue();
Preconditions.checkArgument(this.key != null, "null key");
Preconditions.checkArgument(this.value != null, "null value");
}
/**
* Get the key.
*
* @return the key
*/
public byte[] getKey() {
return this.key;
}
/**
* Get the value.
*
* @return the value
*/
public byte[] getValue() {
return this.value;
}
// Cloneable
/**
* Deep-clone this instance. Copys this instance as well as the key and value {@code byte[]} arrays.
*
* @return cloned instance
*/
@Override
public KVPair clone() {
final KVPair clone;
try {
clone = (KVPair)super.clone();
} catch (CloneNotSupportedException e) {
throw new RuntimeException(e);
}
clone.key = clone.key.clone();
clone.value = clone.value.clone();
return clone;
}
// Object
@Override
public String toString() {
return "{" + ByteUtil.toString(this.key) + "," + ByteUtil.toString(this.value) + "}";
}
/**
* Compare for equality.
*
* <p>
* Two {@link KVPair} instances are equal if the keys and values both match
* according to {@link Arrays#equals(byte[], byte[])}.
*
* @return true if objects are equal
*/
@Override
public boolean equals(Object obj) {
if (obj == this)
return true;
if (obj == null || obj.getClass() != this.getClass())
return false;
final KVPair that = (KVPair)obj;
return Arrays.equals(this.key, that.key) && Arrays.equals(this.value, that.value);
}
/**
* Calculate hash code.
*
* <p>
* The hash code of a {@link KVPair} is the exclusive-OR of the hash codes of the key
* and the value, each according to {@link Arrays#hashCode(byte[])}.
*
* @return hash value for this instance
*/
@Override
public int hashCode() {
return Arrays.hashCode(this.key) ^ Arrays.hashCode(this.value);
}
}
| {
"content_hash": "9f30b453024cfd85457789ddead97317",
"timestamp": "",
"source": "github",
"line_count": 132,
"max_line_length": 104,
"avg_line_length": 25.984848484848484,
"alnum_prop": 0.5862973760932945,
"repo_name": "permazen/permazen",
"id": "354b63939a21ec4e1c76589d4993c90108795fbf",
"size": "3496",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "permazen-kv/src/main/java/io/permazen/kv/KVPair.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "297472"
},
{
"name": "HTML",
"bytes": "36524914"
},
{
"name": "Java",
"bytes": "5423144"
},
{
"name": "JavaScript",
"bytes": "827"
}
],
"symlink_target": ""
} |
package com.nice.czp.htmlsocket.push.ws.itf;
import java.util.Map;
public interface IWebsocket {
/**
* 1000 indicates a normal closure, meaning that the purpose for which the
* connection was established has been fulfilled.
* <p>
* See <a href="https://tools.ietf.org/html/rfc6455#section-7.4.1">RFC 6455,
* Section 7.4.1 Defined Status Codes</a>.
*/
public final static int NORMAL = 1000;
/**
* 1001 indicates that an endpoint is "going away", such as a server going
* down or a browser having navigated away from a page.
* <p>
* See <a href="https://tools.ietf.org/html/rfc6455#section-7.4.1">RFC 6455,
* Section 7.4.1 Defined Status Codes</a>.
*/
public final static int SHUTDOWN = 1001;
/**
* 1002 indicates that an endpoint is terminating the connection due to a
* protocol error.
* <p>
* See <a href="https://tools.ietf.org/html/rfc6455#section-7.4.1">RFC 6455,
* Section 7.4.1 Defined Status Codes</a>.
*/
public final static int PROTOCOL = 1002;
/**
* 1003 indicates that an endpoint is terminating the connection because it
* has received a type of data it cannot accept (e.g., an endpoint that
* understands only text data MAY send this if it receives a binary
* message).
* <p>
* See <a href="https://tools.ietf.org/html/rfc6455#section-7.4.1">RFC 6455,
* Section 7.4.1 Defined Status Codes</a>.
*/
public final static int BAD_DATA = 1003;
/**
* Reserved. The specific meaning might be defined in the future.
* <p>
* See <a href="https://tools.ietf.org/html/rfc6455#section-7.4.1">RFC 6455,
* Section 7.4.1 Defined Status Codes</a>.
*/
public final static int UNDEFINED = 1004;
/**
* 1005 is a reserved value and MUST NOT be set as a status code in a Close
* control frame by an endpoint. It is designated for use in applications
* expecting a status code to indicate that no status code was actually
* present.
* <p>
* See <a href="https://tools.ietf.org/html/rfc6455#section-7.4.1">RFC 6455,
* Section 7.4.1 Defined Status Codes</a>.
*/
public final static int NO_CODE = 1005;
/**
* 1006 is a reserved value and MUST NOT be set as a status code in a Close
* control frame by an endpoint. It is designated for use in applications
* expecting a status code to indicate that the connection was closed
* abnormally, e.g., without sending or receiving a Close control frame.
* <p>
* See <a href="https://tools.ietf.org/html/rfc6455#section-7.4.1">RFC 6455,
* Section 7.4.1 Defined Status Codes</a>.
*/
public final static int NO_CLOSE = 1006;
/**
* 1007 indicates that an endpoint is terminating the connection because it
* has received data within a message that was not consistent with the type
* of the message (e.g., non-UTF-8 [<a
* href="https://tools.ietf.org/html/rfc3629">RFC3629</a>] data within a
* text message).
* <p>
* See <a href="https://tools.ietf.org/html/rfc6455#section-7.4.1">RFC 6455,
* Section 7.4.1 Defined Status Codes</a>.
*/
public final static int BAD_PAYLOAD = 1007;
/**
* 1008 indicates that an endpoint is terminating the connection because it
* has received a message that violates its policy. This is a generic status
* code that can be returned when there is no other more suitable status
* code (e.g., 1003 or 1009) or if there is a need to hide specific details
* about the policy.
* <p>
* See <a href="https://tools.ietf.org/html/rfc6455#section-7.4.1">RFC 6455,
* Section 7.4.1 Defined Status Codes</a>.
*/
public final static int POLICY_VIOLATION = 1008;
/**
* 1009 indicates that an endpoint is terminating the connection because it
* has received a message that is too big for it to process.
* <p>
* See <a href="https://tools.ietf.org/html/rfc6455#section-7.4.1">RFC 6455,
* Section 7.4.1 Defined Status Codes</a>.
*/
public final static int MSG_TOO_LARGE = 1009;
/**
* 1010 indicates that an endpoint (client) is terminating the connection
* because it has expected the server to negotiate one or more extension,
* but the server didn't return them in the response message of the
* WebSocket handshake. The list of extensions that are needed SHOULD appear
* in the /reason/ part of the Close frame. Note that this status code is
* not used by the server, because it can fail the WebSocket handshake
* instead.
* <p>
* See <a href="https://tools.ietf.org/html/rfc6455#section-7.4.1">RFC 6455,
* Section 7.4.1 Defined Status Codes</a>.
*/
public final static int REQUIRED_EXTENSION = 1010;
/**
* 1011 indicates that a server is terminating the connection because it
* encountered an unexpected condition that prevented it from fulfilling the
* request.
* <p>
* See <a href="https://tools.ietf.org/html/rfc6455#section-7.4.1">RFC 6455,
* Section 7.4.1 Defined Status Codes</a>.
*/
public final static int SERVER_ERROR = 1011;
/**
* 1012 indicates that the service is restarted. a client may reconnect, and
* if it chooses to do, should reconnect using a randomized delay of 5 -
* 30s.
* <p>
* See <a
* href="https://www.ietf.org/mail-archive/web/hybi/current/msg09649.html"
* >[hybi] Additional WebSocket Close Error Codes</a>
*/
public final static int SERVICE_RESTART = 1012;
/**
* 1013 indicates that the service is experiencing overload. a client should
* only connect to a different IP (when there are multiple for the target)
* or reconnect to the same IP upon user action.
* <p>
* See <a
* href="https://www.ietf.org/mail-archive/web/hybi/current/msg09649.html"
* >[hybi] Additional WebSocket Close Error Codes</a>
*/
public final static int TRY_AGAIN_LATER = 1013;
/**
* 1015 is a reserved value and MUST NOT be set as a status code in a Close
* control frame by an endpoint. It is designated for use in applications
* expecting a status code to indicate that the connection was closed due to
* a failure to perform a TLS handshake (e.g., the server certificate can't
* be verified).
* <p>
* See <a href="https://tools.ietf.org/html/rfc6455#section-7.4.1">RFC 6455,
* Section 7.4.1 Defined Status Codes</a>.
*/
public final static int FAILED_TLS_HANDSHAKE = 1015;
public static final String SERVER_KEY_HASH = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
public static final String SEC_WS_KEY_HEADER = "Sec-WebSocket-Key";
public static final String SEC_WS_VERSION = "Sec-WebSocket-Version";
public static final String SERVER_NAME = "HtmlSocket Server 1.0";
public static final int MASK_SIZE = 4;
public IWSCodec getCodec();
public void send(Object message);
public String getRemoteAddress();
public void close(int code, String info);
public void onDisconnect(int code, String info);
public void onConnected(Map<String, String[]> params);
public void dipatchMessage(WSMessage message);
public boolean addListener(WSListener listener);
}
| {
"content_hash": "b4c85630577946791135be8c4446f0db",
"timestamp": "",
"source": "github",
"line_count": 187,
"max_line_length": 85,
"avg_line_length": 37.80748663101604,
"alnum_prop": 0.6858557284299859,
"repo_name": "coderczp/HtmlSocket",
"id": "c4db06d46dd91c452d299cc5f3ffe00e7d1965a6",
"size": "7070",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/nice/czp/htmlsocket/push/ws/itf/IWebsocket.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "9899"
},
{
"name": "Java",
"bytes": "80925"
},
{
"name": "JavaScript",
"bytes": "11881"
}
],
"symlink_target": ""
} |
import sys
import os
import string
import argparse
import logging
from math import ceil
from getpass import getpass
from PyQt5.QtWidgets import (
QWidget,
QToolTip,
QPushButton,
QApplication,
QLineEdit, QFileDialog, QMessageBox, QLabel)
log = logging.getLogger(__name__)
logging.basicConfig(
format='%(levelname)s: %(name)s:%(lineno)s: %(message)s',
stream=sys.stdout,
level=logging.ERROR,
)
class Encryption(object):
alphabet = "".join(chr(x) for x in range(128))
data = None
key = ''
extra_chars = ''
def __init__(self, file_path, password):
self.file_path = file_path
self.password = password
def read(self):
log.info("Reading file: %r", self.file_path)
with open(self.file_path, 'r') as file:
self.data = file.read()
log.debug("Data: %s", self.data)
def save(self, postfix=""):
log.info("Saving file: %r", self.file_path + postfix)
with open(self.file_path + postfix, 'w+') as file:
file.seek(0)
file.write(self.data)
log.debug("Data: %s", self.data)
def get_blocks(self, blocks_amount, block_size):
log.info("Preparing blocks.")
log.debug(
"Splitting data to %d blocks with size of %d characters",
blocks_amount, block_size
)
blocks = []
for i in range(blocks_amount):
chunk = self.data[i*block_size:(i+1)*block_size]
# Last block will be filled in with first letters
if len(chunk) < block_size:
missing_chars = '.' * (block_size - len(chunk))
log.debug(
"Filling in last block with characters: %s",
missing_chars
)
chunk += missing_chars
blocks.append(chunk)
log.debug("Blocks: \n%s", '\n'.join(blocks))
return blocks
def make_permutation(self):
log.info("Making permutation.")
data_length, blocks_amount = len(self.data), len(self.password)
block_size = int(ceil(data_length / blocks_amount))
blocks = self.get_blocks(blocks_amount, block_size)
new_data = ''
for idx in range(block_size):
for block in blocks:
new_data += block[idx]
self.data = new_data
log.debug("New data: %s", self.data)
def revert_permutation(self):
log.info("Reverting permutation.")
block_size = len(self.password)
blocks_amount = int(ceil(len(self.data) / block_size))
blocks = self.get_blocks(blocks_amount, block_size)
new_data = ''
for idx in range(block_size):
for block in blocks:
if block[idx] != '.':
new_data += block[idx]
self.data = new_data
log.debug("New data: %s", self.data)
def generate_key(self):
log.info("Generating key.")
data_length = len(self.data)
repeat_times = int(ceil(data_length / len(self.password)))
log.debug("Data length: %s", data_length)
for idx in range(0, repeat_times + 1):
for letter in self.password:
new_letter_idx = self.alphabet.index(letter) + idx**2
new_letter_idx %= len(self.alphabet)
self.key += self.alphabet[new_letter_idx]
self.key = self.key[:data_length]
log.debug("Key length: %r", len(self.key))
log.debug("Using key: %r", self.key)
def make_polymorphism(self):
log.info("Polymorphism.")
data_indexes = [
self.alphabet.index(letter)
for letter in self.data
]
log.debug("Data indexes: %s", data_indexes)
key_indexes = [
self.alphabet.index(letter)
for letter in self.key
]
log.debug("Key indexes: %s", key_indexes)
sum_indexes = [
data_indexes[i] + key_indexes[i]
for i in range(len(self.data))
]
log.debug("New data indexes: %s", sum_indexes)
alphabet_length = len(self.alphabet)
self.data = ''.join(
self.alphabet[idx % alphabet_length]
for idx in sum_indexes
)
log.debug("New data: %s", self.data)
def revert_polymorphism(self):
log.info("Polymorphism. Data: %r", self.data)
data_indexes = [
self.alphabet.index(letter)
for letter in self.data
]
log.debug("Data indexes: %s", data_indexes)
key_indexes = [
self.alphabet.index(letter)
for letter in self.key
]
log.debug("Key indexes: %s", key_indexes)
sum_indexes = [
data_indexes[i] - key_indexes[i]
for i in range(len(self.data))
]
log.debug("New data indexes: %s", sum_indexes)
alphabet_length = len(self.alphabet)
self.data = ''.join(
self.alphabet[idx if idx < alphabet_length else alphabet_length - idx]
for idx in sum_indexes
)
log.debug("New data: %s", self.data)
def encode(self):
self.read()
self.make_permutation()
self.generate_key()
self.make_polymorphism()
os.remove(self.file_path)
self.save()
def decode(self):
self.read()
self.generate_key()
self.revert_polymorphism()
self.revert_permutation()
self.save(postfix='-decrypted')
class Example(QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
input_label = QLabel("Select file path", self)
input_label.move(50, 25)
self.input_filepath = QLineEdit(self)
self.input_filepath.move(50, 50)
self.input_filepath.setReadOnly(True)
self.input_filepath.resize(225, 20)
btn_upload = QPushButton('Select', self)
btn_upload.move(285, 45)
btn_upload.clicked.connect(self.handle_upload)
input_label = QLabel("Insert your password", self)
input_label.move(50, 80)
self.input_pwd = QLineEdit(self)
self.input_pwd.setEchoMode(QLineEdit.Password)
self.input_pwd.move(50, 105)
self.input_pwd.resize(225, 20)
btn = QPushButton('Encryption', self)
btn.move(175, 150)
btn.clicked.connect(self.handle_encode)
btn = QPushButton('Decryption', self)
btn.clicked.connect(self.handle_decode)
btn.move(50, 150)
btn = QPushButton('Info', self)
btn.clicked.connect(self.handle_info)
btn.move(300, 150)
self.setGeometry(500, 500, 400, 220)
self.setWindowTitle('Code')
self.show()
def validate_inputs(self):
if not self.input_filepath.text() or not self.input_pwd.text():
msg = QMessageBox(self)
msg.setIcon(QMessageBox.Warning)
msg.setText("You should provide file path and password.")
msg.setWindowTitle("Validation")
msg.exec_()
return False
return True
def handle_encode(self):
if self.validate_inputs():
enc = Encryption(
self.input_filepath.text(),
self.input_pwd.text()
)
enc.encode()
self.input_pwd.setText("")
self.input_filepath.setText("")
msg = QMessageBox(self)
msg.setIcon(QMessageBox.Information)
msg.setText("File encrypted")
msg.setWindowTitle("Encryption")
msg.exec_()
def handle_decode(self):
if self.validate_inputs():
enc = Encryption(
self.input_filepath.text(),
self.input_pwd.text()
)
enc.decode()
self.input_pwd.setText("")
self.input_filepath.setText("")
msg = QMessageBox(self)
msg.setIcon(QMessageBox.Information)
msg.setText("File decrypted")
msg.setWindowTitle("Decryption")
msg.exec_()
def handle_info(self):
msg = QMessageBox(self)
msg.setIcon(QMessageBox.Information)
msg.setText(
"1. Decoded or Encoded file is saved in the same directory as you select file.\n"
"2. Newly created file has '-decoded' or '-encoded' prefix.\n"
"3. Key should be non empty ascii value.\n"
)
msg.setWindowTitle("Info")
msg.exec_()
def handle_upload(self):
filename = QFileDialog.getOpenFileName(
self, "File", "."
)
if filename[0]:
self.input_filepath.setText(filename[0])
log.debug('Path file :', filename)
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
app.exec_()
| {
"content_hash": "8fc93ce0696680cf0f7ca754bd0a7de8",
"timestamp": "",
"source": "github",
"line_count": 310,
"max_line_length": 93,
"avg_line_length": 28.825806451612902,
"alnum_prop": 0.5525962399283796,
"repo_name": "novirael/school-codebase",
"id": "153702c51aa73ee0ba8df821580ad711f6551c9e",
"size": "8956",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "code/encryption.py",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "23375"
},
{
"name": "CMake",
"bytes": "204"
},
{
"name": "HTML",
"bytes": "13499"
},
{
"name": "Java",
"bytes": "125155"
},
{
"name": "JavaScript",
"bytes": "4483"
},
{
"name": "OCaml",
"bytes": "4896"
},
{
"name": "Python",
"bytes": "18679"
}
],
"symlink_target": ""
} |
namespace pik {
double Now() {
#if OS_WIN
LARGE_INTEGER counter;
(void)QueryPerformanceCounter(&counter);
LARGE_INTEGER freq;
(void)QueryPerformanceFrequency(&freq);
return double(counter.QuadPart) / freq.QuadPart;
#elif OS_MAC
const auto t = mach_absolute_time();
// On OSX/iOS platform the elapsed time is cpu time unit
// We have to query the time base information to convert it back
// See https://developer.apple.com/library/mac/qa/qa1398/_index.html
static mach_timebase_info_data_t timebase;
if (timebase.denom == 0) {
(void)mach_timebase_info(&timebase);
}
return double(t) * timebase.numer / timebase.denom * 1E-9;
#else
timespec t;
clock_gettime(CLOCK_MONOTONIC, &t);
return t.tv_sec + t.tv_nsec * 1E-9;
#endif
}
struct ThreadAffinity {
#if OS_WIN
DWORD_PTR mask;
#elif OS_LINUX
cpu_set_t set;
#elif OS_FREEBSD
cpuset_t set;
#endif
};
ThreadAffinity* GetThreadAffinity() {
ThreadAffinity* affinity =
static_cast<ThreadAffinity*>(malloc(sizeof(ThreadAffinity)));
#if OS_WIN
DWORD_PTR system_affinity;
const BOOL ok = GetProcessAffinityMask(GetCurrentProcess(), &affinity->mask,
&system_affinity);
PIK_CHECK(ok);
#elif OS_LINUX
const pid_t pid = 0; // current thread
const int err = sched_getaffinity(pid, sizeof(cpu_set_t), &affinity->set);
PIK_CHECK(err == 0);
#elif OS_FREEBSD
const pid_t pid = getpid(); // current thread
const int err = cpuset_getaffinity(CPU_LEVEL_WHICH, CPU_WHICH_PID, pid,
sizeof(cpuset_t), &affinity->set);
PIK_CHECK(err == 0);
#endif
return affinity;
}
namespace {
ThreadAffinity* OriginalThreadAffinity() {
static ThreadAffinity* original = GetThreadAffinity();
return original;
}
} // namespace
Status SetThreadAffinity(ThreadAffinity* affinity) {
// Ensure original is initialized before changing.
const ThreadAffinity* const original = OriginalThreadAffinity();
PIK_CHECK(original != nullptr);
#if OS_WIN
const HANDLE hThread = GetCurrentThread();
const DWORD_PTR prev = SetThreadAffinityMask(hThread, affinity->mask);
if (prev == 0) return PIK_FAILURE("SetThreadAffinityMask failed");
#elif OS_LINUX
const pid_t pid = 0; // current thread
const int err = sched_setaffinity(pid, sizeof(cpu_set_t), &affinity->set);
if (err != 0) return PIK_FAILURE("sched_setaffinity failed");
#elif OS_FREEBSD
const pid_t pid = getpid(); // current thread
const int err = cpuset_setaffinity(CPU_LEVEL_WHICH, CPU_WHICH_PID, pid,
sizeof(cpuset_t), &affinity->set);
if (err != 0) return PIK_FAILURE("cpuset_setaffinity failed");
#else
printf("Don't know how to SetThreadAffinity on this platform.\n");
return false;
#endif
return true;
}
std::vector<int> AvailableCPUs() {
std::vector<int> cpus;
cpus.reserve(64);
#if OS_WIN
const ThreadAffinity* const affinity = OriginalThreadAffinity();
for (int cpu = 0; cpu < 64; ++cpu) {
if (affinity->mask & (1ULL << cpu)) {
cpus.push_back(cpu);
}
}
#elif OS_LINUX
const ThreadAffinity* const affinity = OriginalThreadAffinity();
for (size_t cpu = 0; cpu < sizeof(cpu_set_t) * 8; ++cpu) {
if (CPU_ISSET(cpu, &affinity->set)) {
cpus.push_back(cpu);
}
}
#elif OS_FREEBSD
const ThreadAffinity* const affinity = OriginalThreadAffinity();
for (size_t cpu = 0; cpu < sizeof(cpuset_t) * 8; ++cpu) {
if (CPU_ISSET(cpu, &affinity->set)) {
cpus.push_back(cpu);
}
}
#else
cpus.push_back(0);
#endif
return cpus;
}
Status PinThreadToCPU(const int cpu) {
ThreadAffinity affinity;
#if OS_WIN
affinity.mask = 1ULL << cpu;
#elif OS_LINUX
CPU_ZERO(&affinity.set);
CPU_SET(cpu, &affinity.set);
#elif OS_FREEBSD
CPU_ZERO(&affinity.set);
CPU_SET(cpu, &affinity.set);
#endif
return SetThreadAffinity(&affinity);
}
Status PinThreadToRandomCPU() {
std::vector<int> cpus = AvailableCPUs();
// Remove first two CPUs because interrupts are often pinned to them.
PIK_CHECK(cpus.size() > 2);
cpus.erase(cpus.begin(), cpus.begin() + 2);
// Random choice to prevent burning up the same core.
std::random_device device;
std::ranlux48 generator(device());
std::shuffle(cpus.begin(), cpus.end(), generator);
const int cpu = cpus.front();
PIK_RETURN_IF_ERROR(PinThreadToCPU(cpu));
// After setting affinity, we should be running on the desired CPU.
#if PIK_ARCH_X64
printf("Running on CPU #%d, APIC ID %02x\n", cpu, ApicId());
#else
printf("Running on CPU #%d\n", cpu);
#endif
return true;
}
Status RunCommand(const std::vector<std::string>& args) {
#if _POSIX_VERSION >= 200112L
// Avoid system(), but do not try to be over-zealous about not passing along
// some special resources further (such as: inherited-not-marked-FD_CLOEXEC
// file descriptors).
std::vector<const char*> c_args;
c_args.reserve(args.size() + 1);
for (size_t i = 0; i < args.size(); ++i) {
c_args.push_back(args[i].c_str());
}
c_args.push_back(nullptr);
const pid_t pid = fork();
if (pid == -1) // fork() failed.
return false;
if (pid != 0) { // Parent process.
int ret_status;
if (pid != waitpid(pid, &ret_status, 0)) {
return false; // waitpid() error.
}
return ret_status == 0;
} else { // Child process.
execvp(c_args[0],
// Address benign-but-annoying execvp() signature weirdness.
const_cast<char * const *>(c_args.data()));
fprintf(stderr, "execvp() failed. Exiting child process.\n");
exit(EXIT_FAILURE);
}
#elif OS_WIN
// Synthesize a string for system(). And warn about it.
// TODO(user): Fix this - research the safe way to run a command on Windows.
// Likely, the solution is along these lines:
// https://docs.microsoft.com/en-us/windows/desktop/ProcThread/creating-processes
std::ostringstream cmd;
std::copy(args.begin(), args.end(),
std::ostream_iterator<std::string>(cmd, " "));
printf(stderr, "Warning: Using system() on string: %s\n", cmd.str.c_str());
int ret = system(cmd.str.c_str());
if (errno != ENOENT && // Windows: Command interpreter not found.
ret == 0) {
return true;
}
return false;
#else
#error Neither a POSIX-1.2001 nor a Windows System.
#endif
}
} // namespace pik
| {
"content_hash": "df97e633145bcd1ea6038f0a38537d51",
"timestamp": "",
"source": "github",
"line_count": 208,
"max_line_length": 83,
"avg_line_length": 30.240384615384617,
"alnum_prop": 0.660731319554849,
"repo_name": "google/pik",
"id": "06c4683f2826ff6be85bca8e34b157a618bc1c2e",
"size": "7411",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pik/os_specific.cc",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "14059"
},
{
"name": "C++",
"bytes": "2611904"
},
{
"name": "CMake",
"bytes": "17318"
},
{
"name": "Makefile",
"bytes": "8313"
}
],
"symlink_target": ""
} |
package com.amazonaws.services.kinesisfirehose.model.transform;
import java.util.Map;
import java.util.Map.Entry;
import com.amazonaws.services.kinesisfirehose.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* UpdateDestinationResult JSON Unmarshaller
*/
public class UpdateDestinationResultJsonUnmarshaller implements
Unmarshaller<UpdateDestinationResult, JsonUnmarshallerContext> {
public UpdateDestinationResult unmarshall(JsonUnmarshallerContext context)
throws Exception {
UpdateDestinationResult updateDestinationResult = new UpdateDestinationResult();
return updateDestinationResult;
}
private static UpdateDestinationResultJsonUnmarshaller instance;
public static UpdateDestinationResultJsonUnmarshaller getInstance() {
if (instance == null)
instance = new UpdateDestinationResultJsonUnmarshaller();
return instance;
}
}
| {
"content_hash": "9b91630f69389500a5ab552f33365606",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 88,
"avg_line_length": 31,
"alnum_prop": 0.7797235023041474,
"repo_name": "dump247/aws-sdk-java",
"id": "58364a0c8300c26e0d202880e74be9525e6df045",
"size": "1672",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "aws-java-sdk-kinesis/src/main/java/com/amazonaws/services/kinesisfirehose/model/transform/UpdateDestinationResultJsonUnmarshaller.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "FreeMarker",
"bytes": "117958"
},
{
"name": "Java",
"bytes": "104374753"
},
{
"name": "Scilab",
"bytes": "3375"
}
],
"symlink_target": ""
} |
<?php
use yii\db\Migration;
/**
* Handles the creation for table `company`.
*/
class m160816_090802_create_company_table extends Migration
{
/**
* @inheritdoc
*/
public function up()
{
$this->createTable('company', [
'id' => $this->primaryKey(),
'user_id' => $this->integer()->notNull(),
'type' => $this->smallInteger()->notNull(),
'domain' => $this->string(),
'logo' => $this->string(),
'name' => $this->string()->notNull(),
'name_short' => $this->string()->notNull(),
'description' => $this->string(),
'text' => $this->string(),
'website' => $this->string()
]);
$this->addForeignKey('fk-company-user_id', 'company', 'user_id', 'user', 'id', 'CASCADE');
}
/**
* @inheritdoc
*/
public function down()
{
$this->dropForeignKey('fk-company-user_id', 'company');
$this->dropTable('company');
}
}
| {
"content_hash": "b7baf84e44486abda41a789db814d4dc",
"timestamp": "",
"source": "github",
"line_count": 40,
"max_line_length": 98,
"avg_line_length": 25.275,
"alnum_prop": 0.4896142433234421,
"repo_name": "dench/webportal",
"id": "c6c04fdaf21d0acdc253e2e1b4b1962f13efa421",
"size": "1011",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "migrations/m160816_090802_create_company_table.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "1026"
},
{
"name": "CSS",
"bytes": "50586"
},
{
"name": "PHP",
"bytes": "296006"
}
],
"symlink_target": ""
} |
#include "base/macros.h"
#include "base/logging.h"
#include "compiler_driver.h"
#include "system_load_metric.h"
namespace art {
const char* InstantLoadMetric::kLoadavgFilename = "/proc/loadavg";
ThreadNumberAction InstantLoadMetric::GetAction(size_t working_tasks_count ATTRIBUTE_UNUSED,
size_t active_working_tasks_count) {
int32_t threads_in_queue = GetQueueLength();
double other_threads = threads_in_queue - static_cast<int32_t>(active_working_tasks_count);
double active_tasks_target = work_units_ - other_threads;
active_tasks_virtual_ += (active_tasks_target - active_tasks_virtual_) *
kReactionFactor * GetUpdateIntervalMs() / 1000;
active_tasks_virtual_ = std::max(active_tasks_virtual_, 1.0);
active_tasks_virtual_ = std::min(active_tasks_virtual_, static_cast<double>(work_units_));
size_t active_tasks_virtual_rounded = static_cast<size_t>(round(active_tasks_virtual_));
if (active_tasks_virtual_rounded == active_working_tasks_count) {
return kDoNotChangeThreadNumber;
} else if (active_tasks_virtual_rounded > active_working_tasks_count) {
return kIncreaseThreadNumber;
} else {
return kDecreaseThreadNumber;
}
}
bool InstantLoadMetric::Initialize() {
if (!loadavg_file_.is_open()) {
loadavg_file_.open(kLoadavgFilename, std::ios::in);
}
if (!loadavg_file_.is_open()) {
return false;
}
active_tasks_virtual_ = active_tasks_virtual_init_;
return true;
}
int32_t InstantLoadMetric::GetQueueLength() {
DCHECK(loadavg_file_.is_open());
// Shift to file beginning.
loadavg_file_.seekg(0);
// Skip values for average system load for last 1, 5, and 15 minutes.
std::string skip_string;
for (int i = 0; i < 3; i++) {
loadavg_file_ >> skip_string;
}
// Get instant system load.
size_t result = 0;
loadavg_file_ >> result;
DCHECK_GT(result, 0u);
// We should subtract 1 from queue length,
// because the thread that access to this value is always counted in it.
return result - 1;
}
} // namespace art.
| {
"content_hash": "d2df85e05e31a04d2b0561809aa814aa",
"timestamp": "",
"source": "github",
"line_count": 60,
"max_line_length": 93,
"avg_line_length": 34.266666666666666,
"alnum_prop": 0.6877431906614786,
"repo_name": "android-art-intel/marshmallow",
"id": "e568642c19c1504dbdc36c77b0af2765bf5afebf",
"size": "2661",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "art-extension/compiler/driver/system_load_metric.cc",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "505427"
},
{
"name": "C",
"bytes": "57031"
},
{
"name": "C++",
"bytes": "16360103"
},
{
"name": "Java",
"bytes": "7260608"
},
{
"name": "Lex",
"bytes": "1775"
},
{
"name": "Makefile",
"bytes": "178336"
},
{
"name": "Objective-J",
"bytes": "892"
},
{
"name": "Python",
"bytes": "78048"
},
{
"name": "Shell",
"bytes": "742921"
},
{
"name": "Smali",
"bytes": "78883"
}
],
"symlink_target": ""
} |
package com.intellij.util.io;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.LowMemoryWatcher;
import com.intellij.openapi.util.ThreadLocalCachedValue;
import com.intellij.openapi.util.io.BufferExposingByteArrayOutputStream;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.*;
import com.intellij.util.containers.LimitedPool;
import com.intellij.util.containers.SLRUCache;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
import java.io.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
* @author Eugene Zhuravlev
*/
public class PersistentHashMap<Key, Value> extends PersistentEnumeratorDelegate<Key> implements PersistentMap<Key, Value> {
// PersistentHashMap (PHM) works in the following (generic) way:
// - Particular key is translated via myEnumerator into an int.
// - As part of enumeration process for the new key, additional space is reserved in
// myEnumerator.myStorage for offset in ".values" file (myValueStorage) where (serialized) value is stored.
// - Once new value is written the offset storage is updated.
// - When the key is removed from PHM, offset storage is set to zero.
//
// It is important to note that offset
// is non-negative and can be 4 or 8 bytes, depending on the size of the ".values" file.
// PHM can work in appendable mode: for particular key additional calculated chunk of value can be appended to ".values" file with the offset
// of previously calculated chunk.
// For performance reasons we try hard to minimize storage occupied by keys / offsets in ".values" file: this storage is allocated as (limited)
// direct byte buffers so 4 bytes offset is used until it is possible. Generic record produced by enumerator used with PHM as part of new
// key enumeration is <enumerated_id>? [.values file offset 4 or 8 bytes], however for unique integral keys enumerate_id isn't produced.
// Also for certain Value types it is possible to avoid random reads at all: e.g. in case Value is non-negative integer the value can be stored
// directly in storage used for offset and in case of btree enumerator directly in btree leaf.
private static final Logger LOG = Logger.getInstance("#com.intellij.util.io.PersistentHashMap");
private static final boolean myDoTrace = SystemProperties.getBooleanProperty("idea.trace.persistent.map", false);
private static final int DEAD_KEY_NUMBER_MASK = 0xFFFFFFFF;
private final File myStorageFile;
private final boolean myIsReadOnly;
private final KeyDescriptor<Key> myKeyDescriptor;
private PersistentHashMapValueStorage myValueStorage;
protected final DataExternalizer<Value> myValueExternalizer;
private static final long NULL_ADDR = 0;
private static final int INITIAL_INDEX_SIZE;
static {
String property = System.getProperty("idea.initialIndexSize");
INITIAL_INDEX_SIZE = property == null ? 4 * 1024 : Integer.valueOf(property);
}
@NonNls
static final String DATA_FILE_EXTENSION = ".values";
private long myLiveAndGarbageKeysCounter;
// first four bytes contain live keys count (updated via LIVE_KEY_MASK), last four bytes - number of dead keys
private int myReadCompactionGarbageSize;
private static final long LIVE_KEY_MASK = 1L << 32;
private static final long USED_LONG_VALUE_MASK = 1L << 62;
private static final int POSITIVE_VALUE_SHIFT = 1;
private final int myParentValueRefOffset;
@NotNull private final byte[] myRecordBuffer;
@NotNull private final byte[] mySmallRecordBuffer;
private final boolean myIntMapping;
private final boolean myDirectlyStoreLongFileOffsetMode;
private final boolean myCanReEnumerate;
private int myLargeIndexWatermarkId; // starting with this id we store offset in adjacent file in long format
private boolean myIntAddressForNewRecord;
private static final boolean doHardConsistencyChecks = false;
private volatile boolean myBusyReading;
private static class AppendStream extends DataOutputStream {
private AppendStream() {
super(null);
}
private void setOut(BufferExposingByteArrayOutputStream stream) {
out = stream;
}
}
private final LimitedPool<BufferExposingByteArrayOutputStream> myStreamPool =
new LimitedPool<BufferExposingByteArrayOutputStream>(10, new LimitedPool.ObjectFactory<BufferExposingByteArrayOutputStream>() {
@Override
@NotNull
public BufferExposingByteArrayOutputStream create() {
return new BufferExposingByteArrayOutputStream();
}
@Override
public void cleanup(@NotNull final BufferExposingByteArrayOutputStream appendStream) {
appendStream.reset();
}
});
private final SLRUCache<Key, BufferExposingByteArrayOutputStream> myAppendCache;
private boolean canUseIntAddressForNewRecord(long size) {
return myCanReEnumerate && size + POSITIVE_VALUE_SHIFT < Integer.MAX_VALUE;
}
private final LowMemoryWatcher myAppendCacheFlusher = LowMemoryWatcher.register(new Runnable() {
@Override
public void run() {
dropMemoryCaches();
}
});
public PersistentHashMap(@NotNull final File file,
@NotNull KeyDescriptor<Key> keyDescriptor,
@NotNull DataExternalizer<Value> valueExternalizer) throws IOException {
this(file, keyDescriptor, valueExternalizer, INITIAL_INDEX_SIZE);
}
public PersistentHashMap(@NotNull final File file,
@NotNull KeyDescriptor<Key> keyDescriptor,
@NotNull DataExternalizer<Value> valueExternalizer,
final int initialSize) throws IOException {
this(file, keyDescriptor, valueExternalizer, initialSize, 0);
}
public PersistentHashMap(@NotNull final File file,
@NotNull KeyDescriptor<Key> keyDescriptor,
@NotNull DataExternalizer<Value> valueExternalizer,
final int initialSize,
int version) throws IOException {
this(file, keyDescriptor, valueExternalizer, initialSize, version, null);
}
public PersistentHashMap(@NotNull final File file,
@NotNull KeyDescriptor<Key> keyDescriptor,
@NotNull DataExternalizer<Value> valueExternalizer,
final int initialSize,
int version,
@Nullable PagedFileStorage.StorageLockContext lockContext) throws IOException {
this(file, keyDescriptor, valueExternalizer, initialSize, version, lockContext,
PersistentHashMapValueStorage.CreationTimeOptions.threadLocalOptions());
}
private PersistentHashMap(@NotNull final File file,
@NotNull KeyDescriptor<Key> keyDescriptor,
@NotNull DataExternalizer<Value> valueExternalizer,
final int initialSize,
int version,
@Nullable PagedFileStorage.StorageLockContext lockContext,
@NotNull PersistentHashMapValueStorage.CreationTimeOptions options) throws IOException {
super(checkDataFiles(file), keyDescriptor, initialSize, lockContext, modifyVersionDependingOnOptions(version, options));
myStorageFile = file;
myKeyDescriptor = keyDescriptor;
myIsReadOnly = isReadOnly();
if (myIsReadOnly) options = options.setReadOnly();
myAppendCache = createAppendCache(keyDescriptor);
final PersistentEnumeratorBase.RecordBufferHandler<PersistentEnumeratorBase> recordHandler = myEnumerator.getRecordHandler();
myParentValueRefOffset = recordHandler.getRecordBuffer(myEnumerator).length;
myIntMapping = valueExternalizer instanceof IntInlineKeyDescriptor && wantNonNegativeIntegralValues();
myDirectlyStoreLongFileOffsetMode = keyDescriptor instanceof InlineKeyDescriptor && myEnumerator instanceof PersistentBTreeEnumerator;
myRecordBuffer = myDirectlyStoreLongFileOffsetMode ? ArrayUtil.EMPTY_BYTE_ARRAY : new byte[myParentValueRefOffset + 8];
mySmallRecordBuffer = myDirectlyStoreLongFileOffsetMode ? ArrayUtil.EMPTY_BYTE_ARRAY : new byte[myParentValueRefOffset + 4];
myEnumerator.setRecordHandler(new PersistentEnumeratorBase.RecordBufferHandler<PersistentEnumeratorBase>() {
@Override
int recordWriteOffset(PersistentEnumeratorBase enumerator, byte[] buf) {
return recordHandler.recordWriteOffset(enumerator, buf);
}
@NotNull
@Override
byte[] getRecordBuffer(PersistentEnumeratorBase enumerator) {
return myIntAddressForNewRecord ? mySmallRecordBuffer : myRecordBuffer;
}
@Override
void setupRecord(PersistentEnumeratorBase enumerator, int hashCode, int dataOffset, @NotNull byte[] buf) {
recordHandler.setupRecord(enumerator, hashCode, dataOffset, buf);
for (int i = myParentValueRefOffset; i < buf.length; i++) {
buf[i] = 0;
}
}
});
myEnumerator.setMarkCleanCallback(
new Flushable() {
@Override
public void flush() {
myEnumerator.putMetaData(myLiveAndGarbageKeysCounter);
myEnumerator.putMetaData2(myLargeIndexWatermarkId | ((long)myReadCompactionGarbageSize << 32));
}
}
);
if (myDoTrace) LOG.info("Opened " + file);
try {
myValueExternalizer = valueExternalizer;
myValueStorage = PersistentHashMapValueStorage.create(getDataFile(file).getPath(), options);
myLiveAndGarbageKeysCounter = myEnumerator.getMetaData();
long data2 = myEnumerator.getMetaData2();
myLargeIndexWatermarkId = (int)(data2 & DEAD_KEY_NUMBER_MASK);
myReadCompactionGarbageSize = (int)(data2 >>> 32);
myCanReEnumerate = myEnumerator.canReEnumerate();
if (makesSenseToCompact()) {
compact();
}
}
catch (IOException e) {
try {
// attempt to close already opened resources
close();
}
catch (Throwable ignored) {
}
throw e; // rethrow
}
catch (Throwable t) {
LOG.error(t);
try {
// attempt to close already opened resources
close();
}
catch (Throwable ignored) {
}
throw new PersistentEnumerator.CorruptedException(file);
}
}
private static int modifyVersionDependingOnOptions(int version, @NotNull PersistentHashMapValueStorage.CreationTimeOptions options) {
return version + options.getVersion();
}
protected boolean wantNonNegativeIntegralValues() {
return false;
}
protected boolean isReadOnly() {
return false;
}
private SLRUCache<Key, BufferExposingByteArrayOutputStream> createAppendCache(final KeyDescriptor<Key> keyDescriptor) {
return new SLRUCache<Key, BufferExposingByteArrayOutputStream>(16 * 1024, 4 * 1024, keyDescriptor) {
@Override
@NotNull
public BufferExposingByteArrayOutputStream createValue(final Key key) {
return myStreamPool.alloc();
}
@Override
protected void onDropFromCache(final Key key, @NotNull final BufferExposingByteArrayOutputStream bytes) {
myEnumerator.lockStorage();
try {
long previousRecord;
final int id;
if (myDirectlyStoreLongFileOffsetMode) {
previousRecord = ((PersistentBTreeEnumerator<Key>)myEnumerator).getNonNegativeValue(key);
id = -1;
}
else {
id = enumerate(key);
previousRecord = readValueId(id);
}
long headerRecord = myValueStorage.appendBytes(bytes.toByteArraySequence(), previousRecord);
if (myDirectlyStoreLongFileOffsetMode) {
((PersistentBTreeEnumerator<Key>)myEnumerator).putNonNegativeValue(key, headerRecord);
}
else {
updateValueId(id, headerRecord, previousRecord, key, 0);
}
if (previousRecord == NULL_ADDR) {
myLiveAndGarbageKeysCounter += LIVE_KEY_MASK;
}
myStreamPool.recycle(bytes);
}
catch (IOException e) {
markCorrupted();
throw new RuntimeException(e);
}
finally {
myEnumerator.unlockStorage();
}
}
};
}
private static boolean doNewCompact() {
return System.getProperty("idea.persistent.hash.map.oldcompact") == null;
}
private boolean forceNewCompact() {
return System.getProperty("idea.persistent.hash.map.newcompact") != null &&
(int)(myLiveAndGarbageKeysCounter & DEAD_KEY_NUMBER_MASK) > 0;
}
public final void dropMemoryCaches() {
if (myDoTrace) LOG.info("Drop memory caches " + myStorageFile);
synchronized (myEnumerator) {
doDropMemoryCaches();
}
}
protected void doDropMemoryCaches() {
myEnumerator.lockStorage();
try {
clearAppenderCaches();
}
finally {
myEnumerator.unlockStorage();
}
}
int getGarbageSize() {
return (int)myLiveAndGarbageKeysCounter;
}
public File getBaseFile() {
return myEnumerator.myFile;
}
@TestOnly // public for tests
@SuppressWarnings("WeakerAccess") // used in upsource for some reason
public boolean makesSenseToCompact() {
if (myIsReadOnly) return false;
final long fileSize = myValueStorage.getSize();
final int megabyte = 1024 * 1024;
if (fileSize > 5 * megabyte) { // file is longer than 5MB and (more than 50% of keys is garbage or approximate benefit larger than 100M)
int liveKeys = (int)(myLiveAndGarbageKeysCounter / LIVE_KEY_MASK);
int deadKeys = (int)(myLiveAndGarbageKeysCounter & DEAD_KEY_NUMBER_MASK);
if (fileSize > 50 * megabyte && forceNewCompact()) return true;
if (deadKeys < 50) return false;
final long benefitSize = Math.max(100 * megabyte, fileSize / 4);
final long avgValueSize = fileSize / (liveKeys + deadKeys);
return deadKeys > liveKeys ||
avgValueSize * deadKeys > benefitSize ||
myReadCompactionGarbageSize > fileSize / 2;
}
return false;
}
@NotNull
private static File checkDataFiles(@NotNull final File file) {
if (!file.exists()) {
deleteFilesStartingWith(getDataFile(file));
}
return file;
}
public static void deleteFilesStartingWith(@NotNull File prefixFile) {
IOUtil.deleteAllFilesStartingWith(prefixFile);
}
@NotNull
static File getDataFile(@NotNull final File file) { // made public for testing
return new File(file.getParentFile(), file.getName() + DATA_FILE_EXTENSION);
}
@Override
public final void put(Key key, Value value) throws IOException {
if (myIsReadOnly) throw new IncorrectOperationException();
synchronized (myEnumerator) {
try {
doPut(key, value);
}
catch (IOException ex) {
myEnumerator.markCorrupted();
throw ex;
}
}
}
protected void doPut(Key key, Value value) throws IOException {
long newValueOffset = -1;
if (!myIntMapping) {
final BufferExposingByteArrayOutputStream bytes = new BufferExposingByteArrayOutputStream();
AppendStream appenderStream = ourFlyweightAppenderStream.getValue();
appenderStream.setOut(bytes);
myValueExternalizer.save(appenderStream, value);
appenderStream.setOut(null);
newValueOffset = myValueStorage.appendBytes(bytes.toByteArraySequence(), 0);
}
myEnumerator.lockStorage();
try {
myEnumerator.markDirty(true);
myAppendCache.remove(key);
long oldValueOffset;
if (myDirectlyStoreLongFileOffsetMode) {
if (myIntMapping) {
((PersistentBTreeEnumerator<Key>)myEnumerator).putNonNegativeValue(key, (Integer)value);
return;
}
oldValueOffset = ((PersistentBTreeEnumerator<Key>)myEnumerator).getNonNegativeValue(key);
((PersistentBTreeEnumerator<Key>)myEnumerator).putNonNegativeValue(key, newValueOffset);
}
else {
final int id = enumerate(key);
if (myIntMapping) {
myEnumerator.myStorage.putInt(id + myParentValueRefOffset, (Integer)value);
return;
}
oldValueOffset = readValueId(id);
updateValueId(id, newValueOffset, oldValueOffset, key, 0);
}
if (oldValueOffset != NULL_ADDR) {
myLiveAndGarbageKeysCounter++;
}
else {
myLiveAndGarbageKeysCounter += LIVE_KEY_MASK;
}
}
finally {
myEnumerator.unlockStorage();
}
}
@Override
public final int enumerate(Key name) throws IOException {
if (myIsReadOnly) throw new IncorrectOperationException();
synchronized (myEnumerator) {
myIntAddressForNewRecord = canUseIntAddressForNewRecord(myValueStorage.getSize());
return super.enumerate(name);
}
}
public interface ValueDataAppender {
void append(DataOutput out) throws IOException;
}
/**
* Appends value chunk from specified appender to key's value.
* Important use note: value externalizer used by this map should process all bytes from DataInput during deserialization and make sure
* that deserialized value is consistent with value chunks appended.
* E.g. Value can be Set of String and individual Strings can be appended with this method for particular key, when {@link #get(Object)} will
* be eventually called for the key, deserializer will read all bytes retrieving Strings and collecting them into Set
*/
public final void appendData(Key key, @NotNull ValueDataAppender appender) throws IOException {
if (myIsReadOnly) throw new IncorrectOperationException();
synchronized (myEnumerator) {
try {
doAppendData(key, appender);
}
catch (IOException ex) {
myEnumerator.markCorrupted();
throw ex;
}
}
}
private static final ThreadLocalCachedValue<AppendStream> ourFlyweightAppenderStream = new ThreadLocalCachedValue<AppendStream>() {
@NotNull
@Override
protected AppendStream create() {
return new AppendStream();
}
};
private void doAppendData(Key key, @NotNull ValueDataAppender appender) throws IOException {
assert !myIntMapping;
myEnumerator.markDirty(true);
AppendStream appenderStream = ourFlyweightAppenderStream.getValue();
BufferExposingByteArrayOutputStream stream = myAppendCache.get(key);
appenderStream.setOut(stream);
myValueStorage.checkAppendsAllowed(stream.size());
appender.append(appenderStream);
appenderStream.setOut(null);
}
/**
* Process all keys registered in the map. Note that keys which were removed after {@link #compact()} call will be processed as well. Use
* {@link #processKeysWithExistingMapping(Processor)} to process only keys with existing mappings
*/
@Override
public final boolean processKeys(@NotNull Processor<? super Key> processor) throws IOException {
synchronized (myEnumerator) {
try {
myAppendCache.clear();
return myEnumerator.iterateData(processor);
}
catch (IOException e) {
myEnumerator.markCorrupted();
throw e;
}
}
}
@NotNull
public Collection<Key> getAllKeysWithExistingMapping() throws IOException {
final List<Key> values = new ArrayList<Key>();
processKeysWithExistingMapping(new CommonProcessors.CollectProcessor<Key>(values));
return values;
}
public final boolean processKeysWithExistingMapping(Processor<? super Key> processor) throws IOException {
synchronized (myEnumerator) {
try {
myAppendCache.clear();
return myEnumerator.processAllDataObject(processor, new PersistentEnumerator.DataFilter() {
@Override
public boolean accept(final int id) {
return readValueId(id) != NULL_ADDR;
}
});
}
catch (IOException e) {
myEnumerator.markCorrupted();
throw e;
}
}
}
@Override
public final Value get(Key key) throws IOException {
synchronized (myEnumerator) {
myBusyReading = true;
try {
return doGet(key);
}
catch (IOException ex) {
myEnumerator.markCorrupted();
throw ex;
}
finally {
myBusyReading = false;
}
}
}
public boolean isBusyReading() {
return myBusyReading;
}
@Nullable
protected Value doGet(Key key) throws IOException {
myEnumerator.lockStorage();
final long valueOffset;
final int id;
try {
myAppendCache.remove(key);
if (myDirectlyStoreLongFileOffsetMode) {
valueOffset = ((PersistentBTreeEnumerator<Key>)myEnumerator).getNonNegativeValue(key);
if (myIntMapping) {
return (Value)(Integer)(int)valueOffset;
}
id = -1;
}
else {
id = tryEnumerate(key);
if (id == PersistentEnumeratorBase.NULL_ID) {
return null;
}
if (myIntMapping) {
return (Value)(Integer)myEnumerator.myStorage.getInt(id + myParentValueRefOffset);
}
valueOffset = readValueId(id);
}
if (valueOffset == NULL_ADDR) {
return null;
}
}
finally {
myEnumerator.unlockStorage();
}
final PersistentHashMapValueStorage.ReadResult readResult = myValueStorage.readBytes(valueOffset);
DataInputStream input = new DataInputStream(new UnsyncByteArrayInputStream(readResult.buffer));
final Value valueRead;
try {
valueRead = myValueExternalizer.read(input);
}
finally {
input.close();
}
if (myValueStorage.performChunksCompaction(readResult.chunksCount, readResult.buffer.length)) {
long newValueOffset = myValueStorage.compactChunks(new ValueDataAppender() {
@Override
public void append(DataOutput out) throws IOException {
myValueExternalizer.save(out, valueRead);
}
}, readResult);
myEnumerator.lockStorage();
try {
myEnumerator.markDirty(true);
if (myDirectlyStoreLongFileOffsetMode) {
((PersistentBTreeEnumerator<Key>)myEnumerator).putNonNegativeValue(key, newValueOffset);
}
else {
updateValueId(id, newValueOffset, valueOffset, key, 0);
}
myLiveAndGarbageKeysCounter++;
myReadCompactionGarbageSize += readResult.buffer.length;
}
finally {
myEnumerator.unlockStorage();
}
}
return valueRead;
}
public final boolean containsMapping(Key key) throws IOException {
synchronized (myEnumerator) {
return doContainsMapping(key);
}
}
private boolean doContainsMapping(Key key) throws IOException {
myEnumerator.lockStorage();
try {
myAppendCache.remove(key);
if (myDirectlyStoreLongFileOffsetMode) {
return ((PersistentBTreeEnumerator<Key>)myEnumerator).getNonNegativeValue(key) != NULL_ADDR;
}
else {
final int id = tryEnumerate(key);
if (id == PersistentEnumeratorBase.NULL_ID) {
return false;
}
if (myIntMapping) return true;
return readValueId(id) != NULL_ADDR;
}
}
finally {
myEnumerator.unlockStorage();
}
}
public final void remove(Key key) throws IOException {
if (myIsReadOnly) throw new IncorrectOperationException();
synchronized (myEnumerator) {
doRemove(key);
}
}
protected void doRemove(Key key) throws IOException {
myEnumerator.lockStorage();
try {
myAppendCache.remove(key);
final long record;
if (myDirectlyStoreLongFileOffsetMode) {
assert !myIntMapping; // removal isn't supported
record = ((PersistentBTreeEnumerator<Key>)myEnumerator).getNonNegativeValue(key);
if (record != NULL_ADDR) {
((PersistentBTreeEnumerator<Key>)myEnumerator).putNonNegativeValue(key, NULL_ADDR);
}
}
else {
final int id = tryEnumerate(key);
if (id == PersistentEnumeratorBase.NULL_ID) {
return;
}
assert !myIntMapping; // removal isn't supported
myEnumerator.markDirty(true);
record = readValueId(id);
updateValueId(id, NULL_ADDR, record, key, 0);
}
if (record != NULL_ADDR) {
myLiveAndGarbageKeysCounter++;
myLiveAndGarbageKeysCounter -= LIVE_KEY_MASK;
}
}
finally {
myEnumerator.unlockStorage();
}
}
@Override
public final void force() {
if (myIsReadOnly) return;
if (myDoTrace) LOG.info("Forcing " + myStorageFile);
synchronized (myEnumerator) {
doForce();
}
}
protected void doForce() {
myEnumerator.lockStorage();
try {
try {
clearAppenderCaches();
}
finally {
super.force();
}
}
finally {
myEnumerator.unlockStorage();
}
}
private void clearAppenderCaches() {
myAppendCache.clear();
myValueStorage.force();
}
@Override
public final void close() throws IOException {
if (myDoTrace) LOG.info("Closed " + myStorageFile);
synchronized (myEnumerator) {
doClose();
}
}
private void doClose() throws IOException {
myEnumerator.lockStorage();
try {
try {
myAppendCacheFlusher.stop();
try {
myAppendCache.clear();
}
catch (RuntimeException ex) {
Throwable cause = ex.getCause();
if (cause instanceof IOException) throw (IOException)cause;
throw ex;
}
}
finally {
final PersistentHashMapValueStorage valueStorage = myValueStorage;
try {
if (valueStorage != null) {
valueStorage.dispose();
}
}
finally {
super.close();
}
}
}
finally {
myEnumerator.unlockStorage();
}
}
static class CompactionRecordInfo {
final int key;
final int address;
long valueAddress;
long newValueAddress;
byte[] value;
CompactionRecordInfo(int _key, long _valueAddress, int _address) {
key = _key;
address = _address;
valueAddress = _valueAddress;
}
}
// made public for tests
public void compact() throws IOException {
if (myIsReadOnly) throw new IncorrectOperationException();
synchronized (myEnumerator) {
force();
LOG.info("Compacting " + myEnumerator.myFile.getPath());
LOG.info("Live keys:" + (int)(myLiveAndGarbageKeysCounter / LIVE_KEY_MASK) +
", dead keys:" + (int)(myLiveAndGarbageKeysCounter & DEAD_KEY_NUMBER_MASK) +
", read compaction size:" + myReadCompactionGarbageSize);
final long now = System.currentTimeMillis();
final File oldDataFile = getDataFile(myEnumerator.myFile);
final String oldDataFileBaseName = oldDataFile.getName();
final File[] oldFiles = getFilesInDirectoryWithNameStartingWith(oldDataFile, oldDataFileBaseName);
final String newPath = getDataFile(myEnumerator.myFile).getPath() + ".new";
PersistentHashMapValueStorage.CreationTimeOptions options = myValueStorage.getOptions();
final PersistentHashMapValueStorage newStorage = PersistentHashMapValueStorage.create(newPath, options);
myValueStorage.switchToCompactionMode();
myEnumerator.markDirty(true);
long sizeBefore = myValueStorage.getSize();
myLiveAndGarbageKeysCounter = 0;
myReadCompactionGarbageSize = 0;
try {
if (doNewCompact()) {
newCompact(newStorage);
}
else {
traverseAllRecords(new PersistentEnumerator.RecordsProcessor() {
@Override
public boolean process(final int keyId) throws IOException {
final long record = readValueId(keyId);
if (record != NULL_ADDR) {
PersistentHashMapValueStorage.ReadResult readResult = myValueStorage.readBytes(record);
long value = newStorage.appendBytes(readResult.buffer, 0, readResult.buffer.length, 0);
updateValueId(keyId, value, record, null, getCurrentKey());
myLiveAndGarbageKeysCounter += LIVE_KEY_MASK;
}
return true;
}
});
}
}
finally {
newStorage.dispose();
}
myValueStorage.dispose();
if (oldFiles != null) {
for (File f : oldFiles) {
assert FileUtil.deleteWithRenaming(f);
}
}
final long newSize = newStorage.getSize();
File newDataFile = new File(newPath);
final String newBaseName = newDataFile.getName();
final File[] newFiles = getFilesInDirectoryWithNameStartingWith(newDataFile, newBaseName);
if (newFiles != null) {
File parentFile = newDataFile.getParentFile();
// newFiles should get the same names as oldDataFiles
for (File f : newFiles) {
String nameAfterRename = StringUtil.replace(f.getName(), newBaseName, oldDataFileBaseName);
FileUtil.rename(f, new File(parentFile, nameAfterRename));
}
}
myValueStorage = PersistentHashMapValueStorage.create(oldDataFile.getPath(), options);
LOG.info("Compacted " + myEnumerator.myFile.getPath() + ":" + sizeBefore + " bytes into " +
newSize + " bytes in " + (System.currentTimeMillis() - now) + "ms.");
myEnumerator.putMetaData(myLiveAndGarbageKeysCounter);
myEnumerator.putMetaData2(myLargeIndexWatermarkId);
if (myDoTrace) LOG.assertTrue(myEnumerator.isDirty());
}
}
private static File[] getFilesInDirectoryWithNameStartingWith(@NotNull File fileFromDirectory, @NotNull final String baseFileName) {
File parentFile = fileFromDirectory.getParentFile();
return parentFile != null ? parentFile.listFiles(new FileFilter() {
@Override
public boolean accept(final File pathname) {
return pathname.getName().startsWith(baseFileName);
}
}) : null;
}
private void newCompact(@NotNull PersistentHashMapValueStorage newStorage) throws IOException {
long started = System.currentTimeMillis();
final List<CompactionRecordInfo> infos = new ArrayList<CompactionRecordInfo>(10000);
traverseAllRecords(new PersistentEnumerator.RecordsProcessor() {
@Override
public boolean process(final int keyId) {
final long record = readValueId(keyId);
if (record != NULL_ADDR) {
infos.add(new CompactionRecordInfo(getCurrentKey(), record, keyId));
}
return true;
}
});
LOG.info("Loaded mappings:" + (System.currentTimeMillis() - started) + "ms, keys:" + infos.size());
started = System.currentTimeMillis();
long fragments = 0;
if (!infos.isEmpty()) {
try {
fragments = myValueStorage.compactValues(infos, newStorage);
}
catch (Throwable t) {
if (!(t instanceof IOException)) throw new IOException("Compaction failed", t);
throw (IOException)t;
}
}
LOG.info("Compacted values for:" + (System.currentTimeMillis() - started) + "ms fragments:" +
(int)fragments + ", new fragments:" + (fragments >> 32));
started = System.currentTimeMillis();
try {
myEnumerator.lockStorage();
for (CompactionRecordInfo info : infos) {
updateValueId(info.address, info.newValueAddress, info.valueAddress, null, info.key);
myLiveAndGarbageKeysCounter += LIVE_KEY_MASK;
}
}
finally {
myEnumerator.unlockStorage();
}
LOG.info("Updated mappings:" + (System.currentTimeMillis() - started) + " ms");
}
private long readValueId(final int keyId) {
if (myDirectlyStoreLongFileOffsetMode) {
return ((PersistentBTreeEnumerator<Key>)myEnumerator).keyIdToNonNegativeOffset(keyId);
}
long address = myEnumerator.myStorage.getInt(keyId + myParentValueRefOffset);
if (address == 0 || address == -POSITIVE_VALUE_SHIFT) {
return NULL_ADDR;
}
if (address < 0) {
address = -address - POSITIVE_VALUE_SHIFT;
}
else {
long value = myEnumerator.myStorage.getInt(keyId + myParentValueRefOffset + 4) & 0xFFFFFFFFL;
address = ((address << 32) + value) & ~USED_LONG_VALUE_MASK;
}
return address;
}
private int smallKeys;
private int largeKeys;
private int transformedKeys;
private int requests;
private int updateValueId(int keyId, long value, long oldValue, @Nullable Key key, int processingKey) throws IOException {
if (myDirectlyStoreLongFileOffsetMode) {
((PersistentBTreeEnumerator<Key>)myEnumerator).putNonNegativeValue(((InlineKeyDescriptor<Key>)myKeyDescriptor).fromInt(processingKey), value);
return keyId;
}
final boolean newKey = oldValue == NULL_ADDR;
if (newKey) ++requests;
boolean defaultSizeInfo = true;
if (myCanReEnumerate) {
if (canUseIntAddressForNewRecord(value)) {
defaultSizeInfo = false;
myEnumerator.myStorage.putInt(keyId + myParentValueRefOffset, -(int)(value + POSITIVE_VALUE_SHIFT));
if (newKey) ++smallKeys;
}
else if ((keyId < myLargeIndexWatermarkId || myLargeIndexWatermarkId == 0) && (newKey || canUseIntAddressForNewRecord(oldValue))) {
// keyId is result of enumerate, if we do re-enumerate then it is no longer accessible unless somebody cached it
myIntAddressForNewRecord = false;
keyId = myEnumerator.reEnumerate(key == null ? myEnumerator.getValue(keyId, processingKey) : key);
++transformedKeys;
if (myLargeIndexWatermarkId == 0) {
myLargeIndexWatermarkId = keyId;
}
}
}
if (defaultSizeInfo) {
value |= USED_LONG_VALUE_MASK;
myEnumerator.myStorage.putInt(keyId + myParentValueRefOffset, (int)(value >>> 32));
myEnumerator.myStorage.putInt(keyId + myParentValueRefOffset + 4, (int)value);
if (newKey) ++largeKeys;
}
if (newKey && IOStatistics.DEBUG && (requests & IOStatistics.KEYS_FACTOR_MASK) == 0) {
IOStatistics.dump("small:" + smallKeys + ", large:" + largeKeys + ", transformed:" + transformedKeys +
",@" + getBaseFile().getPath());
}
if (doHardConsistencyChecks) {
long checkRecord = readValueId(keyId);
assert checkRecord == (value & ~USED_LONG_VALUE_MASK) : value;
}
return keyId;
}
@Override
public String toString() {
return super.toString() + ": " + myStorageFile;
}
@TestOnly
PersistentHashMapValueStorage getValueStorage() {
return myValueStorage;
}
@TestOnly
public boolean getReadOnly() {
return myIsReadOnly;
}
}
| {
"content_hash": "5a1c796e7cbca9c78df873da05384c34",
"timestamp": "",
"source": "github",
"line_count": 1002,
"max_line_length": 148,
"avg_line_length": 34.740518962075846,
"alnum_prop": 0.6717897155989658,
"repo_name": "msebire/intellij-community",
"id": "44d069f0520ce93a5f325963ac9bb2ee745e285c",
"size": "35410",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "platform/util/src/com/intellij/util/io/PersistentHashMap.java",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
/* Rashad Saab, 201301697, rms78 */
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
public class DesEncrypter {
public final static String accountSeperator = ":";
private static String key = "1234abcd";
public static String decrypt(String message) throws Exception {
byte[] bytesrc = convertHexString(message);
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));
cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
byte[] retByte = cipher.doFinal(bytesrc);
return new String(retByte);
}
public static String encrypt(String message) throws Exception {
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));
cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
return toHexString(cipher.doFinal(message.getBytes("UTF-8")));
}
private static byte[] convertHexString(String ss) {
byte digest[] = new byte[ss.length() / 2];
for (int i = 0; i < digest.length; i++) {
String byteString = ss.substring(2 * i, 2 * i + 2);
int byteValue = Integer.parseInt(byteString, 16);
digest[i] = (byte) byteValue;
}
return digest;
}
private static String toHexString(byte b[]) {
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < b.length; i++) {
String plainText = Integer.toHexString(0xff & b[i]);
if (plainText.length() < 2)
plainText = "0" + plainText;
hexString.append(plainText);
}
return hexString.toString();
}
public static String[] decodeAccount(String cookieValue) {
try {
String origi = DesEncrypter.decrypt(cookieValue);
String[] parts = origi.split(DesEncrypter.accountSeperator);
if (parts.length == 2 && !parts[0].equals("") && !parts[1].equals("")) {
return parts;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static String encodeAccount(String username, String password) {
String encryptString = null;
try {
encryptString = DesEncrypter.encrypt(username + DesEncrypter.accountSeperator + password);
} catch (Exception e) {
}
return encryptString;
}
} | {
"content_hash": "d1d16527993ae1b8996ca3734a9aada4",
"timestamp": "",
"source": "github",
"line_count": 79,
"max_line_length": 97,
"avg_line_length": 37.08860759493671,
"alnum_prop": 0.6546075085324232,
"repo_name": "RSaab/MyCal",
"id": "5ef186cbf175546d635cc864ebfe283e85547905",
"size": "2930",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "DesEncrypter.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "171605"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_80) on Thu Oct 15 19:27:58 UTC 2015 -->
<title>DecisionContext (AWS SDK for Java - 1.10.27)</title>
<meta name="date" content="2015-10-15">
<link rel="stylesheet" type="text/css" href="../../../../../JavaDoc.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="DecisionContext (AWS SDK for Java - 1.10.27)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage"><em>
<!-- Scripts for Syntax Highlighter START-->
<script id="syntaxhighlight_script_core" type="text/javascript" src = "http://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/resources/syntaxhighlight/scripts/shCore.js">
</script>
<script id="syntaxhighlight_script_java" type="text/javascript" src = "http://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/resources/syntaxhighlight/scripts/shBrushJava.js">
</script>
<link id="syntaxhighlight_css_core" rel="stylesheet" type="text/css" href = "http://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/resources/syntaxhighlight/styles/shCoreDefault.css"/>
<link id="syntaxhighlight_css_theme" rel="stylesheet" type="text/css" href = "http://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/resources/syntaxhighlight/styles/shThemeDefault.css"/>
<!-- Scripts for Syntax Highlighter END-->
<div>
<!-- BEGIN-SECTION -->
<div id="divsearch" style="float:left;">
<span id="lblsearch" for="searchQuery">
<label>Search</label>
</span>
<form id="nav-search-form" target="_parent" method="get" action="http://docs.aws.amazon.com/search/doc-search.html#facet_doc_guide=API+Reference&facet_doc_product=AWS+SDK+for+Java">
<div id="nav-searchfield-outer" class="nav-sprite">
<div class="nav-searchfield-inner nav-sprite">
<div id="nav-searchfield-width">
<input id="nav-searchfield" name="searchQuery">
</div>
</div>
</div>
<div id="nav-search-button" class="nav-sprite">
<input alt="" id="nav-search-button-inner" type="image">
</div>
<input name="searchPath" type="hidden" value="documentation-guide" />
<input name="this_doc_product" type="hidden" value="AWS SDK for Java" />
<input name="this_doc_guide" type="hidden" value="API Reference" />
<input name="doc_locale" type="hidden" value="en_us" />
</form>
</div>
<!-- END-SECTION -->
<!-- BEGIN-FEEDBACK-SECTION -->
<div id="feedback-section">
<h3>Did this page help you?</h3>
<div id="feedback-link-sectioin">
<a id="feedback_yes" target="_blank" style="display:inline;">Yes</a>
<a id="feedback_no" target="_blank" style="display:inline;">No</a>
<a id="go_cti" target="_blank" style="display:inline;">Tell us about it...</a>
</div>
</div>
<script type="text/javascript">
window.onload = function(){
/* Dynamically add feedback links */
var javadoc_root_name = "/javadoc/";
var javadoc_path = location.href.substring(0, location.href.lastIndexOf(javadoc_root_name) + javadoc_root_name.length);
var file_path = location.href.substring(location.href.lastIndexOf(javadoc_root_name) + javadoc_root_name.length);
var feedback_yes_url = javadoc_path + "javadoc-resources/feedbackyes.html?topic_id=";
var feedback_no_url = javadoc_path + "javadoc-resources/feedbackno.html?topic_id=";
var feedback_tellmore_url = "https://aws-portal.amazon.com/gp/aws/html-forms-controller/documentation/aws_doc_feedback_04?service_name=Java-Ref&file_name=";
if(file_path != "overview-frame.html") {
var file_name = file_path.replace(/[/.]/g, '_');
document.getElementById("feedback_yes").setAttribute("href", feedback_yes_url + file_name);
document.getElementById("feedback_no").setAttribute("href", feedback_no_url + file_name);
document.getElementById("go_cti").setAttribute("href", feedback_tellmore_url + file_name);
} else {
// hide the search box and the feeback links in overview-frame page,
// show "AWS SDK for Java" instead.
document.getElementById("feedback-section").outerHTML = "AWS SDK for Java";
document.getElementById("divsearch").outerHTML = "";
}
};
</script>
<!-- END-FEEDBACK-SECTION -->
</div>
</em></div>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../com/amazonaws/services/simpleworkflow/flow/DataConverterException.html" title="class in com.amazonaws.services.simpleworkflow.flow"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../../com/amazonaws/services/simpleworkflow/flow/DecisionContextProvider.html" title="interface in com.amazonaws.services.simpleworkflow.flow"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?com/amazonaws/services/simpleworkflow/flow/DecisionContext.html" target="_top">Frames</a></li>
<li><a href="DecisionContext.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">com.amazonaws.services.simpleworkflow.flow</div>
<h2 title="Class DecisionContext" class="title">Class DecisionContext</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>com.amazonaws.services.simpleworkflow.flow.DecisionContext</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>Direct Known Subclasses:</dt>
<dd><a href="../../../../../com/amazonaws/services/simpleworkflow/flow/test/TestDecisionContext.html" title="class in com.amazonaws.services.simpleworkflow.flow.test">TestDecisionContext</a></dd>
</dl>
<hr>
<br>
<pre>public abstract class <span class="strong">DecisionContext</span>
extends java.lang.Object</pre>
<div class="block">Represents the context for decider. Should only be used within the scope of
workflow definition code, meaning any code which is not part of activity
implementations.</div>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_summary">
<!-- -->
</a>
<h3>Constructor Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><strong><a href="../../../../../com/amazonaws/services/simpleworkflow/flow/DecisionContext.html#DecisionContext()">DecisionContext</a></strong>()</code> </td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method_summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span>Methods</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>abstract <a href="../../../../../com/amazonaws/services/simpleworkflow/flow/generic/GenericActivityClient.html" title="interface in com.amazonaws.services.simpleworkflow.flow.generic">GenericActivityClient</a></code></td>
<td class="colLast"><code><strong><a href="../../../../../com/amazonaws/services/simpleworkflow/flow/DecisionContext.html#getActivityClient()">getActivityClient</a></strong>()</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>abstract <a href="../../../../../com/amazonaws/services/simpleworkflow/flow/worker/LambdaFunctionClient.html" title="interface in com.amazonaws.services.simpleworkflow.flow.worker">LambdaFunctionClient</a></code></td>
<td class="colLast"><code><strong><a href="../../../../../com/amazonaws/services/simpleworkflow/flow/DecisionContext.html#getLambdaFunctionClient()">getLambdaFunctionClient</a></strong>()</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>abstract <a href="../../../../../com/amazonaws/services/simpleworkflow/flow/generic/GenericWorkflowClient.html" title="interface in com.amazonaws.services.simpleworkflow.flow.generic">GenericWorkflowClient</a></code></td>
<td class="colLast"><code><strong><a href="../../../../../com/amazonaws/services/simpleworkflow/flow/DecisionContext.html#getWorkflowClient()">getWorkflowClient</a></strong>()</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>abstract <a href="../../../../../com/amazonaws/services/simpleworkflow/flow/WorkflowClock.html" title="interface in com.amazonaws.services.simpleworkflow.flow">WorkflowClock</a></code></td>
<td class="colLast"><code><strong><a href="../../../../../com/amazonaws/services/simpleworkflow/flow/DecisionContext.html#getWorkflowClock()">getWorkflowClock</a></strong>()</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>abstract <a href="../../../../../com/amazonaws/services/simpleworkflow/flow/WorkflowContext.html" title="interface in com.amazonaws.services.simpleworkflow.flow">WorkflowContext</a></code></td>
<td class="colLast"><code><strong><a href="../../../../../com/amazonaws/services/simpleworkflow/flow/DecisionContext.html#getWorkflowContext()">getWorkflowContext</a></strong>()</code> </td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_detail">
<!-- -->
</a>
<h3>Constructor Detail</h3>
<a name="DecisionContext()">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>DecisionContext</h4>
<pre>public DecisionContext()</pre>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method_detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="getActivityClient()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getActivityClient</h4>
<pre>public abstract <a href="../../../../../com/amazonaws/services/simpleworkflow/flow/generic/GenericActivityClient.html" title="interface in com.amazonaws.services.simpleworkflow.flow.generic">GenericActivityClient</a> getActivityClient()</pre>
</li>
</ul>
<a name="getWorkflowClient()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getWorkflowClient</h4>
<pre>public abstract <a href="../../../../../com/amazonaws/services/simpleworkflow/flow/generic/GenericWorkflowClient.html" title="interface in com.amazonaws.services.simpleworkflow.flow.generic">GenericWorkflowClient</a> getWorkflowClient()</pre>
</li>
</ul>
<a name="getWorkflowClock()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getWorkflowClock</h4>
<pre>public abstract <a href="../../../../../com/amazonaws/services/simpleworkflow/flow/WorkflowClock.html" title="interface in com.amazonaws.services.simpleworkflow.flow">WorkflowClock</a> getWorkflowClock()</pre>
</li>
</ul>
<a name="getWorkflowContext()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getWorkflowContext</h4>
<pre>public abstract <a href="../../../../../com/amazonaws/services/simpleworkflow/flow/WorkflowContext.html" title="interface in com.amazonaws.services.simpleworkflow.flow">WorkflowContext</a> getWorkflowContext()</pre>
</li>
</ul>
<a name="getLambdaFunctionClient()">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>getLambdaFunctionClient</h4>
<pre>public abstract <a href="../../../../../com/amazonaws/services/simpleworkflow/flow/worker/LambdaFunctionClient.html" title="interface in com.amazonaws.services.simpleworkflow.flow.worker">LambdaFunctionClient</a> getLambdaFunctionClient()</pre>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage"><em>
<div>
<!-- Script for Syntax Highlighter START -->
<script type="text/javascript">
SyntaxHighlighter.all()
</script>
<!-- Script for Syntax Highlighter END -->
</div>
<script src="http://a0.awsstatic.com/chrome/js/1.0.46/jquery.1.9.js" type="text/javascript"></script>
<script>jQuery.noConflict();</script>
<script>
jQuery(function ($) {
$("div.header").prepend('<!--REGION_DISCLAIMER_DO_NOT_REMOVE-->');
});
</script>
<!-- BEGIN-URCHIN-TRACKER -->
<script src="http://l0.awsstatic.com/js/urchin.js" type="text/javascript"></script>
<script type="text/javascript">urchinTracker();</script>
<!-- END-URCHIN-TRACKER -->
<!-- SiteCatalyst code version: H.25.2. Copyright 1996-2012 Adobe, Inc. All Rights Reserved.
More info available at http://www.omniture.com -->
<script language="JavaScript" type="text/javascript" src="https://media.amazonwebservices.com/js/sitecatalyst/s_code.min.js (view-source:https://media.amazonwebservices.com/js/sitecatalyst/s_code.min.js)" />
<script language="JavaScript" type="text/javascript">
<!--
// Documentation Service Name
s.prop66='AWS SDK for Java';
s.eVar66='D=c66';
// Documentation Guide Name
s.prop65='API Reference';
s.eVar65='D=c65';
var s_code=s.t();if(s_code)document.write(s_code)
//-->
</script>
<script language="JavaScript" type="text/javascript">
<!--if(navigator.appVersion.indexOf('MSIE')>=0)document.write(unescape('%3C')+'\!-'+'-')
//-->
</script>
<noscript>
<img src="http://amazonwebservices.d2.sc.omtrdc.net/b/ss/awsamazondev/1/H.25.2--NS/0" height="1" width="1" border="0" alt="" />
</noscript>
<!--/DO NOT REMOVE/-->
<!-- End SiteCatalyst code version: H.25.2. -->
</em></div>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../com/amazonaws/services/simpleworkflow/flow/DataConverterException.html" title="class in com.amazonaws.services.simpleworkflow.flow"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../../com/amazonaws/services/simpleworkflow/flow/DecisionContextProvider.html" title="interface in com.amazonaws.services.simpleworkflow.flow"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?com/amazonaws/services/simpleworkflow/flow/DecisionContext.html" target="_top">Frames</a></li>
<li><a href="DecisionContext.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>
Copyright © 2013 Amazon Web Services, Inc. All Rights Reserved.
</small></p>
</body>
</html>
| {
"content_hash": "0797b21478211ff0b246eb65779e4c6a",
"timestamp": "",
"source": "github",
"line_count": 433,
"max_line_length": 259,
"avg_line_length": 45.043879907621246,
"alnum_prop": 0.6267945036915504,
"repo_name": "TomNong/Project2-Intel-Edison",
"id": "590933a2e6053fd264ddfa2c0d9e80e149c0872a",
"size": "19504",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "documentation/javadoc/com/amazonaws/services/simpleworkflow/flow/DecisionContext.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "5522"
}
],
"symlink_target": ""
} |
package entidades;
// Generated Jul 4, 2016 12:16:49 PM by Hibernate Tools 4.0.0.Final
import java.util.Date;
/**
* Usuarios generated by hbm2java
*/
public class Usuarios implements java.io.Serializable {
private Integer idUsuario;
private Perfilesusuario perfilesusuario;
private String usuario;
private String password;
private String nombres;
private String apellidos;
private String correo;
private Estados estados;
private Date fechaCreacion;
private int usuarioCrea;
private Date fechaModificacion;
private Integer usuarioModifica;
public Usuarios() {
}
public Usuarios(Perfilesusuario perfilesusuario, String usuario, String password, String nombres, String apellidos,
String correo, Estados estados, Date fechaCreacion, int usuarioCrea) {
this.perfilesusuario = perfilesusuario;
this.usuario = usuario;
this.password = password;
this.nombres = nombres;
this.apellidos = apellidos;
this.correo = correo;
this.estados = estados;
this.fechaCreacion = fechaCreacion;
this.usuarioCrea = usuarioCrea;
}
public Usuarios(Perfilesusuario perfilesusuario, String usuario, String password, String nombres, String apellidos,
String correo, Estados estados, Date fechaCreacion, int usuarioCrea, Date fechaModificacion,
Integer usuarioModifica) {
this.perfilesusuario = perfilesusuario;
this.usuario = usuario;
this.password = password;
this.nombres = nombres;
this.apellidos = apellidos;
this.correo = correo;
this.estados = estados;
this.fechaCreacion = fechaCreacion;
this.usuarioCrea = usuarioCrea;
this.fechaModificacion = fechaModificacion;
this.usuarioModifica = usuarioModifica;
}
public Integer getIdUsuario() {
return this.idUsuario;
}
public void setIdUsuario(Integer idUsuario) {
this.idUsuario = idUsuario;
}
public Perfilesusuario getPerfilesusuario() {
return this.perfilesusuario;
}
public void setPerfilesusuario(Perfilesusuario perfilesusuario) {
this.perfilesusuario = perfilesusuario;
}
public String getUsuario() {
return this.usuario;
}
public void setUsuario(String usuario) {
this.usuario = usuario;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
public String getNombres() {
return this.nombres;
}
public void setNombres(String nombres) {
this.nombres = nombres;
}
public String getApellidos() {
return this.apellidos;
}
public void setApellidos(String apellidos) {
this.apellidos = apellidos;
}
public String getCorreo() {
return this.correo;
}
public void setCorreo(String correo) {
this.correo = correo;
}
public Estados getEstados() {
return this.estados;
}
public void setEstados(Estados estados) {
this.estados = estados;
}
public Date getFechaCreacion() {
return this.fechaCreacion;
}
public void setFechaCreacion(Date fechaCreacion) {
this.fechaCreacion = fechaCreacion;
}
public int getUsuarioCrea() {
return this.usuarioCrea;
}
public void setUsuarioCrea(int usuarioCrea) {
this.usuarioCrea = usuarioCrea;
}
public Date getFechaModificacion() {
return this.fechaModificacion;
}
public void setFechaModificacion(Date fechaModificacion) {
this.fechaModificacion = fechaModificacion;
}
public Integer getUsuarioModifica() {
return this.usuarioModifica;
}
public void setUsuarioModifica(Integer usuarioModifica) {
this.usuarioModifica = usuarioModifica;
}
}
| {
"content_hash": "c1f3926572017a3fcef77223145fcf4b",
"timestamp": "",
"source": "github",
"line_count": 152,
"max_line_length": 116,
"avg_line_length": 22.763157894736842,
"alnum_prop": 0.7563583815028901,
"repo_name": "jeanca93/UTE",
"id": "40bbd69a222fec5180f620b6d0628016b7fef8be",
"size": "3460",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/entidades/Usuarios.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "8713"
},
{
"name": "Java",
"bytes": "399617"
}
],
"symlink_target": ""
} |
Put this python script into cgi-bin directory, and make it executable(`chmod 755`)
``` python
$ more /usr/lib/cgi-bin/helloworld.py
#!/usr/bin/env python
print "Content-Type: text/html"
print
print """\
<html>
<body>
<h2>Hello World!</h2>
</body>
</html>
"""
```
Makesure you can run the script directly like this:
``` python
$ /usr/lib/cgi-bin/helloworld.py
Content-Type: text/html
<html>
<body>
<h2>Hello World!</h2>
</body>
</html>
```
## Test it within Browser
Open browser with `http://IP/cgi-bin/helloworld.py`, and you will see `Hello World!`.
| {
"content_hash": "177d41ff6a682411a395eac149ff4c39",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 85,
"avg_line_length": 17.625,
"alnum_prop": 0.6737588652482269,
"repo_name": "xiaopeng163/getting-started-with-wsgi",
"id": "e1bd49ba2b3598a1584a543a6d359b7a5eb51e2b",
"size": "597",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "cgi/helloworld.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "509"
}
],
"symlink_target": ""
} |
const router = require('express').Router({ mergeParams: true });
const controller = require('../follow/follow.controller');
const authorize = require('../../authorize');
router.post('/:mailboxId/circle/:circleId', authorize.permit('follow:all', 'follow:create'), controller.follow);
router.delete('/:mailboxId/circle/:circleId', authorize.permit('follow:all', 'follow:delete'), controller.unfollow);
// router.post('/:circleId/bulk', authorize.permit('follow:all', 'follow:create'), controller.bulkFollow);
// router.get('/getfollowers/circle/:circleId?limit={limit}&before={mailboxId}&after={mailboxId}', controller.getFollowersMailboxesOfACircle);
router.get('/getfollowers/circle/:circleId', controller.getFollowersMailboxesOfACircle);
module.exports=router;
| {
"content_hash": "9f7a7b81006e8384e1732fffead69458",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 142,
"avg_line_length": 58.92307692307692,
"alnum_prop": 0.7571801566579635,
"repo_name": "himanisingla16/activitystreams-travis",
"id": "2b6f6a7623311595631932832fc34ce373b4943e",
"size": "766",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "components/rest-api/api/follow/index.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "JavaScript",
"bytes": "236403"
},
{
"name": "Shell",
"bytes": "14162"
}
],
"symlink_target": ""
} |
#include <config.h>
#include "dirname.h"
#include <string.h>
#include "xalloc.h"
#include "xstrndup.h"
char *
base_name (char const *name)
{
char const *base = last_component (name);
size_t length;
/* If there is no last component, then name is a file system root or the
empty string. */
if (! *base)
return xstrndup (name, base_len (name));
/* Collapse a sequence of trailing slashes into one. */
length = base_len (base);
if (ISSLASH (base[length]))
length++;
/* On systems with drive letters, "a/b:c" must return "./b:c" rather
than "b:c" to avoid confusion with a drive letter. On systems
with pure POSIX semantics, this is not an issue. */
if (FILE_SYSTEM_PREFIX_LEN (base))
{
char *p = xmalloc (length + 3);
p[0] = '.';
p[1] = '/';
memcpy (p + 2, base, length);
p[length + 2] = '\0';
return p;
}
/* Finally, copy the basename. */
return xstrndup (base, length);
}
| {
"content_hash": "ffe4fe6343e201ce890fc260d420dc51",
"timestamp": "",
"source": "github",
"line_count": 42,
"max_line_length": 74,
"avg_line_length": 23.166666666666668,
"alnum_prop": 0.5971223021582733,
"repo_name": "mko-x/docker-nagios",
"id": "d73fd41aa11b1edbf93b5b12d35e8c890ee67dbd",
"size": "1765",
"binary": false,
"copies": "51",
"ref": "refs/heads/master",
"path": "nagios-plugins-1.5/gl/basename.c",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "688"
},
{
"name": "Awk",
"bytes": "1824"
},
{
"name": "C",
"bytes": "6382523"
},
{
"name": "C++",
"bytes": "120474"
},
{
"name": "CSS",
"bytes": "82101"
},
{
"name": "HTML",
"bytes": "62265"
},
{
"name": "Makefile",
"bytes": "37734"
},
{
"name": "PHP",
"bytes": "31468"
},
{
"name": "Perl",
"bytes": "464993"
},
{
"name": "Shell",
"bytes": "693123"
}
],
"symlink_target": ""
} |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Host")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Host")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("fb57ed85-eb01-470b-a03b-a86307d25dfb")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| {
"content_hash": "085b56b2b696233e7be15232fc466b5a",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 84,
"avg_line_length": 39.361111111111114,
"alnum_prop": 0.7233592095977417,
"repo_name": "edjo23/shows",
"id": "ae0cf30a330f1f4947f9f5a7d25f98ac1a5be358",
"size": "1420",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Shows/Properties/AssemblyInfo.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "8845"
},
{
"name": "CSS",
"bytes": "314"
},
{
"name": "HTML",
"bytes": "377"
},
{
"name": "JavaScript",
"bytes": "438"
},
{
"name": "PowerShell",
"bytes": "217"
},
{
"name": "Puppet",
"bytes": "328"
}
],
"symlink_target": ""
} |
#ifdef _WIN32
#include <winhttp.h>
#endif
using namespace signalr;
using namespace web::http;
using namespace web::http::client;
namespace jabbr
{
default_authentication_provider::default_authentication_provider(const utility::string_t& url)
: m_url(url)
{
// remove trailing 'SignalR(/)?'
if (m_url.size() > 8)
{
auto start_position = url.size() - 1;
if (m_url.back() == U('/'))
{
start_position--;
}
// TODO: should be case insensitive
if ((start_position = m_url.find(U("SignalR"), start_position - 7)) != utility::string_t::npos)
{
m_url.erase(start_position);
}
}
}
pplx::task<void> default_authentication_provider::configure_connection(std::shared_ptr<hub_connection> jabbr_connection,
const utility::string_t& username, const utility::string_t& password)
{
http_client_config config;
#ifdef _WIN32
config.set_nativehandle_options([](native_handle handle)->void
{
auto setting = WINHTTP_DISABLE_REDIRECTS;
if (!WinHttpSetOption(handle,
WINHTTP_OPTION_DISABLE_FEATURE,
&setting,
sizeof(setting)))
{
throw std::runtime_error("could not disable redirects");
}
});
#endif
http_client client(m_url, config);
http_request request{ U("POST") };
request.set_request_uri(U("account/login"));
request.headers().add(U("Content-Type"), U("application/x-www-form-urlencoded"));
request.headers().add(U("sec-jabbr-client"), U("1"));
utility::ostringstream_t body;
body << U("username=") << username << U("&password=") << password;
request.set_body(body.str());
return client.request(request)
.then([jabbr_connection](http_response response)
{
if (response.status_code() != 303)
{
std::ostringstream msg;
msg << "authentication failed. http status code: " << response.status_code();
throw std::runtime_error(msg.str());
}
auto cookie_header = response.headers().find(U("Set-Cookie"));
if (cookie_header != response.headers().end())
{
jabbr_connection->set_headers(std::unordered_map<utility::string_t, utility::string_t>(
{
{ U("Cookie"), cookie_header->second },
{ U("sec-jabbr-client"), U("1") },
}));
}
else
{
throw std::runtime_error("authentication failed - cookie not found");
}
});
}
} | {
"content_hash": "f4a3c5da46474a94d82ba24ff25fe232",
"timestamp": "",
"source": "github",
"line_count": 84,
"max_line_length": 124,
"avg_line_length": 35.404761904761905,
"alnum_prop": 0.495965030262273,
"repo_name": "moozzyk/JabbrClientCpp",
"id": "f1b55105f6d22c9338dcb4291d2de01589e053a0",
"size": "3147",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/JabbrClientCpp/default_authentication_provider.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "1064"
},
{
"name": "C++",
"bytes": "59529"
}
],
"symlink_target": ""
} |
import { LiveAnnouncer } from '@angular/cdk/a11y';
import { AfterViewInit, ChangeDetectionStrategy, ChangeDetectorRef, Component, OnDestroy, Optional } from '@angular/core';
import { merge, Subject } from 'rxjs';
import { delay, filter, takeUntil } from 'rxjs/operators';
import { FocusIndicatorOriginService } from '../../../directives/accessibility/index';
import { DateRangeOptions } from '../../date-range-picker/date-range-picker.directive';
import { DateRangePicker, DateRangeService } from '../../date-range-picker/date-range.service';
import { DatePickerHeaderEvent, DateTimePickerService } from '../date-time-picker.service';
import { compareDays, isDateAfter, isDateBefore } from '../date-time-picker.utils';
import { DayViewItem, DayViewService } from './day-view.service';
@Component({
selector: 'ux-date-time-picker-day-view',
templateUrl: './day-view.component.html',
providers: [DayViewService],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class DayViewComponent implements AfterViewInit, OnDestroy {
/** Determine if we are in range selection mode */
get _isRangeMode(): boolean {
return !!this._rangeOptions;
}
/** Determine if this picker is the start picker */
get _isRangeStart(): boolean {
return this._isRangeMode && this._rangeOptions.picker === DateRangePicker.Start;
}
/** Determine if this picker is the end picker */
get _isRangeEnd(): boolean {
return this._isRangeMode && this._rangeOptions.picker === DateRangePicker.End;
}
get _rangeStart(): Date | null {
return this._isRangeMode && this._rangeService ? this._rangeService.start : null;
}
get _rangeEnd(): Date | null {
return this._isRangeMode && this._rangeService ? this._rangeService.end : null;
}
private _onDestroy = new Subject<void>();
constructor(public datePicker: DateTimePickerService,
public dayService: DayViewService,
private _changeDetector: ChangeDetectorRef,
private _focusOrigin: FocusIndicatorOriginService,
private _liveAnnouncer: LiveAnnouncer,
@Optional() private _rangeService: DateRangeService,
@Optional() private _rangeOptions: DateRangeOptions) {
datePicker.headerEvent$.pipe(takeUntil(this._onDestroy))
.subscribe(event => event === DatePickerHeaderEvent.Next ? this.next() : this.previous());
// if we are a range picker then we also want to subscribe to range changes
if (_rangeService) {
merge(_rangeService.onRangeChange, _rangeService.onHoverChange).pipe(takeUntil(this._onDestroy))
.subscribe(() => _changeDetector.detectChanges());
// subscribe to changes to the start date
_rangeService.onStartChange
.pipe(takeUntil(this._onDestroy), filter(date => !!date && this._isRangeEnd && this.datePicker.initialised), delay(0))
.subscribe(date => this.onRangeChange(date));
// subscribe to changes to the end date
_rangeService.onEndChange
.pipe(takeUntil(this._onDestroy), filter(date => !!date && this._isRangeStart && this.datePicker.initialised), delay(0))
.subscribe(date => this.onRangeChange(date));
// when the range is cleared reset the selected date so we can click on the same date again if we want to
_rangeService.onClear.pipe(takeUntil(this._onDestroy)).subscribe(() => this.datePicker.selected$.next(null));
}
}
ngAfterViewInit(): void {
// update when there are changes to the min/max values
merge(this.datePicker.min$, this.datePicker.max$).pipe(takeUntil(this._onDestroy))
.subscribe(() => this._changeDetector.detectChanges());
// if we open and the range start is already selected, ensure that we move the end picker to a month with options
if (!this.datePicker.initialised && this._rangeStart && !this._rangeEnd && this._isRangeEnd) {
this.onRangeChange(this._rangeStart);
}
// if we open and the range end is already selected, ensure that we move the start picker to a month with options
if (!this.datePicker.initialised && this._rangeEnd && !this._rangeStart && this._isRangeStart) {
this.onRangeChange(this._rangeEnd);
}
}
ngOnDestroy(): void {
this._onDestroy.next();
this._onDestroy.complete();
}
/**
* Navigate to the previous page of dates
*/
previous(): void {
this.datePicker.setViewportMonth(this.datePicker.month$.value - 1);
}
/**
* Navigate to the next page of dates
*/
next(): void {
this.datePicker.setViewportMonth(this.datePicker.month$.value + 1);
}
/**
* Select a particular date
* @param date the date to select
*/
select(date: Date): void {
// if we are range picking, and have no dates selected clear the range (if we select the current day initially it won't get selected)
if (this._isRangeMode && !this._rangeStart && !this._rangeEnd) {
this._rangeService.clear();
}
// if we are the start range picker and we click the already selected day deselect it
if (this._isRangeMode && this._isRangeStart && this._rangeStart && compareDays(this._rangeStart, date)) {
this._rangeService.setStartDate(null);
this.datePicker.selected$.next(null);
return;
}
// if we are the end range picker and we click the already selected day deselect it
if (this._isRangeMode && this._isRangeEnd && this._rangeEnd && compareDays(this._rangeEnd, date)) {
this._rangeService.setEndDate(null);
this.datePicker.selected$.next(null);
return;
}
// if we are in range mode ensure we include the time from the time picker
if (this._isRangeMode) {
// update the current date object
if (this._isRangeStart && !this._rangeService.showTime) {
this.datePicker.setDate(date.getDate(), date.getMonth(), date.getFullYear(), 0, 0, 0);
} else if (this._isRangeEnd && !this._rangeService.showTime) {
this.datePicker.setDate(date.getDate(), date.getMonth(), date.getFullYear(), 23, 59, 59);
} else {
this.datePicker.setDate(date.getDate(), date.getMonth(), date.getFullYear(), this.datePicker.hours, this.datePicker.minutes, this.datePicker.seconds);
}
} else {
// update the current date object
this.datePicker.setDate(date.getDate(), date.getMonth(), date.getFullYear());
}
// focus the newly selected date
this.dayService.setFocus(date.getDate(), date.getMonth(), date.getFullYear());
// if we select a start date that is after the end date then clear the end date
if (this._isRangeMode && this._isRangeStart && this._rangeStart && this._rangeEnd) {
if (this._rangeStart.getTime() > this._rangeEnd.getTime()) {
this._rangeService.setEndDate(null);
}
}
// if we select a end date that is before the start date then clear the start date
if (this._isRangeMode && this._isRangeEnd && this._rangeStart && this._rangeEnd) {
if (this._rangeEnd.getTime() < this._rangeStart.getTime()) {
this._rangeService.setStartDate(null);
}
}
}
trackWeekByFn(index: number): number {
return index;
}
trackDayByFn(_index: number, item: DayViewItem): string {
return `${item.day} ${item.month} ${item.year}`;
}
focusDate(item: DayViewItem, dayOffset: number): void {
// determine the date of the day
const target = new Date(item.date.setDate(item.date.getDate() + dayOffset));
// we should force the origin to be keyboard
this._focusOrigin.setOrigin('keyboard');
// identify which date should be focused
this.dayService.setFocus(target.getDate(), target.getMonth(), target.getFullYear());
}
getTabbable(item: DayViewItem): boolean {
const focused = this.dayService.focused$.value;
const grid = this.dayService.grid$.value;
const month = this.datePicker.month$.value;
// if there is a focused month check if this is it
if (focused) {
// check if the focused day is visible
const isFocusedDayVisible = !!grid.find(row => !!row.find(_item => _item.day === focused.day && _item.month === focused.month && _item.year === focused.year && _item.month === month));
if (isFocusedDayVisible) {
return focused.day === item.day && focused.month === item.month && focused.year === item.year;
}
}
// if there is no focusable day then check if there is a selected day
const isSelectedDayVisible = !!grid.find(row => !!row.find(day => day.isActive));
if (isSelectedDayVisible) {
return item.isActive;
}
// find the first non disabled day that is part of the current month
for (const row of grid) {
for (const column of row) {
if (column === item && column.month === month && !this.getDisabled(column.date)) {
return true;
}
}
}
return false;
}
getDisabled(date: Date): boolean {
// if we are not in range mode then it will always be enabled
if (this._isRangeMode) {
// if we are range start and dates are after the range end then they should also be disabled
if (this._isRangeStart && !this._rangeStart && this._rangeEnd && isDateAfter(date, this._rangeEnd)) {
return true;
}
// if we are range end and dates are before the range start then they should also be disabled
if (this._isRangeEnd && !this._rangeEnd && this._rangeStart && isDateBefore(date, this._rangeStart)) {
return true;
}
}
if (this.datePicker.min$.value && isDateBefore(date, this.datePicker.min$.value)) {
return true;
}
if (this.datePicker.max$.value && isDateAfter(date, this.datePicker.max$.value)) {
return true;
}
return false;
}
isRangeStartDate(date: Date): boolean {
return this._isRangeMode && this._rangeStart && compareDays(date, this._rangeStart);
}
isRangeEndDate(date: Date): boolean {
return this._isRangeMode && this._rangeEnd && compareDays(date, this._rangeEnd);
}
isWithinRange(date: Date): boolean {
return this._isRangeMode && this._rangeStart && isDateAfter(date, this._rangeStart) && isDateBefore(date, this._rangeEnd);
}
isDateHovered(date: Date): boolean {
// if we are not in range mode or both start and end dates are selected then dont show range hover
if (!this._isRangeMode || !this._rangeService.hover || this._rangeStart && this._rangeEnd) {
return;
}
return this._rangeStart && isDateAfter(date, this._rangeStart) && isDateBefore(date, this._rangeService.hover, true) ||
this._rangeEnd && isDateBefore(date, this._rangeEnd) && isDateAfter(date, this._rangeService.hover, true);
}
isItemActive(date: Date, isActive: boolean): boolean {
if (!this._isRangeMode) {
return isActive;
}
return this._isRangeStart && this._rangeStart && compareDays(this._rangeStart, date) ||
this._isRangeEnd && this._rangeEnd && compareDays(this._rangeEnd, date);
}
onRangeMouseEnter(date: Date): void {
if (this._isRangeMode) {
this._rangeService.setDateMouseEnter(date);
}
}
onRangeMouseLeave(date: Date): void {
if (this._isRangeMode) {
this._rangeService.setDateMouseLeave(date);
}
}
/** Announce the date when we focus on a date */
announceRangeMode(): void {
if (this._isRangeMode) {
this._liveAnnouncer.announce(this._isRangeStart ? this._rangeService.startPickerAriaLabel : this._rangeService.endPickerAriaLabel);
}
}
/** Determine if we should focus a date */
shouldFocus(item: DayViewItem): boolean {
// if we are opening the popover initially we never want to focus a date in the range end picker
if (!this.datePicker.initialised && this._isRangeEnd || this._rangeService && this._rangeService.isChangingTime) {
return false;
}
// extract the current focused dates
const { day, month, year } = this.dayService.focused$.value;
// check if the current date is the focused date and it is in the viewport date
return day === item.day && month === item.month && year === item.year && item.isCurrentMonth;
}
/** Update the viewport when the range changes to ensure focus is present on a valid item */
private onRangeChange(date: Date): void {
if (!(this._isRangeStart && !this._rangeStart || this._isRangeEnd && !this._rangeEnd)) {
return;
}
// get the month showing on the other date range picker
const currentDate = new Date(this.datePicker.year$.value, this.datePicker.month$.value);
// if we are the start date and we are after the end date - ONLY then should be change the visible month the match the end date
const startShouldUpdate = this._isRangeStart && !this._rangeStart && (currentDate.getFullYear() > date.getFullYear() || currentDate.getFullYear() === date.getFullYear() && currentDate.getMonth() > date.getMonth());
// if we are the end date and we are before the start date - ONLY then should be change the visible month the match the start date
const endShouldUpdate = this._isRangeEnd && !this._rangeEnd && (currentDate.getFullYear() < date.getFullYear() || currentDate.getFullYear() === date.getFullYear() && currentDate.getMonth() < date.getMonth());
if (startShouldUpdate || endShouldUpdate) {
this.datePicker.setViewportMonth(date.getMonth());
this.datePicker.setViewportYear(date.getFullYear());
this.dayService.setFocus(date.getDate(), date.getMonth(), date.getFullYear());
this._changeDetector.detectChanges();
}
}
} | {
"content_hash": "0f493aecfd8eb73326c943f0f57b888b",
"timestamp": "",
"source": "github",
"line_count": 341,
"max_line_length": 222,
"avg_line_length": 42.56304985337243,
"alnum_prop": 0.6271875430618713,
"repo_name": "UXAspects/UXAspects",
"id": "26c3f7c172c5cd8815dcf08d4b959a0d8e4c3bf4",
"size": "14514",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/components/date-time-picker/day-view/day-view.component.ts",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "10693"
},
{
"name": "HTML",
"bytes": "309731"
},
{
"name": "JavaScript",
"bytes": "33008"
},
{
"name": "Less",
"bytes": "339318"
},
{
"name": "TypeScript",
"bytes": "2633869"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Html;
namespace RazorLight.Internal.Buffering
{
/// <summary>
/// An <see cref="IHtmlContentBuilder"/> that is backed by a buffer provided by <see cref="IViewBufferScope"/>.
/// </summary>
[DebuggerDisplay("{DebuggerToString()}")]
public class ViewBuffer : IHtmlContentBuilder
{
public static readonly int PartialViewPageSize = 32;
public static readonly int TagHelperPageSize = 32;
public static readonly int ViewComponentPageSize = 32;
public static readonly int ViewPageSize = 256;
private readonly IViewBufferScope _bufferScope;
private readonly string _name;
private readonly int _pageSize;
private ViewBufferPage _currentPage; // Limits allocation if the ViewBuffer has only one page (frequent case).
private List<ViewBufferPage> _multiplePages; // Allocated only if necessary
/// <summary>
/// Initializes a new instance of <see cref="ViewBuffer"/>.
/// </summary>
/// <param name="bufferScope">The <see cref="IViewBufferScope"/>.</param>
/// <param name="name">A name to identify this instance.</param>
/// <param name="pageSize">The size of buffer pages.</param>
public ViewBuffer(IViewBufferScope bufferScope, string name, int pageSize)
{
if (bufferScope == null)
{
throw new ArgumentNullException(nameof(bufferScope));
}
if (pageSize <= 0)
{
throw new ArgumentOutOfRangeException(nameof(pageSize));
}
_bufferScope = bufferScope;
_name = name;
_pageSize = pageSize;
}
/// <summary>
/// Get the <see cref="ViewBufferPage"/> count.
/// </summary>
public int Count
{
get
{
if (_multiplePages != null)
{
return _multiplePages.Count;
}
if (_currentPage != null)
{
return 1;
}
return 0;
}
}
/// <summary>
/// Gets a <see cref="ViewBufferPage"/>.
/// </summary>
public ViewBufferPage this[int index]
{
get
{
if (_multiplePages != null)
{
return _multiplePages[index];
}
if (index == 0 && _currentPage != null)
{
return _currentPage;
}
throw new IndexOutOfRangeException();
}
}
/// <inheritdoc />
public IHtmlContentBuilder Append(string unencoded)
{
if (unencoded == null)
{
return this;
}
// Text that needs encoding is the uncommon case in views, which is why it
// creates a wrapper and pre-encoded text does not.
AppendValue(new ViewBufferValue(new EncodingWrapper(unencoded)));
return this;
}
/// <inheritdoc />
public IHtmlContentBuilder AppendHtml(IHtmlContent content)
{
if (content == null)
{
return this;
}
AppendValue(new ViewBufferValue(content));
return this;
}
/// <inheritdoc />
public IHtmlContentBuilder AppendHtml(string encoded)
{
if (encoded == null)
{
return this;
}
AppendValue(new ViewBufferValue(encoded));
return this;
}
private void AppendValue(ViewBufferValue value)
{
var page = GetCurrentPage();
page.Append(value);
}
private ViewBufferPage GetCurrentPage()
{
if (_currentPage == null || _currentPage.IsFull)
{
AddPage(new ViewBufferPage(_bufferScope.GetPage(_pageSize)));
}
return _currentPage;
}
private void AddPage(ViewBufferPage page)
{
if (_multiplePages != null)
{
_multiplePages.Add(page);
}
else if (_currentPage != null)
{
_multiplePages = new List<ViewBufferPage>(2);
_multiplePages.Add(_currentPage);
_multiplePages.Add(page);
}
_currentPage = page;
}
/// <inheritdoc />
public IHtmlContentBuilder Clear()
{
_multiplePages = null;
_currentPage = null;
return this;
}
/// <inheritdoc />
public void WriteTo(TextWriter writer, HtmlEncoder encoder)
{
if (writer == null)
{
throw new ArgumentNullException(nameof(writer));
}
if (encoder == null)
{
throw new ArgumentNullException(nameof(encoder));
}
for (var i = 0; i < Count; i++)
{
var page = this[i];
for (var j = 0; j < page.Count; j++)
{
var value = page.Buffer[j];
if (value.Value is string valueAsString)
{
writer.Write(valueAsString);
continue;
}
if (value.Value is IHtmlContent valueAsHtmlContent)
{
valueAsHtmlContent.WriteTo(writer, encoder);
continue;
}
}
}
}
/// <summary>
/// Writes the buffered content to <paramref name="writer"/>.
/// </summary>
/// <param name="writer">The <see cref="TextWriter"/>.</param>
/// <param name="encoder">The <see cref="HtmlEncoder"/>.</param>
/// <returns>A <see cref="Task"/> which will complete once content has been written.</returns>
public async Task WriteToAsync(TextWriter writer, HtmlEncoder encoder)
{
if (writer == null)
{
throw new ArgumentNullException(nameof(writer));
}
if (encoder == null)
{
throw new ArgumentNullException(nameof(encoder));
}
for (var i = 0; i < Count; i++)
{
var page = this[i];
for (var j = 0; j < page.Count; j++)
{
var value = page.Buffer[j];
if (value.Value is string valueAsString)
{
await writer.WriteAsync(valueAsString);
continue;
}
if (value.Value is ViewBuffer valueAsViewBuffer)
{
await valueAsViewBuffer.WriteToAsync(writer, encoder);
continue;
}
if (value.Value is IHtmlContent valueAsHtmlContent)
{
valueAsHtmlContent.WriteTo(writer, encoder);
await writer.FlushAsync();
continue;
}
}
}
}
private string DebuggerToString() => _name;
public void CopyTo(IHtmlContentBuilder destination)
{
if (destination == null)
{
throw new ArgumentNullException(nameof(destination));
}
for (var i = 0; i < Count; i++)
{
var page = this[i];
for (var j = 0; j < page.Count; j++)
{
var value = page.Buffer[j];
string valueAsString;
IHtmlContentContainer valueAsContainer;
if ((valueAsString = value.Value as string) != null)
{
destination.AppendHtml(valueAsString);
}
else if ((valueAsContainer = value.Value as IHtmlContentContainer) != null)
{
valueAsContainer.CopyTo(destination);
}
else
{
destination.AppendHtml((IHtmlContent)value.Value);
}
}
}
}
public void MoveTo(IHtmlContentBuilder destination)
{
if (destination == null)
{
throw new ArgumentNullException(nameof(destination));
}
// Perf: We have an efficient implementation when the destination is another view buffer,
// we can just insert our pages as-is.
if (destination is ViewBuffer other)
{
MoveTo(other);
return;
}
for (var i = 0; i < Count; i++)
{
var page = this[i];
for (var j = 0; j < page.Count; j++)
{
var value = page.Buffer[j];
string valueAsString;
IHtmlContentContainer valueAsContainer;
if ((valueAsString = value.Value as string) != null)
{
destination.AppendHtml(valueAsString);
}
else if ((valueAsContainer = value.Value as IHtmlContentContainer) != null)
{
valueAsContainer.MoveTo(destination);
}
else
{
destination.AppendHtml((IHtmlContent)value.Value);
}
}
}
for (var i = 0; i < Count; i++)
{
var page = this[i];
Array.Clear(page.Buffer, 0, page.Count);
_bufferScope.ReturnSegment(page.Buffer);
}
Clear();
}
private void MoveTo(ViewBuffer destination)
{
for (var i = 0; i < Count; i++)
{
var page = this[i];
var destinationPage = destination.Count == 0 ? null : destination[destination.Count - 1];
// If the source page is less or equal to than half full, let's copy it's content to the destination
// page if possible.
var isLessThanHalfFull = 2 * page.Count <= page.Capacity;
if (isLessThanHalfFull &&
destinationPage != null &&
destinationPage.Capacity - destinationPage.Count >= page.Count)
{
// We have room, let's copy the items.
Array.Copy(
sourceArray: page.Buffer,
sourceIndex: 0,
destinationArray: destinationPage.Buffer,
destinationIndex: destinationPage.Count,
length: page.Count);
destinationPage.Count += page.Count;
// Now we can return the source page, and it can be reused in the scope of this request.
Array.Clear(page.Buffer, 0, page.Count);
_bufferScope.ReturnSegment(page.Buffer);
}
else
{
// Otherwise, let's just add the source page to the other buffer.
destination.AddPage(page);
}
}
Clear();
}
private class EncodingWrapper : IHtmlContent
{
private readonly string _unencoded;
public EncodingWrapper(string unencoded)
{
_unencoded = unencoded;
}
public void WriteTo(TextWriter writer, HtmlEncoder encoder)
{
encoder.Encode(writer, _unencoded);
}
}
}
}
| {
"content_hash": "bc9338d275ebee840ac30146104ce4d1",
"timestamp": "",
"source": "github",
"line_count": 387,
"max_line_length": 120,
"avg_line_length": 23.24031007751938,
"alnum_prop": 0.6380920613742495,
"repo_name": "toddams/RazorLight",
"id": "fa03e1d1a100968ab834c5c7580930c77aebc19a",
"size": "8996",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/RazorLight/Internal/Buffering/ViewBuffer.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "152"
},
{
"name": "C#",
"bytes": "380836"
},
{
"name": "HTML",
"bytes": "5106"
}
],
"symlink_target": ""
} |
- Data on Friday Apr 14
- Took the articles from the front page of the following pages: new, sports, lifestyles, opinion
- tokenized and part of speach tagged words using NLTK in Python
- Filtered words based on "NN" (Noun) and "VB" (Verb)
- Performed word counts on subsetted noun/verb words
- Need to check these counts
- the counts were done without grouping by noun/verb
- Used SentiWordNet in nltk.corpus.reader to tag the sentiment of each word.
- used the `01` sentiment of the word
- collected the positive, negative, and objective score
- Calculated score based on the positive score - negative score
- Recoded pos/neg/neu word based on difference of pos and neg score
- > 0 = positive
- < 0 = negative
- == 0 = neutral
| {
"content_hash": "e531fa39ecad5a7446560f8facdef89c",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 96,
"avg_line_length": 50.46666666666667,
"alnum_prop": 0.726552179656539,
"repo_name": "chendaniely/collegiate_times_sentiment",
"id": "7025ba2ddf5ecd7cfb6e2117202aead6fb47478b",
"size": "788",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "8227"
}
],
"symlink_target": ""
} |
package de.wenzlaff.umgebung.resource;
import org.restlet.resource.Get;
/**
* Interface für die Umgebung.
*
* @author Thomas Wenzlaff
*
*/
public interface Umgebung {
@Get
String getUmgebung();
} | {
"content_hash": "d3a986273534255f8d4ba75884943d31",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 38,
"avg_line_length": 12.9375,
"alnum_prop": 0.7053140096618358,
"repo_name": "IT-Berater/TWRestUmgebung",
"id": "cd01fcd5eb8f661eef59da19bbf298d56ba99d50",
"size": "208",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/de/wenzlaff/umgebung/resource/Umgebung.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "11483"
}
],
"symlink_target": ""
} |
typedef struct
{
char* banner;
double delay;
int count;
int jpeg;
int motion;
int subsamp;
int stdoutp;
int tstamp;
int rate_ms;
char* outfile;
char* seqfile;
char* v4l2;
// Internal state
size_t framecount;
unsigned char* jpg_buf;
unsigned char* prev_frame;
unsigned char* diff_frame;
size_t jpg_len;
struct timespec start_time;
} FrameCap;
// For collecting file before writing
typedef struct
{
unsigned char* buf;
size_t len;
char fre; // set if buffer needs to be free'd
} ImgBuf;
| {
"content_hash": "c49bd5574bfafde0f53f754215490e4b",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 57,
"avg_line_length": 18.09090909090909,
"alnum_prop": 0.6030150753768844,
"repo_name": "giganib/framecap",
"id": "9ec70a0271c3156b14bcfaa7600ebc08c2d977f2",
"size": "1762",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "framecap.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "77693"
},
{
"name": "Makefile",
"bytes": "346"
}
],
"symlink_target": ""
} |
<?php
/**
*
* @package Core_Resource
* @author Christian Gijtenbeek <gijtenbeek@terena.org>
*/
class Core_Resource_UsersSubmissions extends TA_Model_Resource_Db_Table_Abstract
{
protected $_name = 'users_submissions';
protected $_primary = 'user_submission_id';
// many to many mapping
protected $_referenceMap = array(
'User' => array(
'columns' => array('user_id'),
'refTableClass' => 'Repos_Resource_Users',
'refColumns' => array('user_id')
),
'Submission' => array(
'columns' => array('submission_id'),
'refTableClass' => 'Repos_Resource_Submissions',
'refColumns' => array('submission_id')
)
);
} | {
"content_hash": "18e1663b1318d6ac5beac50e3b772c55",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 80,
"avg_line_length": 21.433333333333334,
"alnum_prop": 0.656298600311042,
"repo_name": "br00k/tnc-web",
"id": "e4f615723031af602060d756c89d4d8f27b5a879",
"size": "1339",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "application/modules/core/models/resources/UsersSubmissions.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ApacheConf",
"bytes": "64"
},
{
"name": "CSS",
"bytes": "59553"
},
{
"name": "HTML",
"bytes": "399136"
},
{
"name": "JavaScript",
"bytes": "25660"
},
{
"name": "PHP",
"bytes": "1760688"
},
{
"name": "PLSQL",
"bytes": "60146"
},
{
"name": "SQLPL",
"bytes": "60140"
},
{
"name": "Smarty",
"bytes": "7111"
}
],
"symlink_target": ""
} |
package cosi
import (
"net/http"
"os"
"path/filepath"
"testing"
"github.com/libopenstorage/openstorage/bucket/drivers/fake"
"github.com/libopenstorage/openstorage/pkg/grpcserver"
"github.com/sirupsen/logrus"
"github.com/stretchr/testify/assert"
"google.golang.org/grpc"
)
type testServer struct {
conn *grpc.ClientConn
server grpcserver.Server
driver *fake.Fake
}
func newCOSITestServer(t *testing.T) *testServer {
// Start fake driver
fakeDriver := fake.New()
go func() {
if err := fakeDriver.Start(); err != http.ErrServerClosed {
logrus.Errorf("failed to start fake driver: %v", err)
}
}()
// Start COSI server
tempDir := os.TempDir()
cosisock := tempDir + "/cosi.sock"
os.Remove(cosisock)
if err := os.MkdirAll(filepath.Dir(cosisock), 0750); err != nil {
logrus.Errorf("failed to create COSI sock")
}
s, err := NewServer(&Config{
Driver: fakeDriver,
Net: "tcp",
Address: "127.0.0.1:0",
})
assert.NoError(t, err)
err = s.Start()
assert.NoError(t, err)
// Setup a connection to the driver
conn, err := grpc.Dial(s.Address(), grpc.WithInsecure())
assert.NoError(t, err)
// Return test server
return &testServer{
conn: conn,
server: s,
driver: fakeDriver,
}
}
// Stop stops a given test server
func (ts *testServer) Stop() {
if err := ts.conn.Close(); err != nil {
logrus.Errorf("failed to close test server conn: %v", err)
}
ts.server.Stop()
if err := ts.driver.Stop(); err != nil {
logrus.Errorf("failed to stop driver: %v", err)
}
}
| {
"content_hash": "a764a88c3667c3abcb8d9e47cc018a22",
"timestamp": "",
"source": "github",
"line_count": 70,
"max_line_length": 66,
"avg_line_length": 21.685714285714287,
"alnum_prop": 0.6712779973649539,
"repo_name": "libopenstorage/openstorage",
"id": "5a7d5a400ad2228bac33ed337587c305a41e0516",
"size": "1518",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "cosi/cosi_test.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Go",
"bytes": "2344037"
},
{
"name": "HTML",
"bytes": "3782"
},
{
"name": "Makefile",
"bytes": "15927"
},
{
"name": "Shell",
"bytes": "30883"
}
],
"symlink_target": ""
} |
using Hudl.FFmpeg.Attributes;
using Hudl.FFmpeg.Filters.Attributes;
using Hudl.FFmpeg.Filters.BaseTypes;
using Hudl.FFmpeg.Resources.BaseTypes;
using Hudl.FFmpeg.Resources.Interfaces;
namespace Hudl.FFmpeg.Filters
{
/// <summary>
/// AMovie Audio filter declares a filter resource that can be given a specific map. This resource can then be used as an input stream in any subsequent filterchains.
/// </summary>
[ForStream(Type = typeof(AudioStream))]
[Filter(Name = "amovie", MinInputs = 0, MaxInputs = 0)]
public class AMovie : BaseMovie
{
public AMovie()
{
}
public AMovie(IContainer file)
: this()
{
Resource = file;
}
}
}
| {
"content_hash": "59e53c9cfa55290763d19ae3f75d27a2",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 170,
"avg_line_length": 29.32,
"alnum_prop": 0.6466575716234653,
"repo_name": "hudl/HudlFfmpeg",
"id": "01f8a4c9c1be52e39c34d21156a65e3f440aafc1",
"size": "735",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Hudl.FFmpeg/Filters/AMovie.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "471695"
},
{
"name": "Smalltalk",
"bytes": "469"
}
],
"symlink_target": ""
} |
<?php
namespace Symfony\Bundle\FrameworkBundle\Routing;
use Symfony\Bundle\FrameworkBundle\Controller\ControllerNameParser;
use Symfony\Component\Config\Exception\FileLoaderLoadException;
use Symfony\Component\Config\Loader\DelegatingLoader as BaseDelegatingLoader;
use Symfony\Component\Config\Loader\LoaderResolverInterface;
use Psr\Log\LoggerInterface;
/**
* DelegatingLoader delegates route loading to other loaders using a loader resolver.
*
* This implementation resolves the _controller attribute from the short notation
* to the fully-qualified form (from a:b:c to class:method).
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class DelegatingLoader extends BaseDelegatingLoader
{
protected $parser;
protected $logger;
private $loading = false;
/**
* Constructor.
*
* @param ControllerNameParser $parser A ControllerNameParser instance
* @param LoggerInterface $logger A LoggerInterface instance
* @param LoaderResolverInterface $resolver A LoaderResolverInterface instance
*/
public function __construct(ControllerNameParser $parser, LoggerInterface $logger = null, LoaderResolverInterface $resolver)
{
$this->parser = $parser;
$this->logger = $logger;
parent::__construct($resolver);
}
/**
* {@inheritdoc}
*/
public function load($resource, $type = null)
{
if ($this->loading) {
// This can happen if a fatal error occurs in parent::load().
// Here is the scenario:
// - while routes are being loaded by parent::load() below, a fatal error
// occurs (e.g. parse error in a controller while loading annotations);
// - PHP abruptly empties the stack trace, bypassing all catch/finally blocks;
// it then calls the registered shutdown functions;
// - the ErrorHandler catches the fatal error and re-injects it for rendering
// thanks to HttpKernel->terminateWithException() (that calls handleException());
// - at this stage, if we try to load the routes again, we must prevent
// the fatal error from occurring a second time,
// otherwise the PHP process would be killed immediately;
// - while rendering the exception page, the router can be required
// (by e.g. the web profiler that needs to generate an URL);
// - this handles the case and prevents the second fatal error
// by triggering an exception beforehand.
throw new FileLoaderLoadException($resource);
}
$this->loading = true;
try {
$collection = parent::load($resource, $type);
} finally {
$this->loading = false;
}
foreach ($collection->all() as $route) {
if ($controller = $route->getDefault('_controller')) {
try {
$controller = $this->parser->parse($controller);
} catch (\Exception $e) {
// unable to optimize unknown notation
}
$route->setDefault('_controller', $controller);
}
}
return $collection;
}
}
| {
"content_hash": "14c7848cb02b13fe70eec847652fe80e",
"timestamp": "",
"source": "github",
"line_count": 88,
"max_line_length": 128,
"avg_line_length": 37.04545454545455,
"alnum_prop": 0.6285276073619632,
"repo_name": "cvuorinen/symfony",
"id": "a0786839b15bda003ed8d3a98c81932d0aa4cda6",
"size": "3489",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/Symfony/Bundle/FrameworkBundle/Routing/DelegatingLoader.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "8656"
},
{
"name": "CSS",
"bytes": "10309"
},
{
"name": "HTML",
"bytes": "253148"
},
{
"name": "PHP",
"bytes": "11129638"
},
{
"name": "Shell",
"bytes": "643"
},
{
"name": "TypeScript",
"bytes": "195"
}
],
"symlink_target": ""
} |
import copy
class Board:
PLAYER = "O"
AI = "X"
ROW_LEN = 3
grid_str = " {} | {} | {} \n___|___|___\n {} | {} | {}\n___|___|___\n {} | {} | {}\n | | \n"
def __init__(self):
self.grid = [[" ", " ", " "], [" ", " ", " "], [" ", " ", " "]]
self.player_turn = True
self.ai_turn = False
def get_empty_spots(self, grid):
empty = []
for row in range(3):
for col in range(3):
if grid[row][col] == " ":
empty.append([row, col])
return empty
def get_new_state(self, grid, move):
if self.player_turn:
grid[move[0]][move[1]] = Board.PLAYER
else:
grid[move[0]][move[1]] = Board.AI
return grid
def minimax(self, grid, depth):
if self.is_game_over():
return self.score(grid, depth)
depth += 1
scores = []
moves = []
for move in self.get_empty_spots(grid):
possible_game = self.get_new_state(grid, move)
if self.game_win(possible_game, Board.AI) or self.game_win(possible_game, Board.PLAYER):
return move
scores.append(self.score(possible_game, depth))
moves.append(move)
if self.player_turn:
max_score_index = scores.index(max(scores))
move = moves[max_score_index]
return move
else:
min_score_index = scores.index(min(scores))
move = moves[min_score_index]
return move
def game_win(self, grid, participant):
for row in grid:
if row.count(participant) == Board.ROW_LEN:
return True
transposed = [[row[i] for row in grid] for i in range(Board.ROW_LEN)]
for row in transposed:
if row.count(participant) == Board.ROW_LEN:
return True
main_diagonal = [grid[row][row] for row in range(Board.ROW_LEN)]
if main_diagonal.count(participant) == Board.ROW_LEN:
return True
other_diagonal = [grid[row][2 - row] for row in range(Board.ROW_LEN)]
if other_diagonal.count(participant) == Board.ROW_LEN:
return True
return False
def score(self, board, depth):
if self.game_win(board, Board.PLAYER):
return 10 - depth
elif self.game_win(board, Board.AI):
return depth - 10
else:
return 0
def is_game_over(self):
grid_elements = [row[i] for row in self.grid for i in range(Board.ROW_LEN)]
if " " in grid_elements:
return False
return True
def make_player_turn(self):
while True:
try:
row = int(input("Select row: "))
col = int(input("Select col: "))
break
except Exception:
print("Only integer values are accepted.")
return row-1, col-1
def main():
board = Board()
grid_print_list = [row[i] for row in board.grid for i in range(Board.ROW_LEN)]
print(Board.grid_str.format(*grid_print_list))
while not board.is_game_over():
board.grid = board.get_new_state(board.grid, board.make_player_turn())
grid_copy = copy.deepcopy(board.grid)
new_minimax = board.minimax(board.grid, 0)
board.player_turn, board.ai_turn = board.ai_turn, board.player_turn
print(new_minimax)
board.grid = board.get_new_state(grid_copy, new_minimax)
board.player_turn, board.ai_turn = board.ai_turn, board.player_turn
grid_print_list = [row[i] for row in board.grid for i in range(Board.ROW_LEN)]
print(Board.grid_str.format(*grid_print_list))
if board.game_win(board.grid, Board.PLAYER):
print("Congratulations! You win!")
break
if board.game_win(board.grid, Board.AI):
print("You lose!")
break
else:
print("It's a draw.")
if __name__ == '__main__':
main()
| {
"content_hash": "02e45182b81590fa41aa3d12ea34f5f6",
"timestamp": "",
"source": "github",
"line_count": 126,
"max_line_length": 102,
"avg_line_length": 32.03968253968254,
"alnum_prop": 0.5281149368342829,
"repo_name": "stoilov/Programming101",
"id": "bac3a3a4326f8b9db81173908a5b603a26ef2ee0",
"size": "4037",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "exams/tic_tac_toe/main.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "510"
},
{
"name": "C++",
"bytes": "4288"
},
{
"name": "Go",
"bytes": "357"
},
{
"name": "Haskell",
"bytes": "221"
},
{
"name": "Java",
"bytes": "512"
},
{
"name": "JavaScript",
"bytes": "785"
},
{
"name": "Python",
"bytes": "121139"
}
],
"symlink_target": ""
} |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Linq;
using System.Reflection;
using Albedo;
using AutoFixture.Idioms;
using AutoFixture.Kernel;
using TestTypeFoundation;
using Xunit;
namespace AutoFixture.IdiomsUnitTest
{
public class ConstructorInitializedMemberAssertionTest
{
[Fact]
public void SutIsIdiomaticAssertion()
{
// Arrange
var dummyComposer = new Fixture();
// Act
var sut = new ConstructorInitializedMemberAssertion(dummyComposer);
// Assert
Assert.IsAssignableFrom<IdiomaticAssertion>(sut);
}
[Fact]
public void ComposerIsCorrect()
{
// Arrange
var expectedComposer = new Fixture();
var sut = new ConstructorInitializedMemberAssertion(expectedComposer);
// Act
ISpecimenBuilder result = sut.Builder;
// Assert
Assert.Equal(expectedComposer, result);
}
[Fact]
public void ConstructWithNullComposerThrows()
{
// Arrange
// Act & Assert
Assert.Throws<ArgumentNullException>(() =>
new ConstructorInitializedMemberAssertion(null));
}
[Fact]
public void ComparerIsCorrect()
{
// Arrange
var dummyComposer = new Fixture();
var expectedComparer = new FakeEqualityComparer<object>();
var dummyMatcher = new FakeReflectionElementComparer();
var sut = new ConstructorInitializedMemberAssertion(
dummyComposer, expectedComparer, dummyMatcher);
// Act
IEqualityComparer result = sut.Comparer;
// Assert
Assert.Equal(expectedComparer, result);
}
[Fact]
public void ConstructWithNullComparerThrows()
{
// Arrange
var dummyComposer = new Fixture();
var dummyMatcher = new FakeReflectionElementComparer();
// Act & Assert
Assert.Throws<ArgumentNullException>(() =>
new ConstructorInitializedMemberAssertion(dummyComposer, null, dummyMatcher));
}
[Fact]
public void ParameterMemberMatcherIsCorrect()
{
// Arrange
var dummyComposer = new Fixture();
var dummyComparer = new FakeEqualityComparer<object>();
var expectedMatcher = new FakeReflectionElementComparer();
var sut = new ConstructorInitializedMemberAssertion(
dummyComposer, dummyComparer, expectedMatcher);
// Act
IEqualityComparer<IReflectionElement> result = sut.ParameterMemberMatcher;
// Assert
Assert.Equal(expectedMatcher, result);
}
[Fact]
public void ConstructWithNullParameterMemberMatcherThrows()
{
// Arrange
var dummyComposer = new Fixture();
var dummyComparer = new FakeEqualityComparer<object>();
// Act & Assert
Assert.Throws<ArgumentNullException>(() =>
new ConstructorInitializedMemberAssertion(dummyComposer, dummyComparer, null));
}
[Fact]
public void VerifyNullPropertyThrows()
{
// Arrange
var dummyComposer = new Fixture();
var sut = new ConstructorInitializedMemberAssertion(dummyComposer);
// Act & Assert
Assert.Throws<ArgumentNullException>(() =>
sut.Verify((PropertyInfo)null));
}
[Fact]
public void VerifyNullFieldThrows()
{
// Arrange
var dummyComposer = new Fixture();
var sut = new ConstructorInitializedMemberAssertion(dummyComposer);
// Act & Assert
Assert.Throws<ArgumentNullException>(() =>
sut.Verify((FieldInfo)null));
}
[Fact]
public void VerifyNullConstructorInfoThrows()
{
// Arrange
var dummyComposer = new Fixture();
var sut = new ConstructorInitializedMemberAssertion(dummyComposer);
// Act & Assert
Assert.Throws<ArgumentNullException>(() =>
sut.Verify((ConstructorInfo)null));
}
[Fact]
public void VerifyDefaultConstructorDoesNotThrow()
{
// Arrange
var dummyComposer = new Fixture();
var sut = new ConstructorInitializedMemberAssertion(dummyComposer);
// Act & Assert
var constructorWithNoParameters = typeof(PropertyHolder<object>).GetConstructors().First();
Assert.Empty(constructorWithNoParameters.GetParameters());
Assert.Null(Record.Exception(() =>
sut.Verify(constructorWithNoParameters)));
}
[Fact]
public void VerifyWritablePropertyWithNoMatchingConstructorDoesNotThrow()
{
// Arrange
var composer = new Fixture();
var sut = new ConstructorInitializedMemberAssertion(composer);
var propertyInfo = typeof(PropertyHolder<object>).GetProperty("Property");
// Act & Assert
Assert.Null(Record.Exception(() =>
sut.Verify(propertyInfo)));
}
[Fact]
public void VerifyWritableFieldWithNoMatchingConstructorDoesNotThrow()
{
// Arrange
var composer = new Fixture();
var sut = new ConstructorInitializedMemberAssertion(composer);
var propertyInfo = typeof(FieldHolder<object>).GetField("Field");
// Act & Assert
Assert.Null(Record.Exception(() =>
sut.Verify(propertyInfo)));
}
[Fact]
public void VerifyReadOnlyPropertyWithPrivateSetterAndNoMatchingConstructorThrows()
{
// Arrange
var dummyComposer = new Fixture();
var sut = new ConstructorInitializedMemberAssertion(dummyComposer);
var propertyInfo = typeof(ReadOnlyPropertyHolder<int>).GetProperty("Property");
// Act & Assert
var e = Assert.Throws<ConstructorInitializedMemberException>(() =>
sut.Verify(propertyInfo));
AssertExceptionPropertiesEqual(e, propertyInfo);
}
[Fact]
public void VerifyReadOnlyPropertyWithNoSetterAndNoMatchingConstructorThrows()
{
// Arrange
var dummyComposer = new Fixture();
var sut = new ConstructorInitializedMemberAssertion(dummyComposer);
var propertyInfo = typeof(ReadOnlyPropertyWithNoSetterHolder<int>).GetProperty("Property");
// Act & Assert
var e = Assert.Throws<ConstructorInitializedMemberException>(() =>
sut.Verify(propertyInfo));
AssertExceptionPropertiesEqual(e, propertyInfo);
}
[Fact]
public void VerifyWellBehavedReadOnlyPropertyInitializedViaConstructorDoesNotThrow()
{
// Arrange
var dummyComposer = new Fixture();
var sut = new ConstructorInitializedMemberAssertion(dummyComposer);
var propertyInfo = typeof(ReadOnlyPropertyInitializedViaConstructor<object>).GetProperty("Property");
// Act & Assert
Assert.Null(Record.Exception(() => sut.Verify(propertyInfo)));
}
[Fact]
public void VerifyIllBehavedPropertiesInitializedViaConstructorThrows()
{
// Arrange
var dummyComposer = new Fixture();
var sut = new ConstructorInitializedMemberAssertion(dummyComposer);
var illBehavedType = typeof(PropertiesIncorrectlyInitializedViaConstructor<object, object>);
var propertyInfo1 = illBehavedType.GetProperty("Property1");
var propertyInfo2 = illBehavedType.GetProperty("Property2");
// Act & Assert
var e1 = Assert.Throws<ConstructorInitializedMemberException>(() => sut.Verify(propertyInfo1));
AssertExceptionPropertiesEqual(e1, propertyInfo1);
var e2 = Assert.Throws<ConstructorInitializedMemberException>(() => sut.Verify(propertyInfo2));
AssertExceptionPropertiesEqual(e2, propertyInfo2);
}
[Fact]
public void VerifyWellBehavedReadOnlyFieldInitializedViaConstructorDoesNotThrow()
{
// Arrange
var dummyComposer = new Fixture();
var sut = new ConstructorInitializedMemberAssertion(dummyComposer);
var fieldInfo = typeof(ReadOnlyFieldInitializedViaConstructor<object>).GetField("Field");
// Act & Assert
Assert.Null(Record.Exception(() => sut.Verify(fieldInfo)));
}
[Fact]
public void VerifyReadOnlyFieldInitializedViaConstructorWithDifferentTypeThrows()
{
// Arrange
var dummyComposer = new Fixture();
var sut = new ConstructorInitializedMemberAssertion(dummyComposer);
var fieldInfo = typeof(ReadOnlyFieldInitializedViaConstructorWithDifferentType).GetField("Field");
// Act & Assert
var e = Assert.Throws<ConstructorInitializedMemberException>(() => sut.Verify(fieldInfo));
AssertExceptionPropertiesEqual(e, fieldInfo);
}
[Fact]
public void VerifyAllConstructorArgumentsAreExposedAsFieldsDoesNotThrow()
{
// Arrange
var dummyComposer = new Fixture();
var sut = new ConstructorInitializedMemberAssertion(dummyComposer);
var ctor1 = typeof(FieldsInitializedViaConstructor<object, int>).GetConstructor(new[] { typeof(object) });
var ctor2 = typeof(FieldsInitializedViaConstructor<object, int>).GetConstructor(new[] { typeof(int) });
var ctor3 = typeof(FieldsInitializedViaConstructor<object, int>).GetConstructor(new[] { typeof(object), typeof(int) });
// Act & Assert
Assert.Null(Record.Exception(() => sut.Verify(ctor1)));
Assert.Null(Record.Exception(() => sut.Verify(ctor2)));
Assert.Null(Record.Exception(() => sut.Verify(ctor3)));
}
[Fact]
public void VerifyWhenNotAllConstructorArgumentsAreExposedAsFieldsThrows()
{
// Arrange
var dummyComposer = new Fixture();
var sut = new ConstructorInitializedMemberAssertion(dummyComposer);
var ctor = typeof(FieldsInitializedViaConstructor<object, int>)
.GetConstructor(new[] { typeof(object), typeof(int), typeof(TriState) });
// Act & Assert
var e = Assert.Throws<ConstructorInitializedMemberException>(() => sut.Verify(ctor));
var expectedMissingParam = ctor.GetParameters().Single(p => p.Name == "noMatchingField");
AssertExceptionPropertiesEqual(e, ctor, expectedMissingParam);
}
[Fact]
public void VerifyConstructorArgumentsAreExposedAsProperties()
{
// Arrange
var dummyComposer = new Fixture();
var sut = new ConstructorInitializedMemberAssertion(dummyComposer);
var ctor1 = typeof(ReadOnlyPropertiesInitializedViaConstructor<object, int>).GetConstructor(new[] { typeof(object) });
var ctor2 = typeof(ReadOnlyPropertiesInitializedViaConstructor<object, int>).GetConstructor(new[] { typeof(int) });
var ctor3 = typeof(ReadOnlyPropertiesInitializedViaConstructor<object, int>).GetConstructor(new[] { typeof(object), typeof(int) });
// Act & Assert
Assert.Null(Record.Exception(() => sut.Verify(ctor1)));
Assert.Null(Record.Exception(() => sut.Verify(ctor2)));
Assert.Null(Record.Exception(() => sut.Verify(ctor3)));
}
[Fact]
public void VerifyWhenNotAllConstructorArgumentsAreExposedAsPropertiesThrows()
{
// Arrange
var dummyComposer = new Fixture();
var sut = new ConstructorInitializedMemberAssertion(dummyComposer);
var ctor = typeof(ReadOnlyPropertiesInitializedViaConstructor<object, int>)
.GetConstructor(new[] { typeof(object), typeof(int), typeof(TriState) });
// Act & Assert
var e = Assert.Throws<ConstructorInitializedMemberException>(() => sut.Verify(ctor));
var expectedMissingParam = ctor.GetParameters().Single(p => p.Name == "noMatchingProperty");
AssertExceptionPropertiesEqual(e, ctor, expectedMissingParam);
}
[Fact]
public void VerifyWhenConstructorArgumentTypeIsDifferentToFieldThrows()
{
// Arrange
var dummyComposer = new Fixture();
var sut = new ConstructorInitializedMemberAssertion(dummyComposer);
var ctor = typeof(ReadOnlyFieldInitializedViaConstructorWithDifferentType).GetConstructors().First();
// Act & Assert
var e = Assert.Throws<ConstructorInitializedMemberException>(() => sut.Verify(ctor));
var expectedMissingParam = ctor.GetParameters().Single(p => p.Name == "value");
AssertExceptionPropertiesEqual(e, ctor, expectedMissingParam);
}
[Fact]
public void VerifyWhenPropertyTypeIsAssignableFromParameterTypeShouldThrow()
{
// Arrange
var dummyComposer = new Fixture();
var sut = new ConstructorInitializedMemberAssertion(dummyComposer);
var ctor = typeof(PropertyIsAssignableFromConstructorArgumentType).GetConstructors().First();
// Act & Assert
Assert.Throws<ConstructorInitializedMemberException>(() =>
sut.Verify(ctor));
}
[Fact]
public void VerifyWhenMemberTypeIsComplexDoesNotThrow()
{
// Arrange
var dummyComposer = new Fixture();
var sut = new ConstructorInitializedMemberAssertion(dummyComposer);
var ctor = typeof(ReadOnlyPropertiesInitializedViaConstructor<ComplexType, object>)
.GetConstructor(new[] { typeof(ComplexType), typeof(object) });
// Act & Assert
Assert.Null(Record.Exception(() => sut.Verify(ctor)));
}
[Fact]
public void VerifyWhenMemberTypeIsComplexWithIllBehavedConstructorThrows()
{
// Arrange
var dummyComposer = new Fixture();
var sut = new ConstructorInitializedMemberAssertion(dummyComposer);
var ctor = typeof(ReadOnlyPropertiesInitializedViaConstructor<ComplexType, object>)
.GetConstructor(new[] { typeof(ComplexType), typeof(object), typeof(TriState) });
// Act & Assert
var e = Assert.Throws<ConstructorInitializedMemberException>(
() => sut.Verify(ctor));
var expectedMissingParameter = ctor.GetParameters().Single(p => p.Name == "noMatchingProperty");
AssertExceptionPropertiesEqual(e, ctor, expectedMissingParameter);
}
[Fact]
public void VerifyWhenConstructorArgumentHasWriteOnlyPropertyDoesNotThrow()
{
// Arrange
var dummyComposer = new Fixture();
var sut = new ConstructorInitializedMemberAssertion(dummyComposer);
var ctor = typeof(WriteOnlyPropertyHolder<ComplexType>).GetConstructors().First();
// Act & Assert
Assert.Null(
Record.Exception(() => sut.Verify(ctor)));
}
[Fact]
public void VerifyWhenPropertyIsWriteOnlyDoesNotThrow()
{
// Arrange
var dummyComposer = new Fixture();
var sut = new ConstructorInitializedMemberAssertion(dummyComposer);
var propertyInfo = typeof(WriteOnlyPropertyHolder<ComplexType>).GetProperty("WriteOnlyProperty");
// Act & Assert
Assert.Null(Record.Exception(() => sut.Verify(propertyInfo)));
}
[Fact]
public void VerifyWhenPropertyGetterIsInternalDoesNotThrow()
{
// Arrange
var dummyComposer = new Fixture();
var sut = new ConstructorInitializedMemberAssertion(dummyComposer);
var propertyInfo = typeof(InternalGetterPropertyHolder<ComplexType>).GetProperty("Property");
// Act & Assert
Assert.Null(Record.Exception(() => sut.Verify(propertyInfo)));
}
[Fact]
public void VerifyTypeWithPublicWritablePropertyAndNoMatchingConstructorArgumentDoesNotThrow()
{
// Arrange
var dummyComposer = new Fixture();
var sut = new ConstructorInitializedMemberAssertion(dummyComposer);
var typeToVerify = typeof(PropertyHolder<ComplexType>);
// Act & Assert
Assert.Null(Record.Exception(() => sut.Verify(typeToVerify)));
}
[Fact]
public void VerifyTypeWithPublicStaticPropertyAndNoMatchingConstructorArgumentDoesNotThrow()
{
// Arrange
var dummyComposer = new Fixture();
var sut = new ConstructorInitializedMemberAssertion(dummyComposer);
var typeToVerify = typeof(StaticPropertyHolder<ComplexType>);
// Act & Assert
Assert.Null(Record.Exception(() => sut.Verify(typeToVerify)));
}
[Fact]
public void VerifyTypeWithPublicStaticFieldAndNoMatchingConstructorArgumentDoesNotThrow()
{
// Arrange
var dummyComposer = new Fixture();
var sut = new ConstructorInitializedMemberAssertion(dummyComposer);
var typeToVerify = typeof(StaticFieldHolder<ComplexType>);
// Act & Assert
Assert.Null(Record.Exception(() => sut.Verify(typeToVerify)));
}
[Fact]
public void VerifyTypeWithPublicStaticReadOnlyFieldAndNoMatchingGuardedConstuctorArgumentDoesNotThrow()
{
// Arrange
var dummyComposer = new Fixture();
var sut = new ConstructorInitializedMemberAssertion(dummyComposer);
var typeToVerify = typeof(GuardedConstructorHostHoldingStaticReadOnlyField<ComplexType, int>);
// Act & Assert
Assert.Null(Record.Exception(() => sut.Verify(typeToVerify)));
}
[Fact]
public void VerifyTypeWithPublicStaticReadOnlyPropertyAndNoMatchingGuardedConstuctorArgumentDoesNotThrow()
{
// Arrange
var dummyComposer = new Fixture();
var sut = new ConstructorInitializedMemberAssertion(dummyComposer);
var typeToVerify = typeof(GuardedConstructorHostHoldingStaticReadOnlyProperty<ComplexType, int>);
// Act & Assert
Assert.Null(Record.Exception(() => sut.Verify(typeToVerify)));
}
[Fact]
public void VerifyTypeWithReadOnlyPropertyAndIllBehavedConstructorThrows()
{
// Arrange
var dummyComposer = new Fixture();
var sut = new ConstructorInitializedMemberAssertion(dummyComposer);
var typeToVerify = typeof(ReadOnlyPropertiesInitializedViaConstructor<int, string>);
// Act & Assert
var e = Assert.Throws<ConstructorInitializedMemberException>(() => sut.Verify(typeToVerify));
var expectedFailingConstructor = typeToVerify.GetConstructor(new[] { typeof(int), typeof(string), typeof(TriState) });
var expectedFailingParameter = expectedFailingConstructor.GetParameters().Single(p => p.Name == "noMatchingProperty");
AssertExceptionPropertiesEqual(e, expectedFailingConstructor, expectedFailingParameter);
}
[Fact]
public void VerifyTypeWithWritablePropertyAndMatchingIllBehavedConstructorArgumentThrows()
{
// Arrange
var dummyComposer = new Fixture();
var sut = new ConstructorInitializedMemberAssertion(dummyComposer);
var typeToVerify = typeof(WritablePropertyAndIllBehavedConstructor);
// Act & Assert
var e = Assert.Throws<ConstructorInitializedMemberException>(() => sut.Verify(typeToVerify));
var expectedFailingProperty = typeToVerify.GetProperties().Single();
AssertExceptionPropertiesEqual(e, expectedFailingProperty);
}
[Fact]
public void VerifyTypeWithPublicReadOnlyFieldsIncorrectlyInitialisedViaConstructorThrows()
{
// Arrange
var dummyComposer = new Fixture();
var sut = new ConstructorInitializedMemberAssertion(dummyComposer);
var typeToVerify = typeof(PublicReadOnlyFieldNotInitializedByConstructor);
// Act & Assert
var e = Assert.Throws<ConstructorInitializedMemberException>(() => sut.Verify(typeToVerify));
var expectedFailingField = typeToVerify.GetFields().First();
AssertExceptionPropertiesEqual(e, expectedFailingField);
}
[Theory]
[InlineData(typeof(ReadOnlyFieldInitializedViaConstructor<TestIntEnum>))]
[InlineData(typeof(ReadOnlyPropertyInitializedViaConstructor<TestIntEnum>))]
[InlineData(typeof(ReadOnlyFieldInitializedViaConstructor<TestByteEnum>))]
[InlineData(typeof(ReadOnlyPropertyInitializedViaConstructor<TestByteEnum>))]
[InlineData(typeof(ReadOnlyFieldInitializedViaConstructor<TestSByteEnum>))]
[InlineData(typeof(ReadOnlyPropertyInitializedViaConstructor<TestSByteEnum>))]
[InlineData(typeof(ReadOnlyFieldInitializedViaConstructor<TestShortEnum>))]
[InlineData(typeof(ReadOnlyPropertyInitializedViaConstructor<TestShortEnum>))]
[InlineData(typeof(ReadOnlyFieldInitializedViaConstructor<TestUShortEnum>))]
[InlineData(typeof(ReadOnlyPropertyInitializedViaConstructor<TestUShortEnum>))]
[InlineData(typeof(ReadOnlyFieldInitializedViaConstructor<TestUIntEnum>))]
[InlineData(typeof(ReadOnlyPropertyInitializedViaConstructor<TestUIntEnum>))]
[InlineData(typeof(ReadOnlyFieldInitializedViaConstructor<TestLongEnum>))]
[InlineData(typeof(ReadOnlyPropertyInitializedViaConstructor<TestLongEnum>))]
[InlineData(typeof(ReadOnlyFieldInitializedViaConstructor<TestULongEnum>))]
[InlineData(typeof(ReadOnlyPropertyInitializedViaConstructor<TestULongEnum>))]
[InlineData(typeof(ReadOnlyFieldInitializedViaConstructor<TestSingleNonDefaultEnum>))]
[InlineData(typeof(ReadOnlyPropertyInitializedViaConstructor<TestSingleNonDefaultEnum>))]
public void VerifyWellBehavedEnumInitializersDoNotThrow(Type type)
{
// Arrange
var fixture = new Fixture();
var sut = new ConstructorInitializedMemberAssertion(fixture);
// Act & Assert
Assert.Null(Record.Exception(() => sut.Verify(type)));
}
[Theory]
[InlineData(typeof(ReadOnlyFieldIncorrectlyInitializedViaConstructor<TestIntEnum>))]
[InlineData(typeof(ReadOnlyPropertyIncorrectlyInitializedViaConstructor<TestIntEnum>))]
[InlineData(typeof(ReadOnlyFieldIncorrectlyInitializedViaConstructor<TestByteEnum>))]
[InlineData(typeof(ReadOnlyPropertyIncorrectlyInitializedViaConstructor<TestByteEnum>))]
[InlineData(typeof(ReadOnlyFieldIncorrectlyInitializedViaConstructor<TestSByteEnum>))]
[InlineData(typeof(ReadOnlyPropertyIncorrectlyInitializedViaConstructor<TestSByteEnum>))]
[InlineData(typeof(ReadOnlyFieldIncorrectlyInitializedViaConstructor<TestShortEnum>))]
[InlineData(typeof(ReadOnlyPropertyIncorrectlyInitializedViaConstructor<TestShortEnum>))]
[InlineData(typeof(ReadOnlyFieldIncorrectlyInitializedViaConstructor<TestUShortEnum>))]
[InlineData(typeof(ReadOnlyPropertyIncorrectlyInitializedViaConstructor<TestUShortEnum>))]
[InlineData(typeof(ReadOnlyFieldIncorrectlyInitializedViaConstructor<TestUIntEnum>))]
[InlineData(typeof(ReadOnlyPropertyIncorrectlyInitializedViaConstructor<TestUIntEnum>))]
[InlineData(typeof(ReadOnlyFieldIncorrectlyInitializedViaConstructor<TestLongEnum>))]
[InlineData(typeof(ReadOnlyPropertyIncorrectlyInitializedViaConstructor<TestLongEnum>))]
[InlineData(typeof(ReadOnlyFieldIncorrectlyInitializedViaConstructor<TestULongEnum>))]
[InlineData(typeof(ReadOnlyPropertyIncorrectlyInitializedViaConstructor<TestULongEnum>))]
[InlineData(typeof(ReadOnlyFieldIncorrectlyInitializedViaConstructor<TestSingleNonDefaultEnum>))]
[InlineData(typeof(ReadOnlyPropertyIncorrectlyInitializedViaConstructor<TestSingleNonDefaultEnum>))]
public void VerifyIllBehavedEnumInitializersDoThrow(Type type)
{
// Arrange
var fixture = new Fixture();
var sut = new ConstructorInitializedMemberAssertion(fixture);
// Act & Assert
Assert.Throws<ConstructorInitializedMemberException>(() => sut.Verify(type));
}
[Theory]
[InlineData(typeof(ReadOnlyFieldInitializedViaConstructor<TestDefaultOnlyEnum>))]
[InlineData(typeof(ReadOnlyPropertyInitializedViaConstructor<TestDefaultOnlyEnum>))]
[InlineData(typeof(ReadOnlyPropertyIncorrectlyInitializedViaConstructor<TestDefaultOnlyEnum>))]
public void VerifyDefaultOnlyEnumDoesThrowBecauseOfPotentialFalsePositive(Type type)
{
// Arrange
var fixture = new Fixture();
var sut = new ConstructorInitializedMemberAssertion(fixture);
// Act & Assert
Assert.Throws<ConstructorInitializedMemberException>(() => sut.Verify(type));
}
[Theory]
[InlineData(typeof(IllBehavedFieldMatchedByEvenPositionConstructorParameter<TestIntEnum, bool>))]
[InlineData(typeof(IllBehavedPropertyMatchedByEvenPositionConstructorParameter<TestIntEnum, bool>))]
public void FailForUninitializedBooleanMember(Type type)
{
// Arrange
var fixture = new Fixture();
var sut = new ConstructorInitializedMemberAssertion(fixture);
// Act & Assert
Assert.Throws<ConstructorInitializedMemberException>(() => sut.Verify(type));
}
private static void AssertExceptionPropertiesEqual(
ConstructorInitializedMemberException ex, ConstructorInfo ctor, ParameterInfo param)
{
Assert.Equal(param, ex.MissingParameter);
Assert.Equal(ctor, ex.MemberInfo);
Assert.Equal(ctor, ex.ConstructorInfo);
Assert.Null(ex.FieldInfo);
Assert.Null(ex.PropertyInfo);
}
private static void AssertExceptionPropertiesEqual(ConstructorInitializedMemberException ex, PropertyInfo pi)
{
Assert.Null(ex.ConstructorInfo);
Assert.Null(ex.MissingParameter);
Assert.Equal(pi, ex.MemberInfo);
Assert.Null(ex.FieldInfo);
Assert.Equal(pi, ex.PropertyInfo);
}
private static void AssertExceptionPropertiesEqual(ConstructorInitializedMemberException ex, FieldInfo fi)
{
Assert.Null(ex.ConstructorInfo);
Assert.Null(ex.MissingParameter);
Assert.Equal(fi, ex.MemberInfo);
Assert.Equal(fi, ex.FieldInfo);
Assert.Null(ex.PropertyInfo);
}
private class IllBehavedPropertyMatchedByEvenPositionConstructorParameter<T1, T2>
{
public IllBehavedPropertyMatchedByEvenPositionConstructorParameter(T1 member1, T2 member2)
{
this.Member1 = member1;
}
public T1 Member1 { get; }
public T2 Member2 { get; }
}
private class IllBehavedFieldMatchedByEvenPositionConstructorParameter<T1, T2>
{
public IllBehavedFieldMatchedByEvenPositionConstructorParameter(T1 member1, T2 member2)
{
this.Member1 = member1;
}
public readonly T1 Member1;
public readonly T2 Member2 = default(T2);
}
private class PublicReadOnlyFieldNotInitializedByConstructor
{
#pragma warning disable 649
public readonly int Field;
#pragma warning restore 649
}
private class ReadOnlyPropertyWithNoSetterHolder<T>
{
public T Property => default(T);
}
private class WritablePropertyAndIllBehavedConstructor
{
public WritablePropertyAndIllBehavedConstructor(int property)
{
}
public int Property { get; set; }
}
private class WriteOnlyPropertyHolder<T>
{
private T writeOnlyPropertyBackingField;
public WriteOnlyPropertyHolder(T writeOnlyProperty)
{
this.writeOnlyPropertyBackingField = writeOnlyProperty;
}
public T GetWriteOnlyProperty()
{
return this.writeOnlyPropertyBackingField;
}
public T WriteOnlyProperty
{
set
{
this.writeOnlyPropertyBackingField = value;
}
}
}
private class ComplexType
{
public ComplexType()
{
this.Children = new Collection<ComplexTypeChild>();
}
public ICollection<ComplexTypeChild> Children { get; set; }
}
private class ComplexTypeChild
{
public string Name { get; set; }
}
private class PropertyIsAssignableFromConstructorArgumentType
{
private readonly IEnumerable<string> bribbets;
public PropertyIsAssignableFromConstructorArgumentType(params string[] bribbets)
{
this.bribbets = bribbets;
}
public IEnumerable<string> Bribbets
{
get { return this.bribbets; }
}
}
private class ReadOnlyFieldInitializedViaConstructorWithDifferentType
{
public readonly string Field;
public ReadOnlyFieldInitializedViaConstructorWithDifferentType(int value)
{
this.Field = value.ToString(CultureInfo.CurrentCulture);
}
}
private class ReadOnlyFieldInitializedViaConstructor<T>
{
public readonly T Field;
public ReadOnlyFieldInitializedViaConstructor(T field)
{
this.Field = field;
}
}
private class ReadOnlyFieldIncorrectlyInitializedViaConstructor<T>
{
#pragma warning disable 649
public readonly T Field;
#pragma warning restore 649
public ReadOnlyFieldIncorrectlyInitializedViaConstructor(T field)
{
}
}
private class ReadOnlyPropertiesInitializedViaConstructor<T1, T2>
{
public ReadOnlyPropertiesInitializedViaConstructor(T1 property1)
{
this.Property1 = property1;
}
public ReadOnlyPropertiesInitializedViaConstructor(T2 property2)
{
this.Property2 = property2;
}
public ReadOnlyPropertiesInitializedViaConstructor(T1 property1, T2 property2)
{
this.Property1 = property1;
this.Property2 = property2;
}
public ReadOnlyPropertiesInitializedViaConstructor(T1 property1, T2 property2, TriState noMatchingProperty)
{
this.Property1 = property1;
this.Property2 = property2;
}
public T1 Property1 { get; private set; }
public T2 Property2 { get; private set; }
}
private class PropertiesIncorrectlyInitializedViaConstructor<T1, T2>
{
public PropertiesIncorrectlyInitializedViaConstructor(T1 property1, T2 property2)
{
}
public PropertiesIncorrectlyInitializedViaConstructor(T1 property1)
{
}
public PropertiesIncorrectlyInitializedViaConstructor(T2 property2)
{
}
public T1 Property1 { get; set; }
public T2 Property2 { get; set; }
}
private class FieldsInitializedViaConstructor<T1, T2>
{
public FieldsInitializedViaConstructor(T1 field1)
{
this.Field1 = field1;
}
public FieldsInitializedViaConstructor(T2 field2)
{
this.Field2 = field2;
}
public FieldsInitializedViaConstructor(T1 field1, T2 field2)
{
this.Field1 = field1;
this.Field2 = field2;
}
public FieldsInitializedViaConstructor(T1 field1, T2 field2, TriState noMatchingField)
{
this.Field1 = field1;
this.Field2 = field2;
}
public T1 Field1;
public T2 Field2;
}
private class ReadOnlyPropertyInitializedViaConstructor<T>
{
public ReadOnlyPropertyInitializedViaConstructor(T property)
{
this.Property = property;
}
public T Property { get; private set; }
}
private class ReadOnlyPropertyIncorrectlyInitializedViaConstructor<T>
{
public ReadOnlyPropertyIncorrectlyInitializedViaConstructor(T property)
{
}
public T Property { get; private set; }
}
private class FakeReflectionElementComparer : IEqualityComparer<IReflectionElement>
{
public bool Equals(IReflectionElement x, IReflectionElement y)
{
throw new NotImplementedException();
}
public int GetHashCode(IReflectionElement obj)
{
throw new NotImplementedException();
}
}
private class FakeEqualityComparer<T> : IEqualityComparer
{
bool IEqualityComparer.Equals(object x, object y)
{
throw new NotImplementedException();
}
int IEqualityComparer.GetHashCode(object obj)
{
throw new NotImplementedException();
}
}
// All approved enum type variants : https://msdn.microsoft.com/en-us/library/sbbt4032.aspx?f=255&MSPPError=-2147217396
private enum TestIntEnum
{
None = 0,
One,
Two,
Three
}
private enum TestByteEnum : byte
{
None = 0,
One,
Two,
Three
}
private enum TestSByteEnum : sbyte
{
None = 0,
One,
Two,
Three
}
private enum TestShortEnum : short
{
None = 0,
One,
Two,
Three
}
private enum TestUShortEnum : ushort
{
None = 0,
One,
Two,
Three
}
private enum TestUIntEnum : uint
{
None = 0,
One,
Two,
Three
}
private enum TestLongEnum : long
{
None = 0,
One,
Two,
Three
}
private enum TestULongEnum : ulong
{
None = 0,
One,
Two,
Three
}
private enum TestDefaultOnlyEnum
{
None = 0
}
private enum TestSingleNonDefaultEnum
{
None = 1
}
}
}
| {
"content_hash": "54a05698e0b8178274da21964fb0eb1a",
"timestamp": "",
"source": "github",
"line_count": 916,
"max_line_length": 143,
"avg_line_length": 39.52292576419214,
"alnum_prop": 0.6216335662790377,
"repo_name": "sean-gilliam/AutoFixture",
"id": "576a6372f59516e61b75048936d00e9b52a87c33",
"size": "36205",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Src/IdiomsUnitTest/ConstructorInitializedMemberAssertionTest.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "636"
},
{
"name": "C#",
"bytes": "3789585"
},
{
"name": "F#",
"bytes": "42075"
},
{
"name": "Puppet",
"bytes": "156"
}
],
"symlink_target": ""
} |
module Azure::NetApp::Mgmt::V2019_06_01
module Models
#
# Defines values for CheckNameResourceTypes
#
module CheckNameResourceTypes
MicrosoftNetAppnetAppAccounts = "Microsoft.NetApp/netAppAccounts"
MicrosoftNetAppnetAppAccountscapacityPools = "Microsoft.NetApp/netAppAccounts/capacityPools"
MicrosoftNetAppnetAppAccountscapacityPoolsvolumes = "Microsoft.NetApp/netAppAccounts/capacityPools/volumes"
MicrosoftNetAppnetAppAccountscapacityPoolsvolumessnapshots = "Microsoft.NetApp/netAppAccounts/capacityPools/volumes/snapshots"
end
end
end
| {
"content_hash": "e84e476f45e50a3d7812bfc218b0a1b6",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 132,
"avg_line_length": 45.07692307692308,
"alnum_prop": 0.8071672354948806,
"repo_name": "Azure/azure-sdk-for-ruby",
"id": "e76691e40ee10f74e0883c8c9f857bfde48fa99d",
"size": "750",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "management/azure_mgmt_netapp/lib/2019-06-01/generated/azure_mgmt_netapp/models/check_name_resource_types.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "345216400"
},
{
"name": "Shell",
"bytes": "305"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="generator" content="Docutils 0.19: https://docutils.sourceforge.io/" />
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="lang:clipboard.copy" content="Copy to clipboard">
<meta name="lang:clipboard.copied" content="Copied to clipboard">
<meta name="lang:search.language" content="en">
<meta name="lang:search.pipeline.stopwords" content="True">
<meta name="lang:search.pipeline.trimmer" content="True">
<meta name="lang:search.result.none" content="No matching documents">
<meta name="lang:search.result.one" content="1 matching document">
<meta name="lang:search.result.other" content="# matching documents">
<meta name="lang:search.tokenizer" content="[\s\-]+">
<link href="https://fonts.gstatic.com/" rel="preconnect" crossorigin>
<link href="https://fonts.googleapis.com/css?family=Roboto+Mono:400,500,700|Roboto:300,400,400i,700&display=fallback" rel="stylesheet">
<style>
body,
input {
font-family: "Roboto", "Helvetica Neue", Helvetica, Arial, sans-serif
}
code,
kbd,
pre {
font-family: "Roboto Mono", "Courier New", Courier, monospace
}
</style>
<link rel="stylesheet" href="../_static/stylesheets/application.css"/>
<link rel="stylesheet" href="../_static/stylesheets/application-palette.css"/>
<link rel="stylesheet" href="../_static/stylesheets/application-fixes.css"/>
<link rel="stylesheet" href="../_static/fonts/material-icons.css"/>
<meta name="theme-color" content="#3f51b5">
<script src="../_static/javascripts/modernizr.js"></script>
<title>statsmodels.discrete.discrete_model.MultinomialModel.cdf — statsmodels</title>
<link rel="icon" type="image/png" sizes="32x32" href="../_static/icons/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="../_static/icons/favicon-16x16.png">
<link rel="manifest" href="../_static/icons/site.webmanifest">
<link rel="mask-icon" href="../_static/icons/safari-pinned-tab.svg" color="#919191">
<meta name="msapplication-TileColor" content="#2b5797">
<meta name="msapplication-config" content="../_static/icons/browserconfig.xml">
<link rel="stylesheet" href="../_static/stylesheets/examples.css">
<link rel="stylesheet" href="../_static/stylesheets/deprecation.css">
<link rel="stylesheet" type="text/css" href="../_static/pygments.css" />
<link rel="stylesheet" type="text/css" href="../_static/material.css" />
<link rel="stylesheet" type="text/css" href="../_static/graphviz.css" />
<link rel="stylesheet" type="text/css" href="../_static/plot_directive.css" />
<script data-url_root="../" id="documentation_options" src="../_static/documentation_options.js"></script>
<script src="../_static/jquery.js"></script>
<script src="../_static/underscore.js"></script>
<script src="../_static/_sphinx_javascript_frameworks_compat.js"></script>
<script src="../_static/doctools.js"></script>
<script src="../_static/sphinx_highlight.js"></script>
<script crossorigin="anonymous" integrity="sha256-Ae2Vz/4ePdIu6ZyI/5ZGsYnb+m0JlOmKPjt6XZ9JJkA=" src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.4/require.min.js"></script>
<link rel="shortcut icon" href="../_static/favicon.ico"/>
<link rel="author" title="About these documents" href="../about.html" />
<link rel="index" title="Index" href="../genindex.html" />
<link rel="search" title="Search" href="../search.html" />
<link rel="next" title="statsmodels.discrete.discrete_model.MultinomialModel.cov_params_func_l1" href="statsmodels.discrete.discrete_model.MultinomialModel.cov_params_func_l1.html" />
<link rel="prev" title="statsmodels.discrete.discrete_model.MultinomialModel" href="statsmodels.discrete.discrete_model.MultinomialModel.html" />
</head>
<body dir=ltr
data-md-color-primary=indigo data-md-color-accent=blue>
<svg class="md-svg">
<defs data-children-count="0">
<svg xmlns="http://www.w3.org/2000/svg" width="416" height="448" viewBox="0 0 416 448" id="__github"><path fill="currentColor" d="M160 304q0 10-3.125 20.5t-10.75 19T128 352t-18.125-8.5-10.75-19T96 304t3.125-20.5 10.75-19T128 256t18.125 8.5 10.75 19T160 304zm160 0q0 10-3.125 20.5t-10.75 19T288 352t-18.125-8.5-10.75-19T256 304t3.125-20.5 10.75-19T288 256t18.125 8.5 10.75 19T320 304zm40 0q0-30-17.25-51T296 232q-10.25 0-48.75 5.25Q229.5 240 208 240t-39.25-2.75Q130.75 232 120 232q-29.5 0-46.75 21T56 304q0 22 8 38.375t20.25 25.75 30.5 15 35 7.375 37.25 1.75h42q20.5 0 37.25-1.75t35-7.375 30.5-15 20.25-25.75T360 304zm56-44q0 51.75-15.25 82.75-9.5 19.25-26.375 33.25t-35.25 21.5-42.5 11.875-42.875 5.5T212 416q-19.5 0-35.5-.75t-36.875-3.125-38.125-7.5-34.25-12.875T37 371.5t-21.5-28.75Q0 312 0 260q0-59.25 34-99-6.75-20.5-6.75-42.5 0-29 12.75-54.5 27 0 47.5 9.875t47.25 30.875Q171.5 96 212 96q37 0 70 8 26.25-20.5 46.75-30.25T376 64q12.75 25.5 12.75 54.5 0 21.75-6.75 42 34 40 34 99.5z"/></svg>
</defs>
</svg>
<input class="md-toggle" data-md-toggle="drawer" type="checkbox" id="__drawer">
<input class="md-toggle" data-md-toggle="search" type="checkbox" id="__search">
<label class="md-overlay" data-md-component="overlay" for="__drawer"></label>
<a href="#generated/statsmodels.discrete.discrete_model.MultinomialModel.cdf" tabindex="1" class="md-skip"> Skip to content </a>
<header class="md-header" data-md-component="header">
<nav class="md-header-nav md-grid">
<div class="md-flex navheader">
<div class="md-flex__cell md-flex__cell--shrink">
<a href="../index.html" title="statsmodels"
class="md-header-nav__button md-logo">
<img src="../_static/statsmodels-logo-v2-bw.svg" height="26"
alt="statsmodels logo">
</a>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<label class="md-icon md-icon--menu md-header-nav__button" for="__drawer"></label>
</div>
<div class="md-flex__cell md-flex__cell--stretch">
<div class="md-flex__ellipsis md-header-nav__title" data-md-component="title">
<span class="md-header-nav__topic">statsmodels 0.13.4</span>
<span class="md-header-nav__topic"> statsmodels.discrete.discrete_model.MultinomialModel.cdf </span>
</div>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<label class="md-icon md-icon--search md-header-nav__button" for="__search"></label>
<div class="md-search" data-md-component="search" role="dialog">
<label class="md-search__overlay" for="__search"></label>
<div class="md-search__inner" role="search">
<form class="md-search__form" action="../search.html" method="get" name="search">
<input type="text" class="md-search__input" name="q" placeholder="Search"
autocapitalize="off" autocomplete="off" spellcheck="false"
data-md-component="query" data-md-state="active">
<label class="md-icon md-search__icon" for="__search"></label>
<button type="reset" class="md-icon md-search__icon" data-md-component="reset" tabindex="-1">

</button>
</form>
<div class="md-search__output">
<div class="md-search__scrollwrap" data-md-scrollfix>
<div class="md-search-result" data-md-component="result">
<div class="md-search-result__meta">
Type to start searching
</div>
<ol class="md-search-result__list"></ol>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<div class="md-header-nav__source">
<a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github">
<div class="md-source__icon">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28">
<use xlink:href="#__github" width="24" height="24"></use>
</svg>
</div>
<div class="md-source__repository">
statsmodels
</div>
</a>
</div>
</div>
<script src="../_static/javascripts/version_dropdown.js"></script>
<script>
var json_loc = "../../versions-v2.json",
target_loc = "../../",
text = "Versions";
$( document ).ready( add_version_dropdown(json_loc, target_loc, text));
</script>
</div>
</nav>
</header>
<div class="md-container">
<nav class="md-tabs" data-md-component="tabs">
<div class="md-tabs__inner md-grid">
<ul class="md-tabs__list">
<li class="md-tabs__item"><a href="../user-guide.html" class="md-tabs__link">User Guide</a></li>
<li class="md-tabs__item"><a href="../discretemod.html" class="md-tabs__link">Regression with Discrete Dependent Variable</a></li>
<li class="md-tabs__item"><a href="statsmodels.discrete.discrete_model.MultinomialModel.html" class="md-tabs__link">statsmodels.discrete.discrete_model.MultinomialModel</a></li>
</ul>
</div>
</nav>
<main class="md-main">
<div class="md-main__inner md-grid" data-md-component="container">
<div class="md-sidebar md-sidebar--primary" data-md-component="navigation">
<div class="md-sidebar__scrollwrap">
<div class="md-sidebar__inner">
<nav class="md-nav md-nav--primary" data-md-level="0">
<label class="md-nav__title md-nav__title--site" for="__drawer">
<a href="../index.html" title="statsmodels" class="md-nav__button md-logo">
<img src="../_static/statsmodels-logo-v2-bw.svg" alt=" logo" width="48" height="48">
</a>
<a href="../index.html"
title="statsmodels">statsmodels 0.13.4</a>
</label>
<div class="md-nav__source">
<a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github">
<div class="md-source__icon">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28">
<use xlink:href="#__github" width="24" height="24"></use>
</svg>
</div>
<div class="md-source__repository">
statsmodels
</div>
</a>
</div>
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="../install.html" class="md-nav__link">Installing statsmodels</a>
</li>
<li class="md-nav__item">
<a href="../gettingstarted.html" class="md-nav__link">Getting started</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html" class="md-nav__link">User Guide</a>
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="../user-guide.html#background" class="md-nav__link">Background</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#regression-and-linear-models" class="md-nav__link">Regression and Linear Models</a>
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="../regression.html" class="md-nav__link">Linear Regression</a>
</li>
<li class="md-nav__item">
<a href="../glm.html" class="md-nav__link">Generalized Linear Models</a>
</li>
<li class="md-nav__item">
<a href="../gee.html" class="md-nav__link">Generalized Estimating Equations</a>
</li>
<li class="md-nav__item">
<a href="../gam.html" class="md-nav__link">Generalized Additive Models (GAM)</a>
</li>
<li class="md-nav__item">
<a href="../rlm.html" class="md-nav__link">Robust Linear Models</a>
</li>
<li class="md-nav__item">
<a href="../mixed_linear.html" class="md-nav__link">Linear Mixed Effects Models</a>
</li>
<li class="md-nav__item">
<a href="../discretemod.html" class="md-nav__link">Regression with Discrete Dependent Variable</a>
</li>
<li class="md-nav__item">
<a href="../mixed_glm.html" class="md-nav__link">Generalized Linear Mixed Effects Models</a>
</li>
<li class="md-nav__item">
<a href="../anova.html" class="md-nav__link">ANOVA</a>
</li>
<li class="md-nav__item">
<a href="../other_models.html" class="md-nav__link">Other Models <code class="xref py py-mod docutils literal notranslate"><span class="pre">othermod</span></code></a>
</li></ul>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#time-series-analysis" class="md-nav__link">Time Series Analysis</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#other-models" class="md-nav__link">Other Models</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#statistics-and-tools" class="md-nav__link">Statistics and Tools</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#data-sets" class="md-nav__link">Data Sets</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#sandbox" class="md-nav__link">Sandbox</a>
</li></ul>
</li>
<li class="md-nav__item">
<a href="../examples/index.html" class="md-nav__link">Examples</a>
</li>
<li class="md-nav__item">
<a href="../api.html" class="md-nav__link">API Reference</a>
</li>
<li class="md-nav__item">
<a href="../about.html" class="md-nav__link">About statsmodels</a>
</li>
<li class="md-nav__item">
<a href="../dev/index.html" class="md-nav__link">Developer Page</a>
</li>
<li class="md-nav__item">
<a href="../release/index.html" class="md-nav__link">Release Notes</a>
</li>
</ul>
</nav>
</div>
</div>
</div>
<div class="md-sidebar md-sidebar--secondary" data-md-component="toc">
<div class="md-sidebar__scrollwrap">
<div class="md-sidebar__inner">
<nav class="md-nav md-nav--secondary">
<label class="md-nav__title" for="__toc">Contents</label>
<ul class="md-nav__list" data-md-scrollfix="">
<li class="md-nav__item"><a href="#generated-statsmodels-discrete-discrete-model-multinomialmodel-cdf--page-root" class="md-nav__link">statsmodels.discrete.discrete_model.MultinomialModel.cdf</a><nav class="md-nav">
<ul class="md-nav__list">
<li class="md-nav__item"><a href="#statsmodels.discrete.discrete_model.MultinomialModel.cdf" class="md-nav__link"><code class="docutils literal notranslate"><span class="pre">MultinomialModel.cdf</span></code></a>
</li></ul>
</nav>
</li>
<li class="md-nav__item"><a class="md-nav__extra_link" href="../_sources/generated/statsmodels.discrete.discrete_model.MultinomialModel.cdf.rst.txt">Show Source</a> </li>
<li id="searchbox" class="md-nav__item"></li>
</ul>
</nav>
</div>
</div>
</div>
<div class="md-content">
<article class="md-content__inner md-typeset" role="main">
<section id="statsmodels-discrete-discrete-model-multinomialmodel-cdf">
<h1 id="generated-statsmodels-discrete-discrete-model-multinomialmodel-cdf--page-root">statsmodels.discrete.discrete_model.MultinomialModel.cdf<a class="headerlink" href="#generated-statsmodels-discrete-discrete-model-multinomialmodel-cdf--page-root" title="Permalink to this heading">¶</a></h1>
<dl class="py method">
<dt class="sig sig-object py" id="statsmodels.discrete.discrete_model.MultinomialModel.cdf">
<span class="sig-prename descclassname"><span class="pre">MultinomialModel.</span></span><span class="sig-name descname"><span class="pre">cdf</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">X</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#statsmodels.discrete.discrete_model.MultinomialModel.cdf" title="Permalink to this definition">¶</a></dt>
<dd><p>The cumulative distribution function of the model.</p>
</dd></dl>
</section>
</article>
</div>
</div>
</main>
</div>
<footer class="md-footer">
<div class="md-footer-nav">
<nav class="md-footer-nav__inner md-grid">
<a href="statsmodels.discrete.discrete_model.MultinomialModel.html" title="statsmodels.discrete.discrete_model.MultinomialModel"
class="md-flex md-footer-nav__link md-footer-nav__link--prev"
rel="prev">
<div class="md-flex__cell md-flex__cell--shrink">
<i class="md-icon md-icon--arrow-back md-footer-nav__button"></i>
</div>
<div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title">
<span class="md-flex__ellipsis">
<span
class="md-footer-nav__direction"> Previous </span> statsmodels.discrete.discrete_model.MultinomialModel </span>
</div>
</a>
<a href="statsmodels.discrete.discrete_model.MultinomialModel.cov_params_func_l1.html" title="statsmodels.discrete.discrete_model.MultinomialModel.cov_params_func_l1"
class="md-flex md-footer-nav__link md-footer-nav__link--next"
rel="next">
<div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"><span
class="md-flex__ellipsis"> <span
class="md-footer-nav__direction"> Next </span> statsmodels.discrete.discrete_model.MultinomialModel.cov_params_func_l1 </span>
</div>
<div class="md-flex__cell md-flex__cell--shrink"><i
class="md-icon md-icon--arrow-forward md-footer-nav__button"></i>
</div>
</a>
</nav>
</div>
<div class="md-footer-meta md-typeset">
<div class="md-footer-meta__inner md-grid">
<div class="md-footer-copyright">
<div class="md-footer-copyright__highlight">
© Copyright 2009-2019, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers.
</div>
Last updated on
Nov 01, 2022.
<br/>
Created using
<a href="http://www.sphinx-doc.org/">Sphinx</a> 5.3.0.
and
<a href="https://github.com/bashtage/sphinx-material/">Material for
Sphinx</a>
</div>
</div>
</div>
</footer>
<script src="../_static/javascripts/application.js"></script>
<script>app.initialize({version: "1.0.4", url: {base: ".."}})</script>
</body>
</html> | {
"content_hash": "488a23e830e732e66a934eab96a6beef",
"timestamp": "",
"source": "github",
"line_count": 506,
"max_line_length": 999,
"avg_line_length": 38.3399209486166,
"alnum_prop": 0.6001030927835052,
"repo_name": "statsmodels/statsmodels.github.io",
"id": "18545fc59f91b94a20dfdf16c6dcb2faf0237149",
"size": "19404",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "v0.13.4/generated/statsmodels.discrete.discrete_model.MultinomialModel.cdf.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
<TS language="cy" version="2.1">
<context>
<name>AddressBookPage</name>
<message>
<source>Double-click to edit address or label</source>
<translation>Clicio dwywaith i olygu cyfeiriad neu label</translation>
</message>
<message>
<source>Create a new address</source>
<translation>Creu cyfeiriad newydd</translation>
</message>
<message>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Copio'r cyfeiriad sydd wedi'i ddewis i'r clipfwrdd system</translation>
</message>
<message>
<source>&Delete</source>
<translation>&Dileu</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<source>Label</source>
<translation>Label</translation>
</message>
<message>
<source>Address</source>
<translation>Cyfeiriad</translation>
</message>
<message>
<source>(no label)</source>
<translation>(heb label)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<source>Enter passphrase</source>
<translation>Teipiwch gyfrinymadrodd</translation>
</message>
<message>
<source>New passphrase</source>
<translation>Cyfrinymadrodd newydd</translation>
</message>
<message>
<source>Repeat new passphrase</source>
<translation>Ailadroddwch gyfrinymadrodd newydd</translation>
</message>
<message>
<source>Encrypt wallet</source>
<translation>Amgryptio'r waled</translation>
</message>
<message>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>Mae angen i'r gweithred hon ddefnyddio'ch cyfrinymadrodd er mwyn datgloi'r waled.</translation>
</message>
<message>
<source>Unlock wallet</source>
<translation>Datgloi'r waled</translation>
</message>
<message>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>Mae angen i'r gweithred hon ddefnyddio'ch cyfrinymadrodd er mwyn dadgryptio'r waled.</translation>
</message>
<message>
<source>Decrypt wallet</source>
<translation>Dadgryptio'r waled</translation>
</message>
<message>
<source>Change passphrase</source>
<translation>Newid cyfrinymadrodd</translation>
</message>
<message>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>Teipiwch yr hen cyfrinymadrodd a chyfrinymadrodd newydd i mewn i'r waled.</translation>
</message>
<message>
<source>Confirm wallet encryption</source>
<translation>Cadarnau amgryptiad y waled</translation>
</message>
<message>
<source>Wallet encrypted</source>
<translation>Waled wedi'i amgryptio</translation>
</message>
<message>
<source>Wallet encryption failed</source>
<translation>Amgryptiad waled wedi methu</translation>
</message>
<message>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>Methodd amgryptiad y waled oherwydd gwall mewnol. Ni amgryptwyd eich waled.</translation>
</message>
<message>
<source>The supplied passphrases do not match.</source>
<translation>Dydy'r cyfrinymadroddion a ddarparwyd ddim yn cyd-fynd â'u gilydd.</translation>
</message>
<message>
<source>Wallet unlock failed</source>
<translation>Methodd ddatgloi'r waled</translation>
</message>
<message>
<source>Wallet decryption failed</source>
<translation>Methodd dadgryptiad y waled</translation>
</message>
</context>
<context>
<name>FlirtcoinGUI</name>
<message>
<source>Synchronizing with network...</source>
<translation>Cysoni â'r rhwydwaith...</translation>
</message>
<message>
<source>&Overview</source>
<translation>&Trosolwg</translation>
</message>
<message>
<source>Show general overview of wallet</source>
<translation>Dangos trosolwg cyffredinol y waled</translation>
</message>
<message>
<source>&Transactions</source>
<translation>&Trafodion</translation>
</message>
<message>
<source>Browse transaction history</source>
<translation>Pori hanes trafodion</translation>
</message>
<message>
<source>Quit application</source>
<translation>Gadael rhaglen</translation>
</message>
<message>
<source>&Options...</source>
<translation>&Opsiynau</translation>
</message>
<message>
<source>Change the passphrase used for wallet encryption</source>
<translation>Newid y cyfrinymadrodd a ddefnyddiwyd ar gyfer amgryptio'r waled</translation>
</message>
<message>
<source>&File</source>
<translation>&Ffeil</translation>
</message>
<message>
<source>&Settings</source>
<translation>&Gosodiadau</translation>
</message>
<message>
<source>&Help</source>
<translation>&Cymorth</translation>
</message>
<message>
<source>Tabs toolbar</source>
<translation>Bar offer tabiau</translation>
</message>
<message>
<source>Error</source>
<translation>Gwall</translation>
</message>
<message>
<source>Warning</source>
<translation>Rhybudd</translation>
</message>
<message>
<source>Information</source>
<translation>Gwybodaeth</translation>
</message>
<message>
<source>Up to date</source>
<translation>Cyfamserol</translation>
</message>
<message>
<source>Catching up...</source>
<translation>Dal i fyny</translation>
</message>
<message>
<source>Sent transaction</source>
<translation>Trafodiad a anfonwyd</translation>
</message>
<message>
<source>Incoming transaction</source>
<translation>Trafodiad sy'n cyrraedd</translation>
</message>
<message>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>Mae'r waled <b>wedi'i amgryptio</b> ac <b>heb ei gloi</b> ar hyn o bryd</translation>
</message>
<message>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>Mae'r waled <b>wedi'i amgryptio</b> ac <b>ar glo</b> ar hyn o bryd</translation>
</message>
</context>
<context>
<name>ClientModel</name>
</context>
<context>
<name>CoinControlDialog</name>
<message>
<source>Address</source>
<translation>Cyfeiriad</translation>
</message>
<message>
<source>Date</source>
<translation>Dyddiad</translation>
</message>
<message>
<source>(no label)</source>
<translation>(heb label)</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<source>Edit Address</source>
<translation>Golygu'r cyfeiriad</translation>
</message>
<message>
<source>&Label</source>
<translation>&Label</translation>
</message>
<message>
<source>&Address</source>
<translation>&Cyfeiriad</translation>
</message>
<message>
<source>New receiving address</source>
<translation>Cyfeiriad derbyn newydd</translation>
</message>
<message>
<source>New sending address</source>
<translation>Cyfeiriad anfon newydd</translation>
</message>
<message>
<source>Edit receiving address</source>
<translation>Golygu'r cyfeiriad derbyn</translation>
</message>
<message>
<source>Edit sending address</source>
<translation>Golygu'r cyfeiriad anfon</translation>
</message>
<message>
<source>The entered address "%1" is already in the address book.</source>
<translation>Mae'r cyfeiriad "%1" sydd newydd gael ei geisio gennych yn y llyfr cyfeiriad yn barod.</translation>
</message>
<message>
<source>Could not unlock wallet.</source>
<translation>Methodd ddatgloi'r waled.</translation>
</message>
<message>
<source>New key generation failed.</source>
<translation>Methodd gynhyrchu allwedd newydd.</translation>
</message>
</context>
<context>
<name>FreespaceChecker</name>
</context>
<context>
<name>HelpMessageDialog</name>
</context>
<context>
<name>Intro</name>
<message>
<source>Error</source>
<translation>Gwall</translation>
</message>
</context>
<context>
<name>OpenURIDialog</name>
</context>
<context>
<name>OptionsDialog</name>
<message>
<source>Options</source>
<translation>Opsiynau</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<source>Form</source>
<translation>Ffurflen</translation>
</message>
</context>
<context>
<name>PaymentServer</name>
</context>
<context>
<name>PeerTableModel</name>
</context>
<context>
<name>QObject</name>
</context>
<context>
<name>QRImageWidget</name>
</context>
<context>
<name>RPCConsole</name>
<message>
<source>&Information</source>
<translation>Gwybodaeth</translation>
</message>
</context>
<context>
<name>ReceiveCoinsDialog</name>
<message>
<source>&Label:</source>
<translation>&Label:</translation>
</message>
</context>
<context>
<name>ReceiveRequestDialog</name>
<message>
<source>Address</source>
<translation>Cyfeiriad</translation>
</message>
<message>
<source>Label</source>
<translation>Label</translation>
</message>
<message>
<source>Message</source>
<translation>Neges</translation>
</message>
</context>
<context>
<name>RecentRequestsTableModel</name>
<message>
<source>Date</source>
<translation>Dyddiad</translation>
</message>
<message>
<source>Label</source>
<translation>Label</translation>
</message>
<message>
<source>Message</source>
<translation>Neges</translation>
</message>
<message>
<source>(no label)</source>
<translation>(heb label)</translation>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<source>Send Coins</source>
<translation>Anfon arian</translation>
</message>
<message>
<source>Send to multiple recipients at once</source>
<translation>Anfon at pobl lluosog ar yr un pryd</translation>
</message>
<message>
<source>Balance:</source>
<translation>Gweddill:</translation>
</message>
<message>
<source>Confirm the send action</source>
<translation>Cadarnhau'r gweithrediad anfon</translation>
</message>
<message>
<source>%1 to %2</source>
<translation>%1 i %2</translation>
</message>
<message>
<source>(no label)</source>
<translation>(heb label)</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<source>A&mount:</source>
<translation>&Maint</translation>
</message>
<message>
<source>&Label:</source>
<translation>&Label:</translation>
</message>
<message>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<source>Paste address from clipboard</source>
<translation>Gludo cyfeiriad o'r glipfwrdd</translation>
</message>
<message>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
</context>
<context>
<name>ShutdownWindow</name>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<source>Paste address from clipboard</source>
<translation>Gludo cyfeiriad o'r glipfwrdd</translation>
</message>
<message>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
</context>
<context>
<name>SplashScreen</name>
<message>
<source>[testnet]</source>
<translation>[testnet]</translation>
</message>
</context>
<context>
<name>TrafficGraphWidget</name>
</context>
<context>
<name>TransactionDesc</name>
<message>
<source>Open until %1</source>
<translation>Agor tan %1</translation>
</message>
<message>
<source>Date</source>
<translation>Dyddiad</translation>
</message>
<message>
<source>Message</source>
<translation>Neges</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<source>Date</source>
<translation>Dyddiad</translation>
</message>
<message>
<source>Type</source>
<translation>Math</translation>
</message>
<message>
<source>Address</source>
<translation>Cyfeiriad</translation>
</message>
<message>
<source>Open until %1</source>
<translation>Agor tan %1</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<source>Today</source>
<translation>Heddiw</translation>
</message>
<message>
<source>This year</source>
<translation>Eleni</translation>
</message>
<message>
<source>Date</source>
<translation>Dyddiad</translation>
</message>
<message>
<source>Type</source>
<translation>Math</translation>
</message>
<message>
<source>Label</source>
<translation>Label</translation>
</message>
<message>
<source>Address</source>
<translation>Cyfeiriad</translation>
</message>
</context>
<context>
<name>UnitDisplayStatusBarControl</name>
</context>
<context>
<name>WalletFrame</name>
</context>
<context>
<name>WalletModel</name>
<message>
<source>Send Coins</source>
<translation>Anfon arian</translation>
</message>
</context>
<context>
<name>WalletView</name>
</context>
<context>
<name>flirtcoin-core</name>
<message>
<source>Information</source>
<translation>Gwybodaeth</translation>
</message>
<message>
<source>Warning</source>
<translation>Rhybudd</translation>
</message>
<message>
<source>Error</source>
<translation>Gwall</translation>
</message>
</context>
</TS> | {
"content_hash": "7ab9380fb271966598a03a2407834fb8",
"timestamp": "",
"source": "github",
"line_count": 518,
"max_line_length": 130,
"avg_line_length": 29.42664092664093,
"alnum_prop": 0.6252706160204684,
"repo_name": "flirtcoin/flirtcoin",
"id": "ae348c4bc2279e2d9ab47482a8ce627b786a6392",
"size": "15245",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/qt/locale/flirtcoin_cy.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "161768"
},
{
"name": "C++",
"bytes": "3320808"
},
{
"name": "CSS",
"bytes": "1127"
},
{
"name": "Makefile",
"bytes": "620573"
},
{
"name": "Objective-C",
"bytes": "2029"
},
{
"name": "Objective-C++",
"bytes": "6314"
},
{
"name": "Python",
"bytes": "159540"
},
{
"name": "Shell",
"bytes": "51253"
},
{
"name": "TypeScript",
"bytes": "5351410"
}
],
"symlink_target": ""
} |
import argparse
import codecs
import glob
import json
import os
import re
import subprocess
import sys
import threading
if sys.version_info[0] == 2:
import httplib
from urllib import urlencode
else:
import http.client as httplib
from urllib.parse import urlencode
from importlib import reload
# Read package.json and extract the current Blockly version.
blocklyVersion = json.loads(open('package.json', 'r').read())['version']
def import_path(fullpath):
"""Import a file with full path specification.
Allows one to import from any directory, something __import__ does not do.
Args:
fullpath: Path and filename of import.
Returns:
An imported module.
"""
path, filename = os.path.split(fullpath)
filename, ext = os.path.splitext(filename)
sys.path.append(path)
module = __import__(filename)
reload(module) # Might be out of date.
del sys.path[-1]
return module
HEADER = ("// Do not edit this file; automatically generated by build.py.\n"
"'use strict';\n")
class Gen_uncompressed(threading.Thread):
"""Generate a JavaScript file that loads Blockly's raw files.
Runs in a separate thread.
"""
def __init__(self, search_paths, target_filename):
threading.Thread.__init__(self)
self.search_paths = search_paths
self.target_filename = target_filename
def run(self):
f = open(self.target_filename, 'w')
f.write(HEADER)
f.write("""
this.IS_NODE_JS = !!(typeof module !== 'undefined' && module.exports);
this.BLOCKLY_DIR = (function(root) {
if (!root.IS_NODE_JS) {
// Find name of current directory.
var scripts = document.getElementsByTagName('script');
var re = new RegExp('(.+)[\/]blockly_(.*)uncompressed\.js$');
for (var i = 0, script; script = scripts[i]; i++) {
var match = re.exec(script.src);
if (match) {
return match[1];
}
}
alert('Could not detect Blockly\\'s directory name.');
}
return '';
})(this);
this.BLOCKLY_BOOT = function(root) {
// Execute after Closure has loaded.
""")
add_dependency = []
base_path = calcdeps.FindClosureBasePath(self.search_paths)
for dep in calcdeps.BuildDependenciesFromFiles(self.search_paths):
add_dependency.append(calcdeps.GetDepsLine(dep, base_path))
add_dependency.sort() # Deterministic build.
add_dependency = '\n'.join(add_dependency)
f.write(add_dependency + '\n')
f.write('\n')
f.write('// Load Blockly.\n')
f.write('goog.require(\'Blockly.requires\')\n')
f.write("""
delete root.BLOCKLY_DIR;
delete root.BLOCKLY_BOOT;
delete root.IS_NODE_JS;
};
if (this.IS_NODE_JS) {
this.BLOCKLY_BOOT(this);
module.exports = Blockly;
} else {
document.write('<script src="' + this.BLOCKLY_DIR +
'/closure/goog/base.js"></script>');
document.write('<script>this.BLOCKLY_BOOT(this);</script>');
}
""")
f.close()
print("SUCCESS: " + self.target_filename)
class Gen_compressed(threading.Thread):
"""Generate a JavaScript file that contains all of Blockly's core and all
required parts of Closure, compiled together.
Uses the Closure Compiler's online API.
Runs in a separate thread.
"""
def __init__(self, search_paths, bundles):
threading.Thread.__init__(self)
self.search_paths = search_paths
self.bundles = bundles
def run(self):
if (self.bundles.core):
self.gen_core()
self.gen_blocks()
if (self.bundles.generators):
self.gen_generator("javascript")
self.gen_generator("python")
self.gen_generator("php")
self.gen_generator("lua")
self.gen_generator("dart")
def gen_core(self):
target_filename = "blockly_compressed.js"
# Define the parameters for the POST request.
params = [
("compilation_level", "SIMPLE_OPTIMIZATIONS"),
("use_closure_library", "false"),
("output_format", "json"),
("output_info", "compiled_code"),
("output_info", "warnings"),
("output_info", "errors"),
("output_info", "statistics"),
("warning_level", "DEFAULT"),
]
# Read in all the source files.
filenames = calcdeps.CalculateDependencies(self.search_paths,
[os.path.join("core", "requires.js")])
filenames.sort() # Deterministic build.
for filename in filenames:
# Filter out the Closure files (the compiler will add them).
if filename.startswith("closure"):
continue
f = codecs.open(filename, encoding="utf-8")
code = "".join(f.readlines())
# Inject the Blockly version.
if filename == "core/blockly.js":
code = code.replace("Blockly.VERSION = 'uncompiled';",
"Blockly.VERSION = '%s';" % blocklyVersion)
params.append(("js_code", code.encode("utf-8")))
f.close()
self.do_compile(params, target_filename, filenames, "")
def gen_blocks(self):
target_filename = "blocks_compressed.js"
# Define the parameters for the POST request.
params = [
("compilation_level", "SIMPLE_OPTIMIZATIONS"),
("output_format", "json"),
("output_info", "compiled_code"),
("output_info", "warnings"),
("output_info", "errors"),
("output_info", "statistics"),
("warning_level", "DEFAULT"),
]
# Add Blockly, Blockly.Blocks, and all fields to be compatible with the compiler.
params.append(("js_code", """
goog.provide('Blockly');
goog.provide('Blockly.Blocks');
goog.provide('Blockly.Comment');
goog.provide('Blockly.FieldCheckbox');
goog.provide('Blockly.FieldColour');
goog.provide('Blockly.FieldDropdown');
goog.provide('Blockly.FieldImage');
goog.provide('Blockly.FieldLabel');
goog.provide('Blockly.FieldMultilineInput');
goog.provide('Blockly.FieldNumber');
goog.provide('Blockly.FieldTextInput');
goog.provide('Blockly.FieldVariable');
goog.provide('Blockly.Mutator');
"""))
# Read in all the source files.
filenames = glob.glob(os.path.join("blocks", "*.js"))
filenames.sort() # Deterministic build.
for filename in filenames:
f = codecs.open(filename, encoding="utf-8")
params.append(("js_code", "".join(f.readlines()).encode("utf-8")))
f.close()
# Remove Blockly, Blockly.Blocks and all fields to be compatible with Blockly.
remove = r"var Blockly=\{[^;]*\};\n?"
self.do_compile(params, target_filename, filenames, remove)
def gen_generator(self, language):
target_filename = language + "_compressed.js"
# Define the parameters for the POST request.
params = [
("compilation_level", "SIMPLE_OPTIMIZATIONS"),
("output_format", "json"),
("output_info", "compiled_code"),
("output_info", "warnings"),
("output_info", "errors"),
("output_info", "statistics"),
("warning_level", "DEFAULT"),
]
# Read in all the source files.
# Add Blockly.Generator and Blockly.utils.string to be compatible
# with the compiler.
params.append(("js_code", """
goog.provide('Blockly.Generator');
goog.provide('Blockly.utils.string');
"""))
filenames = glob.glob(
os.path.join("generators", language, "*.js"))
filenames.sort() # Deterministic build.
filenames.insert(0, os.path.join("generators", language + ".js"))
for filename in filenames:
f = codecs.open(filename, encoding="utf-8")
params.append(("js_code", "".join(f.readlines()).encode("utf-8")))
f.close()
filenames.insert(0, "[goog.provide]")
# Remove Blockly.Generator and Blockly.utils.string to be compatible
# with Blockly.
remove = r"var Blockly=\{[^;]*\};\s*Blockly.utils.string={};\n?"
self.do_compile(params, target_filename, filenames, remove)
def do_compile(self, params, target_filename, filenames, remove):
# Send the request to Google.
headers = {"Content-type": "application/x-www-form-urlencoded"}
conn = httplib.HTTPSConnection("closure-compiler.appspot.com")
conn.request("POST", "/compile", urlencode(params), headers)
response = conn.getresponse()
# Decode is necessary for Python 3.4 compatibility
json_str = response.read().decode("utf-8")
conn.close()
# Parse the JSON response.
try:
json_data = json.loads(json_str)
except ValueError:
print("ERROR: Could not parse JSON for %s. Raw data:" % target_filename)
print(json_str)
return
def file_lookup(name):
if not name.startswith("Input_"):
return "???"
n = int(name[6:]) - 1
return filenames[n]
if "serverErrors" in json_data:
errors = json_data["serverErrors"]
for error in errors:
print("SERVER ERROR: %s" % target_filename)
print(error["error"])
elif "errors" in json_data:
errors = json_data["errors"]
for error in errors:
print("FATAL ERROR")
print(error["error"])
if error["file"]:
print("%s at line %d:" % (
file_lookup(error["file"]), error["lineno"]))
print(error["line"])
print((" " * error["charno"]) + "^")
sys.exit(1)
else:
if "warnings" in json_data:
warnings = json_data["warnings"]
for warning in warnings:
print("WARNING")
print(warning["warning"])
if warning["file"]:
print("%s at line %d:" % (
file_lookup(warning["file"]), warning["lineno"]))
print(warning["line"])
print((" " * warning["charno"]) + "^")
print()
if not "compiledCode" in json_data:
print("FATAL ERROR: Compiler did not return compiledCode.")
sys.exit(1)
code = HEADER + "\n" + json_data["compiledCode"]
# Remove Blockly definitions to be compatible with Blockly.
code = re.sub(remove, "", code)
code = self.trim_licence(code)
stats = json_data["statistics"]
original_b = stats["originalSize"]
compressed_b = stats["compressedSize"]
if original_b > 0 and compressed_b > 0:
f = open(target_filename, "w")
f.write(code)
f.close()
original_kb = int(original_b / 1024 + 0.5)
compressed_kb = int(compressed_b / 1024 + 0.5)
ratio = int(float(compressed_b) / float(original_b) * 100 + 0.5)
print("SUCCESS: " + target_filename)
print("Size changed from %d KB to %d KB (%d%%)." % (
original_kb, compressed_kb, ratio))
else:
print("UNKNOWN ERROR")
def trim_licence(self, code):
"""Strip out Google's and MIT's Apache licences.
JS Compiler preserves dozens of Apache licences in the Blockly code.
Remove these if they belong to Google or MIT.
MIT's permission to do this is logged in Blockly issue 2412.
Args:
code: Large blob of compiled source code.
Returns:
Code with Google's and MIT's Apache licences trimmed.
"""
apache2 = re.compile("""/\\*
(Copyright \\d+ (Google LLC|Massachusetts Institute of Technology))
( All rights reserved.
)?
Licensed under the Apache License, Version 2.0 \\(the "License"\\);
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
\\*/""")
return re.sub(apache2, "", code)
class Gen_langfiles(threading.Thread):
"""Generate JavaScript file for each natural language supported.
Runs in a separate thread.
"""
def __init__(self):
threading.Thread.__init__(self)
def run(self):
# The files msg/json/{en,qqq,synonyms}.json depend on msg/messages.js.
try:
subprocess.check_call([
"python",
os.path.join("i18n", "js_to_json.py"),
"--input_file", "msg/messages.js",
"--output_dir", "msg/json/",
"--quiet"])
except (subprocess.CalledProcessError, OSError) as e:
# Documentation for subprocess.check_call says that CalledProcessError
# will be raised on failure, but I found that OSError is also possible.
print("Error running i18n/js_to_json.py: ", e)
sys.exit(1)
# Checking whether it is necessary to rebuild the js files would be a lot of
# work since we would have to compare each <lang>.json file with each
# <lang>.js file. Rebuilding is easy and cheap, so just go ahead and do it.
try:
# Use create_messages.py to create .js files from .json files.
cmd = [
"python",
os.path.join("i18n", "create_messages.py"),
"--source_lang_file", os.path.join("msg", "json", "en.json"),
"--source_synonym_file", os.path.join("msg", "json", "synonyms.json"),
"--source_constants_file", os.path.join("msg", "json", "constants.json"),
"--key_file", os.path.join("msg", "json", "keys.json"),
"--output_dir", os.path.join("msg", "js"),
"--quiet"]
json_files = glob.glob(os.path.join("msg", "json", "*.json"))
json_files = [file for file in json_files if not
(file.endswith(("keys.json", "synonyms.json", "qqq.json", "constants.json")))]
cmd.extend(json_files)
subprocess.check_call(cmd)
except (subprocess.CalledProcessError, OSError) as e:
print("Error running i18n/create_messages.py: ", e)
sys.exit(1)
# Output list of .js files created.
for f in json_files:
# This assumes the path to the current directory does not contain "json".
f = f.replace("json", "js")
if os.path.isfile(f):
print("SUCCESS: " + f)
else:
print("FAILED to create " + f)
# Class to hold arguments if user passes in old argument style.
class Arguments:
def __init__(self):
self.core = False
self.generators = False
self.langfiles = False
# Gets the command line arguments.
def get_args():
parser = argparse.ArgumentParser(description="Decide which files to build.")
parser.add_argument('-core', action="store_true", default=False, help="Build core")
parser.add_argument('-generators', action="store_true", default=False, help="Build the generators")
parser.add_argument('-langfiles', action="store_true", default=False, help="Build all the language files")
# New argument style: ./build.py -core
# Old argument style: ./build.py core
# Changed as of July 2019.
try:
args = parser.parse_args()
if (not args.core) and (not args.generators) and (not args.langfiles):
# No arguments, use these defaults:
args.core = True
args.generators = True
args.langfiles = True
except SystemExit:
# Fall back to old argument style.
args = Arguments()
args.core = 'core' in sys.argv
args.generators = 'generators' in sys.argv
args.langfiles = 'langfiles' in sys.argv
if 'accessible' in sys.argv:
print("The Blockly accessibility demo has moved to https://github.com/google/blockly-experimental")
return args
if __name__ == "__main__":
args = get_args()
calcdeps = import_path(os.path.join("closure", "bin", "calcdeps.py"))
full_search_paths = calcdeps.ExpandDirectories(["core", "closure"])
full_search_paths = sorted(full_search_paths) # Deterministic build.
# Uncompressed and compressed are run in parallel threads.
# Uncompressed is limited by processor speed.
if (args.core):
Gen_uncompressed(full_search_paths, 'blockly_uncompressed.js').start()
# Compressed is limited by network and server speed.
Gen_compressed(full_search_paths, args).start()
# This is run locally in a separate thread
if (args.langfiles):
Gen_langfiles().start()
| {
"content_hash": "84e968f7413f9e2678be2ac94f7f6cc8",
"timestamp": "",
"source": "github",
"line_count": 461,
"max_line_length": 108,
"avg_line_length": 34.35791757049891,
"alnum_prop": 0.6367826251657301,
"repo_name": "picklesrus/blockly",
"id": "0ac8efd231fb183c80713898b4dc378b2fa1b443",
"size": "17979",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "build.py",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "14537"
},
{
"name": "HTML",
"bytes": "169831"
},
{
"name": "JavaScript",
"bytes": "4034471"
},
{
"name": "Python",
"bytes": "56065"
}
],
"symlink_target": ""
} |
//
// PNLineChart.m
// PNChartDemo
//
// Created by kevin on 11/7/13.
// Copyright (c) 2013年 kevinzhow. All rights reserved.
//
#import "PNLineChart.h"
#import "PNColor.h"
#import "PNChartLabel.h"
#import "PNLineChartData.h"
#import "PNLineChartDataItem.h"
#import <CoreText/CoreText.h>
@interface PNLineChart ()
@property(nonatomic) NSMutableArray *chartLineArray; // Array[CAShapeLayer]
@property(nonatomic) NSMutableArray *chartPointArray; // Array[CAShapeLayer] save the point layer
@property(nonatomic) NSMutableArray *chartPath; // Array of line path, one for each line.
@property(nonatomic) NSMutableArray *pointPath; // Array of point path, one for each line
@property(nonatomic) NSMutableArray *endPointsOfPath; // Array of start and end points of each line path, one for each line
@property(nonatomic) CABasicAnimation *pathAnimation; // will be set to nil if _displayAnimation is NO
// display grade
@property(nonatomic) NSMutableArray *gradeStringPaths;
@end
@implementation PNLineChart
@synthesize pathAnimation = _pathAnimation;
#pragma mark initialization
- (id)initWithCoder:(NSCoder *)coder {
self = [super initWithCoder:coder];
if (self) {
[self setupDefaultValues];
}
return self;
}
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
[self setupDefaultValues];
}
return self;
}
#pragma mark instance methods
- (void)setYLabels {
CGFloat yStep = (_yValueMax - _yValueMin) / _yLabelNum;
CGFloat yStepHeight = _chartCavanHeight / _yLabelNum;
if (_yChartLabels) {
for (PNChartLabel *label in _yChartLabels) {
[label removeFromSuperview];
}
} else {
_yChartLabels = [NSMutableArray new];
}
if (yStep == 0.0) {
PNChartLabel *minLabel = [[PNChartLabel alloc] initWithFrame:CGRectMake(0.0, (NSInteger) _chartCavanHeight, (NSInteger) _chartMarginBottom, (NSInteger) _yLabelHeight)];
minLabel.text = [self formatYLabel:0.0];
[self setCustomStyleForYLabel:minLabel];
[self addSubview:minLabel];
[_yChartLabels addObject:minLabel];
PNChartLabel *midLabel = [[PNChartLabel alloc] initWithFrame:CGRectMake(0.0, (NSInteger) (_chartCavanHeight / 2), (NSInteger) _chartMarginBottom, (NSInteger) _yLabelHeight)];
midLabel.text = [self formatYLabel:_yValueMax];
[self setCustomStyleForYLabel:midLabel];
[self addSubview:midLabel];
[_yChartLabels addObject:midLabel];
PNChartLabel *maxLabel = [[PNChartLabel alloc] initWithFrame:CGRectMake(0.0, 0.0, (NSInteger) _chartMarginBottom, (NSInteger) _yLabelHeight)];
maxLabel.text = [self formatYLabel:_yValueMax * 2];
[self setCustomStyleForYLabel:maxLabel];
[self addSubview:maxLabel];
[_yChartLabels addObject:maxLabel];
} else {
NSInteger index = 0;
NSInteger num = _yLabelNum + 1;
while (num > 0) {
CGRect labelFrame = CGRectMake(0.0,
(NSInteger) (_chartCavanHeight + _chartMarginTop - index * yStepHeight),
(NSInteger) _chartMarginLeft * 0.9,
(NSInteger) _yLabelHeight);
PNChartLabel *label = [[PNChartLabel alloc] initWithFrame:labelFrame];
[label setTextAlignment:NSTextAlignmentRight];
label.text = [self formatYLabel:_yValueMin + (yStep * index)];
[self setCustomStyleForYLabel:label];
[self addSubview:label];
[_yChartLabels addObject:label];
index += 1;
num -= 1;
}
}
}
- (void)setYLabels:(NSArray *)yLabels {
_showGenYLabels = NO;
_yLabelNum = yLabels.count - 1;
CGFloat yLabelHeight;
if (_showLabel) {
yLabelHeight = _chartCavanHeight / [yLabels count];
} else {
yLabelHeight = (self.frame.size.height) / [yLabels count];
}
return [self setYLabels:yLabels withHeight:yLabelHeight];
}
- (void)setYLabels:(NSArray *)yLabels withHeight:(CGFloat)height {
_yLabels = yLabels;
_yLabelHeight = height;
if (_yChartLabels) {
for (PNChartLabel *label in _yChartLabels) {
[label removeFromSuperview];
}
} else {
_yChartLabels = [NSMutableArray new];
}
NSString *labelText;
if (_showLabel) {
CGFloat yStepHeight = _chartCavanHeight / _yLabelNum;
for (int index = 0; index < yLabels.count; index++) {
labelText = yLabels[index];
NSInteger y = (NSInteger) (_chartCavanHeight + _chartMarginTop - index * yStepHeight);
PNChartLabel *label = [[PNChartLabel alloc] initWithFrame:CGRectMake(0.0, y, (NSInteger) _chartMarginLeft * 0.9, (NSInteger) _yLabelHeight)];
[label setTextAlignment:NSTextAlignmentRight];
label.text = labelText;
[self setCustomStyleForYLabel:label];
[self addSubview:label];
[_yChartLabels addObject:label];
}
}
}
- (CGFloat)computeEqualWidthForXLabels:(NSArray *)xLabels {
CGFloat xLabelWidth;
if (_showLabel) {
xLabelWidth = _chartCavanWidth / [xLabels count];
} else {
xLabelWidth = (self.frame.size.width) / [xLabels count];
}
return xLabelWidth;
}
- (void)setXLabels:(NSArray *)xLabels {
CGFloat xLabelWidth;
if (_showLabel) {
xLabelWidth = _chartCavanWidth / [xLabels count];
} else {
xLabelWidth = (self.frame.size.width - _chartMarginLeft - _chartMarginRight) / [xLabels count];
}
return [self setXLabels:xLabels withWidth:xLabelWidth];
}
- (void)setXLabels:(NSArray *)xLabels withWidth:(CGFloat)width {
_xLabels = xLabels;
_xLabelWidth = width;
if (_xChartLabels) {
for (PNChartLabel *label in _xChartLabels) {
[label removeFromSuperview];
}
} else {
_xChartLabels = [NSMutableArray new];
}
NSString *labelText;
if (_showLabel) {
for (int index = 0; index < xLabels.count; index++) {
labelText = xLabels[index];
NSInteger x = (index * _xLabelWidth + _chartMarginLeft);
NSInteger y = _chartMarginBottom + _chartCavanHeight;
PNChartLabel *label = [[PNChartLabel alloc] initWithFrame:CGRectMake(x, y, (NSInteger) _xLabelWidth, (NSInteger) _chartMarginBottom)];
[label setTextAlignment:NSTextAlignmentCenter];
label.text = labelText;
[self setCustomStyleForXLabel:label];
[self addSubview:label];
[_xChartLabels addObject:label];
}
}
}
- (void)setCustomStyleForXLabel:(UILabel *)label {
if (_xLabelFont) {
label.font = _xLabelFont;
}
if (_xLabelColor) {
label.textColor = _xLabelColor;
}
}
- (void)setCustomStyleForYLabel:(UILabel *)label {
if (_yLabelFont) {
label.font = _yLabelFont;
}
if (_yLabelColor) {
label.textColor = _yLabelColor;
}
}
#pragma mark - Touch at point
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[self touchPoint:touches withEvent:event];
[self touchKeyPoint:touches withEvent:event];
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
[self touchPoint:touches withEvent:event];
[self touchKeyPoint:touches withEvent:event];
}
- (void)touchPoint:(NSSet *)touches withEvent:(UIEvent *)event {
// Get the point user touched
UITouch *touch = [touches anyObject];
CGPoint touchPoint = [touch locationInView:self];
for (NSInteger p = _pathPoints.count - 1; p >= 0; p--) {
NSArray *linePointsArray = _endPointsOfPath[p];
for (int i = 0; i < (int) linePointsArray.count - 1; i += 2) {
CGPoint p1 = [linePointsArray[i] CGPointValue];
CGPoint p2 = [linePointsArray[i + 1] CGPointValue];
// Closest distance from point to line
float distance = fabs(((p2.x - p1.x) * (touchPoint.y - p1.y)) - ((p1.x - touchPoint.x) * (p1.y - p2.y)));
distance /= hypot(p2.x - p1.x, p1.y - p2.y);
if (distance <= 5.0) {
// Conform to delegate parameters, figure out what bezier path this CGPoint belongs to.
for (UIBezierPath *path in _chartPath) {
BOOL pointContainsPath = CGPathContainsPoint(path.CGPath, NULL, p1, NO);
if (pointContainsPath) {
[_delegate userClickedOnLinePoint:touchPoint lineIndex:[_chartPath indexOfObject:path]];
return;
}
}
}
}
}
}
- (void)touchKeyPoint:(NSSet *)touches withEvent:(UIEvent *)event {
// Get the point user touched
UITouch *touch = [touches anyObject];
CGPoint touchPoint = [touch locationInView:self];
for (NSInteger p = _pathPoints.count - 1; p >= 0; p--) {
NSArray *linePointsArray = _pathPoints[p];
for (int i = 0; i < (int) linePointsArray.count - 1; i += 1) {
CGPoint p1 = [linePointsArray[i] CGPointValue];
CGPoint p2 = [linePointsArray[i + 1] CGPointValue];
float distanceToP1 = fabs(hypot(touchPoint.x - p1.x, touchPoint.y - p1.y));
float distanceToP2 = hypot(touchPoint.x - p2.x, touchPoint.y - p2.y);
float distance = MIN(distanceToP1, distanceToP2);
if (distance <= 10.0) {
[_delegate userClickedOnLineKeyPoint:touchPoint
lineIndex:p
pointIndex:(distance == distanceToP2 ? i + 1 : i)];
return;
}
}
}
}
#pragma mark - Draw Chart
- (void)strokeChart {
_chartPath = [[NSMutableArray alloc] init];
_pointPath = [[NSMutableArray alloc] init];
_gradeStringPaths = [NSMutableArray array];
[self calculateChartPath:_chartPath andPointsPath:_pointPath andPathKeyPoints:_pathPoints andPathStartEndPoints:_endPointsOfPath];
// Draw each line
for (NSUInteger lineIndex = 0; lineIndex < self.chartData.count; lineIndex++) {
PNLineChartData *chartData = self.chartData[lineIndex];
CAShapeLayer *chartLine = (CAShapeLayer *) self.chartLineArray[lineIndex];
CAShapeLayer *pointLayer = (CAShapeLayer *) self.chartPointArray[lineIndex];
UIGraphicsBeginImageContext(self.frame.size);
// setup the color of the chart line
if (chartData.color) {
chartLine.strokeColor = [[chartData.color colorWithAlphaComponent:chartData.alpha] CGColor];
if (chartData.inflexionPointColor) {
pointLayer.strokeColor = [[chartData.inflexionPointColor
colorWithAlphaComponent:chartData.alpha] CGColor];
}
} else {
chartLine.strokeColor = [PNGreen CGColor];
pointLayer.strokeColor = [PNGreen CGColor];
}
UIBezierPath *progressline = [_chartPath objectAtIndex:lineIndex];
UIBezierPath *pointPath = [_pointPath objectAtIndex:lineIndex];
chartLine.path = progressline.CGPath;
pointLayer.path = pointPath.CGPath;
[CATransaction begin];
[chartLine addAnimation:self.pathAnimation forKey:@"strokeEndAnimation"];
chartLine.strokeEnd = 1.0;
// if you want cancel the point animation, conment this code, the point will show immediately
if (chartData.inflexionPointStyle != PNLineChartPointStyleNone) {
[pointLayer addAnimation:self.pathAnimation forKey:@"strokeEndAnimation"];
}
[CATransaction commit];
NSMutableArray *textLayerArray = [self.gradeStringPaths objectAtIndex:lineIndex];
for (CATextLayer *textLayer in textLayerArray) {
CABasicAnimation *fadeAnimation = [self fadeAnimation];
[textLayer addAnimation:fadeAnimation forKey:nil];
}
UIGraphicsEndImageContext();
}
}
- (void)calculateChartPath:(NSMutableArray *)chartPath andPointsPath:(NSMutableArray *)pointsPath andPathKeyPoints:(NSMutableArray *)pathPoints andPathStartEndPoints:(NSMutableArray *)pointsOfPath {
// Draw each line
for (NSUInteger lineIndex = 0; lineIndex < self.chartData.count; lineIndex++) {
PNLineChartData *chartData = self.chartData[lineIndex];
CGFloat yValue;
CGFloat innerGrade;
UIBezierPath *progressline = [UIBezierPath bezierPath];
UIBezierPath *pointPath = [UIBezierPath bezierPath];
[chartPath insertObject:progressline atIndex:lineIndex];
[pointsPath insertObject:pointPath atIndex:lineIndex];
NSMutableArray *gradePathArray = [NSMutableArray array];
[self.gradeStringPaths addObject:gradePathArray];
NSMutableArray *linePointsArray = [[NSMutableArray alloc] init];
NSMutableArray *lineStartEndPointsArray = [[NSMutableArray alloc] init];
int last_x = 0;
int last_y = 0;
NSMutableArray<NSDictionary<NSString *, NSValue *> *> *progrssLinePaths = [NSMutableArray new];
CGFloat inflexionWidth = chartData.inflexionPointWidth;
for (NSUInteger i = 0; i < chartData.itemCount; i++) {
yValue = chartData.getData(i).y;
if (!(_yValueMax - _yValueMin)) {
innerGrade = 0.5;
} else {
innerGrade = (yValue - _yValueMin) / (_yValueMax - _yValueMin);
}
int x = i * _xLabelWidth + _chartMarginLeft + _xLabelWidth / 2.0;
int y = _chartCavanHeight - (innerGrade * _chartCavanHeight) - (_yLabelHeight / 2) + _chartMarginTop;
// Circular point
if (chartData.inflexionPointStyle == PNLineChartPointStyleCircle) {
CGRect circleRect = CGRectMake(x - inflexionWidth / 2, y - inflexionWidth / 2, inflexionWidth, inflexionWidth);
CGPoint circleCenter = CGPointMake(circleRect.origin.x + (circleRect.size.width / 2), circleRect.origin.y + (circleRect.size.height / 2));
[pointPath moveToPoint:CGPointMake(circleCenter.x + (inflexionWidth / 2), circleCenter.y)];
[pointPath addArcWithCenter:circleCenter radius:inflexionWidth / 2 startAngle:0 endAngle:2 * M_PI clockwise:YES];
//jet text display text
if (chartData.showPointLabel) {
[gradePathArray addObject:[self createPointLabelFor:chartData.getData(i).rawY pointCenter:circleCenter width:inflexionWidth withChartData:chartData]];
}
if (i > 0) {
// calculate the point for line
float distance = sqrt(pow(x - last_x, 2) + pow(y - last_y, 2));
float last_x1 = last_x + (inflexionWidth / 2) / distance * (x - last_x);
float last_y1 = last_y + (inflexionWidth / 2) / distance * (y - last_y);
float x1 = x - (inflexionWidth / 2) / distance * (x - last_x);
float y1 = y - (inflexionWidth / 2) / distance * (y - last_y);
[progrssLinePaths addObject:@{@"from" : [NSValue valueWithCGPoint:CGPointMake(last_x1, last_y1)],
@"to" : [NSValue valueWithCGPoint:CGPointMake(x1, y1)]}];
}
}
// Square point
else if (chartData.inflexionPointStyle == PNLineChartPointStyleSquare) {
CGRect squareRect = CGRectMake(x - inflexionWidth / 2, y - inflexionWidth / 2, inflexionWidth, inflexionWidth);
CGPoint squareCenter = CGPointMake(squareRect.origin.x + (squareRect.size.width / 2), squareRect.origin.y + (squareRect.size.height / 2));
[pointPath moveToPoint:CGPointMake(squareCenter.x - (inflexionWidth / 2), squareCenter.y - (inflexionWidth / 2))];
[pointPath addLineToPoint:CGPointMake(squareCenter.x + (inflexionWidth / 2), squareCenter.y - (inflexionWidth / 2))];
[pointPath addLineToPoint:CGPointMake(squareCenter.x + (inflexionWidth / 2), squareCenter.y + (inflexionWidth / 2))];
[pointPath addLineToPoint:CGPointMake(squareCenter.x - (inflexionWidth / 2), squareCenter.y + (inflexionWidth / 2))];
[pointPath closePath];
// text display text
if (chartData.showPointLabel) {
[gradePathArray addObject:[self createPointLabelFor:chartData.getData(i).rawY pointCenter:squareCenter width:inflexionWidth withChartData:chartData]];
}
if (i > 0) {
// calculate the point for line
float distance = sqrt(pow(x - last_x, 2) + pow(y - last_y, 2));
float last_x1 = last_x + (inflexionWidth / 2);
float last_y1 = last_y + (inflexionWidth / 2) / distance * (y - last_y);
float x1 = x - (inflexionWidth / 2);
float y1 = y - (inflexionWidth / 2) / distance * (y - last_y);
[progrssLinePaths addObject:@{@"from" : [NSValue valueWithCGPoint:CGPointMake(last_x1, last_y1)],
@"to" : [NSValue valueWithCGPoint:CGPointMake(x1, y1)]}];
}
}
// Triangle point
else if (chartData.inflexionPointStyle == PNLineChartPointStyleTriangle) {
CGRect squareRect = CGRectMake(x - inflexionWidth / 2, y - inflexionWidth / 2, inflexionWidth, inflexionWidth);
CGPoint startPoint = CGPointMake(squareRect.origin.x, squareRect.origin.y + squareRect.size.height);
CGPoint endPoint = CGPointMake(squareRect.origin.x + (squareRect.size.width / 2), squareRect.origin.y);
CGPoint middlePoint = CGPointMake(squareRect.origin.x + (squareRect.size.width), squareRect.origin.y + squareRect.size.height);
[pointPath moveToPoint:startPoint];
[pointPath addLineToPoint:middlePoint];
[pointPath addLineToPoint:endPoint];
[pointPath closePath];
// text display text
if (chartData.showPointLabel) {
[gradePathArray addObject:[self createPointLabelFor:chartData.getData(i).rawY pointCenter:middlePoint width:inflexionWidth withChartData:chartData]];
}
if (i > 0) {
// calculate the point for triangle
float distance = sqrt(pow(x - last_x, 2) + pow(y - last_y, 2)) * 1.4;
float last_x1 = last_x + (inflexionWidth / 2) / distance * (x - last_x);
float last_y1 = last_y + (inflexionWidth / 2) / distance * (y - last_y);
float x1 = x - (inflexionWidth / 2) / distance * (x - last_x);
float y1 = y - (inflexionWidth / 2) / distance * (y - last_y);
[progrssLinePaths addObject:@{@"from" : [NSValue valueWithCGPoint:CGPointMake(last_x1, last_y1)],
@"to" : [NSValue valueWithCGPoint:CGPointMake(x1, y1)]}];
}
} else {
if (i > 0) {
[progrssLinePaths addObject:@{@"from" : [NSValue valueWithCGPoint:CGPointMake(last_x, last_y)],
@"to" : [NSValue valueWithCGPoint:CGPointMake(x, y)]}];
}
}
[linePointsArray addObject:[NSValue valueWithCGPoint:CGPointMake(x, y)]];
last_x = x;
last_y = y;
}
if (self.showSmoothLines && chartData.itemCount >= 4) {
[progressline moveToPoint:[progrssLinePaths[0][@"from"] CGPointValue]];
for (NSDictionary<NSString *, NSValue *> *item in progrssLinePaths) {
CGPoint p1 = [item[@"from"] CGPointValue];
CGPoint p2 = [item[@"to"] CGPointValue];
[progressline moveToPoint:p1];
CGPoint midPoint = [PNLineChart midPointBetweenPoint1:p1 andPoint2:p2];
[progressline addQuadCurveToPoint:midPoint
controlPoint:[PNLineChart controlPointBetweenPoint1:midPoint andPoint2:p1]];
[progressline addQuadCurveToPoint:p2
controlPoint:[PNLineChart controlPointBetweenPoint1:midPoint andPoint2:p2]];
}
} else {
for (NSDictionary<NSString *, NSValue *> *item in progrssLinePaths) {
if (item[@"from"]) {
[progressline moveToPoint:[item[@"from"] CGPointValue]];
[lineStartEndPointsArray addObject:item[@"from"]];
}
if (item[@"to"]) {
[progressline addLineToPoint:[item[@"to"] CGPointValue]];
[lineStartEndPointsArray addObject:item[@"to"]];
}
}
}
[pathPoints addObject:[linePointsArray copy]];
[pointsOfPath addObject:[lineStartEndPointsArray copy]];
}
}
#pragma mark - Set Chart Data
- (void)setChartData:(NSArray *)data {
if (data != _chartData) {
// remove all shape layers before adding new ones
for (CALayer *layer in self.chartLineArray) {
[layer removeFromSuperlayer];
}
for (CALayer *layer in self.chartPointArray) {
[layer removeFromSuperlayer];
}
self.chartLineArray = [NSMutableArray arrayWithCapacity:data.count];
self.chartPointArray = [NSMutableArray arrayWithCapacity:data.count];
for (PNLineChartData *chartData in data) {
// create as many chart line layers as there are data-lines
CAShapeLayer *chartLine = [CAShapeLayer layer];
chartLine.lineCap = kCALineCapButt;
chartLine.lineJoin = kCALineJoinMiter;
chartLine.fillColor = [[UIColor whiteColor] CGColor];
chartLine.lineWidth = chartData.lineWidth;
chartLine.strokeEnd = 0.0;
[self.layer addSublayer:chartLine];
[self.chartLineArray addObject:chartLine];
// create point
CAShapeLayer *pointLayer = [CAShapeLayer layer];
pointLayer.strokeColor = [[chartData.color colorWithAlphaComponent:chartData.alpha] CGColor];
pointLayer.lineCap = kCALineCapRound;
pointLayer.lineJoin = kCALineJoinBevel;
pointLayer.fillColor = nil;
pointLayer.lineWidth = chartData.lineWidth;
[self.layer addSublayer:pointLayer];
[self.chartPointArray addObject:pointLayer];
}
_chartData = data;
// Cavan height and width needs to be set before
// setNeedsDisplay is invoked because setNeedsDisplay
// will invoke drawRect and if Cavan dimensions is not
// set the chart will be misplaced
_chartCavanHeight = self.frame.size.height - _chartMarginBottom - _chartMarginTop;
if (!_showLabel) {
_chartCavanHeight = self.frame.size.height - 2 * _yLabelHeight;
_chartCavanWidth = self.frame.size.width;
//_chartMargin = chartData.inflexionPointWidth;
_xLabelWidth = (_chartCavanWidth / ([_xLabels count]));
}
[self prepareYLabelsWithData:data];
[self setNeedsDisplay];
}
}
- (void)prepareYLabelsWithData:(NSArray *)data {
CGFloat yMax = 0.0f;
CGFloat yMin = MAXFLOAT;
NSMutableArray *yLabelsArray = [NSMutableArray new];
for (PNLineChartData *chartData in data) {
// create as many chart line layers as there are data-lines
for (NSUInteger i = 0; i < chartData.itemCount; i++) {
CGFloat yValue = chartData.getData(i).y;
[yLabelsArray addObject:[NSString stringWithFormat:@"%2f", yValue]];
yMax = fmaxf(yMax, yValue);
yMin = fminf(yMin, yValue);
}
}
if(_yValueMin == -FLT_MAX) {
_yValueMin = (_yFixedValueMin > -FLT_MAX) ? _yFixedValueMin : yMin;
}
if(_yValueMax == -FLT_MAX) {
_yValueMax = (_yFixedValueMax > -FLT_MAX) ? _yFixedValueMax : yMax + yMax / 10.0;
}
if (_showGenYLabels) {
[self setYLabels];
}
}
#pragma mark - Update Chart Data
- (void)updateChartData:(NSArray *)data {
_chartData = data;
[self prepareYLabelsWithData:data];
[self calculateChartPath:_chartPath andPointsPath:_pointPath andPathKeyPoints:_pathPoints andPathStartEndPoints:_endPointsOfPath];
for (NSUInteger lineIndex = 0; lineIndex < self.chartData.count; lineIndex++) {
CAShapeLayer *chartLine = (CAShapeLayer *) self.chartLineArray[lineIndex];
CAShapeLayer *pointLayer = (CAShapeLayer *) self.chartPointArray[lineIndex];
UIBezierPath *progressline = [_chartPath objectAtIndex:lineIndex];
UIBezierPath *pointPath = [_pointPath objectAtIndex:lineIndex];
CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:@"path"];
pathAnimation.fromValue = (id) chartLine.path;
pathAnimation.toValue = (id) [progressline CGPath];
pathAnimation.duration = 0.5f;
pathAnimation.autoreverses = NO;
pathAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
[chartLine addAnimation:pathAnimation forKey:@"animationKey"];
CABasicAnimation *pointPathAnimation = [CABasicAnimation animationWithKeyPath:@"path"];
pointPathAnimation.fromValue = (id) pointLayer.path;
pointPathAnimation.toValue = (id) [pointPath CGPath];
pointPathAnimation.duration = 0.5f;
pointPathAnimation.autoreverses = NO;
pointPathAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
[pointLayer addAnimation:pointPathAnimation forKey:@"animationKey"];
chartLine.path = progressline.CGPath;
pointLayer.path = pointPath.CGPath;
}
}
#define IOS7_OR_LATER [[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0
- (void)drawRect:(CGRect)rect {
if (self.isShowCoordinateAxis) {
CGFloat yAxisOffset = 10.f;
CGContextRef ctx = UIGraphicsGetCurrentContext();
UIGraphicsPushContext(ctx);
CGContextSetLineWidth(ctx, self.axisWidth);
CGContextSetStrokeColorWithColor(ctx, [self.axisColor CGColor]);
CGFloat xAxisWidth = CGRectGetWidth(rect) - (_chartMarginLeft + _chartMarginRight) / 2;
CGFloat yAxisHeight = _chartMarginBottom + _chartCavanHeight;
// draw coordinate axis
CGContextMoveToPoint(ctx, _chartMarginBottom + yAxisOffset, 0);
CGContextAddLineToPoint(ctx, _chartMarginBottom + yAxisOffset, yAxisHeight);
CGContextAddLineToPoint(ctx, xAxisWidth, yAxisHeight);
CGContextStrokePath(ctx);
// draw y axis arrow
CGContextMoveToPoint(ctx, _chartMarginBottom + yAxisOffset - 3, 6);
CGContextAddLineToPoint(ctx, _chartMarginBottom + yAxisOffset, 0);
CGContextAddLineToPoint(ctx, _chartMarginBottom + yAxisOffset + 3, 6);
CGContextStrokePath(ctx);
// draw x axis arrow
CGContextMoveToPoint(ctx, xAxisWidth - 6, yAxisHeight - 3);
CGContextAddLineToPoint(ctx, xAxisWidth, yAxisHeight);
CGContextAddLineToPoint(ctx, xAxisWidth - 6, yAxisHeight + 3);
CGContextStrokePath(ctx);
if (self.showLabel) {
// draw x axis separator
CGPoint point;
for (NSUInteger i = 0; i < [self.xLabels count]; i++) {
point = CGPointMake(2 * _chartMarginLeft + (i * _xLabelWidth), _chartMarginBottom + _chartCavanHeight);
CGContextMoveToPoint(ctx, point.x, point.y - 2);
CGContextAddLineToPoint(ctx, point.x, point.y);
CGContextStrokePath(ctx);
}
// draw y axis separator
CGFloat yStepHeight = _chartCavanHeight / _yLabelNum;
for (NSUInteger i = 0; i < [self.xLabels count]; i++) {
point = CGPointMake(_chartMarginBottom + yAxisOffset, (_chartCavanHeight - i * yStepHeight + _yLabelHeight / 2));
CGContextMoveToPoint(ctx, point.x, point.y);
CGContextAddLineToPoint(ctx, point.x + 2, point.y);
CGContextStrokePath(ctx);
}
}
UIFont *font = [UIFont systemFontOfSize:11];
// draw y unit
if ([self.yUnit length]) {
CGFloat height = [PNLineChart sizeOfString:self.yUnit withWidth:30.f font:font].height;
CGRect drawRect = CGRectMake(_chartMarginLeft + 10 + 5, 0, 30.f, height);
[self drawTextInContext:ctx text:self.yUnit inRect:drawRect font:font];
}
// draw x unit
if ([self.xUnit length]) {
CGFloat height = [PNLineChart sizeOfString:self.xUnit withWidth:30.f font:font].height;
CGRect drawRect = CGRectMake(CGRectGetWidth(rect) - _chartMarginLeft + 5, _chartMarginBottom + _chartCavanHeight - height / 2, 25.f, height);
[self drawTextInContext:ctx text:self.xUnit inRect:drawRect font:font];
}
}
if (self.showYGridLines) {
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGFloat yAxisOffset = _showLabel ? 10.f : 0.0f;
CGPoint point;
CGFloat yStepHeight = _chartCavanHeight / _yLabelNum;
if (self.yGridLinesColor) {
CGContextSetStrokeColorWithColor(ctx, self.yGridLinesColor.CGColor);
} else {
CGContextSetStrokeColorWithColor(ctx, [UIColor lightGrayColor].CGColor);
}
for (NSUInteger i = 0; i < _yLabelNum; i++) {
point = CGPointMake(_chartMarginLeft + yAxisOffset, (_chartCavanHeight - i * yStepHeight + _yLabelHeight / 2));
CGContextMoveToPoint(ctx, point.x, point.y);
// add dotted style grid
CGFloat dash[] = {6, 5};
// dot diameter is 20 points
CGContextSetLineWidth(ctx, 0.5);
CGContextSetLineCap(ctx, kCGLineCapRound);
CGContextSetLineDash(ctx, 0.0, dash, 2);
CGContextAddLineToPoint(ctx, CGRectGetWidth(rect) - _chartMarginLeft + 5, point.y);
CGContextStrokePath(ctx);
}
}
[super drawRect:rect];
}
#pragma mark private methods
- (void)setupDefaultValues {
[super setupDefaultValues];
// Initialization code
self.backgroundColor = [UIColor whiteColor];
self.clipsToBounds = YES;
self.chartLineArray = [NSMutableArray new];
_showLabel = YES;
_showGenYLabels = YES;
_pathPoints = [[NSMutableArray alloc] init];
_endPointsOfPath = [[NSMutableArray alloc] init];
self.userInteractionEnabled = YES;
_yFixedValueMin = -FLT_MAX;
_yFixedValueMax = -FLT_MAX;
_yValueMax = -FLT_MAX;
_yValueMin = -FLT_MAX;
_yLabelNum = 5.0;
_yLabelHeight = [[[[PNChartLabel alloc] init] font] pointSize];
// _chartMargin = 40;
_chartMarginLeft = 25.0;
_chartMarginRight = 25.0;
_chartMarginTop = 25.0;
_chartMarginBottom = 25.0;
_yLabelFormat = @"%1.f";
_chartCavanWidth = self.frame.size.width - _chartMarginLeft - _chartMarginRight;
_chartCavanHeight = self.frame.size.height - _chartMarginBottom - _chartMarginTop;
// Coordinate Axis Default Values
_showCoordinateAxis = NO;
_axisColor = [UIColor colorWithRed:0.4f green:0.4f blue:0.4f alpha:1.f];
_axisWidth = 1.f;
// do not create curved line chart by default
_showSmoothLines = NO;
}
#pragma mark - tools
+ (CGSize)sizeOfString:(NSString *)text withWidth:(float)width font:(UIFont *)font {
CGSize size = CGSizeMake(width, MAXFLOAT);
if ([text respondsToSelector:@selector(boundingRectWithSize:options:attributes:context:)]) {
NSDictionary *tdic = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName, nil];
size = [text boundingRectWithSize:size
options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
attributes:tdic
context:nil].size;
} else {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
size = [text sizeWithFont:font constrainedToSize:size lineBreakMode:NSLineBreakByCharWrapping];
#pragma clang diagnostic pop
}
return size;
}
+ (CGPoint)midPointBetweenPoint1:(CGPoint)point1 andPoint2:(CGPoint)point2 {
return CGPointMake((point1.x + point2.x) / 2, (point1.y + point2.y) / 2);
}
+ (CGPoint)controlPointBetweenPoint1:(CGPoint)point1 andPoint2:(CGPoint)point2 {
CGPoint controlPoint = [self midPointBetweenPoint1:point1 andPoint2:point2];
CGFloat diffY = abs((int) (point2.y - controlPoint.y));
if (point1.y < point2.y)
controlPoint.y += diffY;
else if (point1.y > point2.y)
controlPoint.y -= diffY;
return controlPoint;
}
- (void)drawTextInContext:(CGContextRef)ctx text:(NSString *)text inRect:(CGRect)rect font:(UIFont *)font {
if (IOS7_OR_LATER) {
NSMutableParagraphStyle *priceParagraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
priceParagraphStyle.lineBreakMode = NSLineBreakByTruncatingTail;
priceParagraphStyle.alignment = NSTextAlignmentLeft;
[text drawInRect:rect
withAttributes:@{NSParagraphStyleAttributeName : priceParagraphStyle, NSFontAttributeName : font}];
} else {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
[text drawInRect:rect
withFont:font
lineBreakMode:NSLineBreakByTruncatingTail
alignment:NSTextAlignmentLeft];
#pragma clang diagnostic pop
}
}
- (NSString *)formatYLabel:(double)value {
if (self.yLabelBlockFormatter) {
return self.yLabelBlockFormatter(value);
}
else {
if (!self.thousandsSeparator) {
NSString *format = self.yLabelFormat ?: @"%1.f";
return [NSString stringWithFormat:format, value];
}
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
return [numberFormatter stringFromNumber:[NSNumber numberWithDouble:value]];
}
}
- (UIView *)getLegendWithMaxWidth:(CGFloat)mWidth {
if ([self.chartData count] < 1) {
return nil;
}
/* This is a short line that refers to the chart data */
CGFloat legendLineWidth = 40;
/* x and y are the coordinates of the starting point of each legend item */
CGFloat x = 0;
CGFloat y = 0;
/* accumulated height */
CGFloat totalHeight = 0;
CGFloat totalWidth = 0;
NSMutableArray *legendViews = [[NSMutableArray alloc] init];
/* Determine the max width of each legend item */
CGFloat maxLabelWidth;
if (self.legendStyle == PNLegendItemStyleStacked) {
maxLabelWidth = mWidth - legendLineWidth;
} else {
maxLabelWidth = MAXFLOAT;
}
/* this is used when labels wrap text and the line
* should be in the middle of the first row */
CGFloat singleRowHeight = [PNLineChart sizeOfString:@"Test"
withWidth:MAXFLOAT
font:self.legendFont ? self.legendFont : [UIFont systemFontOfSize:12.0f]].height;
NSUInteger counter = 0;
NSUInteger rowWidth = 0;
NSUInteger rowMaxHeight = 0;
for (PNLineChartData *pdata in self.chartData) {
/* Expected label size*/
CGSize labelsize = [PNLineChart sizeOfString:pdata.dataTitle
withWidth:maxLabelWidth
font:self.legendFont ? self.legendFont : [UIFont systemFontOfSize:12.0f]];
/* draw lines */
if ((rowWidth + labelsize.width + legendLineWidth > mWidth) && (self.legendStyle == PNLegendItemStyleSerial)) {
rowWidth = 0;
x = 0;
y += rowMaxHeight;
rowMaxHeight = 0;
}
rowWidth += labelsize.width + legendLineWidth;
totalWidth = self.legendStyle == PNLegendItemStyleSerial ? fmaxf(rowWidth, totalWidth) : fmaxf(totalWidth, labelsize.width + legendLineWidth);
/* If there is inflection decorator, the line is composed of two lines
* and this is the space that separates two lines in order to put inflection
* decorator */
CGFloat inflexionWidthSpacer = pdata.inflexionPointStyle == PNLineChartPointStyleTriangle ? pdata.inflexionPointWidth / 2 : pdata.inflexionPointWidth;
CGFloat halfLineLength;
if (pdata.inflexionPointStyle != PNLineChartPointStyleNone) {
halfLineLength = (legendLineWidth * 0.8 - inflexionWidthSpacer) / 2;
} else {
halfLineLength = legendLineWidth * 0.8;
}
UIView *line = [[UIView alloc] initWithFrame:CGRectMake(x + legendLineWidth * 0.1, y + (singleRowHeight - pdata.lineWidth) / 2, halfLineLength, pdata.lineWidth)];
line.backgroundColor = pdata.color;
line.alpha = pdata.alpha;
[legendViews addObject:line];
if (pdata.inflexionPointStyle != PNLineChartPointStyleNone) {
line = [[UIView alloc] initWithFrame:CGRectMake(x + legendLineWidth * 0.1 + halfLineLength + inflexionWidthSpacer, y + (singleRowHeight - pdata.lineWidth) / 2, halfLineLength, pdata.lineWidth)];
line.backgroundColor = pdata.color;
line.alpha = pdata.alpha;
[legendViews addObject:line];
}
// Add inflexion type
UIColor *inflexionPointColor = pdata.inflexionPointColor;
if (!inflexionPointColor) {
inflexionPointColor = pdata.color;
}
[legendViews addObject:[self drawInflexion:pdata.inflexionPointWidth
center:CGPointMake(x + legendLineWidth / 2, y + singleRowHeight / 2)
strokeWidth:pdata.lineWidth
inflexionStyle:pdata.inflexionPointStyle
andColor:inflexionPointColor
andAlpha:pdata.alpha]];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(x + legendLineWidth, y, labelsize.width, labelsize.height)];
label.text = pdata.dataTitle;
label.textColor = self.legendFontColor ? self.legendFontColor : [UIColor blackColor];
label.font = self.legendFont ? self.legendFont : [UIFont systemFontOfSize:12.0f];
label.lineBreakMode = NSLineBreakByWordWrapping;
label.numberOfLines = 0;
rowMaxHeight = fmaxf(rowMaxHeight, labelsize.height);
x += self.legendStyle == PNLegendItemStyleStacked ? 0 : labelsize.width + legendLineWidth;
y += self.legendStyle == PNLegendItemStyleStacked ? labelsize.height : 0;
totalHeight = self.legendStyle == PNLegendItemStyleSerial ? fmaxf(totalHeight, rowMaxHeight + y) : totalHeight + labelsize.height;
[legendViews addObject:label];
counter++;
}
UIView *legend = [[UIView alloc] initWithFrame:CGRectMake(0, 0, mWidth, totalHeight)];
for (UIView *v in legendViews) {
[legend addSubview:v];
}
return legend;
}
- (UIImageView *)drawInflexion:(CGFloat)size center:(CGPoint)center strokeWidth:(CGFloat)sw inflexionStyle:(PNLineChartPointStyle)type andColor:(UIColor *)color andAlpha:(CGFloat)alfa {
//Make the size a little bigger so it includes also border stroke
CGSize aSize = CGSizeMake(size + sw, size + sw);
UIGraphicsBeginImageContextWithOptions(aSize, NO, 0.0);
CGContextRef context = UIGraphicsGetCurrentContext();
if (type == PNLineChartPointStyleCircle) {
CGContextAddArc(context, (size + sw) / 2, (size + sw) / 2, size / 2, 0, M_PI * 2, YES);
} else if (type == PNLineChartPointStyleSquare) {
CGContextAddRect(context, CGRectMake(sw / 2, sw / 2, size, size));
} else if (type == PNLineChartPointStyleTriangle) {
CGContextMoveToPoint(context, sw / 2, size + sw / 2);
CGContextAddLineToPoint(context, size + sw / 2, size + sw / 2);
CGContextAddLineToPoint(context, size / 2 + sw / 2, sw / 2);
CGContextAddLineToPoint(context, sw / 2, size + sw / 2);
CGContextClosePath(context);
}
//Set some stroke properties
CGContextSetLineWidth(context, sw);
CGContextSetAlpha(context, alfa);
CGContextSetStrokeColorWithColor(context, color.CGColor);
//Finally draw
CGContextDrawPath(context, kCGPathStroke);
//now get the image from the context
UIImage *squareImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
//// Translate origin
CGFloat originX = center.x - (size + sw) / 2.0;
CGFloat originY = center.y - (size + sw) / 2.0;
UIImageView *squareImageView = [[UIImageView alloc] initWithImage:squareImage];
[squareImageView setFrame:CGRectMake(originX, originY, size + sw, size + sw)];
return squareImageView;
}
#pragma mark setter and getter
- (CATextLayer *)createPointLabelFor:(CGFloat)grade pointCenter:(CGPoint)pointCenter width:(CGFloat)width withChartData:(PNLineChartData *)chartData {
CATextLayer *textLayer = [[CATextLayer alloc] init];
[textLayer setAlignmentMode:kCAAlignmentCenter];
[textLayer setForegroundColor:[chartData.pointLabelColor CGColor]];
[textLayer setBackgroundColor:[[[UIColor whiteColor] colorWithAlphaComponent:0.8] CGColor]];
[textLayer setCornerRadius:textLayer.fontSize / 8.0];
if (chartData.pointLabelFont != nil) {
[textLayer setFont:(__bridge CFTypeRef) (chartData.pointLabelFont)];
textLayer.fontSize = [chartData.pointLabelFont pointSize];
}
CGFloat textHeight = textLayer.fontSize * 1.1;
CGFloat textWidth = width * 8;
CGFloat textStartPosY;
textStartPosY = pointCenter.y - textLayer.fontSize;
[self.layer addSublayer:textLayer];
if (chartData.pointLabelFormat != nil) {
[textLayer setString:[[NSString alloc] initWithFormat:chartData.pointLabelFormat, grade]];
} else {
[textLayer setString:[[NSString alloc] initWithFormat:_yLabelFormat, grade]];
}
[textLayer setFrame:CGRectMake(0, 0, textWidth, textHeight)];
[textLayer setPosition:CGPointMake(pointCenter.x, textStartPosY)];
textLayer.contentsScale = [UIScreen mainScreen].scale;
return textLayer;
}
- (CABasicAnimation *)fadeAnimation {
CABasicAnimation *fadeAnimation = nil;
if (self.displayAnimated) {
fadeAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"];
fadeAnimation.fromValue = [NSNumber numberWithFloat:0.0];
fadeAnimation.toValue = [NSNumber numberWithFloat:1.0];
fadeAnimation.duration = 2.0;
}
return fadeAnimation;
}
- (CABasicAnimation *)pathAnimation {
if (self.displayAnimated && !_pathAnimation) {
_pathAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
_pathAnimation.duration = 1.0;
_pathAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
_pathAnimation.fromValue = @0.0f;
_pathAnimation.toValue = @1.0f;
}
return _pathAnimation;
}
@end
| {
"content_hash": "bd3a6f6a520a6302cb20b72884465bf0",
"timestamp": "",
"source": "github",
"line_count": 1089,
"max_line_length": 206,
"avg_line_length": 40.02112029384757,
"alnum_prop": 0.6324484317279673,
"repo_name": "ZuoLuFei/CMKit",
"id": "90143c28b3d97ae2e7071c5716de365781e70d2f",
"size": "43585",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Example/CMKit/CMKit-Tool(工具类)/FrameworkManager/Chart(图表)/Tool/PNChart/PNLineChart.m",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "5880"
},
{
"name": "Objective-C",
"bytes": "5688111"
},
{
"name": "Objective-C++",
"bytes": "21708"
},
{
"name": "Ruby",
"bytes": "4125"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.