prompt
large_stringlengths
70
991k
completion
large_stringlengths
0
1.02k
<|file_name|>plot_couplings.py<|end_file_name|><|fim▁begin|>#! /usr/bin/env python """ This programs plots the electronic coupling between two states. It reads all Ham_*_im files and cache them in a tensor saved on disk. Usage: plot_couplings.py -p . -s1 XX -s2 YY -dt 1.0 p = path to the hamiltonian files s1 = state 1 index s2 = state 2 index dt = time step in fs """ import numpy as np import matplotlib.pyplot as plt import argparse<|fim▁hole|>r2meV = 13605.698 # From Rydeberg to eV def main(path_output, s1, s2, dt): # Check if the file with couplings exists if not os.path.isfile('couplings.npy'): # Check all the files stored files_im = glob.glob('Ham_*_im') # Read the couplings couplings = np.stack( np.loadtxt(f'Ham_{f}_im') for f in range(len(files_im))) # Save the file for fast reading afterwards np.save('couplings', couplings) else: couplings = np.load('couplings.npy') ts = np.arange(couplings.shape[0]) * dt plt.plot(ts, couplings[:, s1, s2] * r2meV) plt.xlabel('Time (fs)') plt.ylabel('Energy (meV)') plt.show() def read_cmd_line(parser): """ Parse Command line options. """ args = parser.parse_args() attributes = ['p', 's1', 's2', 'dt'] return [getattr(args, p) for p in attributes] if __name__ == "__main__": msg = "plot_decho -p <path/to/hamiltonians> -s1 <State 1> -s2 <State 2>\ -dt <time step>" parser = argparse.ArgumentParser(description=msg) parser.add_argument('-p', required=True, help='path to the Hamiltonian files in Pyxaid format') parser.add_argument('-s1', required=True, type=int, help='Index of the first state') parser.add_argument('-s2', required=True, type=int, help='Index of the second state') parser.add_argument('-dt', type=float, default=1.0, help='Index of the second state') main(*read_cmd_line(parser))<|fim▁end|>
import glob import os.path
<|file_name|>python.go<|end_file_name|><|fim▁begin|>package tasks import ( "strings" "os/exec" "log"<|fim▁hole|> const ( PYTHON_COMMAND_ARG = "command" PYTHON_ARGS_ARG = "args" ) type Python struct { args []string } func (t *Python) Configure(args map[string]string) statusCode { val, ok := args[PYTHON_COMMAND_ARG] if !ok { return StatusConfigurationError } t.args = make([]string, 0) t.args = append(t.args, val) val, ok = args[PYTHON_ARGS_ARG] if !ok { return StatusConfigurationError } t.args = append(t.args, strings.Split(val, " ")...) return StatusOk } func (t *Python) Execute() statusCode { err := exec.Command("python2.7", t.args...).Run() if err != nil { log.Printf("execute error: %s\n", err.Error()) return StatusExecutionError } return StatusOk } func (t *Python) GetName() string { return "python" }<|fim▁end|>
)
<|file_name|>main.rs<|end_file_name|><|fim▁begin|>extern crate roman_army; use roman_army::ComponentUnit; use roman_army::primitives::{ Archer, Infantryman, Horseman }; use roman_army::composite::CompositeUnit; fn main() { let mut army = CompositeUnit::new(); for _ in 0..4 { let legion = create_legion(); army.add_unit(Box::new(legion)); } { let legions = army.get_units(); println!("Roman army damaging strength is {}", army.get_strength()); println!("Roman army has {} legions\n", legions.len()); } { let legion = army.get_unit(0); println!("Roman legion damaging strength is {}", legion.get_strength()); println!("Roman legion has {} units\n", legion.get_units().len()); } army.remove(0); let legions = army.get_units(); println!("Roman army damaging strength is {}", army.get_strength()); println!("Roman army has {} legions", legions.len()); } fn create_legion() -> CompositeUnit { let mut composite_legion = CompositeUnit::new(); for _ in 0..3000 { composite_legion.add_unit(Box::new(Infantryman)); } for _ in 0..1200 {<|fim▁hole|> composite_legion.add_unit(Box::new(Horseman)); } composite_legion }<|fim▁end|>
composite_legion.add_unit(Box::new(Archer)); } for _ in 0..300 {
<|file_name|>IborFutureTradeTest.java<|end_file_name|><|fim▁begin|>/* * Copyright (C) 2015 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.strata.product.index; import static com.opengamma.strata.collect.TestHelper.assertSerialization;<|fim▁hole|>import static com.opengamma.strata.collect.TestHelper.coverBeanEquals; import static com.opengamma.strata.collect.TestHelper.coverImmutableBean; import static com.opengamma.strata.collect.TestHelper.date; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.data.Offset.offset; import java.time.LocalDate; import java.util.Optional; import org.junit.jupiter.api.Test; import com.opengamma.strata.basics.ReferenceData; import com.opengamma.strata.basics.currency.Currency; import com.opengamma.strata.product.PortfolioItemSummary; import com.opengamma.strata.product.PortfolioItemType; import com.opengamma.strata.product.ProductType; import com.opengamma.strata.product.TradeInfo; import com.opengamma.strata.product.TradedPrice; /** * Test {@link IborFutureTrade}. */ public class IborFutureTradeTest { private static final ReferenceData REF_DATA = ReferenceData.standard(); private static final LocalDate TRADE_DATE = date(2015, 3, 18); private static final TradeInfo TRADE_INFO = TradeInfo.of(TRADE_DATE); private static final IborFuture PRODUCT = IborFutureTest.sut(); private static final IborFuture PRODUCT2 = IborFutureTest.sut2(); private static final double QUANTITY = 35; private static final double QUANTITY2 = 36; private static final double PRICE = 0.99; private static final double PRICE2 = 0.98; //------------------------------------------------------------------------- @Test public void test_builder() { IborFutureTrade test = sut(); assertThat(test.getInfo()).isEqualTo(TRADE_INFO); assertThat(test.getProduct()).isEqualTo(PRODUCT); assertThat(test.getPrice()).isEqualTo(PRICE); assertThat(test.getQuantity()).isEqualTo(QUANTITY); assertThat(test.withInfo(TRADE_INFO).getInfo()).isEqualTo(TRADE_INFO); assertThat(test.withQuantity(0.9129).getQuantity()).isCloseTo(0.9129d, offset(1e-10)); assertThat(test.withPrice(0.9129).getPrice()).isCloseTo(0.9129d, offset(1e-10)); } @Test public void test_builder_badPrice() { assertThatIllegalArgumentException() .isThrownBy(() -> sut().toBuilder().price(2.1).build()); } //------------------------------------------------------------------------- @Test public void test_summarize() { IborFutureTrade trade = sut(); PortfolioItemSummary expected = PortfolioItemSummary.builder() .id(TRADE_INFO.getId().orElse(null)) .portfolioItemType(PortfolioItemType.TRADE) .productType(ProductType.IBOR_FUTURE) .currencies(Currency.USD) .description("IborFuture x 35") .build(); assertThat(trade.summarize()).isEqualTo(expected); } //------------------------------------------------------------------------- @Test public void test_resolve() { IborFutureTrade test = sut(); ResolvedIborFutureTrade resolved = test.resolve(REF_DATA); assertThat(resolved.getInfo()).isEqualTo(TRADE_INFO); assertThat(resolved.getProduct()).isEqualTo(PRODUCT.resolve(REF_DATA)); assertThat(resolved.getQuantity()).isEqualTo(QUANTITY); assertThat(resolved.getTradedPrice()).isEqualTo(Optional.of(TradedPrice.of(TRADE_DATE, PRICE))); } //------------------------------------------------------------------------- @Test public void test_withQuantity() { IborFutureTrade base = sut(); double quantity = 65243; IborFutureTrade computed = base.withQuantity(quantity); IborFutureTrade expected = IborFutureTrade.builder() .info(TRADE_INFO) .product(PRODUCT) .quantity(quantity) .price(PRICE) .build(); assertThat(computed).isEqualTo(expected); } @Test public void test_withPrice() { IborFutureTrade base = sut(); double price = 0.95; IborFutureTrade computed = base.withPrice(price); IborFutureTrade expected = IborFutureTrade.builder() .info(TRADE_INFO) .product(PRODUCT) .quantity(QUANTITY) .price(price) .build(); assertThat(computed).isEqualTo(expected); } //------------------------------------------------------------------------- @Test public void coverage() { coverImmutableBean(sut()); coverBeanEquals(sut(), sut2()); } @Test public void test_serialization() { assertSerialization(sut()); } //------------------------------------------------------------------------- static IborFutureTrade sut() { return IborFutureTrade.builder() .info(TRADE_INFO) .product(PRODUCT) .quantity(QUANTITY) .price(PRICE) .build(); } static IborFutureTrade sut2() { return IborFutureTrade.builder() .product(PRODUCT2) .quantity(QUANTITY2) .price(PRICE2) .build(); } }<|fim▁end|>
<|file_name|>bundle.min.js<|end_file_name|><|fim▁begin|>/******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "/assets/"; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _reactDom = __webpack_require__(36); var _Member = __webpack_require__(182); var _MemberList = __webpack_require__(!(function webpackMissingModule() { var e = new Error("Cannot find module \"./components/ui/MemberList\""); e.code = 'MODULE_NOT_FOUND'; throw e; }())); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // import routes from './routes' window.React = _react2.default; (0, _reactDom.render)(_react2.default.createElement(_MemberList.MemberList, null), document.getElementById('react-container') // <Member admin={true} // name="Edna Welch" // email="edna.welch88@example.com" // thumbnail="https://randomuser.me/api/portraits/women/90.jpg" // makeAdmin={(email) => console.log(email)}/> ); /***/ }), /* 1 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; module.exports = __webpack_require__(2); /***/ }), /* 2 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _assign = __webpack_require__(4); var ReactChildren = __webpack_require__(5); var ReactComponent = __webpack_require__(18); var ReactPureComponent = __webpack_require__(21); var ReactClass = __webpack_require__(22); var ReactDOMFactories = __webpack_require__(24); var ReactElement = __webpack_require__(9); var ReactPropTypes = __webpack_require__(29); var ReactVersion = __webpack_require__(34); var onlyChild = __webpack_require__(35); var warning = __webpack_require__(11); var createElement = ReactElement.createElement; var createFactory = ReactElement.createFactory; var cloneElement = ReactElement.cloneElement; if (process.env.NODE_ENV !== 'production') { var canDefineProperty = __webpack_require__(13); var ReactElementValidator = __webpack_require__(25); var didWarnPropTypesDeprecated = false; createElement = ReactElementValidator.createElement; createFactory = ReactElementValidator.createFactory; cloneElement = ReactElementValidator.cloneElement; } var __spread = _assign; if (process.env.NODE_ENV !== 'production') { var warned = false; __spread = function () { process.env.NODE_ENV !== 'production' ? warning(warned, 'React.__spread is deprecated and should not be used. Use ' + 'Object.assign directly or another helper function with similar ' + 'semantics. You may be seeing this warning due to your compiler. ' + 'See https://fb.me/react-spread-deprecation for more details.') : void 0; warned = true; return _assign.apply(null, arguments); }; } var React = { // Modern Children: { map: ReactChildren.map, forEach: ReactChildren.forEach, count: ReactChildren.count, toArray: ReactChildren.toArray, only: onlyChild }, Component: ReactComponent, PureComponent: ReactPureComponent, createElement: createElement, cloneElement: cloneElement, isValidElement: ReactElement.isValidElement, // Classic PropTypes: ReactPropTypes, createClass: ReactClass.createClass, createFactory: createFactory, createMixin: function (mixin) { // Currently a noop. Will be used to validate and trace mixins. return mixin; }, // This looks DOM specific but these are actually isomorphic helpers // since they are just generating DOM strings. DOM: ReactDOMFactories, version: ReactVersion, // Deprecated hook for JSX spread, don't use this for anything. __spread: __spread }; // TODO: Fix tests so that this deprecation warning doesn't cause failures. if (process.env.NODE_ENV !== 'production') { if (canDefineProperty) { Object.defineProperty(React, 'PropTypes', { get: function () { process.env.NODE_ENV !== 'production' ? warning(didWarnPropTypesDeprecated, 'Accessing PropTypes via the main React package is deprecated. Use ' + 'the prop-types package from npm instead.') : void 0; didWarnPropTypesDeprecated = true; return ReactPropTypes; } }); } } module.exports = React; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 3 */ /***/ (function(module, exports) { // shim for using process in browser var process = module.exports = {}; // cached from whatever global is present so that test runners that stub it // don't break things. But we need to wrap it in a try catch in case it is // wrapped in strict mode code which doesn't define any globals. It's inside a // function because try/catches deoptimize in certain engines. var cachedSetTimeout; var cachedClearTimeout; function defaultSetTimout() { throw new Error('setTimeout has not been defined'); } function defaultClearTimeout () { throw new Error('clearTimeout has not been defined'); } (function () { try { if (typeof setTimeout === 'function') { cachedSetTimeout = setTimeout; } else { cachedSetTimeout = defaultSetTimout; } } catch (e) { cachedSetTimeout = defaultSetTimout; } try { if (typeof clearTimeout === 'function') { cachedClearTimeout = clearTimeout; } else { cachedClearTimeout = defaultClearTimeout; } } catch (e) { cachedClearTimeout = defaultClearTimeout; } } ()) function runTimeout(fun) { if (cachedSetTimeout === setTimeout) { //normal enviroments in sane situations return setTimeout(fun, 0); } // if setTimeout wasn't available but was latter defined if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { cachedSetTimeout = setTimeout; return setTimeout(fun, 0); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedSetTimeout(fun, 0); } catch(e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedSetTimeout.call(null, fun, 0); } catch(e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error return cachedSetTimeout.call(this, fun, 0); } } } function runClearTimeout(marker) { if (cachedClearTimeout === clearTimeout) { //normal enviroments in sane situations return clearTimeout(marker); } // if clearTimeout wasn't available but was latter defined if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { cachedClearTimeout = clearTimeout; return clearTimeout(marker); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedClearTimeout(marker); } catch (e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedClearTimeout.call(null, marker); } catch (e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. // Some versions of I.E. have different rules for clearTimeout vs setTimeout return cachedClearTimeout.call(this, marker); } } } var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { if (!draining || !currentQueue) { return; } draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = runTimeout(cleanUpNextTick); draining = true; var len = queue.length; while(len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; runClearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { runTimeout(drainQueue); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.prependListener = noop; process.prependOnceListener = noop; process.listeners = function (name) { return [] } process.binding = function (name) { throw new Error('process.binding is not supported'); }; process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; /***/ }), /* 4 */ /***/ (function(module, exports) { /* object-assign (c) Sindre Sorhus @license MIT */ 'use strict'; /* eslint-disable no-unused-vars */ var getOwnPropertySymbols = Object.getOwnPropertySymbols; var hasOwnProperty = Object.prototype.hasOwnProperty; var propIsEnumerable = Object.prototype.propertyIsEnumerable; function toObject(val) { if (val === null || val === undefined) { throw new TypeError('Object.assign cannot be called with null or undefined'); } return Object(val); } function shouldUseNative() { try { if (!Object.assign) { return false; } // Detect buggy property enumeration order in older V8 versions. // https://bugs.chromium.org/p/v8/issues/detail?id=4118 var test1 = new String('abc'); // eslint-disable-line no-new-wrappers test1[5] = 'de'; if (Object.getOwnPropertyNames(test1)[0] === '5') { return false; } // https://bugs.chromium.org/p/v8/issues/detail?id=3056 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; } // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test3 = {}; 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { test3[letter] = letter; }); if (Object.keys(Object.assign({}, test3)).join('') !== 'abcdefghijklmnopqrst') { return false; } return true; } catch (err) { // We don't expect any of the above to throw, but better to be safe. return false; } } module.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; }; /***/ }), /* 5 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var PooledClass = __webpack_require__(6); var ReactElement = __webpack_require__(9); var emptyFunction = __webpack_require__(12); var traverseAllChildren = __webpack_require__(15); var twoArgumentPooler = PooledClass.twoArgumentPooler; var fourArgumentPooler = PooledClass.fourArgumentPooler; var userProvidedKeyEscapeRegex = /\/+/g; function escapeUserProvidedKey(text) { return ('' + text).replace(userProvidedKeyEscapeRegex, '$&/'); } /** * PooledClass representing the bookkeeping associated with performing a child * traversal. Allows avoiding binding callbacks. * * @constructor ForEachBookKeeping * @param {!function} forEachFunction Function to perform traversal with. * @param {?*} forEachContext Context to perform context with. */ function ForEachBookKeeping(forEachFunction, forEachContext) { this.func = forEachFunction; this.context = forEachContext; this.count = 0; } ForEachBookKeeping.prototype.destructor = function () { this.func = null; this.context = null; this.count = 0; }; PooledClass.addPoolingTo(ForEachBookKeeping, twoArgumentPooler); function forEachSingleChild(bookKeeping, child, name) { var func = bookKeeping.func, context = bookKeeping.context; func.call(context, child, bookKeeping.count++); } /** * Iterates through children that are typically specified as `props.children`. * * See https://facebook.github.io/react/docs/top-level-api.html#react.children.foreach * * The provided forEachFunc(child, index) will be called for each * leaf child. * * @param {?*} children Children tree container. * @param {function(*, int)} forEachFunc * @param {*} forEachContext Context for forEachContext. */ function forEachChildren(children, forEachFunc, forEachContext) { if (children == null) { return children; } var traverseContext = ForEachBookKeeping.getPooled(forEachFunc, forEachContext); traverseAllChildren(children, forEachSingleChild, traverseContext); ForEachBookKeeping.release(traverseContext); } /** * PooledClass representing the bookkeeping associated with performing a child * mapping. Allows avoiding binding callbacks. * * @constructor MapBookKeeping * @param {!*} mapResult Object containing the ordered map of results. * @param {!function} mapFunction Function to perform mapping with. * @param {?*} mapContext Context to perform mapping with. */ function MapBookKeeping(mapResult, keyPrefix, mapFunction, mapContext) { this.result = mapResult; this.keyPrefix = keyPrefix; this.func = mapFunction; this.context = mapContext; this.count = 0; } MapBookKeeping.prototype.destructor = function () { this.result = null; this.keyPrefix = null; this.func = null; this.context = null; this.count = 0; }; PooledClass.addPoolingTo(MapBookKeeping, fourArgumentPooler); function mapSingleChildIntoContext(bookKeeping, child, childKey) { var result = bookKeeping.result, keyPrefix = bookKeeping.keyPrefix, func = bookKeeping.func, context = bookKeeping.context; var mappedChild = func.call(context, child, bookKeeping.count++); if (Array.isArray(mappedChild)) { mapIntoWithKeyPrefixInternal(mappedChild, result, childKey, emptyFunction.thatReturnsArgument); } else if (mappedChild != null) { if (ReactElement.isValidElement(mappedChild)) { mappedChild = ReactElement.cloneAndReplaceKey(mappedChild, // Keep both the (mapped) and old keys if they differ, just as // traverseAllChildren used to do for objects as children keyPrefix + (mappedChild.key && (!child || child.key !== mappedChild.key) ? escapeUserProvidedKey(mappedChild.key) + '/' : '') + childKey); } result.push(mappedChild); } } function mapIntoWithKeyPrefixInternal(children, array, prefix, func, context) { var escapedPrefix = ''; if (prefix != null) { escapedPrefix = escapeUserProvidedKey(prefix) + '/'; } var traverseContext = MapBookKeeping.getPooled(array, escapedPrefix, func, context); traverseAllChildren(children, mapSingleChildIntoContext, traverseContext); MapBookKeeping.release(traverseContext); } /** * Maps children that are typically specified as `props.children`. * * See https://facebook.github.io/react/docs/top-level-api.html#react.children.map * * The provided mapFunction(child, key, index) will be called for each * leaf child. * * @param {?*} children Children tree container. * @param {function(*, int)} func The map function. * @param {*} context Context for mapFunction. * @return {object} Object containing the ordered map of results. */ function mapChildren(children, func, context) { if (children == null) { return children; } var result = []; mapIntoWithKeyPrefixInternal(children, result, null, func, context); return result; } function forEachSingleChildDummy(traverseContext, child, name) { return null; } /** * Count the number of children that are typically specified as * `props.children`. * * See https://facebook.github.io/react/docs/top-level-api.html#react.children.count * * @param {?*} children Children tree container. * @return {number} The number of children. */ function countChildren(children, context) { return traverseAllChildren(children, forEachSingleChildDummy, null); } /** * Flatten a children object (typically specified as `props.children`) and * return an array with appropriately re-keyed children. * * See https://facebook.github.io/react/docs/top-level-api.html#react.children.toarray */ function toArray(children) { var result = []; mapIntoWithKeyPrefixInternal(children, result, null, emptyFunction.thatReturnsArgument); return result; } var ReactChildren = { forEach: forEachChildren, map: mapChildren, mapIntoWithKeyPrefixInternal: mapIntoWithKeyPrefixInternal, count: countChildren, toArray: toArray }; module.exports = ReactChildren; /***/ }), /* 6 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var _prodInvariant = __webpack_require__(7); var invariant = __webpack_require__(8); /** * Static poolers. Several custom versions for each potential number of * arguments. A completely generic pooler is easy to implement, but would * require accessing the `arguments` object. In each of these, `this` refers to * the Class itself, not an instance. If any others are needed, simply add them * here, or in their own files. */ var oneArgumentPooler = function (copyFieldsFrom) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, copyFieldsFrom); return instance; } else { return new Klass(copyFieldsFrom); } }; var twoArgumentPooler = function (a1, a2) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, a1, a2); return instance; } else { return new Klass(a1, a2); } }; var threeArgumentPooler = function (a1, a2, a3) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, a1, a2, a3); return instance; } else { return new Klass(a1, a2, a3); } }; var fourArgumentPooler = function (a1, a2, a3, a4) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, a1, a2, a3, a4); return instance; } else { return new Klass(a1, a2, a3, a4); } }; var standardReleaser = function (instance) { var Klass = this; !(instance instanceof Klass) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Trying to release an instance into a pool of a different type.') : _prodInvariant('25') : void 0; instance.destructor(); if (Klass.instancePool.length < Klass.poolSize) { Klass.instancePool.push(instance); } }; var DEFAULT_POOL_SIZE = 10; var DEFAULT_POOLER = oneArgumentPooler; /** * Augments `CopyConstructor` to be a poolable class, augmenting only the class * itself (statically) not adding any prototypical fields. Any CopyConstructor * you give this may have a `poolSize` property, and will look for a * prototypical `destructor` on instances. * * @param {Function} CopyConstructor Constructor that can be used to reset. * @param {Function} pooler Customizable pooler. */ var addPoolingTo = function (CopyConstructor, pooler) { // Casting as any so that flow ignores the actual implementation and trusts // it to match the type we declared var NewKlass = CopyConstructor; NewKlass.instancePool = []; NewKlass.getPooled = pooler || DEFAULT_POOLER; if (!NewKlass.poolSize) { NewKlass.poolSize = DEFAULT_POOL_SIZE; } NewKlass.release = standardReleaser; return NewKlass; }; var PooledClass = { addPoolingTo: addPoolingTo, oneArgumentPooler: oneArgumentPooler, twoArgumentPooler: twoArgumentPooler, threeArgumentPooler: threeArgumentPooler, fourArgumentPooler: fourArgumentPooler }; module.exports = PooledClass; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 7 */ /***/ (function(module, exports) { /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; /** * WARNING: DO NOT manually require this module. * This is a replacement for `invariant(...)` used by the error code system * and will _only_ be required by the corresponding babel pass. * It always throws. */ function reactProdInvariant(code) { var argCount = arguments.length - 1; var message = 'Minified React error #' + code + '; visit ' + 'http://facebook.github.io/react/docs/error-decoder.html?invariant=' + code; for (var argIdx = 0; argIdx < argCount; argIdx++) { message += '&args[]=' + encodeURIComponent(arguments[argIdx + 1]); } message += ' for the full message or use the non-minified dev environment' + ' for full errors and additional helpful warnings.'; var error = new Error(message); error.name = 'Invariant Violation'; error.framesToPop = 1; // we don't care about reactProdInvariant's own frame throw error; } module.exports = reactProdInvariant; /***/ }), /* 8 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; /** * Use invariant() to assert state which your program assumes to be true. * * Provide sprintf-style format (only %s is supported) and arguments * to provide information about what broke and what you were * expecting. * * The invariant message will be stripped in production, but the invariant * will remain to ensure logic does not differ in production. */ var validateFormat = function validateFormat(format) {}; if (process.env.NODE_ENV !== 'production') { validateFormat = function validateFormat(format) { if (format === undefined) { throw new Error('invariant requires an error message argument'); } }; } function invariant(condition, format, a, b, c, d, e, f) { validateFormat(format); if (!condition) { var error; if (format === undefined) { error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.'); } else { var args = [a, b, c, d, e, f]; var argIndex = 0; error = new Error(format.replace(/%s/g, function () { return args[argIndex++]; })); error.name = 'Invariant Violation'; } error.framesToPop = 1; // we don't care about invariant's own frame throw error; } } module.exports = invariant; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 9 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _assign = __webpack_require__(4); var ReactCurrentOwner = __webpack_require__(10); var warning = __webpack_require__(11); var canDefineProperty = __webpack_require__(13); var hasOwnProperty = Object.prototype.hasOwnProperty; var REACT_ELEMENT_TYPE = __webpack_require__(14); var RESERVED_PROPS = { key: true, ref: true, __self: true, __source: true }; var specialPropKeyWarningShown, specialPropRefWarningShown; function hasValidRef(config) { if (process.env.NODE_ENV !== 'production') { if (hasOwnProperty.call(config, 'ref')) { var getter = Object.getOwnPropertyDescriptor(config, 'ref').get; if (getter && getter.isReactWarning) { return false; } } } return config.ref !== undefined; } function hasValidKey(config) { if (process.env.NODE_ENV !== 'production') { if (hasOwnProperty.call(config, 'key')) { var getter = Object.getOwnPropertyDescriptor(config, 'key').get; if (getter && getter.isReactWarning) { return false; } } } return config.key !== undefined; } function defineKeyPropWarningGetter(props, displayName) { var warnAboutAccessingKey = function () { if (!specialPropKeyWarningShown) { specialPropKeyWarningShown = true; process.env.NODE_ENV !== 'production' ? warning(false, '%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://fb.me/react-special-props)', displayName) : void 0; } }; warnAboutAccessingKey.isReactWarning = true; Object.defineProperty(props, 'key', { get: warnAboutAccessingKey, configurable: true }); } function defineRefPropWarningGetter(props, displayName) { var warnAboutAccessingRef = function () { if (!specialPropRefWarningShown) { specialPropRefWarningShown = true; process.env.NODE_ENV !== 'production' ? warning(false, '%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://fb.me/react-special-props)', displayName) : void 0; } }; warnAboutAccessingRef.isReactWarning = true; Object.defineProperty(props, 'ref', { get: warnAboutAccessingRef, configurable: true }); } /** * Factory method to create a new React element. This no longer adheres to * the class pattern, so do not use new to call it. Also, no instanceof check * will work. Instead test $$typeof field against Symbol.for('react.element') to check * if something is a React Element. * * @param {*} type * @param {*} key * @param {string|object} ref * @param {*} self A *temporary* helper to detect places where `this` is * different from the `owner` when React.createElement is called, so that we * can warn. We want to get rid of owner and replace string `ref`s with arrow * functions, and as long as `this` and owner are the same, there will be no * change in behavior. * @param {*} source An annotation object (added by a transpiler or otherwise) * indicating filename, line number, and/or other information. * @param {*} owner * @param {*} props * @internal */ var ReactElement = function (type, key, ref, self, source, owner, props) { var element = { // This tag allow us to uniquely identify this as a React Element $$typeof: REACT_ELEMENT_TYPE, // Built-in properties that belong on the element type: type, key: key, ref: ref, props: props, // Record the component responsible for creating this element. _owner: owner }; if (process.env.NODE_ENV !== 'production') { // The validation flag is currently mutative. We put it on // an external backing store so that we can freeze the whole object. // This can be replaced with a WeakMap once they are implemented in // commonly used development environments. element._store = {}; // To make comparing ReactElements easier for testing purposes, we make // the validation flag non-enumerable (where possible, which should // include every environment we run tests in), so the test framework // ignores it. if (canDefineProperty) { Object.defineProperty(element._store, 'validated', { configurable: false, enumerable: false, writable: true, value: false }); // self and source are DEV only properties. Object.defineProperty(element, '_self', { configurable: false, enumerable: false, writable: false, value: self }); // Two elements created in two different places should be considered // equal for testing purposes and therefore we hide it from enumeration. Object.defineProperty(element, '_source', { configurable: false, enumerable: false, writable: false, value: source }); } else { element._store.validated = false; element._self = self; element._source = source; } if (Object.freeze) { Object.freeze(element.props); Object.freeze(element); } } return element; }; /** * Create and return a new ReactElement of the given type. * See https://facebook.github.io/react/docs/top-level-api.html#react.createelement */ ReactElement.createElement = function (type, config, children) { var propName; // Reserved names are extracted var props = {}; var key = null; var ref = null; var self = null; var source = null; if (config != null) { if (hasValidRef(config)) { ref = config.ref; } if (hasValidKey(config)) { key = '' + config.key; } self = config.__self === undefined ? null : config.__self; source = config.__source === undefined ? null : config.__source; // Remaining properties are added to a new props object for (propName in config) { if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { props[propName] = config[propName]; } } } // Children can be more than one argument, and those are transferred onto // the newly allocated props object. 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 (process.env.NODE_ENV !== 'production') { if (Object.freeze) { Object.freeze(childArray); } } props.children = childArray; } // Resolve default props if (type && type.defaultProps) { var defaultProps = type.defaultProps; for (propName in defaultProps) { if (props[propName] === undefined) { props[propName] = defaultProps[propName]; } } } if (process.env.NODE_ENV !== 'production') { if (key || ref) { if (typeof props.$$typeof === 'undefined' || props.$$typeof !== REACT_ELEMENT_TYPE) { 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); }; /** * Return a function that produces ReactElements of a given type. * See https://facebook.github.io/react/docs/top-level-api.html#react.createfactory */ ReactElement.createFactory = function (type) { var factory = ReactElement.createElement.bind(null, type); // Expose the type on the factory and the prototype so that it can be // easily accessed on elements. E.g. `<Foo />.type === Foo`. // This should not be named `constructor` since this may not be the function // that created the element, and it may not even be a constructor. // Legacy hook TODO: Warn if this is accessed factory.type = type; return factory; }; ReactElement.cloneAndReplaceKey = function (oldElement, newKey) { var newElement = ReactElement(oldElement.type, newKey, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, oldElement.props); return newElement; }; /** * Clone and return a new ReactElement using element as the starting point. * See https://facebook.github.io/react/docs/top-level-api.html#react.cloneelement */ ReactElement.cloneElement = function (element, config, children) { var propName; // Original props are copied var props = _assign({}, element.props); // Reserved names are extracted var key = element.key; var ref = element.ref; // Self is preserved since the owner is preserved. var self = element._self; // Source is preserved since cloneElement is unlikely to be targeted by a // transpiler, and the original source is probably a better indicator of the // true owner. var source = element._source; // Owner will be preserved, unless ref is overridden var owner = element._owner; if (config != null) { if (hasValidRef(config)) { // Silently steal the ref from the parent. ref = config.ref; owner = ReactCurrentOwner.current; } if (hasValidKey(config)) { key = '' + config.key; } // Remaining properties override existing props 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] === undefined && defaultProps !== undefined) { // Resolve default props props[propName] = defaultProps[propName]; } else { props[propName] = config[propName]; } } } } // Children can be more than one argument, and those are transferred onto // the newly allocated props object. 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); }; /** * Verifies the object is a ReactElement. * See https://facebook.github.io/react/docs/top-level-api.html#react.isvalidelement * @param {?object} object * @return {boolean} True if `object` is a valid component. * @final */ ReactElement.isValidElement = function (object) { return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; }; module.exports = ReactElement; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 10 */ /***/ (function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; /** * Keeps track of the current owner. * * The current owner is the component who should own any components that are * currently being constructed. */ var ReactCurrentOwner = { /** * @internal * @type {ReactComponent} */ current: null }; module.exports = ReactCurrentOwner; /***/ }), /* 11 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2014-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var emptyFunction = __webpack_require__(12); /** * Similar to invariant but only logs a warning if the condition is not met. * This can be used to log issues in development environments in critical * paths. Removing the logging code for production environments will keep the * same logic and follow the same code paths. */ var warning = emptyFunction; if (process.env.NODE_ENV !== 'production') { (function () { var printWarning = function printWarning(format) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } var argIndex = 0; var message = 'Warning: ' + format.replace(/%s/g, function () { return args[argIndex++]; }); if (typeof console !== 'undefined') { console.error(message); } try { // --- Welcome to debugging React --- // This error was thrown as a convenience so that you can use this stack // to find the callsite that caused this warning to fire. throw new Error(message); } catch (x) {} }; warning = function warning(condition, format) { if (format === undefined) { throw new Error('`warning(condition, format, ...args)` requires a warning ' + 'message argument'); } if (format.indexOf('Failed Composite propType: ') === 0) { return; // Ignore CompositeComponent proptype check. } if (!condition) { for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) { args[_key2 - 2] = arguments[_key2]; } printWarning.apply(undefined, [format].concat(args)); } }; })(); } module.exports = warning; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 12 */ /***/ (function(module, exports) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ function makeEmptyFunction(arg) { return function () { return arg; }; } /** * This function accepts and discards inputs; it has no side effects. This is * primarily useful idiomatically for overridable function endpoints which * always need to be callable, since JS lacks a null-call idiom ala Cocoa. */ var emptyFunction = function emptyFunction() {}; emptyFunction.thatReturns = makeEmptyFunction; emptyFunction.thatReturnsFalse = makeEmptyFunction(false); emptyFunction.thatReturnsTrue = makeEmptyFunction(true); emptyFunction.thatReturnsNull = makeEmptyFunction(null); emptyFunction.thatReturnsThis = function () { return this; }; emptyFunction.thatReturnsArgument = function (arg) { return arg; }; module.exports = emptyFunction; /***/ }), /* 13 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var canDefineProperty = false; if (process.env.NODE_ENV !== 'production') { try { // $FlowFixMe https://github.com/facebook/flow/issues/285 Object.defineProperty({}, 'x', { get: function () {} }); canDefineProperty = true; } catch (x) { // IE will fail on defineProperty } } module.exports = canDefineProperty; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 14 */ /***/ (function(module, exports) { /** * Copyright 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; // The Symbol used to tag the ReactElement type. If there is no native Symbol // nor polyfill, then a plain number is used for performance. var REACT_ELEMENT_TYPE = typeof Symbol === 'function' && Symbol['for'] && Symbol['for']('react.element') || 0xeac7; module.exports = REACT_ELEMENT_TYPE; /***/ }), /* 15 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(7); var ReactCurrentOwner = __webpack_require__(10); var REACT_ELEMENT_TYPE = __webpack_require__(14); var getIteratorFn = __webpack_require__(16); var invariant = __webpack_require__(8); var KeyEscapeUtils = __webpack_require__(17); var warning = __webpack_require__(11); var SEPARATOR = '.'; var SUBSEPARATOR = ':'; /** * This is inlined from ReactElement since this file is shared between * isomorphic and renderers. We could extract this to a * */ /** * TODO: Test that a single child and an array with one item have the same key * pattern. */ var didWarnAboutMaps = false; /** * Generate a key string that identifies a component within a set. * * @param {*} component A component that could contain a manual key. * @param {number} index Index that is used if a manual key is not provided. * @return {string} */ function getComponentKey(component, index) { // Do some typechecking here since we call this blindly. We want to ensure // that we don't block potential future ES APIs. if (component && typeof component === 'object' && component.key != null) { // Explicit key return KeyEscapeUtils.escape(component.key); } // Implicit key determined by the index in the set return index.toString(36); } /** * @param {?*} children Children tree container. * @param {!string} nameSoFar Name of the key path so far. * @param {!function} callback Callback to invoke with each child found. * @param {?*} traverseContext Used to pass information throughout the traversal * process. * @return {!number} The number of children in this subtree. */ function traverseAllChildrenImpl(children, nameSoFar, callback, traverseContext) { var type = typeof children; if (type === 'undefined' || type === 'boolean') { // All of the above are perceived as null. children = null; } if (children === null || type === 'string' || type === 'number' || // The following is inlined from ReactElement. This means we can optimize // some checks. React Fiber also inlines this logic for similar purposes. type === 'object' && children.$$typeof === REACT_ELEMENT_TYPE) { callback(traverseContext, children, // If it's the only child, treat the name as if it was wrapped in an array // so that it's consistent if the number of children grows. nameSoFar === '' ? SEPARATOR + getComponentKey(children, 0) : nameSoFar); return 1; } var child; var nextName; var subtreeCount = 0; // Count of children found in the current subtree. var nextNamePrefix = nameSoFar === '' ? SEPARATOR : nameSoFar + SUBSEPARATOR; if (Array.isArray(children)) { for (var i = 0; i < children.length; i++) { child = children[i]; nextName = nextNamePrefix + getComponentKey(child, i); subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext); } } else { var iteratorFn = getIteratorFn(children); if (iteratorFn) { var iterator = iteratorFn.call(children); var step; if (iteratorFn !== children.entries) { var ii = 0; while (!(step = iterator.next()).done) { child = step.value; nextName = nextNamePrefix + getComponentKey(child, ii++); subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext); } } else { if (process.env.NODE_ENV !== 'production') { var mapsAsChildrenAddendum = ''; if (ReactCurrentOwner.current) { var mapsAsChildrenOwnerName = ReactCurrentOwner.current.getName(); if (mapsAsChildrenOwnerName) { mapsAsChildrenAddendum = ' Check the render method of `' + mapsAsChildrenOwnerName + '`.'; } } process.env.NODE_ENV !== 'production' ? warning(didWarnAboutMaps, 'Using Maps as children is not yet fully supported. It is an ' + 'experimental feature that might be removed. Convert it to a ' + 'sequence / iterable of keyed ReactElements instead.%s', mapsAsChildrenAddendum) : void 0; didWarnAboutMaps = true; } // Iterator will provide entry [k,v] tuples rather than values. while (!(step = iterator.next()).done) { var entry = step.value; if (entry) { child = entry[1]; nextName = nextNamePrefix + KeyEscapeUtils.escape(entry[0]) + SUBSEPARATOR + getComponentKey(child, 0); subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext); } } } } else if (type === 'object') { var addendum = ''; if (process.env.NODE_ENV !== 'production') { addendum = ' If you meant to render a collection of children, use an array ' + 'instead or wrap the object using createFragment(object) from the ' + 'React add-ons.'; if (children._isReactElement) { addendum = ' It looks like you\'re using an element created by a different ' + 'version of React. Make sure to use only one copy of React.'; } if (ReactCurrentOwner.current) { var name = ReactCurrentOwner.current.getName(); if (name) { addendum += ' Check the render method of `' + name + '`.'; } } } var childrenString = String(children); true ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Objects are not valid as a React child (found: %s).%s', childrenString === '[object Object]' ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString, addendum) : _prodInvariant('31', childrenString === '[object Object]' ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString, addendum) : void 0; } } return subtreeCount; } /** * Traverses children that are typically specified as `props.children`, but * might also be specified through attributes: * * - `traverseAllChildren(this.props.children, ...)` * - `traverseAllChildren(this.props.leftPanelChildren, ...)` * * The `traverseContext` is an optional argument that is passed through the * entire traversal. It can be used to store accumulations or anything else that * the callback might find relevant. * * @param {?*} children Children tree object. * @param {!function} callback To invoke upon traversing each child. * @param {?*} traverseContext Context for traversal. * @return {!number} The number of children in this subtree. */ function traverseAllChildren(children, callback, traverseContext) { if (children == null) { return 0; } return traverseAllChildrenImpl(children, '', callback, traverseContext); } module.exports = traverseAllChildren; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 16 */ /***/ (function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; /* global Symbol */ var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator; var FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec. /** * Returns the iterator method function contained on the iterable object. * * Be sure to invoke the function with the iterable as context: * * var iteratorFn = getIteratorFn(myIterable); * if (iteratorFn) { * var iterator = iteratorFn.call(myIterable); * ... * } * * @param {?object} maybeIterable * @return {?function} */ function getIteratorFn(maybeIterable) { var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]); if (typeof iteratorFn === 'function') { return iteratorFn; } } module.exports = getIteratorFn; /***/ }), /* 17 */ /***/ (function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; /** * Escape and wrap key so it is safe to use as a reactid * * @param {string} key to be escaped. * @return {string} the escaped key. */ function escape(key) { var escapeRegex = /[=:]/g; var escaperLookup = { '=': '=0', ':': '=2' }; var escapedString = ('' + key).replace(escapeRegex, function (match) { return escaperLookup[match]; }); return '$' + escapedString; } /** * Unescape and unwrap key for human-readable display * * @param {string} key to unescape. * @return {string} the unescaped key. */ function unescape(key) { var unescapeRegex = /(=0|=2)/g; var unescaperLookup = { '=0': '=', '=2': ':' }; var keySubstring = key[0] === '.' && key[1] === '$' ? key.substring(2) : key.substring(1); return ('' + keySubstring).replace(unescapeRegex, function (match) { return unescaperLookup[match]; }); } var KeyEscapeUtils = { escape: escape, unescape: unescape }; module.exports = KeyEscapeUtils; /***/ }), /* 18 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(7); var ReactNoopUpdateQueue = __webpack_require__(19); var canDefineProperty = __webpack_require__(13); var emptyObject = __webpack_require__(20); var invariant = __webpack_require__(8); var warning = __webpack_require__(11); /** * Base class helpers for the updating state of a component. */ function ReactComponent(props, context, updater) { this.props = props; this.context = context; this.refs = emptyObject; // We initialize the default updater but the real one gets injected by the // renderer. this.updater = updater || ReactNoopUpdateQueue; } ReactComponent.prototype.isReactComponent = {}; /** * Sets a subset of the state. Always use this to mutate * state. You should treat `this.state` as immutable. * * There is no guarantee that `this.state` will be immediately updated, so * accessing `this.state` after calling this method may return the old value. * * There is no guarantee that calls to `setState` will run synchronously, * as they may eventually be batched together. You can provide an optional * callback that will be executed when the call to setState is actually * completed. * * When a function is provided to setState, it will be called at some point in * the future (not synchronously). It will be called with the up to date * component arguments (state, props, context). These values can be different * from this.* because your function may be called after receiveProps but before * shouldComponentUpdate, and this new state, props, and context will not yet be * assigned to this. * * @param {object|function} partialState Next partial state or function to * produce next partial state to be merged with current state. * @param {?function} callback Called after state is updated. * @final * @protected */ ReactComponent.prototype.setState = function (partialState, callback) { !(typeof partialState === 'object' || typeof partialState === 'function' || partialState == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'setState(...): takes an object of state variables to update or a function which returns an object of state variables.') : _prodInvariant('85') : void 0; this.updater.enqueueSetState(this, partialState); if (callback) { this.updater.enqueueCallback(this, callback, 'setState'); } }; /** * Forces an update. This should only be invoked when it is known with * certainty that we are **not** in a DOM transaction. * * You may want to call this when you know that some deeper aspect of the * component's state has changed but `setState` was not called. * * This will not invoke `shouldComponentUpdate`, but it will invoke * `componentWillUpdate` and `componentDidUpdate`. * * @param {?function} callback Called after update is complete. * @final * @protected */ ReactComponent.prototype.forceUpdate = function (callback) { this.updater.enqueueForceUpdate(this); if (callback) { this.updater.enqueueCallback(this, callback, 'forceUpdate'); } }; /** * Deprecated APIs. These APIs used to exist on classic React classes but since * we would like to deprecate them, we're not going to move them over to this * modern base class. Instead, we define a getter that warns if it's accessed. */ if (process.env.NODE_ENV !== 'production') { 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) { if (canDefineProperty) { Object.defineProperty(ReactComponent.prototype, methodName, { get: function () { process.env.NODE_ENV !== 'production' ? warning(false, '%s(...) is deprecated in plain JavaScript React classes. %s', info[0], info[1]) : void 0; return undefined; } }); } }; for (var fnName in deprecatedAPIs) { if (deprecatedAPIs.hasOwnProperty(fnName)) { defineDeprecationWarning(fnName, deprecatedAPIs[fnName]); } } } module.exports = ReactComponent; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 19 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var warning = __webpack_require__(11); function warnNoop(publicInstance, callerName) { if (process.env.NODE_ENV !== 'production') { var constructor = publicInstance.constructor; process.env.NODE_ENV !== 'production' ? warning(false, '%s(...): Can only update a mounted or mounting component. ' + 'This usually means you called %s() on an unmounted component. ' + 'This is a no-op. Please check the code for the %s component.', callerName, callerName, constructor && (constructor.displayName || constructor.name) || 'ReactClass') : void 0; } } /** * This is the abstract API for an update queue. */ var ReactNoopUpdateQueue = { /** * Checks whether or not this composite component is mounted. * @param {ReactClass} publicInstance The instance we want to test. * @return {boolean} True if mounted, false otherwise. * @protected * @final */ isMounted: function (publicInstance) { return false; }, /** * Enqueue a callback that will be executed after all the pending updates * have processed. * * @param {ReactClass} publicInstance The instance to use as `this` context. * @param {?function} callback Called after state is updated. * @internal */ enqueueCallback: function (publicInstance, callback) {}, /** * Forces an update. This should only be invoked when it is known with * certainty that we are **not** in a DOM transaction. * * You may want to call this when you know that some deeper aspect of the * component's state has changed but `setState` was not called. * * This will not invoke `shouldComponentUpdate`, but it will invoke * `componentWillUpdate` and `componentDidUpdate`. * * @param {ReactClass} publicInstance The instance that should rerender. * @internal */ enqueueForceUpdate: function (publicInstance) { warnNoop(publicInstance, 'forceUpdate'); }, /** * Replaces all of the state. Always use this or `setState` to mutate state. * You should treat `this.state` as immutable. * * There is no guarantee that `this.state` will be immediately updated, so * accessing `this.state` after calling this method may return the old value. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} completeState Next state. * @internal */ enqueueReplaceState: function (publicInstance, completeState) { warnNoop(publicInstance, 'replaceState'); }, /** * Sets a subset of the state. This only exists because _pendingState is * internal. This provides a merging strategy that is not available to deep * properties which is confusing. TODO: Expose pendingState or don't use it * during the merge. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} partialState Next partial state to be merged with state. * @internal */ enqueueSetState: function (publicInstance, partialState) { warnNoop(publicInstance, 'setState'); } }; module.exports = ReactNoopUpdateQueue; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 20 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var emptyObject = {}; if (process.env.NODE_ENV !== 'production') { Object.freeze(emptyObject); } module.exports = emptyObject; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 21 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _assign = __webpack_require__(4); var ReactComponent = __webpack_require__(18); var ReactNoopUpdateQueue = __webpack_require__(19); var emptyObject = __webpack_require__(20); /** * Base class helpers for the updating state of a component. */ function ReactPureComponent(props, context, updater) { // Duplicated from ReactComponent. this.props = props; this.context = context; this.refs = emptyObject; // We initialize the default updater but the real one gets injected by the // renderer. this.updater = updater || ReactNoopUpdateQueue; } function ComponentDummy() {} ComponentDummy.prototype = ReactComponent.prototype; ReactPureComponent.prototype = new ComponentDummy(); ReactPureComponent.prototype.constructor = ReactPureComponent; // Avoid an extra prototype jump for these methods. _assign(ReactPureComponent.prototype, ReactComponent.prototype); ReactPureComponent.prototype.isPureReactComponent = true; module.exports = ReactPureComponent; /***/ }), /* 22 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(7), _assign = __webpack_require__(4); var ReactComponent = __webpack_require__(18); var ReactElement = __webpack_require__(9); var ReactPropTypeLocationNames = __webpack_require__(23); var ReactNoopUpdateQueue = __webpack_require__(19); var emptyObject = __webpack_require__(20); var invariant = __webpack_require__(8); var warning = __webpack_require__(11); var MIXINS_KEY = 'mixins'; // Helper function to allow the creation of anonymous functions which do not // have .name set to the name of the variable being assigned to. function identity(fn) { return fn; } /** * Policies that describe methods in `ReactClassInterface`. */ var injectedMixins = []; /** * Composite components are higher-level components that compose other composite * or host components. * * To create a new type of `ReactClass`, pass a specification of * your new class to `React.createClass`. The only requirement of your class * specification is that you implement a `render` method. * * var MyComponent = React.createClass({ * render: function() { * return <div>Hello World</div>; * } * }); * * The class specification supports a specific protocol of methods that have * special meaning (e.g. `render`). See `ReactClassInterface` for * more the comprehensive protocol. Any other properties and methods in the * class specification will be available on the prototype. * * @interface ReactClassInterface * @internal */ var ReactClassInterface = { /** * An array of Mixin objects to include when defining your component. * * @type {array} * @optional */ mixins: 'DEFINE_MANY', /** * An object containing properties and methods that should be defined on * the component's constructor instead of its prototype (static methods). * * @type {object} * @optional */ statics: 'DEFINE_MANY', /** * Definition of prop types for this component. * * @type {object} * @optional */ propTypes: 'DEFINE_MANY', /** * Definition of context types for this component. * * @type {object} * @optional */ contextTypes: 'DEFINE_MANY', /** * Definition of context types this component sets for its children. * * @type {object} * @optional */ childContextTypes: 'DEFINE_MANY', // ==== Definition methods ==== /** * Invoked when the component is mounted. Values in the mapping will be set on * `this.props` if that prop is not specified (i.e. using an `in` check). * * This method is invoked before `getInitialState` and therefore cannot rely * on `this.state` or use `this.setState`. * * @return {object} * @optional */ getDefaultProps: 'DEFINE_MANY_MERGED', /** * Invoked once before the component is mounted. The return value will be used * as the initial value of `this.state`. * * getInitialState: function() { * return { * isOn: false, * fooBaz: new BazFoo() * } * } * * @return {object} * @optional */ getInitialState: 'DEFINE_MANY_MERGED', /** * @return {object} * @optional */ getChildContext: 'DEFINE_MANY_MERGED', /** * Uses props from `this.props` and state from `this.state` to render the * structure of the component. * * No guarantees are made about when or how often this method is invoked, so * it must not have side effects. * * render: function() { * var name = this.props.name; * return <div>Hello, {name}!</div>; * } * * @return {ReactComponent} * @required */ render: 'DEFINE_ONCE', // ==== Delegate methods ==== /** * Invoked when the component is initially created and about to be mounted. * This may have side effects, but any external subscriptions or data created * by this method must be cleaned up in `componentWillUnmount`. * * @optional */ componentWillMount: 'DEFINE_MANY', /** * Invoked when the component has been mounted and has a DOM representation. * However, there is no guarantee that the DOM node is in the document. * * Use this as an opportunity to operate on the DOM when the component has * been mounted (initialized and rendered) for the first time. * * @param {DOMElement} rootNode DOM element representing the component. * @optional */ componentDidMount: 'DEFINE_MANY', /** * Invoked before the component receives new props. * * Use this as an opportunity to react to a prop transition by updating the * state using `this.setState`. Current props are accessed via `this.props`. * * componentWillReceiveProps: function(nextProps, nextContext) { * this.setState({ * likesIncreasing: nextProps.likeCount > this.props.likeCount * }); * } * * NOTE: There is no equivalent `componentWillReceiveState`. An incoming prop * transition may cause a state change, but the opposite is not true. If you * need it, you are probably looking for `componentWillUpdate`. * * @param {object} nextProps * @optional */ componentWillReceiveProps: 'DEFINE_MANY', /** * Invoked while deciding if the component should be updated as a result of * receiving new props, state and/or context. * * Use this as an opportunity to `return false` when you're certain that the * transition to the new props/state/context will not require a component * update. * * shouldComponentUpdate: function(nextProps, nextState, nextContext) { * return !equal(nextProps, this.props) || * !equal(nextState, this.state) || * !equal(nextContext, this.context); * } * * @param {object} nextProps * @param {?object} nextState * @param {?object} nextContext * @return {boolean} True if the component should update. * @optional */ shouldComponentUpdate: 'DEFINE_ONCE', /** * Invoked when the component is about to update due to a transition from * `this.props`, `this.state` and `this.context` to `nextProps`, `nextState` * and `nextContext`. * * Use this as an opportunity to perform preparation before an update occurs. * * NOTE: You **cannot** use `this.setState()` in this method. * * @param {object} nextProps * @param {?object} nextState * @param {?object} nextContext * @param {ReactReconcileTransaction} transaction * @optional */ componentWillUpdate: 'DEFINE_MANY', /** * Invoked when the component's DOM representation has been updated. * * Use this as an opportunity to operate on the DOM when the component has * been updated. * * @param {object} prevProps * @param {?object} prevState * @param {?object} prevContext * @param {DOMElement} rootNode DOM element representing the component. * @optional */ componentDidUpdate: 'DEFINE_MANY', /** * Invoked when the component is about to be removed from its parent and have * its DOM representation destroyed. * * Use this as an opportunity to deallocate any external resources. * * NOTE: There is no `componentDidUnmount` since your component will have been * destroyed by that point. * * @optional */ componentWillUnmount: 'DEFINE_MANY', // ==== Advanced methods ==== /** * Updates the component's currently mounted DOM representation. * * By default, this implements React's rendering and reconciliation algorithm. * Sophisticated clients may wish to override this. * * @param {ReactReconcileTransaction} transaction * @internal * @overridable */ updateComponent: 'OVERRIDE_BASE' }; /** * Mapping from class specification keys to special processing functions. * * Although these are declared like instance properties in the specification * when defining classes using `React.createClass`, they are actually static * and are accessible on the constructor instead of the prototype. Despite * being static, they must be defined outside of the "statics" key under * which all other static methods are defined. */ var RESERVED_SPEC_KEYS = { displayName: function (Constructor, displayName) { Constructor.displayName = displayName; }, mixins: function (Constructor, mixins) { if (mixins) { for (var i = 0; i < mixins.length; i++) { mixSpecIntoComponent(Constructor, mixins[i]); } } }, childContextTypes: function (Constructor, childContextTypes) { if (process.env.NODE_ENV !== 'production') { validateTypeDef(Constructor, childContextTypes, 'childContext'); } Constructor.childContextTypes = _assign({}, Constructor.childContextTypes, childContextTypes); }, contextTypes: function (Constructor, contextTypes) { if (process.env.NODE_ENV !== 'production') { validateTypeDef(Constructor, contextTypes, 'context'); } Constructor.contextTypes = _assign({}, Constructor.contextTypes, contextTypes); }, /** * Special case getDefaultProps which should move into statics but requires * automatic merging. */ getDefaultProps: function (Constructor, getDefaultProps) { if (Constructor.getDefaultProps) { Constructor.getDefaultProps = createMergedResultFunction(Constructor.getDefaultProps, getDefaultProps); } else { Constructor.getDefaultProps = getDefaultProps; } }, propTypes: function (Constructor, propTypes) { if (process.env.NODE_ENV !== 'production') { validateTypeDef(Constructor, propTypes, 'prop'); } Constructor.propTypes = _assign({}, Constructor.propTypes, propTypes); }, statics: function (Constructor, statics) { mixStaticSpecIntoComponent(Constructor, statics); }, autobind: function () {} }; function validateTypeDef(Constructor, typeDef, location) { for (var propName in typeDef) { if (typeDef.hasOwnProperty(propName)) { // use a warning instead of an invariant so components // don't show up in prod but only in __DEV__ process.env.NODE_ENV !== 'production' ? warning(typeof typeDef[propName] === 'function', '%s: %s type `%s` is invalid; it must be a function, usually from ' + 'React.PropTypes.', Constructor.displayName || 'ReactClass', ReactPropTypeLocationNames[location], propName) : void 0; } } } function validateMethodOverride(isAlreadyDefined, name) { var specPolicy = ReactClassInterface.hasOwnProperty(name) ? ReactClassInterface[name] : null; // Disallow overriding of base class methods unless explicitly allowed. if (ReactClassMixin.hasOwnProperty(name)) { !(specPolicy === 'OVERRIDE_BASE') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClassInterface: You are attempting to override `%s` from your class specification. Ensure that your method names do not overlap with React methods.', name) : _prodInvariant('73', name) : void 0; } // Disallow defining methods more than once unless explicitly allowed. if (isAlreadyDefined) { !(specPolicy === 'DEFINE_MANY' || specPolicy === 'DEFINE_MANY_MERGED') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClassInterface: You are attempting to define `%s` on your component more than once. This conflict may be due to a mixin.', name) : _prodInvariant('74', name) : void 0; } } /** * Mixin helper which handles policy validation and reserved * specification keys when building React classes. */ function mixSpecIntoComponent(Constructor, spec) { if (!spec) { if (process.env.NODE_ENV !== 'production') { var typeofSpec = typeof spec; var isMixinValid = typeofSpec === 'object' && spec !== null; process.env.NODE_ENV !== 'production' ? warning(isMixinValid, '%s: You\'re attempting to include a mixin that is either null ' + 'or not an object. Check the mixins included by the component, ' + 'as well as any mixins they include themselves. ' + 'Expected object but got %s.', Constructor.displayName || 'ReactClass', spec === null ? null : typeofSpec) : void 0; } return; } !(typeof spec !== 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClass: You\'re attempting to use a component class or function as a mixin. Instead, just use a regular object.') : _prodInvariant('75') : void 0; !!ReactElement.isValidElement(spec) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClass: You\'re attempting to use a component as a mixin. Instead, just use a regular object.') : _prodInvariant('76') : void 0; var proto = Constructor.prototype; var autoBindPairs = proto.__reactAutoBindPairs; // By handling mixins before any other properties, we ensure the same // chaining order is applied to methods with DEFINE_MANY policy, whether // mixins are listed before or after these methods in the spec. if (spec.hasOwnProperty(MIXINS_KEY)) { RESERVED_SPEC_KEYS.mixins(Constructor, spec.mixins); } for (var name in spec) { if (!spec.hasOwnProperty(name)) { continue; } if (name === MIXINS_KEY) { // We have already handled mixins in a special case above. continue; } var property = spec[name]; var isAlreadyDefined = proto.hasOwnProperty(name); validateMethodOverride(isAlreadyDefined, name); if (RESERVED_SPEC_KEYS.hasOwnProperty(name)) { RESERVED_SPEC_KEYS[name](Constructor, property); } else { // Setup methods on prototype: // The following member methods should not be automatically bound: // 1. Expected ReactClass methods (in the "interface"). // 2. Overridden methods (that were mixed in). var isReactClassMethod = ReactClassInterface.hasOwnProperty(name); var isFunction = typeof property === 'function'; var shouldAutoBind = isFunction && !isReactClassMethod && !isAlreadyDefined && spec.autobind !== false; if (shouldAutoBind) { autoBindPairs.push(name, property); proto[name] = property; } else { if (isAlreadyDefined) { var specPolicy = ReactClassInterface[name]; // These cases should already be caught by validateMethodOverride. !(isReactClassMethod && (specPolicy === 'DEFINE_MANY_MERGED' || specPolicy === 'DEFINE_MANY')) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClass: Unexpected spec policy %s for key %s when mixing in component specs.', specPolicy, name) : _prodInvariant('77', specPolicy, name) : void 0; // For methods which are defined more than once, call the existing // methods before calling the new property, merging if appropriate. if (specPolicy === 'DEFINE_MANY_MERGED') { proto[name] = createMergedResultFunction(proto[name], property); } else if (specPolicy === 'DEFINE_MANY') { proto[name] = createChainedFunction(proto[name], property); } } else { proto[name] = property; if (process.env.NODE_ENV !== 'production') { // Add verbose displayName to the function, which helps when looking // at profiling tools. if (typeof property === 'function' && spec.displayName) { proto[name].displayName = spec.displayName + '_' + name; } } } } } } } function mixStaticSpecIntoComponent(Constructor, statics) { if (!statics) { return; } for (var name in statics) { var property = statics[name]; if (!statics.hasOwnProperty(name)) { continue; } var isReserved = name in RESERVED_SPEC_KEYS; !!isReserved ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClass: You are attempting to define a reserved property, `%s`, that shouldn\'t be on the "statics" key. Define it as an instance property instead; it will still be accessible on the constructor.', name) : _prodInvariant('78', name) : void 0; var isInherited = name in Constructor; !!isInherited ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClass: You are attempting to define `%s` on your component more than once. This conflict may be due to a mixin.', name) : _prodInvariant('79', name) : void 0; Constructor[name] = property; } } /** * Merge two objects, but throw if both contain the same key. * * @param {object} one The first object, which is mutated. * @param {object} two The second object * @return {object} one after it has been mutated to contain everything in two. */ function mergeIntoWithNoDuplicateKeys(one, two) { !(one && two && typeof one === 'object' && typeof two === 'object') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'mergeIntoWithNoDuplicateKeys(): Cannot merge non-objects.') : _prodInvariant('80') : void 0; for (var key in two) { if (two.hasOwnProperty(key)) { !(one[key] === undefined) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'mergeIntoWithNoDuplicateKeys(): Tried to merge two objects with the same key: `%s`. This conflict may be due to a mixin; in particular, this may be caused by two getInitialState() or getDefaultProps() methods returning objects with clashing keys.', key) : _prodInvariant('81', key) : void 0; one[key] = two[key]; } } return one; } /** * Creates a function that invokes two functions and merges their return values. * * @param {function} one Function to invoke first. * @param {function} two Function to invoke second. * @return {function} Function that invokes the two argument functions. * @private */ function createMergedResultFunction(one, two) { return function mergedResult() { var a = one.apply(this, arguments); var b = two.apply(this, arguments); if (a == null) { return b; } else if (b == null) { return a; } var c = {}; mergeIntoWithNoDuplicateKeys(c, a); mergeIntoWithNoDuplicateKeys(c, b); return c; }; } /** * Creates a function that invokes two functions and ignores their return vales. * * @param {function} one Function to invoke first. * @param {function} two Function to invoke second. * @return {function} Function that invokes the two argument functions. * @private */ function createChainedFunction(one, two) { return function chainedFunction() { one.apply(this, arguments); two.apply(this, arguments); }; } /** * Binds a method to the component. * * @param {object} component Component whose method is going to be bound. * @param {function} method Method to be bound. * @return {function} The bound method. */ function bindAutoBindMethod(component, method) { var boundMethod = method.bind(component); if (process.env.NODE_ENV !== 'production') { boundMethod.__reactBoundContext = component; boundMethod.__reactBoundMethod = method; boundMethod.__reactBoundArguments = null; var componentName = component.constructor.displayName; var _bind = boundMethod.bind; boundMethod.bind = function (newThis) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } // User is trying to bind() an autobound method; we effectively will // ignore the value of "this" that the user is trying to use, so // let's warn. if (newThis !== component && newThis !== null) { process.env.NODE_ENV !== 'production' ? warning(false, 'bind(): React component methods may only be bound to the ' + 'component instance. See %s', componentName) : void 0; } else if (!args.length) { process.env.NODE_ENV !== 'production' ? warning(false, 'bind(): You are binding a component method to the component. ' + 'React does this for you automatically in a high-performance ' + 'way, so you can safely remove this call. See %s', componentName) : void 0; return boundMethod; } var reboundMethod = _bind.apply(boundMethod, arguments); reboundMethod.__reactBoundContext = component; reboundMethod.__reactBoundMethod = method; reboundMethod.__reactBoundArguments = args; return reboundMethod; }; } return boundMethod; } /** * Binds all auto-bound methods in a component. * * @param {object} component Component whose method is going to be bound. */ function bindAutoBindMethods(component) { var pairs = component.__reactAutoBindPairs; for (var i = 0; i < pairs.length; i += 2) { var autoBindKey = pairs[i]; var method = pairs[i + 1]; component[autoBindKey] = bindAutoBindMethod(component, method); } } /** * Add more to the ReactClass base class. These are all legacy features and * therefore not already part of the modern ReactComponent. */ var ReactClassMixin = { /** * TODO: This will be deprecated because state should always keep a consistent * type signature and the only use case for this, is to avoid that. */ replaceState: function (newState, callback) { this.updater.enqueueReplaceState(this, newState); if (callback) { this.updater.enqueueCallback(this, callback, 'replaceState'); } }, /** * Checks whether or not this composite component is mounted. * @return {boolean} True if mounted, false otherwise. * @protected * @final */ isMounted: function () { return this.updater.isMounted(this); } }; var ReactClassComponent = function () {}; _assign(ReactClassComponent.prototype, ReactComponent.prototype, ReactClassMixin); var didWarnDeprecated = false; /** * Module for creating composite components. * * @class ReactClass */ var ReactClass = { /** * Creates a composite component class given a class specification. * See https://facebook.github.io/react/docs/top-level-api.html#react.createclass * * @param {object} spec Class specification (which must define `render`). * @return {function} Component constructor function. * @public */ createClass: function (spec) { if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(didWarnDeprecated, '%s: React.createClass is deprecated and will be removed in version 16. ' + 'Use plain JavaScript classes instead. If you\'re not yet ready to ' + 'migrate, create-react-class is available on npm as a ' + 'drop-in replacement.', spec && spec.displayName || 'A Component') : void 0; didWarnDeprecated = true; } // To keep our warnings more understandable, we'll use a little hack here to // ensure that Constructor.name !== 'Constructor'. This makes sure we don't // unnecessarily identify a class without displayName as 'Constructor'. var Constructor = identity(function (props, context, updater) { // This constructor gets overridden by mocks. The argument is used // by mocks to assert on what gets mounted. if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(this instanceof Constructor, 'Something is calling a React component directly. Use a factory or ' + 'JSX instead. See: https://fb.me/react-legacyfactory') : void 0; } // Wire up auto-binding if (this.__reactAutoBindPairs.length) { bindAutoBindMethods(this); } this.props = props; this.context = context; this.refs = emptyObject; this.updater = updater || ReactNoopUpdateQueue; this.state = null; // ReactClasses doesn't have constructors. Instead, they use the // getInitialState and componentWillMount methods for initialization. var initialState = this.getInitialState ? this.getInitialState() : null; if (process.env.NODE_ENV !== 'production') { // We allow auto-mocks to proceed as if they're returning null. if (initialState === undefined && this.getInitialState._isMockFunction) { // This is probably bad practice. Consider warning here and // deprecating this convenience. initialState = null; } } !(typeof initialState === 'object' && !Array.isArray(initialState)) ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s.getInitialState(): must return an object or null', Constructor.displayName || 'ReactCompositeComponent') : _prodInvariant('82', Constructor.displayName || 'ReactCompositeComponent') : void 0; this.state = initialState; }); Constructor.prototype = new ReactClassComponent(); Constructor.prototype.constructor = Constructor; Constructor.prototype.__reactAutoBindPairs = []; injectedMixins.forEach(mixSpecIntoComponent.bind(null, Constructor)); mixSpecIntoComponent(Constructor, spec); // Initialize the defaultProps property after all mixins have been merged. if (Constructor.getDefaultProps) { Constructor.defaultProps = Constructor.getDefaultProps(); } if (process.env.NODE_ENV !== 'production') { // This is a tag to indicate that the use of these method names is ok, // since it's used with createClass. If it's not, then it's likely a // mistake so we'll warn you to use the static property, property // initializer or constructor respectively. if (Constructor.getDefaultProps) { Constructor.getDefaultProps.isReactClassApproved = {}; } if (Constructor.prototype.getInitialState) { Constructor.prototype.getInitialState.isReactClassApproved = {}; } } !Constructor.prototype.render ? process.env.NODE_ENV !== 'production' ? invariant(false, 'createClass(...): Class specification must implement a `render` method.') : _prodInvariant('83') : void 0; if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(!Constructor.prototype.componentShouldUpdate, '%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.', spec.displayName || 'A component') : void 0; process.env.NODE_ENV !== 'production' ? warning(!Constructor.prototype.componentWillRecieveProps, '%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', spec.displayName || 'A component') : void 0; } // Reduce time spent doing lookups by setting these on the prototype. for (var methodName in ReactClassInterface) { if (!Constructor.prototype[methodName]) { Constructor.prototype[methodName] = null; } } return Constructor; }, injection: { injectMixin: function (mixin) { injectedMixins.push(mixin); } } }; module.exports = ReactClass; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 23 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var ReactPropTypeLocationNames = {}; if (process.env.NODE_ENV !== 'production') { ReactPropTypeLocationNames = { prop: 'prop', context: 'context', childContext: 'child context' }; } module.exports = ReactPropTypeLocationNames; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 24 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var ReactElement = __webpack_require__(9); /** * Create a factory that creates HTML tag elements. * * @private */ var createDOMFactory = ReactElement.createFactory; if (process.env.NODE_ENV !== 'production') { var ReactElementValidator = __webpack_require__(25); createDOMFactory = ReactElementValidator.createFactory; } /** * Creates a mapping from supported HTML tags to `ReactDOMComponent` classes. * This is also accessible via `React.DOM`. * * @public */ var ReactDOMFactories = { a: createDOMFactory('a'), abbr: createDOMFactory('abbr'), address: createDOMFactory('address'), area: createDOMFactory('area'), article: createDOMFactory('article'), aside: createDOMFactory('aside'), audio: createDOMFactory('audio'), b: createDOMFactory('b'), base: createDOMFactory('base'), bdi: createDOMFactory('bdi'), bdo: createDOMFactory('bdo'), big: createDOMFactory('big'), blockquote: createDOMFactory('blockquote'), body: createDOMFactory('body'), br: createDOMFactory('br'), button: createDOMFactory('button'), canvas: createDOMFactory('canvas'), caption: createDOMFactory('caption'), cite: createDOMFactory('cite'), code: createDOMFactory('code'), col: createDOMFactory('col'), colgroup: createDOMFactory('colgroup'), data: createDOMFactory('data'), datalist: createDOMFactory('datalist'), dd: createDOMFactory('dd'), del: createDOMFactory('del'), details: createDOMFactory('details'), dfn: createDOMFactory('dfn'), dialog: createDOMFactory('dialog'), div: createDOMFactory('div'), dl: createDOMFactory('dl'), dt: createDOMFactory('dt'), em: createDOMFactory('em'), embed: createDOMFactory('embed'), fieldset: createDOMFactory('fieldset'), figcaption: createDOMFactory('figcaption'), figure: createDOMFactory('figure'), footer: createDOMFactory('footer'), form: createDOMFactory('form'), h1: createDOMFactory('h1'), h2: createDOMFactory('h2'), h3: createDOMFactory('h3'), h4: createDOMFactory('h4'), h5: createDOMFactory('h5'), h6: createDOMFactory('h6'), head: createDOMFactory('head'), header: createDOMFactory('header'), hgroup: createDOMFactory('hgroup'), hr: createDOMFactory('hr'), html: createDOMFactory('html'), i: createDOMFactory('i'), iframe: createDOMFactory('iframe'), img: createDOMFactory('img'), input: createDOMFactory('input'), ins: createDOMFactory('ins'), kbd: createDOMFactory('kbd'), keygen: createDOMFactory('keygen'), label: createDOMFactory('label'), legend: createDOMFactory('legend'), li: createDOMFactory('li'), link: createDOMFactory('link'), main: createDOMFactory('main'), map: createDOMFactory('map'), mark: createDOMFactory('mark'), menu: createDOMFactory('menu'), menuitem: createDOMFactory('menuitem'), meta: createDOMFactory('meta'), meter: createDOMFactory('meter'), nav: createDOMFactory('nav'), noscript: createDOMFactory('noscript'), object: createDOMFactory('object'), ol: createDOMFactory('ol'), optgroup: createDOMFactory('optgroup'), option: createDOMFactory('option'), output: createDOMFactory('output'), p: createDOMFactory('p'), param: createDOMFactory('param'), picture: createDOMFactory('picture'), pre: createDOMFactory('pre'), progress: createDOMFactory('progress'), q: createDOMFactory('q'), rp: createDOMFactory('rp'), rt: createDOMFactory('rt'), ruby: createDOMFactory('ruby'), s: createDOMFactory('s'), samp: createDOMFactory('samp'), script: createDOMFactory('script'), section: createDOMFactory('section'), select: createDOMFactory('select'), small: createDOMFactory('small'), source: createDOMFactory('source'), span: createDOMFactory('span'), strong: createDOMFactory('strong'), style: createDOMFactory('style'), sub: createDOMFactory('sub'), summary: createDOMFactory('summary'), sup: createDOMFactory('sup'), table: createDOMFactory('table'), tbody: createDOMFactory('tbody'), td: createDOMFactory('td'), textarea: createDOMFactory('textarea'), tfoot: createDOMFactory('tfoot'), th: createDOMFactory('th'), thead: createDOMFactory('thead'), time: createDOMFactory('time'), title: createDOMFactory('title'), tr: createDOMFactory('tr'), track: createDOMFactory('track'), u: createDOMFactory('u'), ul: createDOMFactory('ul'), 'var': createDOMFactory('var'), video: createDOMFactory('video'), wbr: createDOMFactory('wbr'), // SVG circle: createDOMFactory('circle'), clipPath: createDOMFactory('clipPath'), defs: createDOMFactory('defs'), ellipse: createDOMFactory('ellipse'), g: createDOMFactory('g'), image: createDOMFactory('image'), line: createDOMFactory('line'), linearGradient: createDOMFactory('linearGradient'), mask: createDOMFactory('mask'), path: createDOMFactory('path'), pattern: createDOMFactory('pattern'), polygon: createDOMFactory('polygon'), polyline: createDOMFactory('polyline'), radialGradient: createDOMFactory('radialGradient'), rect: createDOMFactory('rect'), stop: createDOMFactory('stop'), svg: createDOMFactory('svg'), text: createDOMFactory('text'), tspan: createDOMFactory('tspan') }; module.exports = ReactDOMFactories; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 25 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ /** * ReactElementValidator provides a wrapper around a element factory * which validates the props passed to the element. This is intended to be * used only in DEV and could be replaced by a static type checker for languages * that support it. */ 'use strict'; var ReactCurrentOwner = __webpack_require__(10); var ReactComponentTreeHook = __webpack_require__(26); var ReactElement = __webpack_require__(9); var checkReactTypeSpec = __webpack_require__(27); var canDefineProperty = __webpack_require__(13); var getIteratorFn = __webpack_require__(16); var warning = __webpack_require__(11); function getDeclarationErrorAddendum() { if (ReactCurrentOwner.current) { var name = ReactCurrentOwner.current.getName(); if (name) { return ' Check the render method of `' + name + '`.'; } } return ''; } function getSourceInfoErrorAddendum(elementProps) { if (elementProps !== null && elementProps !== undefined && elementProps.__source !== undefined) { var source = elementProps.__source; var fileName = source.fileName.replace(/^.*[\\\/]/, ''); var lineNumber = source.lineNumber; return ' Check your code at ' + fileName + ':' + lineNumber + '.'; } return ''; } /** * Warn if there's no key explicitly set on dynamic arrays of children or * object keys are not valid. This allows us to keep track of children between * updates. */ var ownerHasKeyUseWarning = {}; function getCurrentComponentErrorInfo(parentType) { var info = getDeclarationErrorAddendum(); if (!info) { var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name; if (parentName) { info = ' Check the top-level render call using <' + parentName + '>.'; } } return info; } /** * Warn if the element doesn't have an explicit key assigned to it. * This element is in an array. The array could grow and shrink or be * reordered. All children that haven't already been validated are required to * have a "key" property assigned to it. Error statuses are cached so a warning * will only be shown once. * * @internal * @param {ReactElement} element Element that requires a key. * @param {*} parentType element's parent's type. */ function validateExplicitKey(element, parentType) { if (!element._store || element._store.validated || element.key != null) { return; } element._store.validated = true; var memoizer = ownerHasKeyUseWarning.uniqueKey || (ownerHasKeyUseWarning.uniqueKey = {}); var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType); if (memoizer[currentComponentErrorInfo]) { return; } memoizer[currentComponentErrorInfo] = true; // Usually the current owner is the offender, but if it accepts children as a // property, it may be the creator of the child that's responsible for // assigning it a key. var childOwner = ''; if (element && element._owner && element._owner !== ReactCurrentOwner.current) { // Give the component that originally created this child. childOwner = ' It was passed a child from ' + element._owner.getName() + '.'; } process.env.NODE_ENV !== 'production' ? warning(false, 'Each child in an array or iterator should have a unique "key" prop.' + '%s%s See https://fb.me/react-warning-keys for more information.%s', currentComponentErrorInfo, childOwner, ReactComponentTreeHook.getCurrentStackAddendum(element)) : void 0; } /** * Ensure that every element either is passed in a static location, in an * array with an explicit keys property defined, or in an object literal * with valid key property. * * @internal * @param {ReactNode} node Statically passed child of any type. * @param {*} parentType node's parent's type. */ 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 (ReactElement.isValidElement(child)) { validateExplicitKey(child, parentType); } } } else if (ReactElement.isValidElement(node)) { // This element was passed in a valid location. if (node._store) { node._store.validated = true; } } else if (node) { var iteratorFn = getIteratorFn(node); // Entry iterators provide implicit keys. if (iteratorFn) { if (iteratorFn !== node.entries) { var iterator = iteratorFn.call(node); var step; while (!(step = iterator.next()).done) { if (ReactElement.isValidElement(step.value)) { validateExplicitKey(step.value, parentType); } } } } } } /** * Given an element, validate that its props follow the propTypes definition, * provided by the type. * * @param {ReactElement} element */ function validatePropTypes(element) { var componentClass = element.type; if (typeof componentClass !== 'function') { return; } var name = componentClass.displayName || componentClass.name; if (componentClass.propTypes) { checkReactTypeSpec(componentClass.propTypes, element.props, 'prop', name, element, null); } if (typeof componentClass.getDefaultProps === 'function') { process.env.NODE_ENV !== 'production' ? warning(componentClass.getDefaultProps.isReactClassApproved, 'getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.') : void 0; } } var ReactElementValidator = { createElement: function (type, props, children) { var validType = typeof type === 'string' || typeof type === 'function'; // We warn in this case but don't throw. We expect the element creation to // succeed and there will likely be errors in render. if (!validType) { if (typeof type !== 'function' && typeof type !== 'string') { var info = ''; if (type === undefined || 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.'; } var sourceInfo = getSourceInfoErrorAddendum(props); if (sourceInfo) { info += sourceInfo; } else { info += getDeclarationErrorAddendum(); } info += ReactComponentTreeHook.getCurrentStackAddendum(); process.env.NODE_ENV !== 'production' ? warning(false, 'React.createElement: type is invalid -- expected a string (for ' + 'built-in components) or a class/function (for composite ' + 'components) but got: %s.%s', type == null ? type : typeof type, info) : void 0; } } var element = ReactElement.createElement.apply(this, arguments); // The result can be nullish if a mock or a custom function is used. // TODO: Drop this when these are no longer allowed as the type argument. if (element == null) { return element; } // Skip key warning if the type isn't valid since our key validation logic // doesn't expect a non-string/function type and can throw confusing errors. // We don't want exception behavior to differ between dev and prod. // (Rendering will throw with a helpful message and as soon as the type is // fixed, the key warnings will appear.) if (validType) { for (var i = 2; i < arguments.length; i++) { validateChildKeys(arguments[i], type); } } validatePropTypes(element); return element; }, createFactory: function (type) { var validatedFactory = ReactElementValidator.createElement.bind(null, type); // Legacy hook TODO: Warn if this is accessed validatedFactory.type = type; if (process.env.NODE_ENV !== 'production') { if (canDefineProperty) { Object.defineProperty(validatedFactory, 'type', { enumerable: false, get: function () { process.env.NODE_ENV !== 'production' ? warning(false, 'Factory.type is deprecated. Access the class directly ' + 'before passing it to createFactory.') : void 0; Object.defineProperty(this, 'type', { value: type }); return type; } }); } } return validatedFactory; }, cloneElement: function (element, props, children) { var newElement = ReactElement.cloneElement.apply(this, arguments); for (var i = 2; i < arguments.length; i++) { validateChildKeys(arguments[i], newElement.type); } validatePropTypes(newElement); return newElement; } }; module.exports = ReactElementValidator; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 26 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2016-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var _prodInvariant = __webpack_require__(7); var ReactCurrentOwner = __webpack_require__(10); var invariant = __webpack_require__(8); var warning = __webpack_require__(11); function isNative(fn) { // Based on isNative() from Lodash var funcToString = Function.prototype.toString; var hasOwnProperty = Object.prototype.hasOwnProperty; var reIsNative = RegExp('^' + funcToString // Take an example native function source for comparison .call(hasOwnProperty) // Strip regex characters so we can use it for regex .replace(/[\\^$.*+?()[\]{}|]/g, '\\$&') // Remove hasOwnProperty from the template to make it generic .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'); try { var source = funcToString.call(fn); return reIsNative.test(source); } catch (err) { return false; } } var canUseCollections = // Array.from typeof Array.from === 'function' && // Map typeof Map === 'function' && isNative(Map) && // Map.prototype.keys Map.prototype != null && typeof Map.prototype.keys === 'function' && isNative(Map.prototype.keys) && // Set typeof Set === 'function' && isNative(Set) && // Set.prototype.keys Set.prototype != null && typeof Set.prototype.keys === 'function' && isNative(Set.prototype.keys); var setItem; var getItem; var removeItem; var getItemIDs; var addRoot; var removeRoot; var getRootIDs; if (canUseCollections) { var itemMap = new Map(); var rootIDSet = new Set(); setItem = function (id, item) { itemMap.set(id, item); }; getItem = function (id) { return itemMap.get(id); }; removeItem = function (id) { itemMap['delete'](id); }; getItemIDs = function () { return Array.from(itemMap.keys()); }; addRoot = function (id) { rootIDSet.add(id); }; removeRoot = function (id) { rootIDSet['delete'](id); }; getRootIDs = function () { return Array.from(rootIDSet.keys()); }; } else { var itemByKey = {}; var rootByKey = {}; // Use non-numeric keys to prevent V8 performance issues: // https://github.com/facebook/react/pull/7232 var getKeyFromID = function (id) { return '.' + id; }; var getIDFromKey = function (key) { return parseInt(key.substr(1), 10); }; setItem = function (id, item) { var key = getKeyFromID(id); itemByKey[key] = item; }; getItem = function (id) { var key = getKeyFromID(id); return itemByKey[key]; }; removeItem = function (id) { var key = getKeyFromID(id); delete itemByKey[key]; }; getItemIDs = function () { return Object.keys(itemByKey).map(getIDFromKey); }; addRoot = function (id) { var key = getKeyFromID(id); rootByKey[key] = true; }; removeRoot = function (id) { var key = getKeyFromID(id); delete rootByKey[key]; }; getRootIDs = function () { return Object.keys(rootByKey).map(getIDFromKey); }; } var unmountedIDs = []; function purgeDeep(id) { var item = getItem(id); if (item) { var childIDs = item.childIDs; removeItem(id); childIDs.forEach(purgeDeep); } } function describeComponentFrame(name, source, ownerName) { return '\n in ' + (name || 'Unknown') + (source ? ' (at ' + source.fileName.replace(/^.*[\\\/]/, '') + ':' + source.lineNumber + ')' : ownerName ? ' (created by ' + ownerName + ')' : ''); } function getDisplayName(element) { if (element == null) { return '#empty'; } else if (typeof element === 'string' || typeof element === 'number') { return '#text'; } else if (typeof element.type === 'string') { return element.type; } else { return element.type.displayName || element.type.name || 'Unknown'; } } function describeID(id) { var name = ReactComponentTreeHook.getDisplayName(id); var element = ReactComponentTreeHook.getElement(id); var ownerID = ReactComponentTreeHook.getOwnerID(id); var ownerName; if (ownerID) { ownerName = ReactComponentTreeHook.getDisplayName(ownerID); } process.env.NODE_ENV !== 'production' ? warning(element, 'ReactComponentTreeHook: Missing React element for debugID %s when ' + 'building stack', id) : void 0; return describeComponentFrame(name, element && element._source, ownerName); } var ReactComponentTreeHook = { onSetChildren: function (id, nextChildIDs) { var item = getItem(id); !item ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Item must have been set') : _prodInvariant('144') : void 0; item.childIDs = nextChildIDs; for (var i = 0; i < nextChildIDs.length; i++) { var nextChildID = nextChildIDs[i]; var nextChild = getItem(nextChildID); !nextChild ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Expected hook events to fire for the child before its parent includes it in onSetChildren().') : _prodInvariant('140') : void 0; !(nextChild.childIDs != null || typeof nextChild.element !== 'object' || nextChild.element == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Expected onSetChildren() to fire for a container child before its parent includes it in onSetChildren().') : _prodInvariant('141') : void 0; !nextChild.isMounted ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Expected onMountComponent() to fire for the child before its parent includes it in onSetChildren().') : _prodInvariant('71') : void 0; if (nextChild.parentID == null) { nextChild.parentID = id; // TODO: This shouldn't be necessary but mounting a new root during in // componentWillMount currently causes not-yet-mounted components to // be purged from our tree data so their parent id is missing. } !(nextChild.parentID === id) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Expected onBeforeMountComponent() parent and onSetChildren() to be consistent (%s has parents %s and %s).', nextChildID, nextChild.parentID, id) : _prodInvariant('142', nextChildID, nextChild.parentID, id) : void 0; } }, onBeforeMountComponent: function (id, element, parentID) { var item = { element: element, parentID: parentID, text: null, childIDs: [], isMounted: false, updateCount: 0 }; setItem(id, item); }, onBeforeUpdateComponent: function (id, element) { var item = getItem(id); if (!item || !item.isMounted) { // We may end up here as a result of setState() in componentWillUnmount(). // In this case, ignore the element. return; } item.element = element; }, onMountComponent: function (id) { var item = getItem(id); !item ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Item must have been set') : _prodInvariant('144') : void 0; item.isMounted = true; var isRoot = item.parentID === 0; if (isRoot) { addRoot(id); } }, onUpdateComponent: function (id) { var item = getItem(id); if (!item || !item.isMounted) { // We may end up here as a result of setState() in componentWillUnmount(). // In this case, ignore the element. return; } item.updateCount++; }, onUnmountComponent: function (id) { var item = getItem(id); if (item) { // We need to check if it exists. // `item` might not exist if it is inside an error boundary, and a sibling // error boundary child threw while mounting. Then this instance never // got a chance to mount, but it still gets an unmounting event during // the error boundary cleanup. item.isMounted = false; var isRoot = item.parentID === 0; if (isRoot) { removeRoot(id); } } unmountedIDs.push(id); }, purgeUnmountedComponents: function () { if (ReactComponentTreeHook._preventPurging) { // Should only be used for testing. return; } for (var i = 0; i < unmountedIDs.length; i++) { var id = unmountedIDs[i]; purgeDeep(id); } unmountedIDs.length = 0; }, isMounted: function (id) { var item = getItem(id); return item ? item.isMounted : false; }, getCurrentStackAddendum: function (topElement) { var info = ''; if (topElement) { var name = getDisplayName(topElement); var owner = topElement._owner; info += describeComponentFrame(name, topElement._source, owner && owner.getName()); } var currentOwner = ReactCurrentOwner.current; var id = currentOwner && currentOwner._debugID; info += ReactComponentTreeHook.getStackAddendumByID(id); return info; }, getStackAddendumByID: function (id) { var info = ''; while (id) { info += describeID(id); id = ReactComponentTreeHook.getParentID(id); } return info; }, getChildIDs: function (id) { var item = getItem(id); return item ? item.childIDs : []; }, getDisplayName: function (id) { var element = ReactComponentTreeHook.getElement(id); if (!element) { return null; } return getDisplayName(element); }, getElement: function (id) { var item = getItem(id); return item ? item.element : null; }, getOwnerID: function (id) { var element = ReactComponentTreeHook.getElement(id); if (!element || !element._owner) { return null; } return element._owner._debugID; }, getParentID: function (id) { var item = getItem(id); return item ? item.parentID : null; }, getSource: function (id) { var item = getItem(id); var element = item ? item.element : null; var source = element != null ? element._source : null; return source; }, getText: function (id) { var element = ReactComponentTreeHook.getElement(id); if (typeof element === 'string') { return element; } else if (typeof element === 'number') { return '' + element; } else { return null; } }, getUpdateCount: function (id) { var item = getItem(id); return item ? item.updateCount : 0; }, getRootIDs: getRootIDs, getRegisteredIDs: getItemIDs }; module.exports = ReactComponentTreeHook; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 27 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(7); var ReactPropTypeLocationNames = __webpack_require__(23); var ReactPropTypesSecret = __webpack_require__(28); var invariant = __webpack_require__(8); var warning = __webpack_require__(11); var ReactComponentTreeHook; if (typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'test') { // Temporary hack. // Inline requires don't work well with Jest: // https://github.com/facebook/react/issues/7240 // Remove the inline requires when we don't need them anymore: // https://github.com/facebook/react/pull/7178 ReactComponentTreeHook = __webpack_require__(26); } var loggedTypeFailures = {}; /** * Assert that the values match with the type specs. * Error messages are memorized and will only be shown once. * * @param {object} typeSpecs Map of name to a ReactPropType * @param {object} values Runtime values that need to be type-checked * @param {string} location e.g. "prop", "context", "child context" * @param {string} componentName Name of the component for error messages. * @param {?object} element The React element that is being type-checked * @param {?number} debugID The React component instance that is being type-checked * @private */ function checkReactTypeSpec(typeSpecs, values, location, componentName, element, debugID) { for (var typeSpecName in typeSpecs) { if (typeSpecs.hasOwnProperty(typeSpecName)) { var error; // Prop type validation may throw. In case they do, we don't want to // fail the render phase where it didn't fail before. So we log it. // After these have been cleaned up, we'll let them throw. try { // This is intentionally an invariant that gets caught. It's the same // behavior as without this statement except with a better message. !(typeof typeSpecs[typeSpecName] === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s: %s type `%s` is invalid; it must be a function, usually from React.PropTypes.', componentName || 'React class', ReactPropTypeLocationNames[location], typeSpecName) : _prodInvariant('84', componentName || 'React class', ReactPropTypeLocationNames[location], typeSpecName) : void 0; error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret); } catch (ex) { error = ex; } process.env.NODE_ENV !== 'production' ? warning(!error || error instanceof 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', ReactPropTypeLocationNames[location], typeSpecName, typeof error) : void 0; if (error instanceof Error && !(error.message in loggedTypeFailures)) { // Only monitor this failure once because there tends to be a lot of the // same error. loggedTypeFailures[error.message] = true; var componentStackInfo = ''; if (process.env.NODE_ENV !== 'production') { if (!ReactComponentTreeHook) { ReactComponentTreeHook = __webpack_require__(26); } if (debugID !== null) { componentStackInfo = ReactComponentTreeHook.getStackAddendumByID(debugID); } else if (element !== null) { componentStackInfo = ReactComponentTreeHook.getCurrentStackAddendum(element); } } process.env.NODE_ENV !== 'production' ? warning(false, 'Failed %s type: %s%s', location, error.message, componentStackInfo) : void 0; } } } } module.exports = checkReactTypeSpec; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 28 */ /***/ (function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'; module.exports = ReactPropTypesSecret; /***/ }), /* 29 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _require = __webpack_require__(9), isValidElement = _require.isValidElement; var factory = __webpack_require__(30); module.exports = factory(isValidElement); /***/ }), /* 30 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ 'use strict'; // React 15.5 references this module, and assumes PropTypes are still callable in production. // Therefore we re-export development-only version with all the PropTypes checks here. // However if one is migrating to the `prop-types` npm library, they will go through the // `index.js` entry point, and it will branch depending on the environment. var factory = __webpack_require__(31); module.exports = function(isValidElement) { // It is still allowed in 15.5. var throwOnDirectAccess = false; return factory(isValidElement, throwOnDirectAccess); }; /***/ }), /* 31 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ 'use strict'; var emptyFunction = __webpack_require__(12); var invariant = __webpack_require__(8); var warning = __webpack_require__(11); var ReactPropTypesSecret = __webpack_require__(32); var checkPropTypes = __webpack_require__(33); module.exports = function(isValidElement, throwOnDirectAccess) { /* global Symbol */ var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator; var FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec. /** * Returns the iterator method function contained on the iterable object. * * Be sure to invoke the function with the iterable as context: * * var iteratorFn = getIteratorFn(myIterable); * if (iteratorFn) { * var iterator = iteratorFn.call(myIterable); * ... * } * * @param {?object} maybeIterable * @return {?function} */ function getIteratorFn(maybeIterable) { var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]); if (typeof iteratorFn === 'function') { return iteratorFn; } } /** * Collection of methods that allow declaration and validation of props that are * supplied to React components. Example usage: * * var Props = require('ReactPropTypes'); * var MyArticle = React.createClass({ * propTypes: { * // An optional string prop named "description". * description: Props.string, * * // A required enum prop named "category". * category: Props.oneOf(['News','Photos']).isRequired, * * // A prop named "dialog" that requires an instance of Dialog. * dialog: Props.instanceOf(Dialog).isRequired * }, * render: function() { ... } * }); * * A more formal specification of how these methods are used: * * type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...) * decl := ReactPropTypes.{type}(.isRequired)? * * Each and every declaration produces a function with the same signature. This * allows the creation of custom validation functions. For example: * * var MyLink = React.createClass({ * propTypes: { * // An optional string or URI prop named "href". * href: function(props, propName, componentName) { * var propValue = props[propName]; * if (propValue != null && typeof propValue !== 'string' && * !(propValue instanceof URI)) { * return new Error( * 'Expected a string or an URI for ' + propName + ' in ' + * componentName * ); * } * } * }, * render: function() {...} * }); * * @internal */ var ANONYMOUS = '<<anonymous>>'; // Important! // Keep this list in sync with production version in `./factoryWithThrowingShims.js`. var ReactPropTypes = { array: createPrimitiveTypeChecker('array'), bool: createPrimitiveTypeChecker('boolean'), func: createPrimitiveTypeChecker('function'), number: createPrimitiveTypeChecker('number'), object: createPrimitiveTypeChecker('object'), string: createPrimitiveTypeChecker('string'), symbol: createPrimitiveTypeChecker('symbol'), any: createAnyTypeChecker(), arrayOf: createArrayOfTypeChecker, element: createElementTypeChecker(), instanceOf: createInstanceTypeChecker, node: createNodeChecker(), objectOf: createObjectOfTypeChecker, oneOf: createEnumTypeChecker, oneOfType: createUnionTypeChecker, shape: createShapeTypeChecker }; /** * inlined Object.is polyfill to avoid requiring consumers ship their own * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is */ /*eslint-disable no-self-compare*/ function is(x, y) { // SameValue algorithm if (x === y) { // Steps 1-5, 7-10 // Steps 6.b-6.e: +0 != -0 return x !== 0 || 1 / x === 1 / y; } else { // Step 6.a: NaN == NaN return x !== x && y !== y; } } /*eslint-enable no-self-compare*/ /** * We use an Error-like object for backward compatibility as people may call * PropTypes directly and inspect their output. However, we don't use real * Errors anymore. We don't inspect their stack anyway, and creating them * is prohibitively expensive if they are created too often, such as what * happens in oneOfType() for any type before the one that matched. */ function PropTypeError(message) { this.message = message; this.stack = ''; } // Make `instanceof Error` still work for returned errors. PropTypeError.prototype = Error.prototype; function createChainableTypeChecker(validate) { if (process.env.NODE_ENV !== 'production') { var manualPropTypeCallCache = {}; var manualPropTypeWarningCount = 0; } function checkType(isRequired, props, propName, componentName, location, propFullName, secret) { componentName = componentName || ANONYMOUS; propFullName = propFullName || propName; if (secret !== ReactPropTypesSecret) { if (throwOnDirectAccess) { // New behavior only for users of `prop-types` package invariant( false, 'Calling PropTypes validators directly is not supported by the `prop-types` package. ' + 'Use `PropTypes.checkPropTypes()` to call them. ' + 'Read more at http://fb.me/use-check-prop-types' ); } else if (process.env.NODE_ENV !== 'production' && typeof console !== 'undefined') { // Old behavior for people using React.PropTypes var cacheKey = componentName + ':' + propName; if ( !manualPropTypeCallCache[cacheKey] && // Avoid spamming the console because they are often not actionable except for lib authors manualPropTypeWarningCount < 3 ) { warning( false, 'You are manually calling a React.PropTypes validation ' + 'function for the `%s` prop on `%s`. This is deprecated ' + 'and will throw in the standalone `prop-types` package. ' + 'You may be seeing this warning due to a third-party PropTypes ' + 'library. See https://fb.me/react-warning-dont-call-proptypes ' + 'for details.', propFullName, componentName ); manualPropTypeCallCache[cacheKey] = true; manualPropTypeWarningCount++; } } } if (props[propName] == null) { if (isRequired) { if (props[propName] === null) { return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required ' + ('in `' + componentName + '`, but its value is `null`.')); } return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required in ' + ('`' + componentName + '`, but its value is `undefined`.')); } return null; } else { return validate(props, propName, componentName, location, propFullName); } } var chainedCheckType = checkType.bind(null, false); chainedCheckType.isRequired = checkType.bind(null, true); return chainedCheckType; } function createPrimitiveTypeChecker(expectedType) { function validate(props, propName, componentName, location, propFullName, secret) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== expectedType) { // `propValue` being instance of, say, date/regexp, pass the 'object' // check, but we can offer a more precise error message here rather than // 'of type `object`'. var preciseType = getPreciseType(propValue); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + preciseType + '` supplied to `' + componentName + '`, expected ') + ('`' + expectedType + '`.')); } return null; } return createChainableTypeChecker(validate); } function createAnyTypeChecker() { return createChainableTypeChecker(emptyFunction.thatReturnsNull); } function createArrayOfTypeChecker(typeChecker) { function validate(props, propName, componentName, location, propFullName) { if (typeof typeChecker !== 'function') { return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside arrayOf.'); } var propValue = props[propName]; if (!Array.isArray(propValue)) { var propType = getPropType(propValue); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an array.')); } for (var i = 0; i < propValue.length; i++) { var error = typeChecker(propValue, i, componentName, location, propFullName + '[' + i + ']', ReactPropTypesSecret); if (error instanceof Error) { return error; } } return null; } return createChainableTypeChecker(validate); } function createElementTypeChecker() { function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; if (!isValidElement(propValue)) { var propType = getPropType(propValue); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected a single ReactElement.')); } return null; } return createChainableTypeChecker(validate); } function createInstanceTypeChecker(expectedClass) { function validate(props, propName, componentName, location, propFullName) { if (!(props[propName] instanceof expectedClass)) { var expectedClassName = expectedClass.name || ANONYMOUS; var actualClassName = getClassName(props[propName]); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + actualClassName + '` supplied to `' + componentName + '`, expected ') + ('instance of `' + expectedClassName + '`.')); } return null; } return createChainableTypeChecker(validate); } function createEnumTypeChecker(expectedValues) { if (!Array.isArray(expectedValues)) { process.env.NODE_ENV !== 'production' ? warning(false, 'Invalid argument supplied to oneOf, expected an instance of array.') : void 0; return emptyFunction.thatReturnsNull; } function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; for (var i = 0; i < expectedValues.length; i++) { if (is(propValue, expectedValues[i])) { return null; } } var valuesString = JSON.stringify(expectedValues); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of value `' + propValue + '` ' + ('supplied to `' + componentName + '`, expected one of ' + valuesString + '.')); } return createChainableTypeChecker(validate); } function createObjectOfTypeChecker(typeChecker) { function validate(props, propName, componentName, location, propFullName) { if (typeof typeChecker !== 'function') { return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside objectOf.'); } var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== 'object') { return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an object.')); } for (var key in propValue) { if (propValue.hasOwnProperty(key)) { var error = typeChecker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret); if (error instanceof Error) { return error; } } } return null; } return createChainableTypeChecker(validate); } function createUnionTypeChecker(arrayOfTypeCheckers) { if (!Array.isArray(arrayOfTypeCheckers)) { process.env.NODE_ENV !== 'production' ? warning(false, 'Invalid argument supplied to oneOfType, expected an instance of array.') : void 0; return emptyFunction.thatReturnsNull; } for (var i = 0; i < arrayOfTypeCheckers.length; i++) { var checker = arrayOfTypeCheckers[i]; if (typeof checker !== 'function') { warning( false, 'Invalid argument supplid to oneOfType. Expected an array of check functions, but ' + 'received %s at index %s.', getPostfixForTypeWarning(checker), i ); return emptyFunction.thatReturnsNull; } } function validate(props, propName, componentName, location, propFullName) { for (var i = 0; i < arrayOfTypeCheckers.length; i++) { var checker = arrayOfTypeCheckers[i]; if (checker(props, propName, componentName, location, propFullName, ReactPropTypesSecret) == null) { return null; } } return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`.')); } return createChainableTypeChecker(validate); } function createNodeChecker() { function validate(props, propName, componentName, location, propFullName) { if (!isNode(props[propName])) { return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`, expected a ReactNode.')); } return null; } return createChainableTypeChecker(validate); } function createShapeTypeChecker(shapeTypes) { function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== 'object') { return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.')); } for (var key in shapeTypes) { var checker = shapeTypes[key]; if (!checker) { continue; } var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret); if (error) { return error; } } return null; } return createChainableTypeChecker(validate); } function isNode(propValue) { switch (typeof propValue) { case 'number': case 'string': case 'undefined': return true; case 'boolean': return !propValue; case 'object': if (Array.isArray(propValue)) { return propValue.every(isNode); } if (propValue === null || isValidElement(propValue)) { return true; } var iteratorFn = getIteratorFn(propValue); if (iteratorFn) { var iterator = iteratorFn.call(propValue); var step; if (iteratorFn !== propValue.entries) { while (!(step = iterator.next()).done) { if (!isNode(step.value)) { return false; } } } else { // Iterator will provide entry [k,v] tuples rather than values. while (!(step = iterator.next()).done) { var entry = step.value; if (entry) { if (!isNode(entry[1])) { return false; } } } } } else { return false; } return true; default: return false; } } function isSymbol(propType, propValue) { // Native Symbol. if (propType === 'symbol') { return true; } // 19.4.3.5 Symbol.prototype[@@toStringTag] === 'Symbol' if (propValue['@@toStringTag'] === 'Symbol') { return true; } // Fallback for non-spec compliant Symbols which are polyfilled. if (typeof Symbol === 'function' && propValue instanceof Symbol) { return true; } return false; } // Equivalent of `typeof` but with special handling for array and regexp. function getPropType(propValue) { var propType = typeof propValue; if (Array.isArray(propValue)) { return 'array'; } if (propValue instanceof RegExp) { // Old webkits (at least until Android 4.0) return 'function' rather than // 'object' for typeof a RegExp. We'll normalize this here so that /bla/ // passes PropTypes.object. return 'object'; } if (isSymbol(propType, propValue)) { return 'symbol'; } return propType; } // This handles more types than `getPropType`. Only used for error messages. // See `createPrimitiveTypeChecker`. function getPreciseType(propValue) { if (typeof propValue === 'undefined' || propValue === null) { return '' + propValue; } var propType = getPropType(propValue); if (propType === 'object') { if (propValue instanceof Date) { return 'date'; } else if (propValue instanceof RegExp) { return 'regexp'; } } return propType; } // Returns a string that is postfixed to a warning about an invalid type. // For example, "undefined" or "of type array" function getPostfixForTypeWarning(value) { var type = getPreciseType(value); switch (type) { case 'array': case 'object': return 'an ' + type; case 'boolean': case 'date': case 'regexp': return 'a ' + type; default: return type; } } // Returns class name of the object, if any. function getClassName(propValue) { if (!propValue.constructor || !propValue.constructor.name) { return ANONYMOUS; } return propValue.constructor.name; } ReactPropTypes.checkPropTypes = checkPropTypes; ReactPropTypes.PropTypes = ReactPropTypes; return ReactPropTypes; }; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 32 */ /***/ (function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ 'use strict'; var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'; module.exports = ReactPropTypesSecret; /***/ }), /* 33 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ 'use strict'; if (process.env.NODE_ENV !== 'production') { var invariant = __webpack_require__(8); var warning = __webpack_require__(11); var ReactPropTypesSecret = __webpack_require__(32); var loggedTypeFailures = {}; } /** * Assert that the values match with the type specs. * Error messages are memorized and will only be shown once. * * @param {object} typeSpecs Map of name to a ReactPropType * @param {object} values Runtime values that need to be type-checked * @param {string} location e.g. "prop", "context", "child context" * @param {string} componentName Name of the component for error messages. * @param {?Function} getStack Returns the component stack. * @private */ function checkPropTypes(typeSpecs, values, location, componentName, getStack) { if (process.env.NODE_ENV !== 'production') { for (var typeSpecName in typeSpecs) { if (typeSpecs.hasOwnProperty(typeSpecName)) { var error; // Prop type validation may throw. In case they do, we don't want to // fail the render phase where it didn't fail before. So we log it. // After these have been cleaned up, we'll let them throw. try { // This is intentionally an invariant that gets caught. It's the same // behavior as without this statement except with a better message. invariant(typeof typeSpecs[typeSpecName] === 'function', '%s: %s type `%s` is invalid; it must be a function, usually from ' + 'React.PropTypes.', componentName || 'React class', location, typeSpecName); error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret); } catch (ex) { error = ex; } warning(!error || error instanceof 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); if (error instanceof Error && !(error.message in loggedTypeFailures)) { // Only monitor this failure once because there tends to be a lot of the // same error. loggedTypeFailures[error.message] = true; var stack = getStack ? getStack() : ''; warning(false, 'Failed %s type: %s%s', location, error.message, stack != null ? stack : ''); } } } } } module.exports = checkPropTypes; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 34 */ /***/ (function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; module.exports = '15.5.4'; /***/ }), /* 35 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(7); var ReactElement = __webpack_require__(9); var invariant = __webpack_require__(8); /** * Returns the first child in a collection of children and verifies that there * is only one child in the collection. * * See https://facebook.github.io/react/docs/top-level-api.html#react.children.only * * The current implementation of this function assumes that a single child gets * passed without a wrapper, but the purpose of this helper function is to * abstract away the particular structure of children. * * @param {?object} children Child collection structure. * @return {ReactElement} The first and only `ReactElement` contained in the * structure. */ function onlyChild(children) { !ReactElement.isValidElement(children) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'React.Children.only expected to receive a single React element child.') : _prodInvariant('143') : void 0; return children; } module.exports = onlyChild; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 36 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; module.exports = __webpack_require__(37); /***/ }), /* 37 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ /* globals __REACT_DEVTOOLS_GLOBAL_HOOK__*/ 'use strict'; var ReactDOMComponentTree = __webpack_require__(38); var ReactDefaultInjection = __webpack_require__(42); var ReactMount = __webpack_require__(170); var ReactReconciler = __webpack_require__(63); var ReactUpdates = __webpack_require__(60); var ReactVersion = __webpack_require__(175); var findDOMNode = __webpack_require__(176); var getHostComponentFromComposite = __webpack_require__(177); var renderSubtreeIntoContainer = __webpack_require__(178); var warning = __webpack_require__(11); ReactDefaultInjection.inject(); var ReactDOM = { findDOMNode: findDOMNode, render: ReactMount.render, unmountComponentAtNode: ReactMount.unmountComponentAtNode, version: ReactVersion, /* eslint-disable camelcase */ unstable_batchedUpdates: ReactUpdates.batchedUpdates, unstable_renderSubtreeIntoContainer: renderSubtreeIntoContainer }; // Inject the runtime into a devtools global hook regardless of browser. // Allows for debugging when the hook is injected on the page. if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.inject === 'function') { __REACT_DEVTOOLS_GLOBAL_HOOK__.inject({ ComponentTree: { getClosestInstanceFromNode: ReactDOMComponentTree.getClosestInstanceFromNode, getNodeFromInstance: function (inst) { // inst is an internal instance (but could be a composite) if (inst._renderedComponent) { inst = getHostComponentFromComposite(inst); } if (inst) { return ReactDOMComponentTree.getNodeFromInstance(inst); } else { return null; } } }, Mount: ReactMount, Reconciler: ReactReconciler }); } if (process.env.NODE_ENV !== 'production') { var ExecutionEnvironment = __webpack_require__(52); if (ExecutionEnvironment.canUseDOM && window.top === window.self) { // First check if devtools is not installed if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined') { // If we're in Chrome or Firefox, provide a download link if not installed. if (navigator.userAgent.indexOf('Chrome') > -1 && navigator.userAgent.indexOf('Edge') === -1 || navigator.userAgent.indexOf('Firefox') > -1) { // Firefox does not have the issue with devtools loaded over file:// var showFileUrlMessage = window.location.protocol.indexOf('http') === -1 && navigator.userAgent.indexOf('Firefox') === -1; console.debug('Download the React DevTools ' + (showFileUrlMessage ? 'and use an HTTP server (instead of a file: URL) ' : '') + 'for a better development experience: ' + 'https://fb.me/react-devtools'); } } var testFunc = function testFn() {}; process.env.NODE_ENV !== 'production' ? warning((testFunc.name || testFunc.toString()).indexOf('testFn') !== -1, 'It looks like you\'re using a minified copy of the development build ' + 'of React. When deploying React apps to production, make sure to use ' + 'the production build which skips development warnings and is faster. ' + 'See https://fb.me/react-minification for more details.') : void 0; // If we're in IE8, check to see if we are in compatibility mode and provide // information on preventing compatibility mode var ieCompatibilityMode = document.documentMode && document.documentMode < 8; process.env.NODE_ENV !== 'production' ? warning(!ieCompatibilityMode, 'Internet Explorer is running in compatibility mode; please add the ' + 'following tag to your HTML to prevent this from happening: ' + '<meta http-equiv="X-UA-Compatible" content="IE=edge" />') : void 0; var expectedFeatures = [ // shims Array.isArray, Array.prototype.every, Array.prototype.forEach, Array.prototype.indexOf, Array.prototype.map, Date.now, Function.prototype.bind, Object.keys, String.prototype.trim]; for (var i = 0; i < expectedFeatures.length; i++) { if (!expectedFeatures[i]) { process.env.NODE_ENV !== 'production' ? warning(false, 'One or more ES5 shims expected by React are not available: ' + 'https://fb.me/react-warning-polyfills') : void 0; break; } } } } if (process.env.NODE_ENV !== 'production') { var ReactInstrumentation = __webpack_require__(66); var ReactDOMUnknownPropertyHook = __webpack_require__(179); var ReactDOMNullInputValuePropHook = __webpack_require__(180); var ReactDOMInvalidARIAHook = __webpack_require__(181); ReactInstrumentation.debugTool.addHook(ReactDOMUnknownPropertyHook); ReactInstrumentation.debugTool.addHook(ReactDOMNullInputValuePropHook); ReactInstrumentation.debugTool.addHook(ReactDOMInvalidARIAHook); } module.exports = ReactDOM; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 38 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(39); var DOMProperty = __webpack_require__(40); var ReactDOMComponentFlags = __webpack_require__(41); var invariant = __webpack_require__(8); var ATTR_NAME = DOMProperty.ID_ATTRIBUTE_NAME; var Flags = ReactDOMComponentFlags; var internalInstanceKey = '__reactInternalInstance$' + Math.random().toString(36).slice(2); /** * Check if a given node should be cached. */ function shouldPrecacheNode(node, nodeID) { return node.nodeType === 1 && node.getAttribute(ATTR_NAME) === String(nodeID) || node.nodeType === 8 && node.nodeValue === ' react-text: ' + nodeID + ' ' || node.nodeType === 8 && node.nodeValue === ' react-empty: ' + nodeID + ' '; } /** * Drill down (through composites and empty components) until we get a host or * host text component. * * This is pretty polymorphic but unavoidable with the current structure we have * for `_renderedChildren`. */ function getRenderedHostOrTextFromComponent(component) { var rendered; while (rendered = component._renderedComponent) { component = rendered; } return component; } /** * Populate `_hostNode` on the rendered host/text component with the given * DOM node. The passed `inst` can be a composite. */ function precacheNode(inst, node) { var hostInst = getRenderedHostOrTextFromComponent(inst); hostInst._hostNode = node; node[internalInstanceKey] = hostInst; } function uncacheNode(inst) { var node = inst._hostNode; if (node) { delete node[internalInstanceKey]; inst._hostNode = null; } } /** * Populate `_hostNode` on each child of `inst`, assuming that the children * match up with the DOM (element) children of `node`. * * We cache entire levels at once to avoid an n^2 problem where we access the * children of a node sequentially and have to walk from the start to our target * node every time. * * Since we update `_renderedChildren` and the actual DOM at (slightly) * different times, we could race here and see a newer `_renderedChildren` than * the DOM nodes we see. To avoid this, ReactMultiChild calls * `prepareToManageChildren` before we change `_renderedChildren`, at which * time the container's child nodes are always cached (until it unmounts). */ function precacheChildNodes(inst, node) { if (inst._flags & Flags.hasCachedChildNodes) { return; } var children = inst._renderedChildren; var childNode = node.firstChild; outer: for (var name in children) { if (!children.hasOwnProperty(name)) { continue; } var childInst = children[name]; var childID = getRenderedHostOrTextFromComponent(childInst)._domID; if (childID === 0) { // We're currently unmounting this child in ReactMultiChild; skip it. continue; } // We assume the child nodes are in the same order as the child instances. for (; childNode !== null; childNode = childNode.nextSibling) { if (shouldPrecacheNode(childNode, childID)) { precacheNode(childInst, childNode); continue outer; } } // We reached the end of the DOM children without finding an ID match. true ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Unable to find element with ID %s.', childID) : _prodInvariant('32', childID) : void 0; } inst._flags |= Flags.hasCachedChildNodes; } /** * Given a DOM node, return the closest ReactDOMComponent or * ReactDOMTextComponent instance ancestor. */ function getClosestInstanceFromNode(node) { if (node[internalInstanceKey]) { return node[internalInstanceKey]; } // Walk up the tree until we find an ancestor whose instance we have cached. var parents = []; while (!node[internalInstanceKey]) { parents.push(node); if (node.parentNode) { node = node.parentNode; } else { // Top of the tree. This node must not be part of a React tree (or is // unmounted, potentially). return null; } } var closest; var inst; for (; node && (inst = node[internalInstanceKey]); node = parents.pop()) { closest = inst; if (parents.length) { precacheChildNodes(inst, node); } } return closest; } /** * Given a DOM node, return the ReactDOMComponent or ReactDOMTextComponent * instance, or null if the node was not rendered by this React. */ function getInstanceFromNode(node) { var inst = getClosestInstanceFromNode(node); if (inst != null && inst._hostNode === node) { return inst; } else { return null; } } /** * Given a ReactDOMComponent or ReactDOMTextComponent, return the corresponding * DOM node. */ function getNodeFromInstance(inst) { // Without this first invariant, passing a non-DOM-component triggers the next // invariant for a missing parent, which is super confusing. !(inst._hostNode !== undefined) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'getNodeFromInstance: Invalid argument.') : _prodInvariant('33') : void 0; if (inst._hostNode) { return inst._hostNode; } // Walk up the tree until we find an ancestor whose DOM node we have cached. var parents = []; while (!inst._hostNode) { parents.push(inst); !inst._hostParent ? process.env.NODE_ENV !== 'production' ? invariant(false, 'React DOM tree root should always have a node reference.') : _prodInvariant('34') : void 0; inst = inst._hostParent; } // Now parents contains each ancestor that does *not* have a cached native // node, and `inst` is the deepest ancestor that does. for (; parents.length; inst = parents.pop()) { precacheChildNodes(inst, inst._hostNode); } return inst._hostNode; } var ReactDOMComponentTree = { getClosestInstanceFromNode: getClosestInstanceFromNode, getInstanceFromNode: getInstanceFromNode, getNodeFromInstance: getNodeFromInstance, precacheChildNodes: precacheChildNodes, precacheNode: precacheNode, uncacheNode: uncacheNode }; module.exports = ReactDOMComponentTree; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 39 */ /***/ (function(module, exports) { /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; /** * WARNING: DO NOT manually require this module. * This is a replacement for `invariant(...)` used by the error code system * and will _only_ be required by the corresponding babel pass. * It always throws. */ function reactProdInvariant(code) { var argCount = arguments.length - 1; var message = 'Minified React error #' + code + '; visit ' + 'http://facebook.github.io/react/docs/error-decoder.html?invariant=' + code; for (var argIdx = 0; argIdx < argCount; argIdx++) { message += '&args[]=' + encodeURIComponent(arguments[argIdx + 1]); } message += ' for the full message or use the non-minified dev environment' + ' for full errors and additional helpful warnings.'; var error = new Error(message); error.name = 'Invariant Violation'; error.framesToPop = 1; // we don't care about reactProdInvariant's own frame throw error; } module.exports = reactProdInvariant; /***/ }), /* 40 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(39); var invariant = __webpack_require__(8); function checkMask(value, bitmask) { return (value & bitmask) === bitmask; } var DOMPropertyInjection = { /** * Mapping from normalized, camelcased property names to a configuration that * specifies how the associated DOM property should be accessed or rendered. */ MUST_USE_PROPERTY: 0x1, HAS_BOOLEAN_VALUE: 0x4, HAS_NUMERIC_VALUE: 0x8, HAS_POSITIVE_NUMERIC_VALUE: 0x10 | 0x8, HAS_OVERLOADED_BOOLEAN_VALUE: 0x20, /** * Inject some specialized knowledge about the DOM. This takes a config object * with the following properties: * * isCustomAttribute: function that given an attribute name will return true * if it can be inserted into the DOM verbatim. Useful for data-* or aria-* * attributes where it's impossible to enumerate all of the possible * attribute names, * * Properties: object mapping DOM property name to one of the * DOMPropertyInjection constants or null. If your attribute isn't in here, * it won't get written to the DOM. * * DOMAttributeNames: object mapping React attribute name to the DOM * attribute name. Attribute names not specified use the **lowercase** * normalized name. * * DOMAttributeNamespaces: object mapping React attribute name to the DOM * attribute namespace URL. (Attribute names not specified use no namespace.) * * DOMPropertyNames: similar to DOMAttributeNames but for DOM properties. * Property names not specified use the normalized name. * * DOMMutationMethods: Properties that require special mutation methods. If * `value` is undefined, the mutation method should unset the property. * * @param {object} domPropertyConfig the config as described above. */ injectDOMPropertyConfig: function (domPropertyConfig) { var Injection = DOMPropertyInjection; var Properties = domPropertyConfig.Properties || {}; var DOMAttributeNamespaces = domPropertyConfig.DOMAttributeNamespaces || {}; var DOMAttributeNames = domPropertyConfig.DOMAttributeNames || {}; var DOMPropertyNames = domPropertyConfig.DOMPropertyNames || {}; var DOMMutationMethods = domPropertyConfig.DOMMutationMethods || {}; if (domPropertyConfig.isCustomAttribute) { DOMProperty._isCustomAttributeFunctions.push(domPropertyConfig.isCustomAttribute); } for (var propName in Properties) { !!DOMProperty.properties.hasOwnProperty(propName) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'injectDOMPropertyConfig(...): You\'re trying to inject DOM property \'%s\' which has already been injected. You may be accidentally injecting the same DOM property config twice, or you may be injecting two configs that have conflicting property names.', propName) : _prodInvariant('48', propName) : void 0; var lowerCased = propName.toLowerCase(); var propConfig = Properties[propName]; var propertyInfo = { attributeName: lowerCased, attributeNamespace: null, propertyName: propName, mutationMethod: null, mustUseProperty: checkMask(propConfig, Injection.MUST_USE_PROPERTY), hasBooleanValue: checkMask(propConfig, Injection.HAS_BOOLEAN_VALUE), hasNumericValue: checkMask(propConfig, Injection.HAS_NUMERIC_VALUE), hasPositiveNumericValue: checkMask(propConfig, Injection.HAS_POSITIVE_NUMERIC_VALUE), hasOverloadedBooleanValue: checkMask(propConfig, Injection.HAS_OVERLOADED_BOOLEAN_VALUE) }; !(propertyInfo.hasBooleanValue + propertyInfo.hasNumericValue + propertyInfo.hasOverloadedBooleanValue <= 1) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'DOMProperty: Value can be one of boolean, overloaded boolean, or numeric value, but not a combination: %s', propName) : _prodInvariant('50', propName) : void 0; if (process.env.NODE_ENV !== 'production') { DOMProperty.getPossibleStandardName[lowerCased] = propName; } if (DOMAttributeNames.hasOwnProperty(propName)) { var attributeName = DOMAttributeNames[propName]; propertyInfo.attributeName = attributeName; if (process.env.NODE_ENV !== 'production') { DOMProperty.getPossibleStandardName[attributeName] = propName; } } if (DOMAttributeNamespaces.hasOwnProperty(propName)) { propertyInfo.attributeNamespace = DOMAttributeNamespaces[propName]; } if (DOMPropertyNames.hasOwnProperty(propName)) { propertyInfo.propertyName = DOMPropertyNames[propName]; } if (DOMMutationMethods.hasOwnProperty(propName)) { propertyInfo.mutationMethod = DOMMutationMethods[propName]; } DOMProperty.properties[propName] = propertyInfo; } } }; /* eslint-disable max-len */ 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'; /* eslint-enable max-len */ /** * DOMProperty exports lookup objects that can be used like functions: * * > DOMProperty.isValid['id'] * true * > DOMProperty.isValid['foobar'] * undefined * * Although this may be confusing, it performs better in general. * * @see http://jsperf.com/key-exists * @see http://jsperf.com/key-missing */ var DOMProperty = { ID_ATTRIBUTE_NAME: 'data-reactid', ROOT_ATTRIBUTE_NAME: 'data-reactroot', ATTRIBUTE_NAME_START_CHAR: ATTRIBUTE_NAME_START_CHAR, ATTRIBUTE_NAME_CHAR: ATTRIBUTE_NAME_START_CHAR + '\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040', /** * Map from property "standard name" to an object with info about how to set * the property in the DOM. Each object contains: * * attributeName: * Used when rendering markup or with `*Attribute()`. * attributeNamespace * propertyName: * Used on DOM node instances. (This includes properties that mutate due to * external factors.) * mutationMethod: * If non-null, used instead of the property or `setAttribute()` after * initial render. * mustUseProperty: * Whether the property must be accessed and mutated as an object property. * hasBooleanValue: * Whether the property should be removed when set to a falsey value. * hasNumericValue: * Whether the property must be numeric or parse as a numeric and should be * removed when set to a falsey value. * hasPositiveNumericValue: * Whether the property must be positive numeric or parse as a positive * numeric and should be removed when set to a falsey value. * hasOverloadedBooleanValue: * Whether the property can be used as a flag as well as with a value. * Removed when strictly equal to false; present without a value when * strictly equal to true; present with a value otherwise. */ properties: {}, /** * Mapping from lowercase property names to the properly cased version, used * to warn in the case of missing properties. Available only in __DEV__. * * autofocus is predefined, because adding it to the property whitelist * causes unintended side effects. * * @type {Object} */ getPossibleStandardName: process.env.NODE_ENV !== 'production' ? { autofocus: 'autoFocus' } : null, /** * All of the isCustomAttribute() functions that have been injected. */ _isCustomAttributeFunctions: [], /** * Checks whether a property name is a custom attribute. * @method */ isCustomAttribute: function (attributeName) { for (var i = 0; i < DOMProperty._isCustomAttributeFunctions.length; i++) { var isCustomAttributeFn = DOMProperty._isCustomAttributeFunctions[i]; if (isCustomAttributeFn(attributeName)) { return true; } } return false; }, injection: DOMPropertyInjection }; module.exports = DOMProperty; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 41 */ /***/ (function(module, exports) { /** * Copyright 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var ReactDOMComponentFlags = { hasCachedChildNodes: 1 << 0 }; module.exports = ReactDOMComponentFlags; /***/ }), /* 42 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var ARIADOMPropertyConfig = __webpack_require__(43); var BeforeInputEventPlugin = __webpack_require__(44); var ChangeEventPlugin = __webpack_require__(59); var DefaultEventPluginOrder = __webpack_require__(76); var EnterLeaveEventPlugin = __webpack_require__(77); var HTMLDOMPropertyConfig = __webpack_require__(82); var ReactComponentBrowserEnvironment = __webpack_require__(83); var ReactDOMComponent = __webpack_require__(96); var ReactDOMComponentTree = __webpack_require__(38); var ReactDOMEmptyComponent = __webpack_require__(141); var ReactDOMTreeTraversal = __webpack_require__(142); var ReactDOMTextComponent = __webpack_require__(143); var ReactDefaultBatchingStrategy = __webpack_require__(144); var ReactEventListener = __webpack_require__(145); var ReactInjection = __webpack_require__(148); var ReactReconcileTransaction = __webpack_require__(149); var SVGDOMPropertyConfig = __webpack_require__(157); var SelectEventPlugin = __webpack_require__(158); var SimpleEventPlugin = __webpack_require__(159); var alreadyInjected = false; function inject() { if (alreadyInjected) { // TODO: This is currently true because these injections are shared between // the client and the server package. They should be built independently // and not share any injection state. Then this problem will be solved. return; } alreadyInjected = true; ReactInjection.EventEmitter.injectReactEventListener(ReactEventListener); /** * Inject modules for resolving DOM hierarchy and plugin ordering. */ ReactInjection.EventPluginHub.injectEventPluginOrder(DefaultEventPluginOrder); ReactInjection.EventPluginUtils.injectComponentTree(ReactDOMComponentTree); ReactInjection.EventPluginUtils.injectTreeTraversal(ReactDOMTreeTraversal); /** * Some important event plugins included by default (without having to require * them). */ ReactInjection.EventPluginHub.injectEventPluginsByName({ SimpleEventPlugin: SimpleEventPlugin, EnterLeaveEventPlugin: EnterLeaveEventPlugin, ChangeEventPlugin: ChangeEventPlugin, SelectEventPlugin: SelectEventPlugin, BeforeInputEventPlugin: BeforeInputEventPlugin }); ReactInjection.HostComponent.injectGenericComponentClass(ReactDOMComponent); ReactInjection.HostComponent.injectTextComponentClass(ReactDOMTextComponent); ReactInjection.DOMProperty.injectDOMPropertyConfig(ARIADOMPropertyConfig); ReactInjection.DOMProperty.injectDOMPropertyConfig(HTMLDOMPropertyConfig); ReactInjection.DOMProperty.injectDOMPropertyConfig(SVGDOMPropertyConfig); ReactInjection.EmptyComponent.injectEmptyComponentFactory(function (instantiate) { return new ReactDOMEmptyComponent(instantiate); }); ReactInjection.Updates.injectReconcileTransaction(ReactReconcileTransaction); ReactInjection.Updates.injectBatchingStrategy(ReactDefaultBatchingStrategy); ReactInjection.Component.injectEnvironment(ReactComponentBrowserEnvironment); } module.exports = { inject: inject }; /***/ }), /* 43 */ /***/ (function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var ARIADOMPropertyConfig = { Properties: { // Global States and Properties 'aria-current': 0, // state 'aria-details': 0, 'aria-disabled': 0, // state 'aria-hidden': 0, // state 'aria-invalid': 0, // state 'aria-keyshortcuts': 0, 'aria-label': 0, 'aria-roledescription': 0, // Widget Attributes '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, // Live Region Attributes 'aria-atomic': 0, 'aria-busy': 0, 'aria-live': 0, 'aria-relevant': 0, // Drag-and-Drop Attributes 'aria-dropeffect': 0, 'aria-grabbed': 0, // Relationship Attributes '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 }, DOMAttributeNames: {}, DOMPropertyNames: {} }; module.exports = ARIADOMPropertyConfig; /***/ }), /* 44 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var EventPropagators = __webpack_require__(45); var ExecutionEnvironment = __webpack_require__(52); var FallbackCompositionState = __webpack_require__(53); var SyntheticCompositionEvent = __webpack_require__(56); var SyntheticInputEvent = __webpack_require__(58); var END_KEYCODES = [9, 13, 27, 32]; // Tab, Return, Esc, Space var START_KEYCODE = 229; var canUseCompositionEvent = ExecutionEnvironment.canUseDOM && 'CompositionEvent' in window; var documentMode = null; if (ExecutionEnvironment.canUseDOM && 'documentMode' in document) { documentMode = document.documentMode; } // Webkit offers a very useful `textInput` event that can be used to // directly represent `beforeInput`. The IE `textinput` event is not as // useful, so we don't use it. var canUseTextInputEvent = ExecutionEnvironment.canUseDOM && 'TextEvent' in window && !documentMode && !isPresto(); // In IE9+, we have access to composition events, but the data supplied // by the native compositionend event may be incorrect. Japanese ideographic // spaces, for instance (\u3000) are not recorded correctly. var useFallbackCompositionData = ExecutionEnvironment.canUseDOM && (!canUseCompositionEvent || documentMode && documentMode > 8 && documentMode <= 11); /** * Opera <= 12 includes TextEvent in window, but does not fire * text input events. Rely on keypress instead. */ function isPresto() { var opera = window.opera; return typeof opera === 'object' && typeof opera.version === 'function' && parseInt(opera.version(), 10) <= 12; } var SPACEBAR_CODE = 32; var SPACEBAR_CHAR = String.fromCharCode(SPACEBAR_CODE); // Events and their corresponding property names. var eventTypes = { beforeInput: { phasedRegistrationNames: { bubbled: 'onBeforeInput', captured: 'onBeforeInputCapture' }, dependencies: ['topCompositionEnd', 'topKeyPress', 'topTextInput', 'topPaste'] }, compositionEnd: { phasedRegistrationNames: { bubbled: 'onCompositionEnd', captured: 'onCompositionEndCapture' }, dependencies: ['topBlur', 'topCompositionEnd', 'topKeyDown', 'topKeyPress', 'topKeyUp', 'topMouseDown'] }, compositionStart: { phasedRegistrationNames: { bubbled: 'onCompositionStart', captured: 'onCompositionStartCapture' }, dependencies: ['topBlur', 'topCompositionStart', 'topKeyDown', 'topKeyPress', 'topKeyUp', 'topMouseDown'] }, compositionUpdate: { phasedRegistrationNames: { bubbled: 'onCompositionUpdate', captured: 'onCompositionUpdateCapture' }, dependencies: ['topBlur', 'topCompositionUpdate', 'topKeyDown', 'topKeyPress', 'topKeyUp', 'topMouseDown'] } }; // Track whether we've ever handled a keypress on the space key. var hasSpaceKeypress = false; /** * Return whether a native keypress event is assumed to be a command. * This is required because Firefox fires `keypress` events for key commands * (cut, copy, select-all, etc.) even though no character is inserted. */ function isKeypressCommand(nativeEvent) { return (nativeEvent.ctrlKey || nativeEvent.altKey || nativeEvent.metaKey) && // ctrlKey && altKey is equivalent to AltGr, and is not a command. !(nativeEvent.ctrlKey && nativeEvent.altKey); } /** * Translate native top level events into event types. * * @param {string} topLevelType * @return {object} */ function getCompositionEventType(topLevelType) { switch (topLevelType) { case 'topCompositionStart': return eventTypes.compositionStart; case 'topCompositionEnd': return eventTypes.compositionEnd; case 'topCompositionUpdate': return eventTypes.compositionUpdate; } } /** * Does our fallback best-guess model think this event signifies that * composition has begun? * * @param {string} topLevelType * @param {object} nativeEvent * @return {boolean} */ function isFallbackCompositionStart(topLevelType, nativeEvent) { return topLevelType === 'topKeyDown' && nativeEvent.keyCode === START_KEYCODE; } /** * Does our fallback mode think that this event is the end of composition? * * @param {string} topLevelType * @param {object} nativeEvent * @return {boolean} */ function isFallbackCompositionEnd(topLevelType, nativeEvent) { switch (topLevelType) { case 'topKeyUp': // Command keys insert or clear IME input. return END_KEYCODES.indexOf(nativeEvent.keyCode) !== -1; case 'topKeyDown': // Expect IME keyCode on each keydown. If we get any other // code we must have exited earlier. return nativeEvent.keyCode !== START_KEYCODE; case 'topKeyPress': case 'topMouseDown': case 'topBlur': // Events are not possible without cancelling IME. return true; default: return false; } } /** * Google Input Tools provides composition data via a CustomEvent, * with the `data` property populated in the `detail` object. If this * is available on the event object, use it. If not, this is a plain * composition event and we have nothing special to extract. * * @param {object} nativeEvent * @return {?string} */ function getDataFromCustomEvent(nativeEvent) { var detail = nativeEvent.detail; if (typeof detail === 'object' && 'data' in detail) { return detail.data; } return null; } // Track the current IME composition fallback object, if any. var currentComposition = null; /** * @return {?object} A SyntheticCompositionEvent. */ function extractCompositionEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget) { var eventType; var fallbackData; if (canUseCompositionEvent) { eventType = getCompositionEventType(topLevelType); } else if (!currentComposition) { if (isFallbackCompositionStart(topLevelType, nativeEvent)) { eventType = eventTypes.compositionStart; } } else if (isFallbackCompositionEnd(topLevelType, nativeEvent)) { eventType = eventTypes.compositionEnd; } if (!eventType) { return null; } if (useFallbackCompositionData) { // The current composition is stored statically and must not be // overwritten while composition continues. if (!currentComposition && eventType === eventTypes.compositionStart) { currentComposition = FallbackCompositionState.getPooled(nativeEventTarget); } else if (eventType === eventTypes.compositionEnd) { if (currentComposition) { fallbackData = currentComposition.getData(); } } } var event = SyntheticCompositionEvent.getPooled(eventType, targetInst, nativeEvent, nativeEventTarget); if (fallbackData) { // Inject data generated from fallback path into the synthetic event. // This matches the property of native CompositionEventInterface. event.data = fallbackData; } else { var customData = getDataFromCustomEvent(nativeEvent); if (customData !== null) { event.data = customData; } } EventPropagators.accumulateTwoPhaseDispatches(event); return event; } /** * @param {string} topLevelType Record from `EventConstants`. * @param {object} nativeEvent Native browser event. * @return {?string} The string corresponding to this `beforeInput` event. */ function getNativeBeforeInputChars(topLevelType, nativeEvent) { switch (topLevelType) { case 'topCompositionEnd': return getDataFromCustomEvent(nativeEvent); case 'topKeyPress': /** * If native `textInput` events are available, our goal is to make * use of them. However, there is a special case: the spacebar key. * In Webkit, preventing default on a spacebar `textInput` event * cancels character insertion, but it *also* causes the browser * to fall back to its default spacebar behavior of scrolling the * page. * * Tracking at: * https://code.google.com/p/chromium/issues/detail?id=355103 * * To avoid this issue, use the keypress event as if no `textInput` * event is available. */ var which = nativeEvent.which; if (which !== SPACEBAR_CODE) { return null; } hasSpaceKeypress = true; return SPACEBAR_CHAR; case 'topTextInput': // Record the characters to be added to the DOM. var chars = nativeEvent.data; // If it's a spacebar character, assume that we have already handled // it at the keypress level and bail immediately. Android Chrome // doesn't give us keycodes, so we need to blacklist it. if (chars === SPACEBAR_CHAR && hasSpaceKeypress) { return null; } return chars; default: // For other native event types, do nothing. return null; } } /** * For browsers that do not provide the `textInput` event, extract the * appropriate string to use for SyntheticInputEvent. * * @param {string} topLevelType Record from `EventConstants`. * @param {object} nativeEvent Native browser event. * @return {?string} The fallback string for this `beforeInput` event. */ function getFallbackBeforeInputChars(topLevelType, nativeEvent) { // If we are currently composing (IME) and using a fallback to do so, // try to extract the composed characters from the fallback object. // If composition event is available, we extract a string only at // compositionevent, otherwise extract it at fallback events. if (currentComposition) { if (topLevelType === 'topCompositionEnd' || !canUseCompositionEvent && isFallbackCompositionEnd(topLevelType, nativeEvent)) { var chars = currentComposition.getData(); FallbackCompositionState.release(currentComposition); currentComposition = null; return chars; } return null; } switch (topLevelType) { case 'topPaste': // If a paste event occurs after a keypress, throw out the input // chars. Paste events should not lead to BeforeInput events. return null; case 'topKeyPress': /** * As of v27, Firefox may fire keypress events even when no character * will be inserted. A few possibilities: * * - `which` is `0`. Arrow keys, Esc key, etc. * * - `which` is the pressed key code, but no char is available. * Ex: 'AltGr + d` in Polish. There is no modified character for * this key combination and no character is inserted into the * document, but FF fires the keypress for char code `100` anyway. * No `input` event will occur. * * - `which` is the pressed key code, but a command combination is * being used. Ex: `Cmd+C`. No character is inserted, and no * `input` event will occur. */ if (nativeEvent.which && !isKeypressCommand(nativeEvent)) { return String.fromCharCode(nativeEvent.which); } return null; case 'topCompositionEnd': return useFallbackCompositionData ? null : nativeEvent.data; default: return null; } } /** * Extract a SyntheticInputEvent for `beforeInput`, based on either native * `textInput` or fallback behavior. * * @return {?object} A SyntheticInputEvent. */ function extractBeforeInputEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget) { var chars; if (canUseTextInputEvent) { chars = getNativeBeforeInputChars(topLevelType, nativeEvent); } else { chars = getFallbackBeforeInputChars(topLevelType, nativeEvent); } // If no characters are being inserted, no BeforeInput event should // be fired. if (!chars) { return null; } var event = SyntheticInputEvent.getPooled(eventTypes.beforeInput, targetInst, nativeEvent, nativeEventTarget); event.data = chars; EventPropagators.accumulateTwoPhaseDispatches(event); return event; } /** * Create an `onBeforeInput` event to match * http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105/#events-inputevents. * * This event plugin is based on the native `textInput` event * available in Chrome, Safari, Opera, and IE. This event fires after * `onKeyPress` and `onCompositionEnd`, but before `onInput`. * * `beforeInput` is spec'd but not implemented in any browsers, and * the `input` event does not provide any useful information about what has * actually been added, contrary to the spec. Thus, `textInput` is the best * available event to identify the characters that have actually been inserted * into the target node. * * This plugin is also responsible for emitting `composition` events, thus * allowing us to share composition fallback code for both `beforeInput` and * `composition` event types. */ var BeforeInputEventPlugin = { eventTypes: eventTypes, extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { return [extractCompositionEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget), extractBeforeInputEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget)]; } }; module.exports = BeforeInputEventPlugin; /***/ }), /* 45 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var EventPluginHub = __webpack_require__(46); var EventPluginUtils = __webpack_require__(48); var accumulateInto = __webpack_require__(50); var forEachAccumulated = __webpack_require__(51); var warning = __webpack_require__(11); var getListener = EventPluginHub.getListener; /** * Some event types have a notion of different registration names for different * "phases" of propagation. This finds listeners by a given phase. */ function listenerAtPhase(inst, event, propagationPhase) { var registrationName = event.dispatchConfig.phasedRegistrationNames[propagationPhase]; return getListener(inst, registrationName); } /** * Tags a `SyntheticEvent` with dispatched listeners. Creating this function * here, allows us to not have to bind or create functions for each event. * Mutating the event's members allows us to not have to create a wrapping * "dispatch" object that pairs the event with the listener. */ function accumulateDirectionalDispatches(inst, phase, event) { if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(inst, 'Dispatching inst must not be null') : void 0; } var listener = listenerAtPhase(inst, event, phase); if (listener) { event._dispatchListeners = accumulateInto(event._dispatchListeners, listener); event._dispatchInstances = accumulateInto(event._dispatchInstances, inst); } } /** * Collect dispatches (must be entirely collected before dispatching - see unit * tests). Lazily allocate the array to conserve memory. We must loop through * each event and perform the traversal for each one. We cannot perform a * single traversal for the entire collection of events because each event may * have a different target. */ function accumulateTwoPhaseDispatchesSingle(event) { if (event && event.dispatchConfig.phasedRegistrationNames) { EventPluginUtils.traverseTwoPhase(event._targetInst, accumulateDirectionalDispatches, event); } } /** * Same as `accumulateTwoPhaseDispatchesSingle`, but skips over the targetID. */ function accumulateTwoPhaseDispatchesSingleSkipTarget(event) { if (event && event.dispatchConfig.phasedRegistrationNames) { var targetInst = event._targetInst; var parentInst = targetInst ? EventPluginUtils.getParentInstance(targetInst) : null; EventPluginUtils.traverseTwoPhase(parentInst, accumulateDirectionalDispatches, event); } } /** * Accumulates without regard to direction, does not look for phased * registration names. Same as `accumulateDirectDispatchesSingle` but without * requiring that the `dispatchMarker` be the same as the dispatched ID. */ function accumulateDispatches(inst, ignoredDirection, event) { if (event && event.dispatchConfig.registrationName) { var registrationName = event.dispatchConfig.registrationName; var listener = getListener(inst, registrationName); if (listener) { event._dispatchListeners = accumulateInto(event._dispatchListeners, listener); event._dispatchInstances = accumulateInto(event._dispatchInstances, inst); } } } /** * Accumulates dispatches on an `SyntheticEvent`, but only for the * `dispatchMarker`. * @param {SyntheticEvent} event */ function accumulateDirectDispatchesSingle(event) { if (event && event.dispatchConfig.registrationName) { accumulateDispatches(event._targetInst, null, event); } } function accumulateTwoPhaseDispatches(events) { forEachAccumulated(events, accumulateTwoPhaseDispatchesSingle); } function accumulateTwoPhaseDispatchesSkipTarget(events) { forEachAccumulated(events, accumulateTwoPhaseDispatchesSingleSkipTarget); } function accumulateEnterLeaveDispatches(leave, enter, from, to) { EventPluginUtils.traverseEnterLeave(from, to, accumulateDispatches, leave, enter); } function accumulateDirectDispatches(events) { forEachAccumulated(events, accumulateDirectDispatchesSingle); } /** * A small set of propagation patterns, each of which will accept a small amount * of information, and generate a set of "dispatch ready event objects" - which * are sets of events that have already been annotated with a set of dispatched * listener functions/ids. The API is designed this way to discourage these * propagation strategies from actually executing the dispatches, since we * always want to collect the entire set of dispatches before executing event a * single one. * * @constructor EventPropagators */ var EventPropagators = { accumulateTwoPhaseDispatches: accumulateTwoPhaseDispatches, accumulateTwoPhaseDispatchesSkipTarget: accumulateTwoPhaseDispatchesSkipTarget, accumulateDirectDispatches: accumulateDirectDispatches, accumulateEnterLeaveDispatches: accumulateEnterLeaveDispatches }; module.exports = EventPropagators; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 46 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(39); var EventPluginRegistry = __webpack_require__(47); var EventPluginUtils = __webpack_require__(48); var ReactErrorUtils = __webpack_require__(49); var accumulateInto = __webpack_require__(50); var forEachAccumulated = __webpack_require__(51); var invariant = __webpack_require__(8); /** * Internal store for event listeners */ var listenerBank = {}; /** * Internal queue of events that have accumulated their dispatches and are * waiting to have their dispatches executed. */ var eventQueue = null; /** * Dispatches an event and releases it back into the pool, unless persistent. * * @param {?object} event Synthetic event to be dispatched. * @param {boolean} simulated If the event is simulated (changes exn behavior) * @private */ var executeDispatchesAndRelease = function (event, simulated) { if (event) { EventPluginUtils.executeDispatchesInOrder(event, simulated); if (!event.isPersistent()) { event.constructor.release(event); } } }; var executeDispatchesAndReleaseSimulated = function (e) { return executeDispatchesAndRelease(e, true); }; var executeDispatchesAndReleaseTopLevel = function (e) { return executeDispatchesAndRelease(e, false); }; var getDictionaryKey = function (inst) { // Prevents V8 performance issue: // https://github.com/facebook/react/pull/7232 return '.' + inst._rootNodeID; }; 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': return !!(props.disabled && isInteractive(type)); default: return false; } } /** * This is a unified interface for event plugins to be installed and configured. * * Event plugins can implement the following properties: * * `extractEvents` {function(string, DOMEventTarget, string, object): *} * Required. When a top-level event is fired, this method is expected to * extract synthetic events that will in turn be queued and dispatched. * * `eventTypes` {object} * Optional, plugins that fire events must publish a mapping of registration * names that are used to register listeners. Values of this mapping must * be objects that contain `registrationName` or `phasedRegistrationNames`. * * `executeDispatch` {function(object, function, string)} * Optional, allows plugins to override how an event gets dispatched. By * default, the listener is simply invoked. * * Each plugin that is injected into `EventsPluginHub` is immediately operable. * * @public */ var EventPluginHub = { /** * Methods for injecting dependencies. */ injection: { /** * @param {array} InjectedEventPluginOrder * @public */ injectEventPluginOrder: EventPluginRegistry.injectEventPluginOrder, /** * @param {object} injectedNamesToPlugins Map from names to plugin modules. */ injectEventPluginsByName: EventPluginRegistry.injectEventPluginsByName }, /** * Stores `listener` at `listenerBank[registrationName][key]`. Is idempotent. * * @param {object} inst The instance, which is the source of events. * @param {string} registrationName Name of listener (e.g. `onClick`). * @param {function} listener The callback to store. */ putListener: function (inst, registrationName, listener) { !(typeof listener === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Expected %s listener to be a function, instead got type %s', registrationName, typeof listener) : _prodInvariant('94', registrationName, typeof listener) : void 0; var key = getDictionaryKey(inst); var bankForRegistrationName = listenerBank[registrationName] || (listenerBank[registrationName] = {}); bankForRegistrationName[key] = listener; var PluginModule = EventPluginRegistry.registrationNameModules[registrationName]; if (PluginModule && PluginModule.didPutListener) { PluginModule.didPutListener(inst, registrationName, listener); } }, /** * @param {object} inst The instance, which is the source of events. * @param {string} registrationName Name of listener (e.g. `onClick`). * @return {?function} The stored callback. */ getListener: function (inst, registrationName) { // TODO: shouldPreventMouseEvent is DOM-specific and definitely should not // live here; needs to be moved to a better place soon var bankForRegistrationName = listenerBank[registrationName]; if (shouldPreventMouseEvent(registrationName, inst._currentElement.type, inst._currentElement.props)) { return null; } var key = getDictionaryKey(inst); return bankForRegistrationName && bankForRegistrationName[key]; }, /** * Deletes a listener from the registration bank. * * @param {object} inst The instance, which is the source of events. * @param {string} registrationName Name of listener (e.g. `onClick`). */ deleteListener: function (inst, registrationName) { var PluginModule = EventPluginRegistry.registrationNameModules[registrationName]; if (PluginModule && PluginModule.willDeleteListener) { PluginModule.willDeleteListener(inst, registrationName); } var bankForRegistrationName = listenerBank[registrationName]; // TODO: This should never be null -- when is it? if (bankForRegistrationName) { var key = getDictionaryKey(inst); delete bankForRegistrationName[key]; } }, /** * Deletes all listeners for the DOM element with the supplied ID. * * @param {object} inst The instance, which is the source of events. */ deleteAllListeners: function (inst) { var key = getDictionaryKey(inst); for (var registrationName in listenerBank) { if (!listenerBank.hasOwnProperty(registrationName)) { continue; } if (!listenerBank[registrationName][key]) { continue; } var PluginModule = EventPluginRegistry.registrationNameModules[registrationName]; if (PluginModule && PluginModule.willDeleteListener) { PluginModule.willDeleteListener(inst, registrationName); } delete listenerBank[registrationName][key]; } }, /** * Allows registered plugins an opportunity to extract events from top-level * native browser events. * * @return {*} An accumulation of synthetic events. * @internal */ extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { var events; var plugins = EventPluginRegistry.plugins; for (var i = 0; i < plugins.length; i++) { // Not every plugin in the ordering may be loaded at runtime. var possiblePlugin = plugins[i]; if (possiblePlugin) { var extractedEvents = possiblePlugin.extractEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget); if (extractedEvents) { events = accumulateInto(events, extractedEvents); } } } return events; }, /** * Enqueues a synthetic event that should be dispatched when * `processEventQueue` is invoked. * * @param {*} events An accumulation of synthetic events. * @internal */ enqueueEvents: function (events) { if (events) { eventQueue = accumulateInto(eventQueue, events); } }, /** * Dispatches all synthetic events on the event queue. * * @internal */ processEventQueue: function (simulated) { // Set `eventQueue` to null before processing it so that we can tell if more // events get enqueued while processing. var processingEventQueue = eventQueue; eventQueue = null; if (simulated) { forEachAccumulated(processingEventQueue, executeDispatchesAndReleaseSimulated); } else { forEachAccumulated(processingEventQueue, executeDispatchesAndReleaseTopLevel); } !!eventQueue ? process.env.NODE_ENV !== 'production' ? invariant(false, 'processEventQueue(): Additional events were enqueued while processing an event queue. Support for this has not yet been implemented.') : _prodInvariant('95') : void 0; // This would be a good time to rethrow if any of the event handlers threw. ReactErrorUtils.rethrowCaughtError(); }, /** * These are needed for tests only. Do not use! */ __purge: function () { listenerBank = {}; }, __getListenerBank: function () { return listenerBank; } }; module.exports = EventPluginHub; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 47 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var _prodInvariant = __webpack_require__(39); var invariant = __webpack_require__(8); /** * Injectable ordering of event plugins. */ var eventPluginOrder = null; /** * Injectable mapping from names to event plugin modules. */ var namesToPlugins = {}; /** * Recomputes the plugin list using the injected plugins and plugin ordering. * * @private */ function recomputePluginOrdering() { if (!eventPluginOrder) { // Wait until an `eventPluginOrder` is injected. return; } for (var pluginName in namesToPlugins) { var pluginModule = namesToPlugins[pluginName]; var pluginIndex = eventPluginOrder.indexOf(pluginName); !(pluginIndex > -1) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginRegistry: Cannot inject event plugins that do not exist in the plugin ordering, `%s`.', pluginName) : _prodInvariant('96', pluginName) : void 0; if (EventPluginRegistry.plugins[pluginIndex]) { continue; } !pluginModule.extractEvents ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginRegistry: Event plugins must implement an `extractEvents` method, but `%s` does not.', pluginName) : _prodInvariant('97', pluginName) : void 0; EventPluginRegistry.plugins[pluginIndex] = pluginModule; var publishedEvents = pluginModule.eventTypes; for (var eventName in publishedEvents) { !publishEventForPlugin(publishedEvents[eventName], pluginModule, eventName) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginRegistry: Failed to publish event `%s` for plugin `%s`.', eventName, pluginName) : _prodInvariant('98', eventName, pluginName) : void 0; } } } /** * Publishes an event so that it can be dispatched by the supplied plugin. * * @param {object} dispatchConfig Dispatch configuration for the event. * @param {object} PluginModule Plugin publishing the event. * @return {boolean} True if the event was successfully published. * @private */ function publishEventForPlugin(dispatchConfig, pluginModule, eventName) { !!EventPluginRegistry.eventNameDispatchConfigs.hasOwnProperty(eventName) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginHub: More than one plugin attempted to publish the same event name, `%s`.', eventName) : _prodInvariant('99', eventName) : void 0; EventPluginRegistry.eventNameDispatchConfigs[eventName] = dispatchConfig; var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames; if (phasedRegistrationNames) { for (var phaseName in phasedRegistrationNames) { if (phasedRegistrationNames.hasOwnProperty(phaseName)) { var phasedRegistrationName = phasedRegistrationNames[phaseName]; publishRegistrationName(phasedRegistrationName, pluginModule, eventName); } } return true; } else if (dispatchConfig.registrationName) { publishRegistrationName(dispatchConfig.registrationName, pluginModule, eventName); return true; } return false; } /** * Publishes a registration name that is used to identify dispatched events and * can be used with `EventPluginHub.putListener` to register listeners. * * @param {string} registrationName Registration name to add. * @param {object} PluginModule Plugin publishing the event. * @private */ function publishRegistrationName(registrationName, pluginModule, eventName) { !!EventPluginRegistry.registrationNameModules[registrationName] ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginHub: More than one plugin attempted to publish the same registration name, `%s`.', registrationName) : _prodInvariant('100', registrationName) : void 0; EventPluginRegistry.registrationNameModules[registrationName] = pluginModule; EventPluginRegistry.registrationNameDependencies[registrationName] = pluginModule.eventTypes[eventName].dependencies; if (process.env.NODE_ENV !== 'production') { var lowerCasedName = registrationName.toLowerCase(); EventPluginRegistry.possibleRegistrationNames[lowerCasedName] = registrationName; if (registrationName === 'onDoubleClick') { EventPluginRegistry.possibleRegistrationNames.ondblclick = registrationName; } } } /** * Registers plugins so that they can extract and dispatch events. * * @see {EventPluginHub} */ var EventPluginRegistry = { /** * Ordered list of injected plugins. */ plugins: [], /** * Mapping from event name to dispatch config */ eventNameDispatchConfigs: {}, /** * Mapping from registration name to plugin module */ registrationNameModules: {}, /** * Mapping from registration name to event name */ registrationNameDependencies: {}, /** * Mapping from lowercase registration names to the properly cased version, * used to warn in the case of missing event handlers. Available * only in __DEV__. * @type {Object} */ possibleRegistrationNames: process.env.NODE_ENV !== 'production' ? {} : null, // Trust the developer to only use possibleRegistrationNames in __DEV__ /** * Injects an ordering of plugins (by plugin name). This allows the ordering * to be decoupled from injection of the actual plugins so that ordering is * always deterministic regardless of packaging, on-the-fly injection, etc. * * @param {array} InjectedEventPluginOrder * @internal * @see {EventPluginHub.injection.injectEventPluginOrder} */ injectEventPluginOrder: function (injectedEventPluginOrder) { !!eventPluginOrder ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginRegistry: Cannot inject event plugin ordering more than once. You are likely trying to load more than one copy of React.') : _prodInvariant('101') : void 0; // Clone the ordering so it cannot be dynamically mutated. eventPluginOrder = Array.prototype.slice.call(injectedEventPluginOrder); recomputePluginOrdering(); }, /** * Injects plugins to be used by `EventPluginHub`. The plugin names must be * in the ordering injected by `injectEventPluginOrder`. * * Plugins can be injected as part of page initialization or on-the-fly. * * @param {object} injectedNamesToPlugins Map from names to plugin modules. * @internal * @see {EventPluginHub.injection.injectEventPluginsByName} */ injectEventPluginsByName: function (injectedNamesToPlugins) { var isOrderingDirty = false; for (var pluginName in injectedNamesToPlugins) { if (!injectedNamesToPlugins.hasOwnProperty(pluginName)) { continue; } var pluginModule = injectedNamesToPlugins[pluginName]; if (!namesToPlugins.hasOwnProperty(pluginName) || namesToPlugins[pluginName] !== pluginModule) { !!namesToPlugins[pluginName] ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginRegistry: Cannot inject two different event plugins using the same name, `%s`.', pluginName) : _prodInvariant('102', pluginName) : void 0; namesToPlugins[pluginName] = pluginModule; isOrderingDirty = true; } } if (isOrderingDirty) { recomputePluginOrdering(); } }, /** * Looks up the plugin for the supplied event. * * @param {object} event A synthetic event. * @return {?object} The plugin that created the supplied event. * @internal */ getPluginModuleForEvent: function (event) { var dispatchConfig = event.dispatchConfig; if (dispatchConfig.registrationName) { return EventPluginRegistry.registrationNameModules[dispatchConfig.registrationName] || null; } if (dispatchConfig.phasedRegistrationNames !== undefined) { // pulling phasedRegistrationNames out of dispatchConfig helps Flow see // that it is not undefined. var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames; for (var phase in phasedRegistrationNames) { if (!phasedRegistrationNames.hasOwnProperty(phase)) { continue; } var pluginModule = EventPluginRegistry.registrationNameModules[phasedRegistrationNames[phase]]; if (pluginModule) { return pluginModule; } } } return null; }, /** * Exposed for unit testing. * @private */ _resetEventPlugins: function () { eventPluginOrder = null; for (var pluginName in namesToPlugins) { if (namesToPlugins.hasOwnProperty(pluginName)) { delete namesToPlugins[pluginName]; } } EventPluginRegistry.plugins.length = 0; var eventNameDispatchConfigs = EventPluginRegistry.eventNameDispatchConfigs; for (var eventName in eventNameDispatchConfigs) { if (eventNameDispatchConfigs.hasOwnProperty(eventName)) { delete eventNameDispatchConfigs[eventName]; } } var registrationNameModules = EventPluginRegistry.registrationNameModules; for (var registrationName in registrationNameModules) { if (registrationNameModules.hasOwnProperty(registrationName)) { delete registrationNameModules[registrationName]; } } if (process.env.NODE_ENV !== 'production') { var possibleRegistrationNames = EventPluginRegistry.possibleRegistrationNames; for (var lowerCasedName in possibleRegistrationNames) { if (possibleRegistrationNames.hasOwnProperty(lowerCasedName)) { delete possibleRegistrationNames[lowerCasedName]; } } } } }; module.exports = EventPluginRegistry; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 48 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(39); var ReactErrorUtils = __webpack_require__(49); var invariant = __webpack_require__(8); var warning = __webpack_require__(11); /** * Injected dependencies: */ /** * - `ComponentTree`: [required] Module that can convert between React instances * and actual node references. */ var ComponentTree; var TreeTraversal; var injection = { injectComponentTree: function (Injected) { ComponentTree = Injected; if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(Injected && Injected.getNodeFromInstance && Injected.getInstanceFromNode, 'EventPluginUtils.injection.injectComponentTree(...): Injected ' + 'module is missing getNodeFromInstance or getInstanceFromNode.') : void 0; } }, injectTreeTraversal: function (Injected) { TreeTraversal = Injected; if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(Injected && Injected.isAncestor && Injected.getLowestCommonAncestor, 'EventPluginUtils.injection.injectTreeTraversal(...): Injected ' + 'module is missing isAncestor or getLowestCommonAncestor.') : void 0; } } }; function isEndish(topLevelType) { return topLevelType === 'topMouseUp' || topLevelType === 'topTouchEnd' || topLevelType === 'topTouchCancel'; } function isMoveish(topLevelType) { return topLevelType === 'topMouseMove' || topLevelType === 'topTouchMove'; } function isStartish(topLevelType) { return topLevelType === 'topMouseDown' || topLevelType === 'topTouchStart'; } var validateEventDispatches; if (process.env.NODE_ENV !== 'production') { validateEventDispatches = function (event) { var dispatchListeners = event._dispatchListeners; var dispatchInstances = event._dispatchInstances; var listenersIsArr = Array.isArray(dispatchListeners); var listenersLen = listenersIsArr ? dispatchListeners.length : dispatchListeners ? 1 : 0; var instancesIsArr = Array.isArray(dispatchInstances); var instancesLen = instancesIsArr ? dispatchInstances.length : dispatchInstances ? 1 : 0; process.env.NODE_ENV !== 'production' ? warning(instancesIsArr === listenersIsArr && instancesLen === listenersLen, 'EventPluginUtils: Invalid `event`.') : void 0; }; } /** * Dispatch the event to the listener. * @param {SyntheticEvent} event SyntheticEvent to handle * @param {boolean} simulated If the event is simulated (changes exn behavior) * @param {function} listener Application-level callback * @param {*} inst Internal component instance */ function executeDispatch(event, simulated, listener, inst) { var type = event.type || 'unknown-event'; event.currentTarget = EventPluginUtils.getNodeFromInstance(inst); if (simulated) { ReactErrorUtils.invokeGuardedCallbackWithCatch(type, listener, event); } else { ReactErrorUtils.invokeGuardedCallback(type, listener, event); } event.currentTarget = null; } /** * Standard/simple iteration through an event's collected dispatches. */ function executeDispatchesInOrder(event, simulated) { var dispatchListeners = event._dispatchListeners; var dispatchInstances = event._dispatchInstances; if (process.env.NODE_ENV !== 'production') { validateEventDispatches(event); } if (Array.isArray(dispatchListeners)) { for (var i = 0; i < dispatchListeners.length; i++) { if (event.isPropagationStopped()) { break; } // Listeners and Instances are two parallel arrays that are always in sync. executeDispatch(event, simulated, dispatchListeners[i], dispatchInstances[i]); } } else if (dispatchListeners) { executeDispatch(event, simulated, dispatchListeners, dispatchInstances); } event._dispatchListeners = null; event._dispatchInstances = null; } /** * Standard/simple iteration through an event's collected dispatches, but stops * at the first dispatch execution returning true, and returns that id. * * @return {?string} id of the first dispatch execution who's listener returns * true, or null if no listener returned true. */ function executeDispatchesInOrderStopAtTrueImpl(event) { var dispatchListeners = event._dispatchListeners; var dispatchInstances = event._dispatchInstances; if (process.env.NODE_ENV !== 'production') { validateEventDispatches(event); } if (Array.isArray(dispatchListeners)) { for (var i = 0; i < dispatchListeners.length; i++) { if (event.isPropagationStopped()) { break; } // Listeners and Instances are two parallel arrays that are always in sync. if (dispatchListeners[i](event, dispatchInstances[i])) { return dispatchInstances[i]; } } } else if (dispatchListeners) { if (dispatchListeners(event, dispatchInstances)) { return dispatchInstances; } } return null; } /** * @see executeDispatchesInOrderStopAtTrueImpl */ function executeDispatchesInOrderStopAtTrue(event) { var ret = executeDispatchesInOrderStopAtTrueImpl(event); event._dispatchInstances = null; event._dispatchListeners = null; return ret; } /** * Execution of a "direct" dispatch - there must be at most one dispatch * accumulated on the event or it is considered an error. It doesn't really make * sense for an event with multiple dispatches (bubbled) to keep track of the * return values at each dispatch execution, but it does tend to make sense when * dealing with "direct" dispatches. * * @return {*} The return value of executing the single dispatch. */ function executeDirectDispatch(event) { if (process.env.NODE_ENV !== 'production') { validateEventDispatches(event); } var dispatchListener = event._dispatchListeners; var dispatchInstance = event._dispatchInstances; !!Array.isArray(dispatchListener) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'executeDirectDispatch(...): Invalid `event`.') : _prodInvariant('103') : void 0; event.currentTarget = dispatchListener ? EventPluginUtils.getNodeFromInstance(dispatchInstance) : null; var res = dispatchListener ? dispatchListener(event) : null; event.currentTarget = null; event._dispatchListeners = null; event._dispatchInstances = null; return res; } /** * @param {SyntheticEvent} event * @return {boolean} True iff number of dispatches accumulated is greater than 0. */ function hasDispatches(event) { return !!event._dispatchListeners; } /** * General utilities that are useful in creating custom Event Plugins. */ var EventPluginUtils = { isEndish: isEndish, isMoveish: isMoveish, isStartish: isStartish, executeDirectDispatch: executeDirectDispatch, executeDispatchesInOrder: executeDispatchesInOrder, executeDispatchesInOrderStopAtTrue: executeDispatchesInOrderStopAtTrue, hasDispatches: hasDispatches, getInstanceFromNode: function (node) { return ComponentTree.getInstanceFromNode(node); }, getNodeFromInstance: function (node) { return ComponentTree.getNodeFromInstance(node); }, isAncestor: function (a, b) { return TreeTraversal.isAncestor(a, b); }, getLowestCommonAncestor: function (a, b) { return TreeTraversal.getLowestCommonAncestor(a, b); }, getParentInstance: function (inst) { return TreeTraversal.getParentInstance(inst); }, traverseTwoPhase: function (target, fn, arg) { return TreeTraversal.traverseTwoPhase(target, fn, arg); }, traverseEnterLeave: function (from, to, fn, argFrom, argTo) { return TreeTraversal.traverseEnterLeave(from, to, fn, argFrom, argTo); }, injection: injection }; module.exports = EventPluginUtils; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 49 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var caughtError = null; /** * Call a function while guarding against errors that happens within it. * * @param {String} name of the guard to use for logging or debugging * @param {Function} func The function to invoke * @param {*} a First argument * @param {*} b Second argument */ function invokeGuardedCallback(name, func, a) { try { func(a); } catch (x) { if (caughtError === null) { caughtError = x; } } } var ReactErrorUtils = { invokeGuardedCallback: invokeGuardedCallback, /** * Invoked by ReactTestUtils.Simulate so that any errors thrown by the event * handler are sure to be rethrown by rethrowCaughtError. */ invokeGuardedCallbackWithCatch: invokeGuardedCallback, /** * During execution of guarded functions we will capture the first error which * we will rethrow to be handled by the top level error handler. */ rethrowCaughtError: function () { if (caughtError) { var error = caughtError; caughtError = null; throw error; } } }; if (process.env.NODE_ENV !== 'production') { /** * To help development we can get better devtools integration by simulating a * real browser event. */ if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function' && typeof document !== 'undefined' && typeof document.createEvent === 'function') { var fakeNode = document.createElement('react'); ReactErrorUtils.invokeGuardedCallback = function (name, func, a) { var boundFunc = func.bind(null, a); var evtType = 'react-' + name; fakeNode.addEventListener(evtType, boundFunc, false); var evt = document.createEvent('Event'); evt.initEvent(evtType, false, false); fakeNode.dispatchEvent(evt); fakeNode.removeEventListener(evtType, boundFunc, false); }; } } module.exports = ReactErrorUtils; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 50 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var _prodInvariant = __webpack_require__(39); var invariant = __webpack_require__(8); /** * Accumulates items that must not be null or undefined into the first one. This * is used to conserve memory by avoiding array allocations, and thus sacrifices * API cleanness. Since `current` can be null before being passed in and not * null after this function, make sure to assign it back to `current`: * * `a = accumulateInto(a, b);` * * This API should be sparingly used. Try `accumulate` for something cleaner. * * @return {*|array<*>} An accumulation of items. */ function accumulateInto(current, next) { !(next != null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'accumulateInto(...): Accumulated items must not be null or undefined.') : _prodInvariant('30') : void 0; if (current == null) { return next; } // Both are not empty. Warning: Never call x.concat(y) when you are not // certain that x is an Array (x could be a string with concat method). if (Array.isArray(current)) { if (Array.isArray(next)) { current.push.apply(current, next); return current; } current.push(next); return current; } if (Array.isArray(next)) { // A bit too dangerous to mutate `next`. return [current].concat(next); } return [current, next]; } module.exports = accumulateInto; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 51 */ /***/ (function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; /** * @param {array} arr an "accumulation" of items which is either an Array or * a single item. Useful when paired with the `accumulate` module. This is a * simple utility that allows us to reason about a collection of items, but * handling the case when there is exactly one item (and we do not need to * allocate an array). */ function forEachAccumulated(arr, cb, scope) { if (Array.isArray(arr)) { arr.forEach(cb, scope); } else if (arr) { cb.call(scope, arr); } } module.exports = forEachAccumulated; /***/ }), /* 52 */ /***/ (function(module, exports) { /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var canUseDOM = !!(typeof window !== 'undefined' && window.document && window.document.createElement); /** * Simple, lightweight module assisting with the detection and context of * Worker. Helps avoid circular dependencies and allows code to reason about * whether or not they are in a Worker, even if they never include the main * `ReactWorker` dependency. */ var ExecutionEnvironment = { canUseDOM: canUseDOM, canUseWorkers: typeof Worker !== 'undefined', canUseEventListeners: canUseDOM && !!(window.addEventListener || window.attachEvent), canUseViewport: canUseDOM && !!window.screen, isInWorker: !canUseDOM // For now, this is true - might change in the future. }; module.exports = ExecutionEnvironment; /***/ }), /* 53 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _assign = __webpack_require__(4); var PooledClass = __webpack_require__(54); var getTextContentAccessor = __webpack_require__(55); /** * This helper class stores information about text content of a target node, * allowing comparison of content before and after a given event. * * Identify the node where selection currently begins, then observe * both its text content and its current position in the DOM. Since the * browser may natively replace the target node during composition, we can * use its position to find its replacement. * * @param {DOMEventTarget} root */ function FallbackCompositionState(root) { this._root = root; this._startText = this.getText(); this._fallbackText = null; } _assign(FallbackCompositionState.prototype, { destructor: function () { this._root = null; this._startText = null; this._fallbackText = null; }, /** * Get current text of input. * * @return {string} */ getText: function () { if ('value' in this._root) { return this._root.value; } return this._root[getTextContentAccessor()]; }, /** * Determine the differing substring between the initially stored * text content and the current content. * * @return {string} */ getData: function () { if (this._fallbackText) { return this._fallbackText; } var start; var startValue = this._startText; var startLength = startValue.length; var end; var endValue = this.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 : undefined; this._fallbackText = endValue.slice(start, sliceTail); return this._fallbackText; } }); PooledClass.addPoolingTo(FallbackCompositionState); module.exports = FallbackCompositionState; /***/ }), /* 54 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var _prodInvariant = __webpack_require__(39); var invariant = __webpack_require__(8); /** * Static poolers. Several custom versions for each potential number of * arguments. A completely generic pooler is easy to implement, but would * require accessing the `arguments` object. In each of these, `this` refers to * the Class itself, not an instance. If any others are needed, simply add them * here, or in their own files. */ var oneArgumentPooler = function (copyFieldsFrom) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, copyFieldsFrom); return instance; } else { return new Klass(copyFieldsFrom); } }; var twoArgumentPooler = function (a1, a2) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, a1, a2); return instance; } else { return new Klass(a1, a2); } }; var threeArgumentPooler = function (a1, a2, a3) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, a1, a2, a3); return instance; } else { return new Klass(a1, a2, a3); } }; var fourArgumentPooler = function (a1, a2, a3, a4) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, a1, a2, a3, a4); return instance; } else { return new Klass(a1, a2, a3, a4); } }; var standardReleaser = function (instance) { var Klass = this; !(instance instanceof Klass) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Trying to release an instance into a pool of a different type.') : _prodInvariant('25') : void 0; instance.destructor(); if (Klass.instancePool.length < Klass.poolSize) { Klass.instancePool.push(instance); } }; var DEFAULT_POOL_SIZE = 10; var DEFAULT_POOLER = oneArgumentPooler; /** * Augments `CopyConstructor` to be a poolable class, augmenting only the class * itself (statically) not adding any prototypical fields. Any CopyConstructor * you give this may have a `poolSize` property, and will look for a * prototypical `destructor` on instances. * * @param {Function} CopyConstructor Constructor that can be used to reset. * @param {Function} pooler Customizable pooler. */ var addPoolingTo = function (CopyConstructor, pooler) { // Casting as any so that flow ignores the actual implementation and trusts // it to match the type we declared var NewKlass = CopyConstructor; NewKlass.instancePool = []; NewKlass.getPooled = pooler || DEFAULT_POOLER; if (!NewKlass.poolSize) { NewKlass.poolSize = DEFAULT_POOL_SIZE; } NewKlass.release = standardReleaser; return NewKlass; }; var PooledClass = { addPoolingTo: addPoolingTo, oneArgumentPooler: oneArgumentPooler, twoArgumentPooler: twoArgumentPooler, threeArgumentPooler: threeArgumentPooler, fourArgumentPooler: fourArgumentPooler }; module.exports = PooledClass; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 55 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var ExecutionEnvironment = __webpack_require__(52); var contentKey = null; /** * Gets the key used to access text content on a DOM node. * * @return {?string} Key used to access text content. * @internal */ function getTextContentAccessor() { if (!contentKey && ExecutionEnvironment.canUseDOM) { // Prefer textContent to innerText because many browsers support both but // SVG <text> elements don't support innerText even when <div> does. contentKey = 'textContent' in document.documentElement ? 'textContent' : 'innerText'; } return contentKey; } module.exports = getTextContentAccessor; /***/ }), /* 56 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var SyntheticEvent = __webpack_require__(57); /** * @interface Event * @see http://www.w3.org/TR/DOM-Level-3-Events/#events-compositionevents */ var CompositionEventInterface = { data: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticCompositionEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticEvent.augmentClass(SyntheticCompositionEvent, CompositionEventInterface); module.exports = SyntheticCompositionEvent; /***/ }), /* 57 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _assign = __webpack_require__(4); var PooledClass = __webpack_require__(54); var emptyFunction = __webpack_require__(12); var warning = __webpack_require__(11); var didWarnForAddedNewProperty = false; var isProxySupported = typeof Proxy === 'function'; var shouldBeReleasedProperties = ['dispatchConfig', '_targetInst', 'nativeEvent', 'isDefaultPrevented', 'isPropagationStopped', '_dispatchListeners', '_dispatchInstances']; /** * @interface Event * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var EventInterface = { type: null, target: null, // currentTarget is set when dispatching; no use in copying it here currentTarget: emptyFunction.thatReturnsNull, eventPhase: null, bubbles: null, cancelable: null, timeStamp: function (event) { return event.timeStamp || Date.now(); }, defaultPrevented: null, isTrusted: null }; /** * Synthetic events are dispatched by event plugins, typically in response to a * top-level event delegation handler. * * These systems should generally use pooling to reduce the frequency of garbage * collection. The system should check `isPersistent` to determine whether the * event should be released into the pool after being dispatched. Users that * need a persisted event should invoke `persist`. * * Synthetic events (and subclasses) implement the DOM Level 3 Events API by * normalizing browser quirks. Subclasses do not necessarily have to implement a * DOM interface; custom application-specific events can also subclass this. * * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {*} targetInst Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @param {DOMEventTarget} nativeEventTarget Target node. */ function SyntheticEvent(dispatchConfig, targetInst, nativeEvent, nativeEventTarget) { if (process.env.NODE_ENV !== 'production') { // these have a getter/setter for warnings delete this.nativeEvent; delete this.preventDefault; delete this.stopPropagation; } this.dispatchConfig = dispatchConfig; this._targetInst = targetInst; this.nativeEvent = nativeEvent; var Interface = this.constructor.Interface; for (var propName in Interface) { if (!Interface.hasOwnProperty(propName)) { continue; } if (process.env.NODE_ENV !== 'production') { delete this[propName]; // this has a getter/setter for warnings } var normalize = Interface[propName]; if (normalize) { this[propName] = normalize(nativeEvent); } else { if (propName === 'target') { this.target = nativeEventTarget; } else { this[propName] = nativeEvent[propName]; } } } var defaultPrevented = nativeEvent.defaultPrevented != null ? nativeEvent.defaultPrevented : nativeEvent.returnValue === false; if (defaultPrevented) { this.isDefaultPrevented = emptyFunction.thatReturnsTrue; } else { this.isDefaultPrevented = emptyFunction.thatReturnsFalse; } this.isPropagationStopped = emptyFunction.thatReturnsFalse; return this; } _assign(SyntheticEvent.prototype, { preventDefault: function () { this.defaultPrevented = true; var event = this.nativeEvent; if (!event) { return; } if (event.preventDefault) { event.preventDefault(); } else if (typeof event.returnValue !== 'unknown') { // eslint-disable-line valid-typeof event.returnValue = false; } this.isDefaultPrevented = emptyFunction.thatReturnsTrue; }, stopPropagation: function () { var event = this.nativeEvent; if (!event) { return; } if (event.stopPropagation) { event.stopPropagation(); } else if (typeof event.cancelBubble !== 'unknown') { // eslint-disable-line valid-typeof // The ChangeEventPlugin registers a "propertychange" event for // IE. This event does not support bubbling or cancelling, and // any references to cancelBubble throw "Member not found". A // typeof check of "unknown" circumvents this issue (and is also // IE specific). event.cancelBubble = true; } this.isPropagationStopped = emptyFunction.thatReturnsTrue; }, /** * We release all dispatched `SyntheticEvent`s after each event loop, adding * them back into the pool. This allows a way to hold onto a reference that * won't be added back into the pool. */ persist: function () { this.isPersistent = emptyFunction.thatReturnsTrue; }, /** * Checks if this event should be released back into the pool. * * @return {boolean} True if this should not be released, false otherwise. */ isPersistent: emptyFunction.thatReturnsFalse, /** * `PooledClass` looks for `destructor` on each instance it releases. */ destructor: function () { var Interface = this.constructor.Interface; for (var propName in Interface) { if (process.env.NODE_ENV !== 'production') { Object.defineProperty(this, propName, getPooledWarningPropertyDefinition(propName, Interface[propName])); } else { this[propName] = null; } } for (var i = 0; i < shouldBeReleasedProperties.length; i++) { this[shouldBeReleasedProperties[i]] = null; } if (process.env.NODE_ENV !== 'production') { Object.defineProperty(this, 'nativeEvent', getPooledWarningPropertyDefinition('nativeEvent', null)); Object.defineProperty(this, 'preventDefault', getPooledWarningPropertyDefinition('preventDefault', emptyFunction)); Object.defineProperty(this, 'stopPropagation', getPooledWarningPropertyDefinition('stopPropagation', emptyFunction)); } } }); SyntheticEvent.Interface = EventInterface; if (process.env.NODE_ENV !== 'production') { if (isProxySupported) { /*eslint-disable no-func-assign */ SyntheticEvent = new Proxy(SyntheticEvent, { construct: function (target, args) { return this.apply(target, Object.create(target.prototype), args); }, apply: function (constructor, that, args) { return new Proxy(constructor.apply(that, args), { set: function (target, prop, value) { if (prop !== 'isPersistent' && !target.constructor.Interface.hasOwnProperty(prop) && shouldBeReleasedProperties.indexOf(prop) === -1) { process.env.NODE_ENV !== 'production' ? warning(didWarnForAddedNewProperty || target.isPersistent(), 'This synthetic event is reused for performance reasons. If you\'re ' + 'seeing this, you\'re adding a new property in the synthetic event object. ' + 'The property is never released. See ' + 'https://fb.me/react-event-pooling for more information.') : void 0; didWarnForAddedNewProperty = true; } target[prop] = value; return true; } }); } }); /*eslint-enable no-func-assign */ } } /** * Helper to reduce boilerplate when creating subclasses. * * @param {function} Class * @param {?object} Interface */ SyntheticEvent.augmentClass = function (Class, Interface) { var Super = this; var E = function () {}; E.prototype = Super.prototype; var prototype = new E(); _assign(prototype, Class.prototype); Class.prototype = prototype; Class.prototype.constructor = Class; Class.Interface = _assign({}, Super.Interface, Interface); Class.augmentClass = Super.augmentClass; PooledClass.addPoolingTo(Class, PooledClass.fourArgumentPooler); }; PooledClass.addPoolingTo(SyntheticEvent, PooledClass.fourArgumentPooler); module.exports = SyntheticEvent; /** * Helper to nullify syntheticEvent instance properties when destructing * * @param {object} SyntheticEvent * @param {String} propName * @return {object} defineProperty object */ function getPooledWarningPropertyDefinition(propName, getVal) { var isFunction = typeof getVal === 'function'; return { configurable: true, set: set, get: get }; function set(val) { var action = isFunction ? 'setting the method' : 'setting the property'; warn(action, 'This is effectively a no-op'); return val; } function get() { var action = isFunction ? 'accessing the method' : 'accessing the property'; var result = isFunction ? 'This is a no-op function' : 'This is set to null'; warn(action, result); return getVal; } function warn(action, result) { var warningCondition = false; process.env.NODE_ENV !== 'production' ? warning(warningCondition, 'This synthetic event is reused for performance reasons. If you\'re seeing this, ' + 'you\'re %s `%s` on a released/nullified synthetic event. %s. ' + 'If you must keep the original synthetic event around, use event.persist(). ' + 'See https://fb.me/react-event-pooling for more information.', action, propName, result) : void 0; } } /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 58 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var SyntheticEvent = __webpack_require__(57); /** * @interface Event * @see http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105 * /#events-inputevents */ var InputEventInterface = { data: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticInputEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticEvent.augmentClass(SyntheticInputEvent, InputEventInterface); module.exports = SyntheticInputEvent; /***/ }), /* 59 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var EventPluginHub = __webpack_require__(46); var EventPropagators = __webpack_require__(45); var ExecutionEnvironment = __webpack_require__(52); var ReactDOMComponentTree = __webpack_require__(38); var ReactUpdates = __webpack_require__(60); var SyntheticEvent = __webpack_require__(57); var getEventTarget = __webpack_require__(73); var isEventSupported = __webpack_require__(74); var isTextInputElement = __webpack_require__(75); var eventTypes = { change: { phasedRegistrationNames: { bubbled: 'onChange', captured: 'onChangeCapture' }, dependencies: ['topBlur', 'topChange', 'topClick', 'topFocus', 'topInput', 'topKeyDown', 'topKeyUp', 'topSelectionChange'] } }; /** * For IE shims */ var activeElement = null; var activeElementInst = null; var activeElementValue = null; var activeElementValueProp = null; /** * SECTION: handle `change` event */ function shouldUseChangeEvent(elem) { var nodeName = elem.nodeName && elem.nodeName.toLowerCase(); return nodeName === 'select' || nodeName === 'input' && elem.type === 'file'; } var doesChangeEventBubble = false; if (ExecutionEnvironment.canUseDOM) { // See `handleChange` comment below doesChangeEventBubble = isEventSupported('change') && (!document.documentMode || document.documentMode > 8); } function manualDispatchChangeEvent(nativeEvent) { var event = SyntheticEvent.getPooled(eventTypes.change, activeElementInst, nativeEvent, getEventTarget(nativeEvent)); EventPropagators.accumulateTwoPhaseDispatches(event); // If change and propertychange bubbled, we'd just bind to it like all the // other events and have it go through ReactBrowserEventEmitter. Since it // doesn't, we manually listen for the events and so we have to enqueue and // process the abstract event manually. // // Batching is necessary here in order to ensure that all event handlers run // before the next rerender (including event handlers attached to ancestor // elements instead of directly on the input). Without this, controlled // components don't work properly in conjunction with event bubbling because // the component is rerendered and the value reverted before all the event // handlers can run. See https://github.com/facebook/react/issues/708. ReactUpdates.batchedUpdates(runEventInBatch, event); } function runEventInBatch(event) { EventPluginHub.enqueueEvents(event); EventPluginHub.processEventQueue(false); } function startWatchingForChangeEventIE8(target, targetInst) { activeElement = target; activeElementInst = targetInst; activeElement.attachEvent('onchange', manualDispatchChangeEvent); } function stopWatchingForChangeEventIE8() { if (!activeElement) { return; } activeElement.detachEvent('onchange', manualDispatchChangeEvent); activeElement = null; activeElementInst = null; } function getTargetInstForChangeEvent(topLevelType, targetInst) { if (topLevelType === 'topChange') { return targetInst; } } function handleEventsForChangeEventIE8(topLevelType, target, targetInst) { if (topLevelType === 'topFocus') { // stopWatching() should be a noop here but we call it just in case we // missed a blur event somehow. stopWatchingForChangeEventIE8(); startWatchingForChangeEventIE8(target, targetInst); } else if (topLevelType === 'topBlur') { stopWatchingForChangeEventIE8(); } } /** * SECTION: handle `input` event */ var isInputEventSupported = false; if (ExecutionEnvironment.canUseDOM) { // IE9 claims to support the input event but fails to trigger it when // deleting text, so we ignore its input events. // IE10+ fire input events to often, such when a placeholder // changes or when an input with a placeholder is focused. isInputEventSupported = isEventSupported('input') && (!document.documentMode || document.documentMode > 11); } /** * (For IE <=11) Replacement getter/setter for the `value` property that gets * set on the active element. */ var newValueProp = { get: function () { return activeElementValueProp.get.call(this); }, set: function (val) { // Cast to a string so we can do equality checks. activeElementValue = '' + val; activeElementValueProp.set.call(this, val); } }; /** * (For IE <=11) Starts tracking propertychange events on the passed-in element * and override the value property so that we can distinguish user events from * value changes in JS. */ function startWatchingForValueChange(target, targetInst) { activeElement = target; activeElementInst = targetInst; activeElementValue = target.value; activeElementValueProp = Object.getOwnPropertyDescriptor(target.constructor.prototype, 'value'); // Not guarded in a canDefineProperty check: IE8 supports defineProperty only // on DOM elements Object.defineProperty(activeElement, 'value', newValueProp); if (activeElement.attachEvent) { activeElement.attachEvent('onpropertychange', handlePropertyChange); } else { activeElement.addEventListener('propertychange', handlePropertyChange, false); } } /** * (For IE <=11) Removes the event listeners from the currently-tracked element, * if any exists. */ function stopWatchingForValueChange() { if (!activeElement) { return; } // delete restores the original property definition delete activeElement.value; if (activeElement.detachEvent) { activeElement.detachEvent('onpropertychange', handlePropertyChange); } else { activeElement.removeEventListener('propertychange', handlePropertyChange, false); } activeElement = null; activeElementInst = null; activeElementValue = null; activeElementValueProp = null; } /** * (For IE <=11) Handles a propertychange event, sending a `change` event if * the value of the active element has changed. */ function handlePropertyChange(nativeEvent) { if (nativeEvent.propertyName !== 'value') { return; } var value = nativeEvent.srcElement.value; if (value === activeElementValue) { return; } activeElementValue = value; manualDispatchChangeEvent(nativeEvent); } /** * If a `change` event should be fired, returns the target's ID. */ function getTargetInstForInputEvent(topLevelType, targetInst) { if (topLevelType === 'topInput') { // In modern browsers (i.e., not IE8 or IE9), the input event is exactly // what we want so fall through here and trigger an abstract event return targetInst; } } function handleEventsForInputEventIE(topLevelType, target, targetInst) { if (topLevelType === 'topFocus') { // In IE8, we can capture almost all .value changes by adding a // propertychange handler and looking for events with propertyName // equal to 'value' // In IE9-11, propertychange fires for most input events but is buggy and // doesn't fire when text is deleted, but conveniently, selectionchange // appears to fire in all of the remaining cases so we catch those and // forward the event if the value has changed // In either case, we don't want to call the event handler if the value // is changed from JS so we redefine a setter for `.value` that updates // our activeElementValue variable, allowing us to ignore those changes // // stopWatching() should be a noop here but we call it just in case we // missed a blur event somehow. stopWatchingForValueChange(); startWatchingForValueChange(target, targetInst); } else if (topLevelType === 'topBlur') { stopWatchingForValueChange(); } } // For IE8 and IE9. function getTargetInstForInputEventIE(topLevelType, targetInst) { if (topLevelType === 'topSelectionChange' || topLevelType === 'topKeyUp' || topLevelType === 'topKeyDown') { // On the selectionchange event, the target is just document which isn't // helpful for us so just check activeElement instead. // // 99% of the time, keydown and keyup aren't necessary. IE8 fails to fire // propertychange on the first input event after setting `value` from a // script and fires only keydown, keypress, keyup. Catching keyup usually // gets it and catching keydown lets us fire an event for the first // keystroke if user does a key repeat (it'll be a little delayed: right // before the second keystroke). Other input methods (e.g., paste) seem to // fire selectionchange normally. if (activeElement && activeElement.value !== activeElementValue) { activeElementValue = activeElement.value; return activeElementInst; } } } /** * SECTION: handle `click` event */ function shouldUseClickEvent(elem) { // Use the `click` event to detect changes to checkbox and radio inputs. // This approach works across all browsers, whereas `change` does not fire // until `blur` in IE8. return elem.nodeName && elem.nodeName.toLowerCase() === 'input' && (elem.type === 'checkbox' || elem.type === 'radio'); } function getTargetInstForClickEvent(topLevelType, targetInst) { if (topLevelType === 'topClick') { return targetInst; } } function handleControlledInputBlur(inst, node) { // TODO: In IE, inst is occasionally null. Why? if (inst == null) { return; } // Fiber and ReactDOM keep wrapper state in separate places var state = inst._wrapperState || node._wrapperState; if (!state || !state.controlled || node.type !== 'number') { return; } // If controlled, assign the value attribute to the current value on blur var value = '' + node.value; if (node.getAttribute('value') !== value) { node.setAttribute('value', value); } } /** * This plugin creates an `onChange` event that normalizes change events * across form elements. This event fires at a time when it's possible to * change the element's value without seeing a flicker. * * Supported elements are: * - input (see `isTextInputElement`) * - textarea * - select */ var ChangeEventPlugin = { eventTypes: eventTypes, extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { var targetNode = targetInst ? ReactDOMComponentTree.getNodeFromInstance(targetInst) : window; var getTargetInstFunc, handleEventFunc; if (shouldUseChangeEvent(targetNode)) { if (doesChangeEventBubble) { getTargetInstFunc = getTargetInstForChangeEvent; } else { handleEventFunc = handleEventsForChangeEventIE8; } } else if (isTextInputElement(targetNode)) { if (isInputEventSupported) { getTargetInstFunc = getTargetInstForInputEvent; } else { getTargetInstFunc = getTargetInstForInputEventIE; handleEventFunc = handleEventsForInputEventIE; } } else if (shouldUseClickEvent(targetNode)) { getTargetInstFunc = getTargetInstForClickEvent; } if (getTargetInstFunc) { var inst = getTargetInstFunc(topLevelType, targetInst); if (inst) { var event = SyntheticEvent.getPooled(eventTypes.change, inst, nativeEvent, nativeEventTarget); event.type = 'change'; EventPropagators.accumulateTwoPhaseDispatches(event); return event; } } if (handleEventFunc) { handleEventFunc(topLevelType, targetNode, targetInst); } // When blurring, set the value attribute for number inputs if (topLevelType === 'topBlur') { handleControlledInputBlur(targetInst, targetNode); } } }; module.exports = ChangeEventPlugin; /***/ }), /* 60 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(39), _assign = __webpack_require__(4); var CallbackQueue = __webpack_require__(61); var PooledClass = __webpack_require__(54); var ReactFeatureFlags = __webpack_require__(62); var ReactReconciler = __webpack_require__(63); var Transaction = __webpack_require__(72); var invariant = __webpack_require__(8); var dirtyComponents = []; var updateBatchNumber = 0; var asapCallbackQueue = CallbackQueue.getPooled(); var asapEnqueued = false; var batchingStrategy = null; function ensureInjected() { !(ReactUpdates.ReactReconcileTransaction && batchingStrategy) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates: must inject a reconcile transaction class and batching strategy') : _prodInvariant('123') : void 0; } var NESTED_UPDATES = { initialize: function () { this.dirtyComponentsLength = dirtyComponents.length; }, close: function () { if (this.dirtyComponentsLength !== dirtyComponents.length) { // Additional updates were enqueued by componentDidUpdate handlers or // similar; before our own UPDATE_QUEUEING wrapper closes, we want to run // these new updates so that if A's componentDidUpdate calls setState on // B, B will update before the callback A's updater provided when calling // setState. dirtyComponents.splice(0, this.dirtyComponentsLength); flushBatchedUpdates(); } else { dirtyComponents.length = 0; } } }; var UPDATE_QUEUEING = { initialize: function () { this.callbackQueue.reset(); }, close: function () { this.callbackQueue.notifyAll(); } }; var TRANSACTION_WRAPPERS = [NESTED_UPDATES, UPDATE_QUEUEING]; function ReactUpdatesFlushTransaction() { this.reinitializeTransaction(); this.dirtyComponentsLength = null; this.callbackQueue = CallbackQueue.getPooled(); this.reconcileTransaction = ReactUpdates.ReactReconcileTransaction.getPooled( /* useCreateElement */true); } _assign(ReactUpdatesFlushTransaction.prototype, Transaction, { getTransactionWrappers: function () { return TRANSACTION_WRAPPERS; }, destructor: function () { this.dirtyComponentsLength = null; CallbackQueue.release(this.callbackQueue); this.callbackQueue = null; ReactUpdates.ReactReconcileTransaction.release(this.reconcileTransaction); this.reconcileTransaction = null; }, perform: function (method, scope, a) { // Essentially calls `this.reconcileTransaction.perform(method, scope, a)` // with this transaction's wrappers around it. return Transaction.perform.call(this, this.reconcileTransaction.perform, this.reconcileTransaction, method, scope, a); } }); PooledClass.addPoolingTo(ReactUpdatesFlushTransaction); function batchedUpdates(callback, a, b, c, d, e) { ensureInjected(); return batchingStrategy.batchedUpdates(callback, a, b, c, d, e); } /** * Array comparator for ReactComponents by mount ordering. * * @param {ReactComponent} c1 first component you're comparing * @param {ReactComponent} c2 second component you're comparing * @return {number} Return value usable by Array.prototype.sort(). */ function mountOrderComparator(c1, c2) { return c1._mountOrder - c2._mountOrder; } function runBatchedUpdates(transaction) { var len = transaction.dirtyComponentsLength; !(len === dirtyComponents.length) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Expected flush transaction\'s stored dirty-components length (%s) to match dirty-components array length (%s).', len, dirtyComponents.length) : _prodInvariant('124', len, dirtyComponents.length) : void 0; // Since reconciling a component higher in the owner hierarchy usually (not // always -- see shouldComponentUpdate()) will reconcile children, reconcile // them before their children by sorting the array. dirtyComponents.sort(mountOrderComparator); // Any updates enqueued while reconciling must be performed after this entire // batch. Otherwise, if dirtyComponents is [A, B] where A has children B and // C, B could update twice in a single batch if C's render enqueues an update // to B (since B would have already updated, we should skip it, and the only // way we can know to do so is by checking the batch counter). updateBatchNumber++; for (var i = 0; i < len; i++) { // If a component is unmounted before pending changes apply, it will still // be here, but we assume that it has cleared its _pendingCallbacks and // that performUpdateIfNecessary is a noop. var component = dirtyComponents[i]; // If performUpdateIfNecessary happens to enqueue any new updates, we // shouldn't execute the callbacks until the next render happens, so // stash the callbacks first var callbacks = component._pendingCallbacks; component._pendingCallbacks = null; var markerName; if (ReactFeatureFlags.logTopLevelRenders) { var namedComponent = component; // Duck type TopLevelWrapper. This is probably always true. if (component._currentElement.type.isReactTopLevelWrapper) { namedComponent = component._renderedComponent; } markerName = 'React update: ' + namedComponent.getName(); console.time(markerName); } ReactReconciler.performUpdateIfNecessary(component, transaction.reconcileTransaction, updateBatchNumber); if (markerName) { console.timeEnd(markerName); } if (callbacks) { for (var j = 0; j < callbacks.length; j++) { transaction.callbackQueue.enqueue(callbacks[j], component.getPublicInstance()); } } } } var flushBatchedUpdates = function () { // ReactUpdatesFlushTransaction's wrappers will clear the dirtyComponents // array and perform any updates enqueued by mount-ready handlers (i.e., // componentDidUpdate) but we need to check here too in order to catch // updates enqueued by setState callbacks and asap calls. while (dirtyComponents.length || asapEnqueued) { if (dirtyComponents.length) { var transaction = ReactUpdatesFlushTransaction.getPooled(); transaction.perform(runBatchedUpdates, null, transaction); ReactUpdatesFlushTransaction.release(transaction); } if (asapEnqueued) { asapEnqueued = false; var queue = asapCallbackQueue; asapCallbackQueue = CallbackQueue.getPooled(); queue.notifyAll(); CallbackQueue.release(queue); } } }; /** * Mark a component as needing a rerender, adding an optional callback to a * list of functions which will be executed once the rerender occurs. */ function enqueueUpdate(component) { ensureInjected(); // Various parts of our code (such as ReactCompositeComponent's // _renderValidatedComponent) assume that calls to render aren't nested; // verify that that's the case. (This is called by each top-level update // function, like setState, forceUpdate, etc.; creation and // destruction of top-level components is guarded in ReactMount.) if (!batchingStrategy.isBatchingUpdates) { batchingStrategy.batchedUpdates(enqueueUpdate, component); return; } dirtyComponents.push(component); if (component._updateBatchNumber == null) { component._updateBatchNumber = updateBatchNumber + 1; } } /** * Enqueue a callback to be run at the end of the current batching cycle. Throws * if no updates are currently being performed. */ function asap(callback, context) { !batchingStrategy.isBatchingUpdates ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates.asap: Can\'t enqueue an asap callback in a context whereupdates are not being batched.') : _prodInvariant('125') : void 0; asapCallbackQueue.enqueue(callback, context); asapEnqueued = true; } var ReactUpdatesInjection = { injectReconcileTransaction: function (ReconcileTransaction) { !ReconcileTransaction ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates: must provide a reconcile transaction class') : _prodInvariant('126') : void 0; ReactUpdates.ReactReconcileTransaction = ReconcileTransaction; }, injectBatchingStrategy: function (_batchingStrategy) { !_batchingStrategy ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates: must provide a batching strategy') : _prodInvariant('127') : void 0; !(typeof _batchingStrategy.batchedUpdates === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates: must provide a batchedUpdates() function') : _prodInvariant('128') : void 0; !(typeof _batchingStrategy.isBatchingUpdates === 'boolean') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates: must provide an isBatchingUpdates boolean attribute') : _prodInvariant('129') : void 0; batchingStrategy = _batchingStrategy; } }; var ReactUpdates = { /** * React references `ReactReconcileTransaction` using this property in order * to allow dependency injection. * * @internal */ ReactReconcileTransaction: null, batchedUpdates: batchedUpdates, enqueueUpdate: enqueueUpdate, flushBatchedUpdates: flushBatchedUpdates, injection: ReactUpdatesInjection, asap: asap }; module.exports = ReactUpdates; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 61 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var _prodInvariant = __webpack_require__(39); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var PooledClass = __webpack_require__(54); var invariant = __webpack_require__(8); /** * A specialized pseudo-event module to help keep track of components waiting to * be notified when their DOM representations are available for use. * * This implements `PooledClass`, so you should never need to instantiate this. * Instead, use `CallbackQueue.getPooled()`. * * @class ReactMountReady * @implements PooledClass * @internal */ var CallbackQueue = function () { function CallbackQueue(arg) { _classCallCheck(this, CallbackQueue); this._callbacks = null; this._contexts = null; this._arg = arg; } /** * Enqueues a callback to be invoked when `notifyAll` is invoked. * * @param {function} callback Invoked when `notifyAll` is invoked. * @param {?object} context Context to call `callback` with. * @internal */ CallbackQueue.prototype.enqueue = function enqueue(callback, context) { this._callbacks = this._callbacks || []; this._callbacks.push(callback); this._contexts = this._contexts || []; this._contexts.push(context); }; /** * Invokes all enqueued callbacks and clears the queue. This is invoked after * the DOM representation of a component has been created or updated. * * @internal */ CallbackQueue.prototype.notifyAll = function notifyAll() { var callbacks = this._callbacks; var contexts = this._contexts; var arg = this._arg; if (callbacks && contexts) { !(callbacks.length === contexts.length) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Mismatched list of contexts in callback queue') : _prodInvariant('24') : void 0; this._callbacks = null; this._contexts = null; for (var i = 0; i < callbacks.length; i++) { callbacks[i].call(contexts[i], arg); } callbacks.length = 0; contexts.length = 0; } }; CallbackQueue.prototype.checkpoint = function checkpoint() { return this._callbacks ? this._callbacks.length : 0; }; CallbackQueue.prototype.rollback = function rollback(len) { if (this._callbacks && this._contexts) { this._callbacks.length = len; this._contexts.length = len; } }; /** * Resets the internal queue. * * @internal */ CallbackQueue.prototype.reset = function reset() { this._callbacks = null; this._contexts = null; }; /** * `PooledClass` looks for this. */ CallbackQueue.prototype.destructor = function destructor() { this.reset(); }; return CallbackQueue; }(); module.exports = PooledClass.addPoolingTo(CallbackQueue); /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 62 */ /***/ (function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var ReactFeatureFlags = { // When true, call console.time() before and .timeEnd() after each top-level // render (both initial renders and updates). Useful when looking at prod-mode // timeline profiles in Chrome, for example. logTopLevelRenders: false }; module.exports = ReactFeatureFlags; /***/ }), /* 63 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var ReactRef = __webpack_require__(64); var ReactInstrumentation = __webpack_require__(66); var warning = __webpack_require__(11); /** * Helper to call ReactRef.attachRefs with this composite component, split out * to avoid allocations in the transaction mount-ready queue. */ function attachRefs() { ReactRef.attachRefs(this, this._currentElement); } var ReactReconciler = { /** * Initializes the component, renders markup, and registers event listeners. * * @param {ReactComponent} internalInstance * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {?object} the containing host component instance * @param {?object} info about the host container * @return {?string} Rendered markup to be inserted into the DOM. * @final * @internal */ mountComponent: function (internalInstance, transaction, hostParent, hostContainerInfo, context, parentDebugID // 0 in production and for roots ) { if (process.env.NODE_ENV !== 'production') { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onBeforeMountComponent(internalInstance._debugID, internalInstance._currentElement, parentDebugID); } } var markup = internalInstance.mountComponent(transaction, hostParent, hostContainerInfo, context, parentDebugID); if (internalInstance._currentElement && internalInstance._currentElement.ref != null) { transaction.getReactMountReady().enqueue(attachRefs, internalInstance); } if (process.env.NODE_ENV !== 'production') { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onMountComponent(internalInstance._debugID); } } return markup; }, /** * Returns a value that can be passed to * ReactComponentEnvironment.replaceNodeWithMarkup. */ getHostNode: function (internalInstance) { return internalInstance.getHostNode(); }, /** * Releases any resources allocated by `mountComponent`. * * @final * @internal */ unmountComponent: function (internalInstance, safely) { if (process.env.NODE_ENV !== 'production') { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onBeforeUnmountComponent(internalInstance._debugID); } } ReactRef.detachRefs(internalInstance, internalInstance._currentElement); internalInstance.unmountComponent(safely); if (process.env.NODE_ENV !== 'production') { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onUnmountComponent(internalInstance._debugID); } } }, /** * Update a component using a new element. * * @param {ReactComponent} internalInstance * @param {ReactElement} nextElement * @param {ReactReconcileTransaction} transaction * @param {object} context * @internal */ receiveComponent: function (internalInstance, nextElement, transaction, context) { var prevElement = internalInstance._currentElement; if (nextElement === prevElement && context === internalInstance._context) { // Since elements are immutable after the owner is rendered, // we can do a cheap identity compare here to determine if this is a // superfluous reconcile. It's possible for state to be mutable but such // change should trigger an update of the owner which would recreate // the element. We explicitly check for the existence of an owner since // it's possible for an element created outside a composite to be // deeply mutated and reused. // TODO: Bailing out early is just a perf optimization right? // TODO: Removing the return statement should affect correctness? return; } if (process.env.NODE_ENV !== 'production') { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onBeforeUpdateComponent(internalInstance._debugID, nextElement); } } var refsChanged = ReactRef.shouldUpdateRefs(prevElement, nextElement); if (refsChanged) { ReactRef.detachRefs(internalInstance, prevElement); } internalInstance.receiveComponent(nextElement, transaction, context); if (refsChanged && internalInstance._currentElement && internalInstance._currentElement.ref != null) { transaction.getReactMountReady().enqueue(attachRefs, internalInstance); } if (process.env.NODE_ENV !== 'production') { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onUpdateComponent(internalInstance._debugID); } } }, /** * Flush any dirty changes in a component. * * @param {ReactComponent} internalInstance * @param {ReactReconcileTransaction} transaction * @internal */ performUpdateIfNecessary: function (internalInstance, transaction, updateBatchNumber) { if (internalInstance._updateBatchNumber !== updateBatchNumber) { // The component's enqueued batch number should always be the current // batch or the following one. process.env.NODE_ENV !== 'production' ? warning(internalInstance._updateBatchNumber == null || internalInstance._updateBatchNumber === updateBatchNumber + 1, 'performUpdateIfNecessary: Unexpected batch number (current %s, ' + 'pending %s)', updateBatchNumber, internalInstance._updateBatchNumber) : void 0; return; } if (process.env.NODE_ENV !== 'production') { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onBeforeUpdateComponent(internalInstance._debugID, internalInstance._currentElement); } } internalInstance.performUpdateIfNecessary(transaction); if (process.env.NODE_ENV !== 'production') { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onUpdateComponent(internalInstance._debugID); } } } }; module.exports = ReactReconciler; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 64 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var ReactOwner = __webpack_require__(65); var ReactRef = {}; function attachRef(ref, component, owner) { if (typeof ref === 'function') { ref(component.getPublicInstance()); } else { // Legacy ref ReactOwner.addComponentAsRefTo(component, ref, owner); } } function detachRef(ref, component, owner) { if (typeof ref === 'function') { ref(null); } else { // Legacy ref ReactOwner.removeComponentAsRefFrom(component, ref, owner); } } ReactRef.attachRefs = function (instance, element) { if (element === null || typeof element !== 'object') { return; } var ref = element.ref; if (ref != null) { attachRef(ref, instance, element._owner); } }; ReactRef.shouldUpdateRefs = function (prevElement, nextElement) { // If either the owner or a `ref` has changed, make sure the newest owner // has stored a reference to `this`, and the previous owner (if different) // has forgotten the reference to `this`. We use the element instead // of the public this.props because the post processing cannot determine // a ref. The ref conceptually lives on the element. // TODO: Should this even be possible? The owner cannot change because // it's forbidden by shouldUpdateReactComponent. The ref can change // if you swap the keys of but not the refs. Reconsider where this check // is made. It probably belongs where the key checking and // instantiateReactComponent is done. var prevRef = null; var prevOwner = null; if (prevElement !== null && typeof prevElement === 'object') { prevRef = prevElement.ref; prevOwner = prevElement._owner; } var nextRef = null; var nextOwner = null; if (nextElement !== null && typeof nextElement === 'object') { nextRef = nextElement.ref; nextOwner = nextElement._owner; } return prevRef !== nextRef || // If owner changes but we have an unchanged function ref, don't update refs typeof nextRef === 'string' && nextOwner !== prevOwner; }; ReactRef.detachRefs = function (instance, element) { if (element === null || typeof element !== 'object') { return; } var ref = element.ref; if (ref != null) { detachRef(ref, instance, element._owner); } }; module.exports = ReactRef; /***/ }), /* 65 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var _prodInvariant = __webpack_require__(39); var invariant = __webpack_require__(8); /** * @param {?object} object * @return {boolean} True if `object` is a valid owner. * @final */ function isValidOwner(object) { return !!(object && typeof object.attachRef === 'function' && typeof object.detachRef === 'function'); } /** * ReactOwners are capable of storing references to owned components. * * All components are capable of //being// referenced by owner components, but * only ReactOwner components are capable of //referencing// owned components. * The named reference is known as a "ref". * * Refs are available when mounted and updated during reconciliation. * * var MyComponent = React.createClass({ * render: function() { * return ( * <div onClick={this.handleClick}> * <CustomComponent ref="custom" /> * </div> * ); * }, * handleClick: function() { * this.refs.custom.handleClick(); * }, * componentDidMount: function() { * this.refs.custom.initialize(); * } * }); * * Refs should rarely be used. When refs are used, they should only be done to * control data that is not handled by React's data flow. * * @class ReactOwner */ var ReactOwner = { /** * Adds a component by ref to an owner component. * * @param {ReactComponent} component Component to reference. * @param {string} ref Name by which to refer to the component. * @param {ReactOwner} owner Component on which to record the ref. * @final * @internal */ addComponentAsRefTo: function (component, ref, owner) { !isValidOwner(owner) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'addComponentAsRefTo(...): Only a ReactOwner can have refs. You might be adding a ref to a component that was not created inside a component\'s `render` method, or you have multiple copies of React loaded (details: https://fb.me/react-refs-must-have-owner).') : _prodInvariant('119') : void 0; owner.attachRef(ref, component); }, /** * Removes a component by ref from an owner component. * * @param {ReactComponent} component Component to dereference. * @param {string} ref Name of the ref to remove. * @param {ReactOwner} owner Component on which the ref is recorded. * @final * @internal */ removeComponentAsRefFrom: function (component, ref, owner) { !isValidOwner(owner) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'removeComponentAsRefFrom(...): Only a ReactOwner can have refs. You might be removing a ref to a component that was not created inside a component\'s `render` method, or you have multiple copies of React loaded (details: https://fb.me/react-refs-must-have-owner).') : _prodInvariant('120') : void 0; var ownerPublicInstance = owner.getPublicInstance(); // Check that `component`'s owner is still alive and that `component` is still the current ref // because we do not want to detach the ref if another component stole it. if (ownerPublicInstance && ownerPublicInstance.refs[ref] === component.getPublicInstance()) { owner.detachRef(ref); } } }; module.exports = ReactOwner; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 66 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2016-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; // Trust the developer to only use ReactInstrumentation with a __DEV__ check var debugTool = null; if (process.env.NODE_ENV !== 'production') { var ReactDebugTool = __webpack_require__(67); debugTool = ReactDebugTool; } module.exports = { debugTool: debugTool }; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 67 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2016-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var ReactInvalidSetStateWarningHook = __webpack_require__(68); var ReactHostOperationHistoryHook = __webpack_require__(69); var ReactComponentTreeHook = __webpack_require__(26); var ExecutionEnvironment = __webpack_require__(52); var performanceNow = __webpack_require__(70); var warning = __webpack_require__(11); var hooks = []; var didHookThrowForEvent = {}; function callHook(event, fn, context, arg1, arg2, arg3, arg4, arg5) { try { fn.call(context, arg1, arg2, arg3, arg4, arg5); } catch (e) { process.env.NODE_ENV !== 'production' ? warning(didHookThrowForEvent[event], 'Exception thrown by hook while handling %s: %s', event, e + '\n' + e.stack) : void 0; didHookThrowForEvent[event] = true; } } function emitEvent(event, arg1, arg2, arg3, arg4, arg5) { for (var i = 0; i < hooks.length; i++) { var hook = hooks[i]; var fn = hook[event]; if (fn) { callHook(event, fn, hook, arg1, arg2, arg3, arg4, arg5); } } } var isProfiling = false; var flushHistory = []; var lifeCycleTimerStack = []; var currentFlushNesting = 0; var currentFlushMeasurements = []; var currentFlushStartTime = 0; var currentTimerDebugID = null; var currentTimerStartTime = 0; var currentTimerNestedFlushDuration = 0; var currentTimerType = null; var lifeCycleTimerHasWarned = false; function clearHistory() { ReactComponentTreeHook.purgeUnmountedComponents(); ReactHostOperationHistoryHook.clearHistory(); } function getTreeSnapshot(registeredIDs) { return registeredIDs.reduce(function (tree, id) { var ownerID = ReactComponentTreeHook.getOwnerID(id); var parentID = ReactComponentTreeHook.getParentID(id); tree[id] = { displayName: ReactComponentTreeHook.getDisplayName(id), text: ReactComponentTreeHook.getText(id), updateCount: ReactComponentTreeHook.getUpdateCount(id), childIDs: ReactComponentTreeHook.getChildIDs(id), // Text nodes don't have owners but this is close enough. ownerID: ownerID || parentID && ReactComponentTreeHook.getOwnerID(parentID) || 0, parentID: parentID }; return tree; }, {}); } function resetMeasurements() { var previousStartTime = currentFlushStartTime; var previousMeasurements = currentFlushMeasurements; var previousOperations = ReactHostOperationHistoryHook.getHistory(); if (currentFlushNesting === 0) { currentFlushStartTime = 0; currentFlushMeasurements = []; clearHistory(); return; } if (previousMeasurements.length || previousOperations.length) { var registeredIDs = ReactComponentTreeHook.getRegisteredIDs(); flushHistory.push({ duration: performanceNow() - previousStartTime, measurements: previousMeasurements || [], operations: previousOperations || [], treeSnapshot: getTreeSnapshot(registeredIDs) }); } clearHistory(); currentFlushStartTime = performanceNow(); currentFlushMeasurements = []; } function checkDebugID(debugID) { var allowRoot = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; if (allowRoot && debugID === 0) { return; } if (!debugID) { process.env.NODE_ENV !== 'production' ? warning(false, 'ReactDebugTool: debugID may not be empty.') : void 0; } } function beginLifeCycleTimer(debugID, timerType) { if (currentFlushNesting === 0) { return; } if (currentTimerType && !lifeCycleTimerHasWarned) { process.env.NODE_ENV !== 'production' ? warning(false, 'There is an internal error in the React performance measurement code. ' + 'Did not expect %s timer to start while %s timer is still in ' + 'progress for %s instance.', timerType, currentTimerType || 'no', debugID === currentTimerDebugID ? 'the same' : 'another') : void 0; lifeCycleTimerHasWarned = true; } currentTimerStartTime = performanceNow(); currentTimerNestedFlushDuration = 0; currentTimerDebugID = debugID; currentTimerType = timerType; } function endLifeCycleTimer(debugID, timerType) { if (currentFlushNesting === 0) { return; } if (currentTimerType !== timerType && !lifeCycleTimerHasWarned) { process.env.NODE_ENV !== 'production' ? warning(false, 'There is an internal error in the React performance measurement code. ' + 'We did not expect %s timer to stop while %s timer is still in ' + 'progress for %s instance. Please report this as a bug in React.', timerType, currentTimerType || 'no', debugID === currentTimerDebugID ? 'the same' : 'another') : void 0; lifeCycleTimerHasWarned = true; } if (isProfiling) { currentFlushMeasurements.push({ timerType: timerType, instanceID: debugID, duration: performanceNow() - currentTimerStartTime - currentTimerNestedFlushDuration }); } currentTimerStartTime = 0; currentTimerNestedFlushDuration = 0; currentTimerDebugID = null; currentTimerType = null; } function pauseCurrentLifeCycleTimer() { var currentTimer = { startTime: currentTimerStartTime, nestedFlushStartTime: performanceNow(), debugID: currentTimerDebugID, timerType: currentTimerType }; lifeCycleTimerStack.push(currentTimer); currentTimerStartTime = 0; currentTimerNestedFlushDuration = 0; currentTimerDebugID = null; currentTimerType = null; } function resumeCurrentLifeCycleTimer() { var _lifeCycleTimerStack$ = lifeCycleTimerStack.pop(), startTime = _lifeCycleTimerStack$.startTime, nestedFlushStartTime = _lifeCycleTimerStack$.nestedFlushStartTime, debugID = _lifeCycleTimerStack$.debugID, timerType = _lifeCycleTimerStack$.timerType; var nestedFlushDuration = performanceNow() - nestedFlushStartTime; currentTimerStartTime = startTime; currentTimerNestedFlushDuration += nestedFlushDuration; currentTimerDebugID = debugID; currentTimerType = timerType; } var lastMarkTimeStamp = 0; var canUsePerformanceMeasure = typeof performance !== 'undefined' && typeof performance.mark === 'function' && typeof performance.clearMarks === 'function' && typeof performance.measure === 'function' && typeof performance.clearMeasures === 'function'; function shouldMark(debugID) { if (!isProfiling || !canUsePerformanceMeasure) { return false; } var element = ReactComponentTreeHook.getElement(debugID); if (element == null || typeof element !== 'object') { return false; } var isHostElement = typeof element.type === 'string'; if (isHostElement) { return false; } return true; } function markBegin(debugID, markType) { if (!shouldMark(debugID)) { return; } var markName = debugID + '::' + markType; lastMarkTimeStamp = performanceNow(); performance.mark(markName); } function markEnd(debugID, markType) { if (!shouldMark(debugID)) { return; } var markName = debugID + '::' + markType; var displayName = ReactComponentTreeHook.getDisplayName(debugID) || 'Unknown'; // Chrome has an issue of dropping markers recorded too fast: // https://bugs.chromium.org/p/chromium/issues/detail?id=640652 // To work around this, we will not report very small measurements. // I determined the magic number by tweaking it back and forth. // 0.05ms was enough to prevent the issue, but I set it to 0.1ms to be safe. // When the bug is fixed, we can `measure()` unconditionally if we want to. var timeStamp = performanceNow(); if (timeStamp - lastMarkTimeStamp > 0.1) { var measurementName = displayName + ' [' + markType + ']'; performance.measure(measurementName, markName); } performance.clearMarks(markName); performance.clearMeasures(measurementName); } var ReactDebugTool = { addHook: function (hook) { hooks.push(hook); }, removeHook: function (hook) { for (var i = 0; i < hooks.length; i++) { if (hooks[i] === hook) { hooks.splice(i, 1); i--; } } }, isProfiling: function () { return isProfiling; }, beginProfiling: function () { if (isProfiling) { return; } isProfiling = true; flushHistory.length = 0; resetMeasurements(); ReactDebugTool.addHook(ReactHostOperationHistoryHook); }, endProfiling: function () { if (!isProfiling) { return; } isProfiling = false; resetMeasurements(); ReactDebugTool.removeHook(ReactHostOperationHistoryHook); }, getFlushHistory: function () { return flushHistory; }, onBeginFlush: function () { currentFlushNesting++; resetMeasurements(); pauseCurrentLifeCycleTimer(); emitEvent('onBeginFlush'); }, onEndFlush: function () { resetMeasurements(); currentFlushNesting--; resumeCurrentLifeCycleTimer(); emitEvent('onEndFlush'); }, onBeginLifeCycleTimer: function (debugID, timerType) { checkDebugID(debugID); emitEvent('onBeginLifeCycleTimer', debugID, timerType); markBegin(debugID, timerType); beginLifeCycleTimer(debugID, timerType); }, onEndLifeCycleTimer: function (debugID, timerType) { checkDebugID(debugID); endLifeCycleTimer(debugID, timerType); markEnd(debugID, timerType); emitEvent('onEndLifeCycleTimer', debugID, timerType); }, onBeginProcessingChildContext: function () { emitEvent('onBeginProcessingChildContext'); }, onEndProcessingChildContext: function () { emitEvent('onEndProcessingChildContext'); }, onHostOperation: function (operation) { checkDebugID(operation.instanceID); emitEvent('onHostOperation', operation); }, onSetState: function () { emitEvent('onSetState'); }, onSetChildren: function (debugID, childDebugIDs) { checkDebugID(debugID); childDebugIDs.forEach(checkDebugID); emitEvent('onSetChildren', debugID, childDebugIDs); }, onBeforeMountComponent: function (debugID, element, parentDebugID) { checkDebugID(debugID); checkDebugID(parentDebugID, true); emitEvent('onBeforeMountComponent', debugID, element, parentDebugID); markBegin(debugID, 'mount'); }, onMountComponent: function (debugID) { checkDebugID(debugID); markEnd(debugID, 'mount'); emitEvent('onMountComponent', debugID); }, onBeforeUpdateComponent: function (debugID, element) { checkDebugID(debugID); emitEvent('onBeforeUpdateComponent', debugID, element); markBegin(debugID, 'update'); }, onUpdateComponent: function (debugID) { checkDebugID(debugID); markEnd(debugID, 'update'); emitEvent('onUpdateComponent', debugID); }, onBeforeUnmountComponent: function (debugID) { checkDebugID(debugID); emitEvent('onBeforeUnmountComponent', debugID); markBegin(debugID, 'unmount'); }, onUnmountComponent: function (debugID) { checkDebugID(debugID); markEnd(debugID, 'unmount'); emitEvent('onUnmountComponent', debugID); }, onTestEvent: function () { emitEvent('onTestEvent'); } }; // TODO remove these when RN/www gets updated ReactDebugTool.addDevtool = ReactDebugTool.addHook; ReactDebugTool.removeDevtool = ReactDebugTool.removeHook; ReactDebugTool.addHook(ReactInvalidSetStateWarningHook); ReactDebugTool.addHook(ReactComponentTreeHook); var url = ExecutionEnvironment.canUseDOM && window.location.href || ''; if (/[?&]react_perf\b/.test(url)) { ReactDebugTool.beginProfiling(); } module.exports = ReactDebugTool; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 68 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2016-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var warning = __webpack_require__(11); if (process.env.NODE_ENV !== 'production') { var processingChildContext = false; var warnInvalidSetState = function () { process.env.NODE_ENV !== 'production' ? warning(!processingChildContext, 'setState(...): Cannot call setState() inside getChildContext()') : void 0; }; } var ReactInvalidSetStateWarningHook = { onBeginProcessingChildContext: function () { processingChildContext = true; }, onEndProcessingChildContext: function () { processingChildContext = false; }, onSetState: function () { warnInvalidSetState(); } }; module.exports = ReactInvalidSetStateWarningHook; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 69 */ /***/ (function(module, exports) { /** * Copyright 2016-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var history = []; var ReactHostOperationHistoryHook = { onHostOperation: function (operation) { history.push(operation); }, clearHistory: function () { if (ReactHostOperationHistoryHook._preventClearing) { // Should only be used for tests. return; } history = []; }, getHistory: function () { return history; } }; module.exports = ReactHostOperationHistoryHook; /***/ }), /* 70 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ var performance = __webpack_require__(71); var performanceNow; /** * Detect if we can use `window.performance.now()` and gracefully fallback to * `Date.now()` if it doesn't exist. We need to support Firefox < 15 for now * because of Facebook's testing infrastructure. */ if (performance.now) { performanceNow = function performanceNow() { return performance.now(); }; } else { performanceNow = function performanceNow() { return Date.now(); }; } module.exports = performanceNow; /***/ }), /* 71 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ 'use strict'; var ExecutionEnvironment = __webpack_require__(52); var performance; if (ExecutionEnvironment.canUseDOM) { performance = window.performance || window.msPerformance || window.webkitPerformance; } module.exports = performance || {}; /***/ }), /* 72 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var _prodInvariant = __webpack_require__(39); var invariant = __webpack_require__(8); var OBSERVED_ERROR = {}; /** * `Transaction` creates a black box that is able to wrap any method such that * certain invariants are maintained before and after the method is invoked * (Even if an exception is thrown while invoking the wrapped method). Whoever * instantiates a transaction can provide enforcers of the invariants at * creation time. The `Transaction` class itself will supply one additional * automatic invariant for you - the invariant that any transaction instance * should not be run while it is already being run. You would typically create a * single instance of a `Transaction` for reuse multiple times, that potentially * is used to wrap several different methods. Wrappers are extremely simple - * they only require implementing two methods. * * <pre> * wrappers (injected at creation time) * + + * | | * +-----------------|--------|--------------+ * | v | | * | +---------------+ | | * | +--| wrapper1 |---|----+ | * | | +---------------+ v | | * | | +-------------+ | | * | | +----| wrapper2 |--------+ | * | | | +-------------+ | | | * | | | | | | * | v v v v | wrapper * | +---+ +---+ +---------+ +---+ +---+ | invariants * perform(anyMethod) | | | | | | | | | | | | maintained * +----------------->|-|---|-|---|-->|anyMethod|---|---|-|---|-|--------> * | | | | | | | | | | | | * | | | | | | | | | | | | * | | | | | | | | | | | | * | +---+ +---+ +---------+ +---+ +---+ | * | initialize close | * +-----------------------------------------+ * </pre> * * Use cases: * - Preserving the input selection ranges before/after reconciliation. * Restoring selection even in the event of an unexpected error. * - Deactivating events while rearranging the DOM, preventing blurs/focuses, * while guaranteeing that afterwards, the event system is reactivated. * - Flushing a queue of collected DOM mutations to the main UI thread after a * reconciliation takes place in a worker thread. * - Invoking any collected `componentDidUpdate` callbacks after rendering new * content. * - (Future use case): Wrapping particular flushes of the `ReactWorker` queue * to preserve the `scrollTop` (an automatic scroll aware DOM). * - (Future use case): Layout calculations before and after DOM updates. * * Transactional plugin API: * - A module that has an `initialize` method that returns any precomputation. * - and a `close` method that accepts the precomputation. `close` is invoked * when the wrapped process is completed, or has failed. * * @param {Array<TransactionalWrapper>} transactionWrapper Wrapper modules * that implement `initialize` and `close`. * @return {Transaction} Single transaction for reuse in thread. * * @class Transaction */ var TransactionImpl = { /** * Sets up this instance so that it is prepared for collecting metrics. Does * so such that this setup method may be used on an instance that is already * initialized, in a way that does not consume additional memory upon reuse. * That can be useful if you decide to make your subclass of this mixin a * "PooledClass". */ reinitializeTransaction: function () { this.transactionWrappers = this.getTransactionWrappers(); if (this.wrapperInitData) { this.wrapperInitData.length = 0; } else { this.wrapperInitData = []; } this._isInTransaction = false; }, _isInTransaction: false, /** * @abstract * @return {Array<TransactionWrapper>} Array of transaction wrappers. */ getTransactionWrappers: null, isInTransaction: function () { return !!this._isInTransaction; }, /** * Executes the function within a safety window. Use this for the top level * methods that result in large amounts of computation/mutations that would * need to be safety checked. The optional arguments helps prevent the need * to bind in many cases. * * @param {function} method Member of scope to call. * @param {Object} scope Scope to invoke from. * @param {Object?=} a Argument to pass to the method. * @param {Object?=} b Argument to pass to the method. * @param {Object?=} c Argument to pass to the method. * @param {Object?=} d Argument to pass to the method. * @param {Object?=} e Argument to pass to the method. * @param {Object?=} f Argument to pass to the method. * * @return {*} Return value from `method`. */ perform: function (method, scope, a, b, c, d, e, f) { !!this.isInTransaction() ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Transaction.perform(...): Cannot initialize a transaction when there is already an outstanding transaction.') : _prodInvariant('27') : void 0; var errorThrown; var ret; try { this._isInTransaction = true; // Catching errors makes debugging more difficult, so we start with // errorThrown set to true before setting it to false after calling // close -- if it's still set to true in the finally block, it means // one of these calls threw. errorThrown = true; this.initializeAll(0); ret = method.call(scope, a, b, c, d, e, f); errorThrown = false; } finally { try { if (errorThrown) { // If `method` throws, prefer to show that stack trace over any thrown // by invoking `closeAll`. try { this.closeAll(0); } catch (err) {} } else { // Since `method` didn't throw, we don't want to silence the exception // here. this.closeAll(0); } } finally { this._isInTransaction = false; } } return ret; }, initializeAll: function (startIndex) { var transactionWrappers = this.transactionWrappers; for (var i = startIndex; i < transactionWrappers.length; i++) { var wrapper = transactionWrappers[i]; try { // Catching errors makes debugging more difficult, so we start with the // OBSERVED_ERROR state before overwriting it with the real return value // of initialize -- if it's still set to OBSERVED_ERROR in the finally // block, it means wrapper.initialize threw. this.wrapperInitData[i] = OBSERVED_ERROR; this.wrapperInitData[i] = wrapper.initialize ? wrapper.initialize.call(this) : null; } finally { if (this.wrapperInitData[i] === OBSERVED_ERROR) { // The initializer for wrapper i threw an error; initialize the // remaining wrappers but silence any exceptions from them to ensure // that the first error is the one to bubble up. try { this.initializeAll(i + 1); } catch (err) {} } } } }, /** * Invokes each of `this.transactionWrappers.close[i]` functions, passing into * them the respective return values of `this.transactionWrappers.init[i]` * (`close`rs that correspond to initializers that failed will not be * invoked). */ closeAll: function (startIndex) { !this.isInTransaction() ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Transaction.closeAll(): Cannot close transaction when none are open.') : _prodInvariant('28') : void 0; var transactionWrappers = this.transactionWrappers; for (var i = startIndex; i < transactionWrappers.length; i++) { var wrapper = transactionWrappers[i]; var initData = this.wrapperInitData[i]; var errorThrown; try { // Catching errors makes debugging more difficult, so we start with // errorThrown set to true before setting it to false after calling // close -- if it's still set to true in the finally block, it means // wrapper.close threw. errorThrown = true; if (initData !== OBSERVED_ERROR && wrapper.close) { wrapper.close.call(this, initData); } errorThrown = false; } finally { if (errorThrown) { // The closer for wrapper i threw an error; close the remaining // wrappers but silence any exceptions from them to ensure that the // first error is the one to bubble up. try { this.closeAll(i + 1); } catch (e) {} } } } this.wrapperInitData.length = 0; } }; module.exports = TransactionImpl; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 73 */ /***/ (function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; /** * Gets the target node from a native browser event by accounting for * inconsistencies in browser DOM APIs. * * @param {object} nativeEvent Native browser event. * @return {DOMEventTarget} Target node. */ function getEventTarget(nativeEvent) { var target = nativeEvent.target || nativeEvent.srcElement || window; // Normalize SVG <use> element events #4963 if (target.correspondingUseElement) { target = target.correspondingUseElement; } // Safari may fire events on text nodes (Node.TEXT_NODE is 3). // @see http://www.quirksmode.org/js/events_properties.html return target.nodeType === 3 ? target.parentNode : target; } module.exports = getEventTarget; /***/ }), /* 74 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var ExecutionEnvironment = __webpack_require__(52); var useHasFeature; if (ExecutionEnvironment.canUseDOM) { useHasFeature = document.implementation && document.implementation.hasFeature && // always returns true in newer browsers as per the standard. // @see http://dom.spec.whatwg.org/#dom-domimplementation-hasfeature document.implementation.hasFeature('', '') !== true; } /** * 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". * @param {?boolean} capture Check if the capture phase is supported. * @return {boolean} True if the event is supported. * @internal * @license Modernizr 3.0.0pre (Custom Build) | MIT */ function isEventSupported(eventNameSuffix, capture) { if (!ExecutionEnvironment.canUseDOM || capture && !('addEventListener' in document)) { 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'; } if (!isSupported && useHasFeature && eventNameSuffix === 'wheel') { // This is the only way to test support for the `wheel` event in IE9+. isSupported = document.implementation.hasFeature('Events.wheel', '3.0'); } return isSupported; } module.exports = isEventSupported; /***/ }), /* 75 */ /***/ (function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; /** * @see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary */ 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; } module.exports = isTextInputElement; /***/ }), /* 76 */ /***/ (function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; /** * Module that is injectable into `EventPluginHub`, that specifies a * deterministic ordering of `EventPlugin`s. A convenient way to reason about * plugins, without having to package every one of them. This is better than * having plugins be ordered in the same order that they are injected because * that ordering would be influenced by the packaging order. * `ResponderEventPlugin` must occur before `SimpleEventPlugin` so that * preventing default on events is convenient in `SimpleEventPlugin` handlers. */ var DefaultEventPluginOrder = ['ResponderEventPlugin', 'SimpleEventPlugin', 'TapEventPlugin', 'EnterLeaveEventPlugin', 'ChangeEventPlugin', 'SelectEventPlugin', 'BeforeInputEventPlugin']; module.exports = DefaultEventPluginOrder; /***/ }), /* 77 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var EventPropagators = __webpack_require__(45); var ReactDOMComponentTree = __webpack_require__(38); var SyntheticMouseEvent = __webpack_require__(78); var eventTypes = { mouseEnter: { registrationName: 'onMouseEnter', dependencies: ['topMouseOut', 'topMouseOver'] }, mouseLeave: { registrationName: 'onMouseLeave', dependencies: ['topMouseOut', 'topMouseOver'] } }; var EnterLeaveEventPlugin = { eventTypes: eventTypes, /** * For almost every interaction we care about, there will be both a top-level * `mouseover` and `mouseout` event that occurs. Only use `mouseout` so that * we do not extract duplicate events. However, moving the mouse into the * browser from outside will not fire a `mouseout` event. In this case, we use * the `mouseover` top-level event. */ extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { if (topLevelType === 'topMouseOver' && (nativeEvent.relatedTarget || nativeEvent.fromElement)) { return null; } if (topLevelType !== 'topMouseOut' && topLevelType !== 'topMouseOver') { // Must not be a mouse in or mouse out - ignoring. return null; } var win; if (nativeEventTarget.window === nativeEventTarget) { // `nativeEventTarget` is probably a window object. win = nativeEventTarget; } else { // TODO: Figure out why `ownerDocument` is sometimes undefined in IE8. var doc = nativeEventTarget.ownerDocument; if (doc) { win = doc.defaultView || doc.parentWindow; } else { win = window; } } var from; var to; if (topLevelType === 'topMouseOut') { from = targetInst; var related = nativeEvent.relatedTarget || nativeEvent.toElement; to = related ? ReactDOMComponentTree.getClosestInstanceFromNode(related) : null; } else { // Moving to a node from outside the window. from = null; to = targetInst; } if (from === to) { // Nothing pertains to our managed components. return null; } var fromNode = from == null ? win : ReactDOMComponentTree.getNodeFromInstance(from); var toNode = to == null ? win : ReactDOMComponentTree.getNodeFromInstance(to); var leave = SyntheticMouseEvent.getPooled(eventTypes.mouseLeave, from, nativeEvent, nativeEventTarget); leave.type = 'mouseleave'; leave.target = fromNode; leave.relatedTarget = toNode; var enter = SyntheticMouseEvent.getPooled(eventTypes.mouseEnter, to, nativeEvent, nativeEventTarget); enter.type = 'mouseenter'; enter.target = toNode; enter.relatedTarget = fromNode; EventPropagators.accumulateEnterLeaveDispatches(leave, enter, from, to); return [leave, enter]; } }; module.exports = EnterLeaveEventPlugin; /***/ }), /* 78 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var SyntheticUIEvent = __webpack_require__(79); var ViewportMetrics = __webpack_require__(80); var getEventModifierState = __webpack_require__(81); /** * @interface MouseEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var MouseEventInterface = { screenX: null, screenY: null, clientX: null, clientY: null, ctrlKey: null, shiftKey: null, altKey: null, metaKey: null, getModifierState: getEventModifierState, button: function (event) { // Webkit, Firefox, IE9+ // which: 1 2 3 // button: 0 1 2 (standard) var button = event.button; if ('which' in event) { return button; } // IE<9 // which: undefined // button: 0 0 0 // button: 1 4 2 (onmouseup) return button === 2 ? 2 : button === 4 ? 1 : 0; }, buttons: null, relatedTarget: function (event) { return event.relatedTarget || (event.fromElement === event.srcElement ? event.toElement : event.fromElement); }, // "Proprietary" Interface. pageX: function (event) { return 'pageX' in event ? event.pageX : event.clientX + ViewportMetrics.currentScrollLeft; }, pageY: function (event) { return 'pageY' in event ? event.pageY : event.clientY + ViewportMetrics.currentScrollTop; } }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticMouseEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticUIEvent.augmentClass(SyntheticMouseEvent, MouseEventInterface); module.exports = SyntheticMouseEvent; /***/ }), /* 79 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var SyntheticEvent = __webpack_require__(57); var getEventTarget = __webpack_require__(73); /** * @interface UIEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var UIEventInterface = { view: function (event) { if (event.view) { return event.view; } var target = getEventTarget(event); if (target.window === target) { // target is a window object return target; } var doc = target.ownerDocument; // TODO: Figure out why `ownerDocument` is sometimes undefined in IE8. if (doc) { return doc.defaultView || doc.parentWindow; } else { return window; } }, detail: function (event) { return event.detail || 0; } }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticEvent} */ function SyntheticUIEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticEvent.augmentClass(SyntheticUIEvent, UIEventInterface); module.exports = SyntheticUIEvent; /***/ }), /* 80 */ /***/ (function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var ViewportMetrics = { currentScrollLeft: 0, currentScrollTop: 0, refreshScrollValues: function (scrollPosition) { ViewportMetrics.currentScrollLeft = scrollPosition.x; ViewportMetrics.currentScrollTop = scrollPosition.y; } }; module.exports = ViewportMetrics; /***/ }), /* 81 */ /***/ (function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; /** * Translation from modifier key to the associated property in the event. * @see http://www.w3.org/TR/DOM-Level-3-Events/#keys-Modifiers */ var modifierKeyToProp = { 'Alt': 'altKey', 'Control': 'ctrlKey', 'Meta': 'metaKey', 'Shift': 'shiftKey' }; // IE8 does not implement getModifierState so we simply map it to the only // modifier keys exposed by the event itself, does not support Lock-keys. // Currently, all major browsers except Chrome seems to support Lock-keys. 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; } module.exports = getEventModifierState; /***/ }), /* 82 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var DOMProperty = __webpack_require__(40); var MUST_USE_PROPERTY = DOMProperty.injection.MUST_USE_PROPERTY; var HAS_BOOLEAN_VALUE = DOMProperty.injection.HAS_BOOLEAN_VALUE; var HAS_NUMERIC_VALUE = DOMProperty.injection.HAS_NUMERIC_VALUE; var HAS_POSITIVE_NUMERIC_VALUE = DOMProperty.injection.HAS_POSITIVE_NUMERIC_VALUE; var HAS_OVERLOADED_BOOLEAN_VALUE = DOMProperty.injection.HAS_OVERLOADED_BOOLEAN_VALUE; var HTMLDOMPropertyConfig = { isCustomAttribute: RegExp.prototype.test.bind(new RegExp('^(data|aria)-[' + DOMProperty.ATTRIBUTE_NAME_CHAR + ']*$')), Properties: { /** * Standard Properties */ accept: 0, acceptCharset: 0, accessKey: 0, action: 0, allowFullScreen: HAS_BOOLEAN_VALUE, allowTransparency: 0, alt: 0, // specifies target context for links with `preload` type as: 0, async: HAS_BOOLEAN_VALUE, autoComplete: 0, // autoFocus is polyfilled/normalized by AutoFocusUtils // autoFocus: HAS_BOOLEAN_VALUE, autoPlay: HAS_BOOLEAN_VALUE, capture: HAS_BOOLEAN_VALUE, cellPadding: 0, cellSpacing: 0, charSet: 0, challenge: 0, checked: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, cite: 0, classID: 0, className: 0, cols: HAS_POSITIVE_NUMERIC_VALUE, colSpan: 0, content: 0, contentEditable: 0, contextMenu: 0, controls: HAS_BOOLEAN_VALUE, coords: 0, crossOrigin: 0, data: 0, // For `<object />` acts as `src`. dateTime: 0, 'default': HAS_BOOLEAN_VALUE, defer: HAS_BOOLEAN_VALUE, dir: 0, disabled: HAS_BOOLEAN_VALUE, download: HAS_OVERLOADED_BOOLEAN_VALUE, draggable: 0, encType: 0, form: 0, formAction: 0, formEncType: 0, formMethod: 0, formNoValidate: HAS_BOOLEAN_VALUE, formTarget: 0, frameBorder: 0, headers: 0, height: 0, hidden: HAS_BOOLEAN_VALUE, high: 0, href: 0, hrefLang: 0, htmlFor: 0, httpEquiv: 0, icon: 0, id: 0, inputMode: 0, integrity: 0, is: 0, keyParams: 0, keyType: 0, kind: 0, label: 0, lang: 0, list: 0, loop: HAS_BOOLEAN_VALUE, low: 0, manifest: 0, marginHeight: 0, marginWidth: 0, max: 0, maxLength: 0, media: 0, mediaGroup: 0, method: 0, min: 0, minLength: 0, // Caution; `option.selected` is not updated if `select.multiple` is // disabled with `removeAttribute`. multiple: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, muted: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, name: 0, nonce: 0, noValidate: HAS_BOOLEAN_VALUE, open: HAS_BOOLEAN_VALUE, optimum: 0, pattern: 0, placeholder: 0, playsInline: HAS_BOOLEAN_VALUE, poster: 0, preload: 0, profile: 0, radioGroup: 0, readOnly: HAS_BOOLEAN_VALUE, referrerPolicy: 0, rel: 0, required: HAS_BOOLEAN_VALUE, reversed: HAS_BOOLEAN_VALUE, role: 0, rows: HAS_POSITIVE_NUMERIC_VALUE, rowSpan: HAS_NUMERIC_VALUE, sandbox: 0, scope: 0, scoped: HAS_BOOLEAN_VALUE, scrolling: 0, seamless: HAS_BOOLEAN_VALUE, selected: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, shape: 0, size: HAS_POSITIVE_NUMERIC_VALUE, sizes: 0, span: HAS_POSITIVE_NUMERIC_VALUE, spellCheck: 0, src: 0, srcDoc: 0, srcLang: 0, srcSet: 0, start: HAS_NUMERIC_VALUE, step: 0, style: 0, summary: 0, tabIndex: 0, target: 0, title: 0, // Setting .type throws on non-<input> tags type: 0, useMap: 0, value: 0, width: 0, wmode: 0, wrap: 0, /** * RDFa Properties */ about: 0, datatype: 0, inlist: 0, prefix: 0, // property is also supported for OpenGraph in meta tags. property: 0, resource: 0, 'typeof': 0, vocab: 0, /** * Non-standard Properties */ // autoCapitalize and autoCorrect are supported in Mobile Safari for // keyboard hints. autoCapitalize: 0, autoCorrect: 0, // autoSave allows WebKit/Blink to persist values of input fields on page reloads autoSave: 0, // color is for Safari mask-icon link color: 0, // itemProp, itemScope, itemType are for // Microdata support. See http://schema.org/docs/gs.html itemProp: 0, itemScope: HAS_BOOLEAN_VALUE, itemType: 0, // itemID and itemRef are for Microdata support as well but // only specified in the WHATWG spec document. See // https://html.spec.whatwg.org/multipage/microdata.html#microdata-dom-api itemID: 0, itemRef: 0, // results show looking glass icon and recent searches on input // search fields in WebKit/Blink results: 0, // IE-only attribute that specifies security restrictions on an iframe // as an alternative to the sandbox attribute on IE<10 security: 0, // IE-only attribute that controls focus behavior unselectable: 0 }, DOMAttributeNames: { acceptCharset: 'accept-charset', className: 'class', htmlFor: 'for', httpEquiv: 'http-equiv' }, DOMPropertyNames: {}, DOMMutationMethods: { value: function (node, value) { if (value == null) { return node.removeAttribute('value'); } // Number inputs get special treatment due to some edge cases in // Chrome. Let everything else assign the value attribute as normal. // https://github.com/facebook/react/issues/7253#issuecomment-236074326 if (node.type !== 'number' || node.hasAttribute('value') === false) { node.setAttribute('value', '' + value); } else if (node.validity && !node.validity.badInput && node.ownerDocument.activeElement !== node) { // Don't assign an attribute if validation reports bad // input. Chrome will clear the value. Additionally, don't // operate on inputs that have focus, otherwise Chrome might // strip off trailing decimal places and cause the user's // cursor position to jump to the beginning of the input. // // In ReactDOMInput, we have an onBlur event that will trigger // this function again when focus is lost. node.setAttribute('value', '' + value); } } } }; module.exports = HTMLDOMPropertyConfig; /***/ }), /* 83 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var DOMChildrenOperations = __webpack_require__(84); var ReactDOMIDOperations = __webpack_require__(95); /** * Abstracts away all functionality of the reconciler that requires knowledge of * the browser context. TODO: These callers should be refactored to avoid the * need for this injection. */ var ReactComponentBrowserEnvironment = { processChildrenUpdates: ReactDOMIDOperations.dangerouslyProcessChildrenUpdates, replaceNodeWithMarkup: DOMChildrenOperations.dangerouslyReplaceNodeWithMarkup }; module.exports = ReactComponentBrowserEnvironment; /***/ }), /* 84 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var DOMLazyTree = __webpack_require__(85); var Danger = __webpack_require__(91); var ReactDOMComponentTree = __webpack_require__(38); var ReactInstrumentation = __webpack_require__(66); var createMicrosoftUnsafeLocalFunction = __webpack_require__(88); var setInnerHTML = __webpack_require__(87); var setTextContent = __webpack_require__(89); function getNodeAfter(parentNode, node) { // Special case for text components, which return [open, close] comments // from getHostNode. if (Array.isArray(node)) { node = node[1]; } return node ? node.nextSibling : parentNode.firstChild; } /** * Inserts `childNode` as a child of `parentNode` at the `index`. * * @param {DOMElement} parentNode Parent node in which to insert. * @param {DOMElement} childNode Child node to insert. * @param {number} index Index at which to insert the child. * @internal */ var insertChildAt = createMicrosoftUnsafeLocalFunction(function (parentNode, childNode, referenceNode) { // We rely exclusively on `insertBefore(node, null)` instead of also using // `appendChild(node)`. (Using `undefined` is not allowed by all browsers so // we are careful to use `null`.) parentNode.insertBefore(childNode, referenceNode); }); function insertLazyTreeChildAt(parentNode, childTree, referenceNode) { DOMLazyTree.insertTreeBefore(parentNode, childTree, referenceNode); } function moveChild(parentNode, childNode, referenceNode) { if (Array.isArray(childNode)) { moveDelimitedText(parentNode, childNode[0], childNode[1], referenceNode); } else { insertChildAt(parentNode, childNode, referenceNode); } } function removeChild(parentNode, childNode) { if (Array.isArray(childNode)) { var closingComment = childNode[1]; childNode = childNode[0]; removeDelimitedText(parentNode, childNode, closingComment); parentNode.removeChild(closingComment); } parentNode.removeChild(childNode); } function moveDelimitedText(parentNode, openingComment, closingComment, referenceNode) { var node = openingComment; while (true) { var nextNode = node.nextSibling; insertChildAt(parentNode, node, referenceNode); if (node === closingComment) { break; } node = nextNode; } } function removeDelimitedText(parentNode, startNode, closingComment) { while (true) { var node = startNode.nextSibling; if (node === closingComment) { // The closing comment is removed by ReactMultiChild. break; } else { parentNode.removeChild(node); } } } function replaceDelimitedText(openingComment, closingComment, stringText) { var parentNode = openingComment.parentNode; var nodeAfterComment = openingComment.nextSibling; if (nodeAfterComment === closingComment) { // There are no text nodes between the opening and closing comments; insert // a new one if stringText isn't empty. if (stringText) { insertChildAt(parentNode, document.createTextNode(stringText), nodeAfterComment); } } else { if (stringText) { // Set the text content of the first node after the opening comment, and // remove all following nodes up until the closing comment. setTextContent(nodeAfterComment, stringText); removeDelimitedText(parentNode, nodeAfterComment, closingComment); } else { removeDelimitedText(parentNode, openingComment, closingComment); } } if (process.env.NODE_ENV !== 'production') { ReactInstrumentation.debugTool.onHostOperation({ instanceID: ReactDOMComponentTree.getInstanceFromNode(openingComment)._debugID, type: 'replace text', payload: stringText }); } } var dangerouslyReplaceNodeWithMarkup = Danger.dangerouslyReplaceNodeWithMarkup; if (process.env.NODE_ENV !== 'production') { dangerouslyReplaceNodeWithMarkup = function (oldChild, markup, prevInstance) { Danger.dangerouslyReplaceNodeWithMarkup(oldChild, markup); if (prevInstance._debugID !== 0) { ReactInstrumentation.debugTool.onHostOperation({ instanceID: prevInstance._debugID, type: 'replace with', payload: markup.toString() }); } else { var nextInstance = ReactDOMComponentTree.getInstanceFromNode(markup.node); if (nextInstance._debugID !== 0) { ReactInstrumentation.debugTool.onHostOperation({ instanceID: nextInstance._debugID, type: 'mount', payload: markup.toString() }); } } }; } /** * Operations for updating with DOM children. */ var DOMChildrenOperations = { dangerouslyReplaceNodeWithMarkup: dangerouslyReplaceNodeWithMarkup, replaceDelimitedText: replaceDelimitedText, /** * Updates a component's children by processing a series of updates. The * update configurations are each expected to have a `parentNode` property. * * @param {array<object>} updates List of update configurations. * @internal */ processUpdates: function (parentNode, updates) { if (process.env.NODE_ENV !== 'production') { var parentNodeDebugID = ReactDOMComponentTree.getInstanceFromNode(parentNode)._debugID; } for (var k = 0; k < updates.length; k++) { var update = updates[k]; switch (update.type) { case 'INSERT_MARKUP': insertLazyTreeChildAt(parentNode, update.content, getNodeAfter(parentNode, update.afterNode)); if (process.env.NODE_ENV !== 'production') { ReactInstrumentation.debugTool.onHostOperation({ instanceID: parentNodeDebugID, type: 'insert child', payload: { toIndex: update.toIndex, content: update.content.toString() } }); } break; case 'MOVE_EXISTING': moveChild(parentNode, update.fromNode, getNodeAfter(parentNode, update.afterNode)); if (process.env.NODE_ENV !== 'production') { ReactInstrumentation.debugTool.onHostOperation({ instanceID: parentNodeDebugID, type: 'move child', payload: { fromIndex: update.fromIndex, toIndex: update.toIndex } }); } break; case 'SET_MARKUP': setInnerHTML(parentNode, update.content); if (process.env.NODE_ENV !== 'production') { ReactInstrumentation.debugTool.onHostOperation({ instanceID: parentNodeDebugID, type: 'replace children', payload: update.content.toString() }); } break; case 'TEXT_CONTENT': setTextContent(parentNode, update.content); if (process.env.NODE_ENV !== 'production') { ReactInstrumentation.debugTool.onHostOperation({ instanceID: parentNodeDebugID, type: 'replace text', payload: update.content.toString() }); } break; case 'REMOVE_NODE': removeChild(parentNode, update.fromNode); if (process.env.NODE_ENV !== 'production') { ReactInstrumentation.debugTool.onHostOperation({ instanceID: parentNodeDebugID, type: 'remove child', payload: { fromIndex: update.fromIndex } }); } break; } } } }; module.exports = DOMChildrenOperations; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 85 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var DOMNamespaces = __webpack_require__(86); var setInnerHTML = __webpack_require__(87); var createMicrosoftUnsafeLocalFunction = __webpack_require__(88); var setTextContent = __webpack_require__(89); var ELEMENT_NODE_TYPE = 1; var DOCUMENT_FRAGMENT_NODE_TYPE = 11; /** * In IE (8-11) and Edge, appending nodes with no children is dramatically * faster than appending a full subtree, so we essentially queue up the * .appendChild calls here and apply them so each node is added to its parent * before any children are added. * * In other browsers, doing so is slower or neutral compared to the other order * (in Firefox, twice as slow) so we only do this inversion in IE. * * See https://github.com/spicyj/innerhtml-vs-createelement-vs-clonenode. */ var enableLazy = typeof document !== 'undefined' && typeof document.documentMode === 'number' || typeof navigator !== 'undefined' && typeof navigator.userAgent === 'string' && /\bEdge\/\d/.test(navigator.userAgent); function insertTreeChildren(tree) { if (!enableLazy) { return; } var node = tree.node; var children = tree.children; if (children.length) { for (var i = 0; i < children.length; i++) { insertTreeBefore(node, children[i], null); } } else if (tree.html != null) { setInnerHTML(node, tree.html); } else if (tree.text != null) { setTextContent(node, tree.text); } } var insertTreeBefore = createMicrosoftUnsafeLocalFunction(function (parentNode, tree, referenceNode) { // DocumentFragments aren't actually part of the DOM after insertion so // appending children won't update the DOM. We need to ensure the fragment // is properly populated first, breaking out of our lazy approach for just // this level. Also, some <object> plugins (like Flash Player) will read // <param> nodes immediately upon insertion into the DOM, so <object> // must also be populated prior to insertion into the DOM. if (tree.node.nodeType === DOCUMENT_FRAGMENT_NODE_TYPE || tree.node.nodeType === ELEMENT_NODE_TYPE && tree.node.nodeName.toLowerCase() === 'object' && (tree.node.namespaceURI == null || tree.node.namespaceURI === DOMNamespaces.html)) { insertTreeChildren(tree); parentNode.insertBefore(tree.node, referenceNode); } else { parentNode.insertBefore(tree.node, referenceNode); insertTreeChildren(tree); } }); function replaceChildWithTree(oldNode, newTree) { oldNode.parentNode.replaceChild(newTree.node, oldNode); insertTreeChildren(newTree); } function queueChild(parentTree, childTree) { if (enableLazy) { parentTree.children.push(childTree); } else { parentTree.node.appendChild(childTree.node); } } function queueHTML(tree, html) { if (enableLazy) { tree.html = html; } else { setInnerHTML(tree.node, html); } } function queueText(tree, text) { if (enableLazy) { tree.text = text; } else { setTextContent(tree.node, text); } } function toString() { return this.node.nodeName; } function DOMLazyTree(node) { return { node: node, children: [], html: null, text: null, toString: toString }; } DOMLazyTree.insertTreeBefore = insertTreeBefore; DOMLazyTree.replaceChildWithTree = replaceChildWithTree; DOMLazyTree.queueChild = queueChild; DOMLazyTree.queueHTML = queueHTML; DOMLazyTree.queueText = queueText; module.exports = DOMLazyTree; /***/ }), /* 86 */ /***/ (function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var DOMNamespaces = { html: 'http://www.w3.org/1999/xhtml', mathml: 'http://www.w3.org/1998/Math/MathML', svg: 'http://www.w3.org/2000/svg' }; module.exports = DOMNamespaces; /***/ }), /* 87 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var ExecutionEnvironment = __webpack_require__(52); var DOMNamespaces = __webpack_require__(86); var WHITESPACE_TEST = /^[ \r\n\t\f]/; var NONVISIBLE_TEST = /<(!--|link|noscript|meta|script|style)[ \r\n\t\f\/>]/; var createMicrosoftUnsafeLocalFunction = __webpack_require__(88); // SVG temp container for IE lacking innerHTML var reusableSVGContainer; /** * Set the innerHTML property of a node, ensuring that whitespace is preserved * even in IE8. * * @param {DOMElement} node * @param {string} html * @internal */ var setInnerHTML = createMicrosoftUnsafeLocalFunction(function (node, html) { // IE does not have innerHTML for SVG nodes, so instead we inject the // new markup in a temp node and then move the child nodes across into // the target node if (node.namespaceURI === DOMNamespaces.svg && !('innerHTML' in node)) { reusableSVGContainer = reusableSVGContainer || document.createElement('div'); reusableSVGContainer.innerHTML = '<svg>' + html + '</svg>'; var svgNode = reusableSVGContainer.firstChild; while (svgNode.firstChild) { node.appendChild(svgNode.firstChild); } } else { node.innerHTML = html; } }); if (ExecutionEnvironment.canUseDOM) { // IE8: When updating a just created node with innerHTML only leading // whitespace is removed. When updating an existing node with innerHTML // whitespace in root TextNodes is also collapsed. // @see quirksmode.org/bugreports/archives/2004/11/innerhtml_and_t.html // Feature detection; only IE8 is known to behave improperly like this. var testElement = document.createElement('div'); testElement.innerHTML = ' '; if (testElement.innerHTML === '') { setInnerHTML = function (node, html) { // Magic theory: IE8 supposedly differentiates between added and updated // nodes when processing innerHTML, innerHTML on updated nodes suffers // from worse whitespace behavior. Re-adding a node like this triggers // the initial and more favorable whitespace behavior. // TODO: What to do on a detached node? if (node.parentNode) { node.parentNode.replaceChild(node, node); } // We also implement a workaround for non-visible tags disappearing into // thin air on IE8, this only happens if there is no visible text // in-front of the non-visible tags. Piggyback on the whitespace fix // and simply check if any non-visible tags appear in the source. if (WHITESPACE_TEST.test(html) || html[0] === '<' && NONVISIBLE_TEST.test(html)) { // Recover leading whitespace by temporarily prepending any character. // \uFEFF has the potential advantage of being zero-width/invisible. // UglifyJS drops U+FEFF chars when parsing, so use String.fromCharCode // in hopes that this is preserved even if "\uFEFF" is transformed to // the actual Unicode character (by Babel, for example). // https://github.com/mishoo/UglifyJS2/blob/v2.4.20/lib/parse.js#L216 node.innerHTML = String.fromCharCode(0xFEFF) + html; // deleteData leaves an empty `TextNode` which offsets the index of all // children. Definitely want to avoid this. var textNode = node.firstChild; if (textNode.data.length === 1) { node.removeChild(textNode); } else { textNode.deleteData(0, 1); } } else { node.innerHTML = html; } }; } testElement = null; } module.exports = setInnerHTML; /***/ }), /* 88 */ /***/ (function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ /* globals MSApp */ 'use strict'; /** * Create a function which has 'unsafe' privileges (required by windows8 apps) */ 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; } }; module.exports = createMicrosoftUnsafeLocalFunction; /***/ }), /* 89 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var ExecutionEnvironment = __webpack_require__(52); var escapeTextContentForBrowser = __webpack_require__(90); var setInnerHTML = __webpack_require__(87); /** * Set the textContent property of a node, ensuring that whitespace is preserved * even in IE8. innerText is a poor substitute for textContent and, among many * issues, inserts <br> instead of the literal newline chars. innerHTML behaves * as it should. * * @param {DOMElement} node * @param {string} text * @internal */ var setTextContent = function (node, text) { if (text) { var firstChild = node.firstChild; if (firstChild && firstChild === node.lastChild && firstChild.nodeType === 3) { firstChild.nodeValue = text; return; } } node.textContent = text; }; if (ExecutionEnvironment.canUseDOM) { if (!('textContent' in document.documentElement)) { setTextContent = function (node, text) { if (node.nodeType === 3) { node.nodeValue = text; return; } setInnerHTML(node, escapeTextContentForBrowser(text)); }; } } module.exports = setTextContent; /***/ }), /* 90 */ /***/ (function(module, exports) { /** * Copyright 2016-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * Based on the escape-html library, which is used under the MIT License below: * * Copyright (c) 2012-2013 TJ Holowaychuk * Copyright (c) 2015 Andreas Lubbe * Copyright (c) 2015 Tiancheng "Timothy" Gu * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * 'Software'), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ 'use strict'; // code copied and modified from escape-html /** * Module variables. * @private */ var matchHtmlRegExp = /["'&<>]/; /** * Escape special characters in the given string of html. * * @param {string} string The string to escape for inserting into HTML * @return {string} * @public */ function escapeHtml(string) { var str = '' + string; var match = matchHtmlRegExp.exec(str); if (!match) { return str; } var escape; var html = ''; var index = 0; var lastIndex = 0; for (index = match.index; index < str.length; index++) { switch (str.charCodeAt(index)) { case 34: // " escape = '&quot;'; break; case 38: // & escape = '&amp;'; break; case 39: // ' escape = '&#x27;'; // modified from escape-html; used to be '&#39' break; case 60: // < escape = '&lt;'; break; case 62: // > escape = '&gt;'; break; default: continue; } if (lastIndex !== index) { html += str.substring(lastIndex, index); } lastIndex = index + 1; html += escape; } return lastIndex !== index ? html + str.substring(lastIndex, index) : html; } // end code copied and modified from escape-html /** * Escapes text to prevent scripting attacks. * * @param {*} text Text value to escape. * @return {string} An escaped string. */ function escapeTextContentForBrowser(text) { if (typeof text === 'boolean' || typeof text === 'number') { // this shortcircuit helps perf for types that we know will never have // special characters, especially given that this function is used often // for numeric dom ids. return '' + text; } return escapeHtml(text); } module.exports = escapeTextContentForBrowser; /***/ }), /* 91 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(39); var DOMLazyTree = __webpack_require__(85); var ExecutionEnvironment = __webpack_require__(52); var createNodesFromMarkup = __webpack_require__(92); var emptyFunction = __webpack_require__(12); var invariant = __webpack_require__(8); var Danger = { /** * Replaces a node with a string of markup at its current position within its * parent. The markup must render into a single root node. * * @param {DOMElement} oldChild Child node to replace. * @param {string} markup Markup to render in place of the child node. * @internal */ dangerouslyReplaceNodeWithMarkup: function (oldChild, markup) { !ExecutionEnvironment.canUseDOM ? process.env.NODE_ENV !== 'production' ? invariant(false, 'dangerouslyReplaceNodeWithMarkup(...): Cannot render markup in a worker thread. Make sure `window` and `document` are available globally before requiring React when unit testing or use ReactDOMServer.renderToString() for server rendering.') : _prodInvariant('56') : void 0; !markup ? process.env.NODE_ENV !== 'production' ? invariant(false, 'dangerouslyReplaceNodeWithMarkup(...): Missing markup.') : _prodInvariant('57') : void 0; !(oldChild.nodeName !== 'HTML') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'dangerouslyReplaceNodeWithMarkup(...): Cannot replace markup of the <html> node. This is because browser quirks make this unreliable and/or slow. If you want to render to the root you must use server rendering. See ReactDOMServer.renderToString().') : _prodInvariant('58') : void 0; if (typeof markup === 'string') { var newChild = createNodesFromMarkup(markup, emptyFunction)[0]; oldChild.parentNode.replaceChild(newChild, oldChild); } else { DOMLazyTree.replaceChildWithTree(oldChild, markup); } } }; module.exports = Danger; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 92 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {'use strict'; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ /*eslint-disable fb-www/unsafe-html*/ var ExecutionEnvironment = __webpack_require__(52); var createArrayFromMixed = __webpack_require__(93); var getMarkupWrap = __webpack_require__(94); var invariant = __webpack_require__(8); /** * Dummy container used to render all markup. */ var dummyNode = ExecutionEnvironment.canUseDOM ? document.createElement('div') : null; /** * Pattern used by `getNodeName`. */ var nodeNamePattern = /^\s*<(\w+)/; /** * Extracts the `nodeName` of the first element in a string of markup. * * @param {string} markup String of markup. * @return {?string} Node name of the supplied markup. */ function getNodeName(markup) { var nodeNameMatch = markup.match(nodeNamePattern); return nodeNameMatch && nodeNameMatch[1].toLowerCase(); } /** * Creates an array containing the nodes rendered from the supplied markup. The * optionally supplied `handleScript` function will be invoked once for each * <script> element that is rendered. If no `handleScript` function is supplied, * an exception is thrown if any <script> elements are rendered. * * @param {string} markup A string of valid HTML markup. * @param {?function} handleScript Invoked once for each rendered <script>. * @return {array<DOMElement|DOMTextNode>} An array of rendered nodes. */ function createNodesFromMarkup(markup, handleScript) { var node = dummyNode; !!!dummyNode ? process.env.NODE_ENV !== 'production' ? invariant(false, 'createNodesFromMarkup dummy not initialized') : invariant(false) : void 0; var nodeName = getNodeName(markup); var wrap = nodeName && getMarkupWrap(nodeName); if (wrap) { node.innerHTML = wrap[1] + markup + wrap[2]; var wrapDepth = wrap[0]; while (wrapDepth--) { node = node.lastChild; } } else { node.innerHTML = markup; } var scripts = node.getElementsByTagName('script'); if (scripts.length) { !handleScript ? process.env.NODE_ENV !== 'production' ? invariant(false, 'createNodesFromMarkup(...): Unexpected <script> element rendered.') : invariant(false) : void 0; createArrayFromMixed(scripts).forEach(handleScript); } var nodes = Array.from(node.childNodes); while (node.lastChild) { node.removeChild(node.lastChild); } return nodes; } module.exports = createNodesFromMarkup; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 93 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {'use strict'; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ var invariant = __webpack_require__(8); /** * Convert array-like objects to arrays. * * This API assumes the caller knows the contents of the data type. For less * well defined inputs use createArrayFromMixed. * * @param {object|function|filelist} obj * @return {array} */ function toArray(obj) { var length = obj.length; // Some browsers builtin objects can report typeof 'function' (e.g. NodeList // in old versions of Safari). !(!Array.isArray(obj) && (typeof obj === 'object' || typeof obj === 'function')) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'toArray: Array-like object expected') : invariant(false) : void 0; !(typeof length === 'number') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'toArray: Object needs a length property') : invariant(false) : void 0; !(length === 0 || length - 1 in obj) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'toArray: Object should have keys for indices') : invariant(false) : void 0; !(typeof obj.callee !== 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'toArray: Object can\'t be `arguments`. Use rest params ' + '(function(...args) {}) or Array.from() instead.') : invariant(false) : void 0; // Old IE doesn't give collections access to hasOwnProperty. Assume inputs // without method will throw during the slice call and skip straight to the // fallback. if (obj.hasOwnProperty) { try { return Array.prototype.slice.call(obj); } catch (e) { // IE < 9 does not support Array#slice on collections objects } } // Fall back to copying key by key. This assumes all keys have a value, // so will not preserve sparsely populated inputs. var ret = Array(length); for (var ii = 0; ii < length; ii++) { ret[ii] = obj[ii]; } return ret; } /** * Perform a heuristic test to determine if an object is "array-like". * * A monk asked Joshu, a Zen master, "Has a dog Buddha nature?" * Joshu replied: "Mu." * * This function determines if its argument has "array nature": it returns * true if the argument is an actual array, an `arguments' object, or an * HTMLCollection (e.g. node.childNodes or node.getElementsByTagName()). * * It will return false for other array-like objects like Filelist. * * @param {*} obj * @return {boolean} */ function hasArrayNature(obj) { return ( // not null/false !!obj && ( // arrays are objects, NodeLists are functions in Safari typeof obj == 'object' || typeof obj == 'function') && // quacks like an array 'length' in obj && // not window !('setInterval' in obj) && // no DOM node should be considered an array-like // a 'select' element has 'length' and 'item' properties on IE8 typeof obj.nodeType != 'number' && ( // a real array Array.isArray(obj) || // arguments 'callee' in obj || // HTMLCollection/NodeList 'item' in obj) ); } /** * Ensure that the argument is an array by wrapping it in an array if it is not. * Creates a copy of the argument if it is already an array. * * This is mostly useful idiomatically: * * var createArrayFromMixed = require('createArrayFromMixed'); * * function takesOneOrMoreThings(things) { * things = createArrayFromMixed(things); * ... * } * * This allows you to treat `things' as an array, but accept scalars in the API. * * If you need to convert an array-like object, like `arguments`, into an array * use toArray instead. * * @param {*} obj * @return {array} */ function createArrayFromMixed(obj) { if (!hasArrayNature(obj)) { return [obj]; } else if (Array.isArray(obj)) { return obj.slice(); } else { return toArray(obj); } } module.exports = createArrayFromMixed; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 94 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {'use strict'; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ /*eslint-disable fb-www/unsafe-html */ var ExecutionEnvironment = __webpack_require__(52); var invariant = __webpack_require__(8); /** * Dummy container used to detect which wraps are necessary. */ var dummyNode = ExecutionEnvironment.canUseDOM ? document.createElement('div') : null; /** * Some browsers cannot use `innerHTML` to render certain elements standalone, * so we wrap them, render the wrapped nodes, then extract the desired node. * * In IE8, certain elements cannot render alone, so wrap all elements ('*'). */ var shouldWrap = {}; var selectWrap = [1, '<select multiple="true">', '</select>']; var tableWrap = [1, '<table>', '</table>']; var trWrap = [3, '<table><tbody><tr>', '</tr></tbody></table>']; var svgWrap = [1, '<svg xmlns="http://www.w3.org/2000/svg">', '</svg>']; var markupWrap = { '*': [1, '?<div>', '</div>'], 'area': [1, '<map>', '</map>'], 'col': [2, '<table><tbody></tbody><colgroup>', '</colgroup></table>'], 'legend': [1, '<fieldset>', '</fieldset>'], 'param': [1, '<object>', '</object>'], 'tr': [2, '<table><tbody>', '</tbody></table>'], 'optgroup': selectWrap, 'option': selectWrap, 'caption': tableWrap, 'colgroup': tableWrap, 'tbody': tableWrap, 'tfoot': tableWrap, 'thead': tableWrap, 'td': trWrap, 'th': trWrap }; // Initialize the SVG elements since we know they'll always need to be wrapped // consistently. If they are created inside a <div> they will be initialized in // the wrong namespace (and will not display). var svgElements = ['circle', 'clipPath', 'defs', 'ellipse', 'g', 'image', 'line', 'linearGradient', 'mask', 'path', 'pattern', 'polygon', 'polyline', 'radialGradient', 'rect', 'stop', 'text', 'tspan']; svgElements.forEach(function (nodeName) { markupWrap[nodeName] = svgWrap; shouldWrap[nodeName] = true; }); /** * Gets the markup wrap configuration for the supplied `nodeName`. * * NOTE: This lazily detects which wraps are necessary for the current browser. * * @param {string} nodeName Lowercase `nodeName`. * @return {?array} Markup wrap configuration, if applicable. */ function getMarkupWrap(nodeName) { !!!dummyNode ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Markup wrapping node not initialized') : invariant(false) : void 0; if (!markupWrap.hasOwnProperty(nodeName)) { nodeName = '*'; } if (!shouldWrap.hasOwnProperty(nodeName)) { if (nodeName === '*') { dummyNode.innerHTML = '<link />'; } else { dummyNode.innerHTML = '<' + nodeName + '></' + nodeName + '>'; } shouldWrap[nodeName] = !dummyNode.firstChild; } return shouldWrap[nodeName] ? markupWrap[nodeName] : null; } module.exports = getMarkupWrap; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 95 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var DOMChildrenOperations = __webpack_require__(84); var ReactDOMComponentTree = __webpack_require__(38); /** * Operations used to process updates to DOM nodes. */ var ReactDOMIDOperations = { /** * Updates a component's children by processing a series of updates. * * @param {array<object>} updates List of update configurations. * @internal */ dangerouslyProcessChildrenUpdates: function (parentInst, updates) { var node = ReactDOMComponentTree.getNodeFromInstance(parentInst); DOMChildrenOperations.processUpdates(node, updates); } }; module.exports = ReactDOMIDOperations; /***/ }), /* 96 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ /* global hasOwnProperty:true */ 'use strict'; var _prodInvariant = __webpack_require__(39), _assign = __webpack_require__(4); var AutoFocusUtils = __webpack_require__(97); var CSSPropertyOperations = __webpack_require__(99); var DOMLazyTree = __webpack_require__(85); var DOMNamespaces = __webpack_require__(86); var DOMProperty = __webpack_require__(40); var DOMPropertyOperations = __webpack_require__(107); var EventPluginHub = __webpack_require__(46); var EventPluginRegistry = __webpack_require__(47); var ReactBrowserEventEmitter = __webpack_require__(109); var ReactDOMComponentFlags = __webpack_require__(41); var ReactDOMComponentTree = __webpack_require__(38); var ReactDOMInput = __webpack_require__(112); var ReactDOMOption = __webpack_require__(115); var ReactDOMSelect = __webpack_require__(116); var ReactDOMTextarea = __webpack_require__(117); var ReactInstrumentation = __webpack_require__(66); var ReactMultiChild = __webpack_require__(118); var ReactServerRenderingTransaction = __webpack_require__(137); var emptyFunction = __webpack_require__(12); var escapeTextContentForBrowser = __webpack_require__(90); var invariant = __webpack_require__(8); var isEventSupported = __webpack_require__(74); var shallowEqual = __webpack_require__(127); var validateDOMNesting = __webpack_require__(140); var warning = __webpack_require__(11); var Flags = ReactDOMComponentFlags; var deleteListener = EventPluginHub.deleteListener; var getNode = ReactDOMComponentTree.getNodeFromInstance; var listenTo = ReactBrowserEventEmitter.listenTo; var registrationNameModules = EventPluginRegistry.registrationNameModules; // For quickly matching children type, to test if can be treated as content. var CONTENT_TYPES = { 'string': true, 'number': true }; var STYLE = 'style'; var HTML = '__html'; var RESERVED_PROPS = { children: null, dangerouslySetInnerHTML: null, suppressContentEditableWarning: null }; // Node type for document fragments (Node.DOCUMENT_FRAGMENT_NODE). var DOC_FRAGMENT_TYPE = 11; function getDeclarationErrorAddendum(internalInstance) { if (internalInstance) { var owner = internalInstance._currentElement._owner || null; if (owner) { var name = owner.getName(); if (name) { return ' This DOM node was rendered by `' + name + '`.'; } } } return ''; } function friendlyStringify(obj) { if (typeof obj === 'object') { if (Array.isArray(obj)) { return '[' + obj.map(friendlyStringify).join(', ') + ']'; } else { var pairs = []; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var keyEscaped = /^[a-z$_][\w$_]*$/i.test(key) ? key : JSON.stringify(key); pairs.push(keyEscaped + ': ' + friendlyStringify(obj[key])); } } return '{' + pairs.join(', ') + '}'; } } else if (typeof obj === 'string') { return JSON.stringify(obj); } else if (typeof obj === 'function') { return '[function object]'; } // Differs from JSON.stringify in that undefined because undefined and that // inf and nan don't become null return String(obj); } var styleMutationWarning = {}; function checkAndWarnForMutatedStyle(style1, style2, component) { if (style1 == null || style2 == null) { return; } if (shallowEqual(style1, style2)) { return; } var componentName = component._tag; var owner = component._currentElement._owner; var ownerName; if (owner) { ownerName = owner.getName(); } var hash = ownerName + '|' + componentName; if (styleMutationWarning.hasOwnProperty(hash)) { return; } styleMutationWarning[hash] = true; process.env.NODE_ENV !== 'production' ? warning(false, '`%s` was passed a style object that has previously been mutated. ' + 'Mutating `style` is deprecated. Consider cloning it beforehand. Check ' + 'the `render` %s. Previous style: %s. Mutated style: %s.', componentName, owner ? 'of `' + ownerName + '`' : 'using <' + componentName + '>', friendlyStringify(style1), friendlyStringify(style2)) : void 0; } /** * @param {object} component * @param {?object} props */ function assertValidProps(component, props) { if (!props) { return; } // Note the use of `==` which checks for null or undefined. if (voidElementTags[component._tag]) { !(props.children == null && props.dangerouslySetInnerHTML == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s is a void element tag and must neither have `children` nor use `dangerouslySetInnerHTML`.%s', component._tag, component._currentElement._owner ? ' Check the render method of ' + component._currentElement._owner.getName() + '.' : '') : _prodInvariant('137', component._tag, component._currentElement._owner ? ' Check the render method of ' + component._currentElement._owner.getName() + '.' : '') : void 0; } if (props.dangerouslySetInnerHTML != null) { !(props.children == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Can only set one of `children` or `props.dangerouslySetInnerHTML`.') : _prodInvariant('60') : void 0; !(typeof props.dangerouslySetInnerHTML === 'object' && HTML in props.dangerouslySetInnerHTML) ? process.env.NODE_ENV !== 'production' ? invariant(false, '`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. Please visit https://fb.me/react-invariant-dangerously-set-inner-html for more information.') : _prodInvariant('61') : void 0; } if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(props.innerHTML == null, 'Directly setting property `innerHTML` is not permitted. ' + 'For more information, lookup documentation on `dangerouslySetInnerHTML`.') : void 0; process.env.NODE_ENV !== 'production' ? warning(props.suppressContentEditableWarning || !props.contentEditable || props.children == null, '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.') : void 0; process.env.NODE_ENV !== 'production' ? warning(props.onFocusIn == null && props.onFocusOut == null, '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.') : void 0; } !(props.style == null || typeof props.style === 'object') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'The `style` prop expects a mapping from style properties to values, not a string. For example, style={{marginRight: spacing + \'em\'}} when using JSX.%s', getDeclarationErrorAddendum(component)) : _prodInvariant('62', getDeclarationErrorAddendum(component)) : void 0; } function enqueuePutListener(inst, registrationName, listener, transaction) { if (transaction instanceof ReactServerRenderingTransaction) { return; } if (process.env.NODE_ENV !== 'production') { // IE8 has no API for event capturing and the `onScroll` event doesn't // bubble. process.env.NODE_ENV !== 'production' ? warning(registrationName !== 'onScroll' || isEventSupported('scroll', true), 'This browser doesn\'t support the `onScroll` event') : void 0; } var containerInfo = inst._hostContainerInfo; var isDocumentFragment = containerInfo._node && containerInfo._node.nodeType === DOC_FRAGMENT_TYPE; var doc = isDocumentFragment ? containerInfo._node : containerInfo._ownerDocument; listenTo(registrationName, doc); transaction.getReactMountReady().enqueue(putListener, { inst: inst, registrationName: registrationName, listener: listener }); } function putListener() { var listenerToPut = this; EventPluginHub.putListener(listenerToPut.inst, listenerToPut.registrationName, listenerToPut.listener); } function inputPostMount() { var inst = this; ReactDOMInput.postMountWrapper(inst); } function textareaPostMount() { var inst = this; ReactDOMTextarea.postMountWrapper(inst); } function optionPostMount() { var inst = this; ReactDOMOption.postMountWrapper(inst); } var setAndValidateContentChildDev = emptyFunction; if (process.env.NODE_ENV !== 'production') { setAndValidateContentChildDev = function (content) { var hasExistingContent = this._contentDebugID != null; var debugID = this._debugID; // This ID represents the inlined child that has no backing instance: var contentDebugID = -debugID; if (content == null) { if (hasExistingContent) { ReactInstrumentation.debugTool.onUnmountComponent(this._contentDebugID); } this._contentDebugID = null; return; } validateDOMNesting(null, String(content), this, this._ancestorInfo); this._contentDebugID = contentDebugID; if (hasExistingContent) { ReactInstrumentation.debugTool.onBeforeUpdateComponent(contentDebugID, content); ReactInstrumentation.debugTool.onUpdateComponent(contentDebugID); } else { ReactInstrumentation.debugTool.onBeforeMountComponent(contentDebugID, content, debugID); ReactInstrumentation.debugTool.onMountComponent(contentDebugID); ReactInstrumentation.debugTool.onSetChildren(debugID, [contentDebugID]); } }; } // There are so many media events, it makes sense to just // maintain a list rather than create a `trapBubbledEvent` for each var mediaEvents = { topAbort: 'abort', topCanPlay: 'canplay', topCanPlayThrough: 'canplaythrough', topDurationChange: 'durationchange', topEmptied: 'emptied', topEncrypted: 'encrypted', topEnded: 'ended', topError: 'error', topLoadedData: 'loadeddata', topLoadedMetadata: 'loadedmetadata', topLoadStart: 'loadstart', topPause: 'pause', topPlay: 'play', topPlaying: 'playing', topProgress: 'progress', topRateChange: 'ratechange', topSeeked: 'seeked', topSeeking: 'seeking', topStalled: 'stalled', topSuspend: 'suspend', topTimeUpdate: 'timeupdate', topVolumeChange: 'volumechange', topWaiting: 'waiting' }; function trapBubbledEventsLocal() { var inst = this; // If a component renders to null or if another component fatals and causes // the state of the tree to be corrupted, `node` here can be null. !inst._rootNodeID ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Must be mounted to trap events') : _prodInvariant('63') : void 0; var node = getNode(inst); !node ? process.env.NODE_ENV !== 'production' ? invariant(false, 'trapBubbledEvent(...): Requires node to be rendered.') : _prodInvariant('64') : void 0; switch (inst._tag) { case 'iframe': case 'object': inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent('topLoad', 'load', node)]; break; case 'video': case 'audio': inst._wrapperState.listeners = []; // Create listener for each media event for (var event in mediaEvents) { if (mediaEvents.hasOwnProperty(event)) { inst._wrapperState.listeners.push(ReactBrowserEventEmitter.trapBubbledEvent(event, mediaEvents[event], node)); } } break; case 'source': inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent('topError', 'error', node)]; break; case 'img': inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent('topError', 'error', node), ReactBrowserEventEmitter.trapBubbledEvent('topLoad', 'load', node)]; break; case 'form': inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent('topReset', 'reset', node), ReactBrowserEventEmitter.trapBubbledEvent('topSubmit', 'submit', node)]; break; case 'input': case 'select': case 'textarea': inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent('topInvalid', 'invalid', node)]; break; } } function postUpdateSelectWrapper() { ReactDOMSelect.postUpdateWrapper(this); } // For HTML, certain tags should omit their close tag. We keep a whitelist for // those special-case tags. 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 newlineEatingTags = { 'listing': true, 'pre': true, 'textarea': true }; // For HTML, certain tags cannot have children. This has the same purpose as // `omittedCloseTags` except that `menuitem` should still have its closing tag. var voidElementTags = _assign({ 'menuitem': true }, omittedCloseTags); // We accept any tag to be rendered but since this gets injected into arbitrary // HTML, we want to make sure that it's a safe tag. // http://www.w3.org/TR/REC-xml/#NT-Name var VALID_TAG_REGEX = /^[a-zA-Z][a-zA-Z:_\.\-\d]*$/; // Simplified subset var validatedTagCache = {}; var hasOwnProperty = {}.hasOwnProperty; function validateDangerousTag(tag) { if (!hasOwnProperty.call(validatedTagCache, tag)) { !VALID_TAG_REGEX.test(tag) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Invalid tag: %s', tag) : _prodInvariant('65', tag) : void 0; validatedTagCache[tag] = true; } } function isCustomComponent(tagName, props) { return tagName.indexOf('-') >= 0 || props.is != null; } var globalIdCounter = 1; /** * Creates a new React class that is idempotent and capable of containing other * React components. It accepts event listeners and DOM properties that are * valid according to `DOMProperty`. * * - Event listeners: `onClick`, `onMouseDown`, etc. * - DOM properties: `className`, `name`, `title`, etc. * * The `style` property functions differently from the DOM API. It accepts an * object mapping of style properties to values. * * @constructor ReactDOMComponent * @extends ReactMultiChild */ function ReactDOMComponent(element) { var tag = element.type; validateDangerousTag(tag); this._currentElement = element; this._tag = tag.toLowerCase(); this._namespaceURI = null; this._renderedChildren = null; this._previousStyle = null; this._previousStyleCopy = null; this._hostNode = null; this._hostParent = null; this._rootNodeID = 0; this._domID = 0; this._hostContainerInfo = null; this._wrapperState = null; this._topLevelWrapper = null; this._flags = 0; if (process.env.NODE_ENV !== 'production') { this._ancestorInfo = null; setAndValidateContentChildDev.call(this, null); } } ReactDOMComponent.displayName = 'ReactDOMComponent'; ReactDOMComponent.Mixin = { /** * Generates root tag markup then recurses. This method has side effects and * is not idempotent. * * @internal * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {?ReactDOMComponent} the parent component instance * @param {?object} info about the host container * @param {object} context * @return {string} The computed markup. */ mountComponent: function (transaction, hostParent, hostContainerInfo, context) { this._rootNodeID = globalIdCounter++; this._domID = hostContainerInfo._idCounter++; this._hostParent = hostParent; this._hostContainerInfo = hostContainerInfo; var props = this._currentElement.props; switch (this._tag) { case 'audio': case 'form': case 'iframe': case 'img': case 'link': case 'object': case 'source': case 'video': this._wrapperState = { listeners: null }; transaction.getReactMountReady().enqueue(trapBubbledEventsLocal, this); break; case 'input': ReactDOMInput.mountWrapper(this, props, hostParent); props = ReactDOMInput.getHostProps(this, props); transaction.getReactMountReady().enqueue(trapBubbledEventsLocal, this); break; case 'option': ReactDOMOption.mountWrapper(this, props, hostParent); props = ReactDOMOption.getHostProps(this, props); break; case 'select': ReactDOMSelect.mountWrapper(this, props, hostParent); props = ReactDOMSelect.getHostProps(this, props); transaction.getReactMountReady().enqueue(trapBubbledEventsLocal, this); break; case 'textarea': ReactDOMTextarea.mountWrapper(this, props, hostParent); props = ReactDOMTextarea.getHostProps(this, props); transaction.getReactMountReady().enqueue(trapBubbledEventsLocal, this); break; } assertValidProps(this, props); // We create tags in the namespace of their parent container, except HTML // tags get no namespace. var namespaceURI; var parentTag; if (hostParent != null) { namespaceURI = hostParent._namespaceURI; parentTag = hostParent._tag; } else if (hostContainerInfo._tag) { namespaceURI = hostContainerInfo._namespaceURI; parentTag = hostContainerInfo._tag; } if (namespaceURI == null || namespaceURI === DOMNamespaces.svg && parentTag === 'foreignobject') { namespaceURI = DOMNamespaces.html; } if (namespaceURI === DOMNamespaces.html) { if (this._tag === 'svg') { namespaceURI = DOMNamespaces.svg; } else if (this._tag === 'math') { namespaceURI = DOMNamespaces.mathml; } } this._namespaceURI = namespaceURI; if (process.env.NODE_ENV !== 'production') { var parentInfo; if (hostParent != null) { parentInfo = hostParent._ancestorInfo; } else if (hostContainerInfo._tag) { parentInfo = hostContainerInfo._ancestorInfo; } if (parentInfo) { // parentInfo should always be present except for the top-level // component when server rendering validateDOMNesting(this._tag, null, this, parentInfo); } this._ancestorInfo = validateDOMNesting.updatedAncestorInfo(parentInfo, this._tag, this); } var mountImage; if (transaction.useCreateElement) { var ownerDocument = hostContainerInfo._ownerDocument; var el; if (namespaceURI === DOMNamespaces.html) { if (this._tag === 'script') { // Create the script via .innerHTML so its "parser-inserted" flag is // set to true and it does not execute var div = ownerDocument.createElement('div'); var type = this._currentElement.type; div.innerHTML = '<' + type + '></' + type + '>'; el = div.removeChild(div.firstChild); } else if (props.is) { el = ownerDocument.createElement(this._currentElement.type, props.is); } else { // Separate else branch instead of using `props.is || undefined` above becuase of a Firefox bug. // See discussion in https://github.com/facebook/react/pull/6896 // and discussion in https://bugzilla.mozilla.org/show_bug.cgi?id=1276240 el = ownerDocument.createElement(this._currentElement.type); } } else { el = ownerDocument.createElementNS(namespaceURI, this._currentElement.type); } ReactDOMComponentTree.precacheNode(this, el); this._flags |= Flags.hasCachedChildNodes; if (!this._hostParent) { DOMPropertyOperations.setAttributeForRoot(el); } this._updateDOMProperties(null, props, transaction); var lazyTree = DOMLazyTree(el); this._createInitialChildren(transaction, props, context, lazyTree); mountImage = lazyTree; } else { var tagOpen = this._createOpenTagMarkupAndPutListeners(transaction, props); var tagContent = this._createContentMarkup(transaction, props, context); if (!tagContent && omittedCloseTags[this._tag]) { mountImage = tagOpen + '/>'; } else { mountImage = tagOpen + '>' + tagContent + '</' + this._currentElement.type + '>'; } } switch (this._tag) { case 'input': transaction.getReactMountReady().enqueue(inputPostMount, this); if (props.autoFocus) { transaction.getReactMountReady().enqueue(AutoFocusUtils.focusDOMComponent, this); } break; case 'textarea': transaction.getReactMountReady().enqueue(textareaPostMount, this); if (props.autoFocus) { transaction.getReactMountReady().enqueue(AutoFocusUtils.focusDOMComponent, this); } break; case 'select': if (props.autoFocus) { transaction.getReactMountReady().enqueue(AutoFocusUtils.focusDOMComponent, this); } break; case 'button': if (props.autoFocus) { transaction.getReactMountReady().enqueue(AutoFocusUtils.focusDOMComponent, this); } break; case 'option': transaction.getReactMountReady().enqueue(optionPostMount, this); break; } return mountImage; }, /** * Creates markup for the open tag and all attributes. * * This method has side effects because events get registered. * * Iterating over object properties is faster than iterating over arrays. * @see http://jsperf.com/obj-vs-arr-iteration * * @private * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {object} props * @return {string} Markup of opening tag. */ _createOpenTagMarkupAndPutListeners: function (transaction, props) { var ret = '<' + this._currentElement.type; for (var propKey in props) { if (!props.hasOwnProperty(propKey)) { continue; } var propValue = props[propKey]; if (propValue == null) { continue; } if (registrationNameModules.hasOwnProperty(propKey)) { if (propValue) { enqueuePutListener(this, propKey, propValue, transaction); } } else { if (propKey === STYLE) { if (propValue) { if (process.env.NODE_ENV !== 'production') { // See `_updateDOMProperties`. style block this._previousStyle = propValue; } propValue = this._previousStyleCopy = _assign({}, props.style); } propValue = CSSPropertyOperations.createMarkupForStyles(propValue, this); } var markup = null; if (this._tag != null && isCustomComponent(this._tag, props)) { if (!RESERVED_PROPS.hasOwnProperty(propKey)) { markup = DOMPropertyOperations.createMarkupForCustomAttribute(propKey, propValue); } } else { markup = DOMPropertyOperations.createMarkupForProperty(propKey, propValue); } if (markup) { ret += ' ' + markup; } } } // For static pages, no need to put React ID and checksum. Saves lots of // bytes. if (transaction.renderToStaticMarkup) { return ret; } if (!this._hostParent) { ret += ' ' + DOMPropertyOperations.createMarkupForRoot(); } ret += ' ' + DOMPropertyOperations.createMarkupForID(this._domID); return ret; }, /** * Creates markup for the content between the tags. * * @private * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {object} props * @param {object} context * @return {string} Content markup. */ _createContentMarkup: function (transaction, props, context) { var ret = ''; // Intentional use of != to avoid catching zero/false. var innerHTML = props.dangerouslySetInnerHTML; if (innerHTML != null) { if (innerHTML.__html != null) { ret = innerHTML.__html; } } else { var contentToUse = CONTENT_TYPES[typeof props.children] ? props.children : null; var childrenToUse = contentToUse != null ? null : props.children; if (contentToUse != null) { // TODO: Validate that text is allowed as a child of this node ret = escapeTextContentForBrowser(contentToUse); if (process.env.NODE_ENV !== 'production') { setAndValidateContentChildDev.call(this, contentToUse); } } else if (childrenToUse != null) { var mountImages = this.mountChildren(childrenToUse, transaction, context); ret = mountImages.join(''); } } if (newlineEatingTags[this._tag] && ret.charAt(0) === '\n') { // text/html ignores the first character in these tags if it's a newline // Prefer to break application/xml over text/html (for now) by adding // a newline specifically to get eaten by the parser. (Alternately for // textareas, replacing "^\n" with "\r\n" doesn't get eaten, and the first // \r is normalized out by HTMLTextAreaElement#value.) // See: <http://www.w3.org/TR/html-polyglot/#newlines-in-textarea-and-pre> // See: <http://www.w3.org/TR/html5/syntax.html#element-restrictions> // See: <http://www.w3.org/TR/html5/syntax.html#newlines> // See: Parsing of "textarea" "listing" and "pre" elements // from <http://www.w3.org/TR/html5/syntax.html#parsing-main-inbody> return '\n' + ret; } else { return ret; } }, _createInitialChildren: function (transaction, props, context, lazyTree) { // Intentional use of != to avoid catching zero/false. var innerHTML = props.dangerouslySetInnerHTML; if (innerHTML != null) { if (innerHTML.__html != null) { DOMLazyTree.queueHTML(lazyTree, innerHTML.__html); } } else { var contentToUse = CONTENT_TYPES[typeof props.children] ? props.children : null; var childrenToUse = contentToUse != null ? null : props.children; // TODO: Validate that text is allowed as a child of this node if (contentToUse != null) { // Avoid setting textContent when the text is empty. In IE11 setting // textContent on a text area will cause the placeholder to not // show within the textarea until it has been focused and blurred again. // https://github.com/facebook/react/issues/6731#issuecomment-254874553 if (contentToUse !== '') { if (process.env.NODE_ENV !== 'production') { setAndValidateContentChildDev.call(this, contentToUse); } DOMLazyTree.queueText(lazyTree, contentToUse); } } else if (childrenToUse != null) { var mountImages = this.mountChildren(childrenToUse, transaction, context); for (var i = 0; i < mountImages.length; i++) { DOMLazyTree.queueChild(lazyTree, mountImages[i]); } } } }, /** * Receives a next element and updates the component. * * @internal * @param {ReactElement} nextElement * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {object} context */ receiveComponent: function (nextElement, transaction, context) { var prevElement = this._currentElement; this._currentElement = nextElement; this.updateComponent(transaction, prevElement, nextElement, context); }, /** * Updates a DOM component after it has already been allocated and * attached to the DOM. Reconciles the root DOM node, then recurses. * * @param {ReactReconcileTransaction} transaction * @param {ReactElement} prevElement * @param {ReactElement} nextElement * @internal * @overridable */ updateComponent: function (transaction, prevElement, nextElement, context) { var lastProps = prevElement.props; var nextProps = this._currentElement.props; switch (this._tag) { case 'input': lastProps = ReactDOMInput.getHostProps(this, lastProps); nextProps = ReactDOMInput.getHostProps(this, nextProps); break; case 'option': lastProps = ReactDOMOption.getHostProps(this, lastProps); nextProps = ReactDOMOption.getHostProps(this, nextProps); break; case 'select': lastProps = ReactDOMSelect.getHostProps(this, lastProps); nextProps = ReactDOMSelect.getHostProps(this, nextProps); break; case 'textarea': lastProps = ReactDOMTextarea.getHostProps(this, lastProps); nextProps = ReactDOMTextarea.getHostProps(this, nextProps); break; } assertValidProps(this, nextProps); this._updateDOMProperties(lastProps, nextProps, transaction); this._updateDOMChildren(lastProps, nextProps, transaction, context); switch (this._tag) { case 'input': // Update the wrapper around inputs *after* updating props. This has to // happen after `_updateDOMProperties`. Otherwise HTML5 input validations // raise warnings and prevent the new value from being assigned. ReactDOMInput.updateWrapper(this); break; case 'textarea': ReactDOMTextarea.updateWrapper(this); break; case 'select': // <select> value update needs to occur after <option> children // reconciliation transaction.getReactMountReady().enqueue(postUpdateSelectWrapper, this); break; } }, /** * Reconciles the properties by detecting differences in property values and * updating the DOM as necessary. This function is probably the single most * critical path for performance optimization. * * TODO: Benchmark whether checking for changed values in memory actually * improves performance (especially statically positioned elements). * TODO: Benchmark the effects of putting this at the top since 99% of props * do not change for a given reconciliation. * TODO: Benchmark areas that can be improved with caching. * * @private * @param {object} lastProps * @param {object} nextProps * @param {?DOMElement} node */ _updateDOMProperties: function (lastProps, nextProps, transaction) { var propKey; var styleName; var styleUpdates; for (propKey in lastProps) { if (nextProps.hasOwnProperty(propKey) || !lastProps.hasOwnProperty(propKey) || lastProps[propKey] == null) { continue; } if (propKey === STYLE) { var lastStyle = this._previousStyleCopy; for (styleName in lastStyle) { if (lastStyle.hasOwnProperty(styleName)) { styleUpdates = styleUpdates || {}; styleUpdates[styleName] = ''; } } this._previousStyleCopy = null; } else if (registrationNameModules.hasOwnProperty(propKey)) { if (lastProps[propKey]) { // Only call deleteListener if there was a listener previously or // else willDeleteListener gets called when there wasn't actually a // listener (e.g., onClick={null}) deleteListener(this, propKey); } } else if (isCustomComponent(this._tag, lastProps)) { if (!RESERVED_PROPS.hasOwnProperty(propKey)) { DOMPropertyOperations.deleteValueForAttribute(getNode(this), propKey); } } else if (DOMProperty.properties[propKey] || DOMProperty.isCustomAttribute(propKey)) { DOMPropertyOperations.deleteValueForProperty(getNode(this), propKey); } } for (propKey in nextProps) { var nextProp = nextProps[propKey]; var lastProp = propKey === STYLE ? this._previousStyleCopy : lastProps != null ? lastProps[propKey] : undefined; if (!nextProps.hasOwnProperty(propKey) || nextProp === lastProp || nextProp == null && lastProp == null) { continue; } if (propKey === STYLE) { if (nextProp) { if (process.env.NODE_ENV !== 'production') { checkAndWarnForMutatedStyle(this._previousStyleCopy, this._previousStyle, this); this._previousStyle = nextProp; } nextProp = this._previousStyleCopy = _assign({}, nextProp); } else { this._previousStyleCopy = null; } if (lastProp) { // Unset styles on `lastProp` but not on `nextProp`. for (styleName in lastProp) { if (lastProp.hasOwnProperty(styleName) && (!nextProp || !nextProp.hasOwnProperty(styleName))) { styleUpdates = styleUpdates || {}; styleUpdates[styleName] = ''; } } // Update styles that changed since `lastProp`. for (styleName in nextProp) { if (nextProp.hasOwnProperty(styleName) && lastProp[styleName] !== nextProp[styleName]) { styleUpdates = styleUpdates || {}; styleUpdates[styleName] = nextProp[styleName]; } } } else { // Relies on `updateStylesByID` not mutating `styleUpdates`. styleUpdates = nextProp; } } else if (registrationNameModules.hasOwnProperty(propKey)) { if (nextProp) { enqueuePutListener(this, propKey, nextProp, transaction); } else if (lastProp) { deleteListener(this, propKey); } } else if (isCustomComponent(this._tag, nextProps)) { if (!RESERVED_PROPS.hasOwnProperty(propKey)) { DOMPropertyOperations.setValueForAttribute(getNode(this), propKey, nextProp); } } else if (DOMProperty.properties[propKey] || DOMProperty.isCustomAttribute(propKey)) { var node = getNode(this); // If we're updating to null or undefined, we should remove the property // from the DOM node instead of inadvertently setting to a string. This // brings us in line with the same behavior we have on initial render. if (nextProp != null) { DOMPropertyOperations.setValueForProperty(node, propKey, nextProp); } else { DOMPropertyOperations.deleteValueForProperty(node, propKey); } } } if (styleUpdates) { CSSPropertyOperations.setValueForStyles(getNode(this), styleUpdates, this); } }, /** * Reconciles the children with the various properties that affect the * children content. * * @param {object} lastProps * @param {object} nextProps * @param {ReactReconcileTransaction} transaction * @param {object} context */ _updateDOMChildren: function (lastProps, nextProps, transaction, context) { var lastContent = CONTENT_TYPES[typeof lastProps.children] ? lastProps.children : null; var nextContent = CONTENT_TYPES[typeof nextProps.children] ? nextProps.children : null; var lastHtml = lastProps.dangerouslySetInnerHTML && lastProps.dangerouslySetInnerHTML.__html; var nextHtml = nextProps.dangerouslySetInnerHTML && nextProps.dangerouslySetInnerHTML.__html; // Note the use of `!=` which checks for null or undefined. var lastChildren = lastContent != null ? null : lastProps.children; var nextChildren = nextContent != null ? null : nextProps.children; // If we're switching from children to content/html or vice versa, remove // the old content var lastHasContentOrHtml = lastContent != null || lastHtml != null; var nextHasContentOrHtml = nextContent != null || nextHtml != null; if (lastChildren != null && nextChildren == null) { this.updateChildren(null, transaction, context); } else if (lastHasContentOrHtml && !nextHasContentOrHtml) { this.updateTextContent(''); if (process.env.NODE_ENV !== 'production') { ReactInstrumentation.debugTool.onSetChildren(this._debugID, []); } } if (nextContent != null) { if (lastContent !== nextContent) { this.updateTextContent('' + nextContent); if (process.env.NODE_ENV !== 'production') { setAndValidateContentChildDev.call(this, nextContent); } } } else if (nextHtml != null) { if (lastHtml !== nextHtml) { this.updateMarkup('' + nextHtml); } if (process.env.NODE_ENV !== 'production') { ReactInstrumentation.debugTool.onSetChildren(this._debugID, []); } } else if (nextChildren != null) { if (process.env.NODE_ENV !== 'production') { setAndValidateContentChildDev.call(this, null); } this.updateChildren(nextChildren, transaction, context); } }, getHostNode: function () { return getNode(this); }, /** * Destroys all event registrations for this instance. Does not remove from * the DOM. That must be done by the parent. * * @internal */ unmountComponent: function (safely) { switch (this._tag) { case 'audio': case 'form': case 'iframe': case 'img': case 'link': case 'object': case 'source': case 'video': var listeners = this._wrapperState.listeners; if (listeners) { for (var i = 0; i < listeners.length; i++) { listeners[i].remove(); } } break; case 'html': case 'head': case 'body': /** * Components like <html> <head> and <body> can't be removed or added * easily in a cross-browser way, however it's valuable to be able to * take advantage of React's reconciliation for styling and <title> * management. So we just document it and throw in dangerous cases. */ true ? process.env.NODE_ENV !== 'production' ? invariant(false, '<%s> tried to unmount. Because of cross-browser quirks it is impossible to unmount some top-level components (eg <html>, <head>, and <body>) reliably and efficiently. To fix this, have a single top-level component that never unmounts render these elements.', this._tag) : _prodInvariant('66', this._tag) : void 0; break; } this.unmountChildren(safely); ReactDOMComponentTree.uncacheNode(this); EventPluginHub.deleteAllListeners(this); this._rootNodeID = 0; this._domID = 0; this._wrapperState = null; if (process.env.NODE_ENV !== 'production') { setAndValidateContentChildDev.call(this, null); } }, getPublicInstance: function () { return getNode(this); } }; _assign(ReactDOMComponent.prototype, ReactDOMComponent.Mixin, ReactMultiChild.Mixin); module.exports = ReactDOMComponent; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 97 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var ReactDOMComponentTree = __webpack_require__(38); var focusNode = __webpack_require__(98); var AutoFocusUtils = { focusDOMComponent: function () { focusNode(ReactDOMComponentTree.getNodeFromInstance(this)); } }; module.exports = AutoFocusUtils; /***/ }), /* 98 */ /***/ (function(module, exports) { /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; /** * @param {DOMElement} node input/textarea to focus */ function focusNode(node) { // IE8 can throw "Can't move focus to the control because it is invisible, // not enabled, or of a type that does not accept the focus." for all kinds of // reasons that are too expensive and fragile to test. try { node.focus(); } catch (e) {} } module.exports = focusNode; /***/ }), /* 99 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var CSSProperty = __webpack_require__(100); var ExecutionEnvironment = __webpack_require__(52); var ReactInstrumentation = __webpack_require__(66); var camelizeStyleName = __webpack_require__(101); var dangerousStyleValue = __webpack_require__(103); var hyphenateStyleName = __webpack_require__(104); var memoizeStringOnly = __webpack_require__(106); var warning = __webpack_require__(11); var processStyleName = memoizeStringOnly(function (styleName) { return hyphenateStyleName(styleName); }); var hasShorthandPropertyBug = false; var styleFloatAccessor = 'cssFloat'; if (ExecutionEnvironment.canUseDOM) { var tempStyle = document.createElement('div').style; try { // IE8 throws "Invalid argument." if resetting shorthand style properties. tempStyle.font = ''; } catch (e) { hasShorthandPropertyBug = true; } // IE8 only supports accessing cssFloat (standard) as styleFloat if (document.documentElement.style.cssFloat === undefined) { styleFloatAccessor = 'styleFloat'; } } if (process.env.NODE_ENV !== 'production') { // 'msTransform' is correct, but the other prefixes should be capitalized var badVendoredStyleNamePattern = /^(?:webkit|moz|o)[A-Z]/; // style values shouldn't contain a semicolon var badStyleValueWithSemicolonPattern = /;\s*$/; var warnedStyleNames = {}; var warnedStyleValues = {}; var warnedForNaNValue = false; var warnHyphenatedStyleName = function (name, owner) { if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) { return; } warnedStyleNames[name] = true; process.env.NODE_ENV !== 'production' ? warning(false, 'Unsupported style property %s. Did you mean %s?%s', name, camelizeStyleName(name), checkRenderMessage(owner)) : void 0; }; var warnBadVendoredStyleName = function (name, owner) { if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) { return; } warnedStyleNames[name] = true; process.env.NODE_ENV !== 'production' ? warning(false, 'Unsupported vendor-prefixed style property %s. Did you mean %s?%s', name, name.charAt(0).toUpperCase() + name.slice(1), checkRenderMessage(owner)) : void 0; }; var warnStyleValueWithSemicolon = function (name, value, owner) { if (warnedStyleValues.hasOwnProperty(value) && warnedStyleValues[value]) { return; } warnedStyleValues[value] = true; process.env.NODE_ENV !== 'production' ? warning(false, 'Style property values shouldn\'t contain a semicolon.%s ' + 'Try "%s: %s" instead.', checkRenderMessage(owner), name, value.replace(badStyleValueWithSemicolonPattern, '')) : void 0; }; var warnStyleValueIsNaN = function (name, value, owner) { if (warnedForNaNValue) { return; } warnedForNaNValue = true; process.env.NODE_ENV !== 'production' ? warning(false, '`NaN` is an invalid value for the `%s` css style property.%s', name, checkRenderMessage(owner)) : void 0; }; var checkRenderMessage = function (owner) { if (owner) { var name = owner.getName(); if (name) { return ' Check the render method of `' + name + '`.'; } } return ''; }; /** * @param {string} name * @param {*} value * @param {ReactDOMComponent} component */ var warnValidStyle = function (name, value, component) { var owner; if (component) { owner = component._currentElement._owner; } if (name.indexOf('-') > -1) { warnHyphenatedStyleName(name, owner); } else if (badVendoredStyleNamePattern.test(name)) { warnBadVendoredStyleName(name, owner); } else if (badStyleValueWithSemicolonPattern.test(value)) { warnStyleValueWithSemicolon(name, value, owner); } if (typeof value === 'number' && isNaN(value)) { warnStyleValueIsNaN(name, value, owner); } }; } /** * Operations for dealing with CSS properties. */ var CSSPropertyOperations = { /** * Serializes a mapping of style properties for use as inline styles: * * > createMarkupForStyles({width: '200px', height: 0}) * "width:200px;height:0;" * * Undefined values are ignored so that declarative programming is easier. * The result should be HTML-escaped before insertion into the DOM. * * @param {object} styles * @param {ReactDOMComponent} component * @return {?string} */ createMarkupForStyles: function (styles, component) { var serialized = ''; for (var styleName in styles) { if (!styles.hasOwnProperty(styleName)) { continue; } var styleValue = styles[styleName]; if (process.env.NODE_ENV !== 'production') { warnValidStyle(styleName, styleValue, component); } if (styleValue != null) { serialized += processStyleName(styleName) + ':'; serialized += dangerousStyleValue(styleName, styleValue, component) + ';'; } } return serialized || null; }, /** * Sets the value for multiple styles on a node. If a value is specified as * '' (empty string), the corresponding style property will be unset. * * @param {DOMElement} node * @param {object} styles * @param {ReactDOMComponent} component */ setValueForStyles: function (node, styles, component) { if (process.env.NODE_ENV !== 'production') { ReactInstrumentation.debugTool.onHostOperation({ instanceID: component._debugID, type: 'update styles', payload: styles }); } var style = node.style; for (var styleName in styles) { if (!styles.hasOwnProperty(styleName)) { continue; } if (process.env.NODE_ENV !== 'production') { warnValidStyle(styleName, styles[styleName], component); } var styleValue = dangerousStyleValue(styleName, styles[styleName], component); if (styleName === 'float' || styleName === 'cssFloat') { styleName = styleFloatAccessor; } if (styleValue) { style[styleName] = styleValue; } else { var expansion = hasShorthandPropertyBug && CSSProperty.shorthandPropertyExpansions[styleName]; if (expansion) { // Shorthand property that IE8 won't like unsetting, so unset each // component to placate it for (var individualStyleName in expansion) { style[individualStyleName] = ''; } } else { style[styleName] = ''; } } } } }; module.exports = CSSPropertyOperations; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 100 */ /***/ (function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; /** * CSS properties which accept numbers but are not in units of "px". */ var isUnitlessNumber = { animationIterationCount: true, borderImageOutset: true, borderImageSlice: true, borderImageWidth: true, boxFlex: true, boxFlexGroup: true, boxOrdinalGroup: true, columnCount: true, flex: true, flexGrow: true, flexPositive: true, flexShrink: true, flexNegative: true, flexOrder: true, gridRow: true, gridColumn: true, fontWeight: true, lineClamp: true, lineHeight: true, opacity: true, order: true, orphans: true, tabSize: true, widows: true, zIndex: true, zoom: true, // SVG-related properties fillOpacity: true, floodOpacity: true, stopOpacity: true, strokeDasharray: true, strokeDashoffset: true, strokeMiterlimit: true, strokeOpacity: true, strokeWidth: true }; /** * @param {string} prefix vendor-specific prefix, eg: Webkit * @param {string} key style name, eg: transitionDuration * @return {string} style name prefixed with `prefix`, properly camelCased, eg: * WebkitTransitionDuration */ function prefixKey(prefix, key) { return prefix + key.charAt(0).toUpperCase() + key.substring(1); } /** * Support style names that may come passed in prefixed by adding permutations * of vendor prefixes. */ var prefixes = ['Webkit', 'ms', 'Moz', 'O']; // Using Object.keys here, or else the vanilla for-in loop makes IE8 go into an // infinite loop, because it iterates over the newly added props too. Object.keys(isUnitlessNumber).forEach(function (prop) { prefixes.forEach(function (prefix) { isUnitlessNumber[prefixKey(prefix, prop)] = isUnitlessNumber[prop]; }); }); /** * Most style properties can be unset by doing .style[prop] = '' but IE8 * doesn't like doing that with shorthand properties so for the properties that * IE8 breaks on, which are listed here, we instead unset each of the * individual properties. See http://bugs.jquery.com/ticket/12385. * The 4-value 'clock' properties like margin, padding, border-width seem to * behave without any problems. Curiously, list-style works too without any * special prodding. */ var shorthandPropertyExpansions = { background: { backgroundAttachment: true, backgroundColor: true, backgroundImage: true, backgroundPositionX: true, backgroundPositionY: true, backgroundRepeat: true }, backgroundPosition: { backgroundPositionX: true, backgroundPositionY: true }, border: { borderWidth: true, borderStyle: true, borderColor: true }, borderBottom: { borderBottomWidth: true, borderBottomStyle: true, borderBottomColor: true }, borderLeft: { borderLeftWidth: true, borderLeftStyle: true, borderLeftColor: true }, borderRight: { borderRightWidth: true, borderRightStyle: true, borderRightColor: true }, borderTop: { borderTopWidth: true, borderTopStyle: true, borderTopColor: true }, font: { fontStyle: true, fontVariant: true, fontWeight: true, fontSize: true, lineHeight: true, fontFamily: true }, outline: { outlineWidth: true, outlineStyle: true, outlineColor: true } }; var CSSProperty = { isUnitlessNumber: isUnitlessNumber, shorthandPropertyExpansions: shorthandPropertyExpansions }; module.exports = CSSProperty; /***/ }), /* 101 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ 'use strict'; var camelize = __webpack_require__(102); var msPattern = /^-ms-/; /** * Camelcases a hyphenated CSS property name, for example: * * > camelizeStyleName('background-color') * < "backgroundColor" * > camelizeStyleName('-moz-transition') * < "MozTransition" * > camelizeStyleName('-ms-transition') * < "msTransition" * * As Andi Smith suggests * (http://www.andismith.com/blog/2012/02/modernizr-prefixed/), an `-ms` prefix * is converted to lowercase `ms`. * * @param {string} string * @return {string} */ function camelizeStyleName(string) { return camelize(string.replace(msPattern, 'ms-')); } module.exports = camelizeStyleName; /***/ }), /* 102 */ /***/ (function(module, exports) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ var _hyphenPattern = /-(.)/g; /** * Camelcases a hyphenated string, for example: * * > camelize('background-color') * < "backgroundColor" * * @param {string} string * @return {string} */ function camelize(string) { return string.replace(_hyphenPattern, function (_, character) { return character.toUpperCase(); }); } module.exports = camelize; /***/ }), /* 103 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var CSSProperty = __webpack_require__(100); var warning = __webpack_require__(11); var isUnitlessNumber = CSSProperty.isUnitlessNumber; var styleWarnings = {}; /** * Convert a value into the proper css writable value. The style name `name` * should be logical (no hyphens), as specified * in `CSSProperty.isUnitlessNumber`. * * @param {string} name CSS property name such as `topMargin`. * @param {*} value CSS property value such as `10px`. * @param {ReactDOMComponent} component * @return {string} Normalized style value with dimensions applied. */ function dangerousStyleValue(name, value, component) { // Note that we've removed escapeTextForBrowser() calls here since the // whole string will be escaped when the attribute is injected into // the markup. If you provide unsafe user data here they can inject // arbitrary CSS which may be problematic (I couldn't repro this): // https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet // http://www.thespanner.co.uk/2007/11/26/ultimate-xss-css-injection/ // This is not an XSS hole but instead a potential CSS injection issue // which has lead to a greater discussion about how we're going to // trust URLs moving forward. See #2115901 var isEmpty = value == null || typeof value === 'boolean' || value === ''; if (isEmpty) { return ''; } var isNonNumeric = isNaN(value); if (isNonNumeric || value === 0 || isUnitlessNumber.hasOwnProperty(name) && isUnitlessNumber[name]) { return '' + value; // cast to string } if (typeof value === 'string') { if (process.env.NODE_ENV !== 'production') { // Allow '0' to pass through without warning. 0 is already special and // doesn't require units, so we don't need to warn about it. if (component && value !== '0') { var owner = component._currentElement._owner; var ownerName = owner ? owner.getName() : null; if (ownerName && !styleWarnings[ownerName]) { styleWarnings[ownerName] = {}; } var warned = false; if (ownerName) { var warnings = styleWarnings[ownerName]; warned = warnings[name]; if (!warned) { warnings[name] = true; } } if (!warned) { process.env.NODE_ENV !== 'production' ? warning(false, 'a `%s` tag (owner: `%s`) was passed a numeric string value ' + 'for CSS property `%s` (value: `%s`) which will be treated ' + 'as a unitless number in a future version of React.', component._currentElement.type, ownerName || 'unknown', name, value) : void 0; } } } value = value.trim(); } return value + 'px'; } module.exports = dangerousStyleValue; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 104 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ 'use strict'; var hyphenate = __webpack_require__(105); var msPattern = /^ms-/; /** * Hyphenates a camelcased CSS property name, for example: * * > hyphenateStyleName('backgroundColor') * < "background-color" * > hyphenateStyleName('MozTransition') * < "-moz-transition" * > hyphenateStyleName('msTransition') * < "-ms-transition" * * As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix * is converted to `-ms-`. * * @param {string} string * @return {string} */ function hyphenateStyleName(string) { return hyphenate(string).replace(msPattern, '-ms-'); } module.exports = hyphenateStyleName; /***/ }), /* 105 */ /***/ (function(module, exports) { 'use strict'; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ var _uppercasePattern = /([A-Z])/g; /** * Hyphenates a camelcased string, for example: * * > hyphenate('backgroundColor') * < "background-color" * * For CSS style names, use `hyphenateStyleName` instead which works properly * with all vendor prefixes, including `ms`. * * @param {string} string * @return {string} */ function hyphenate(string) { return string.replace(_uppercasePattern, '-$1').toLowerCase(); } module.exports = hyphenate; /***/ }), /* 106 */ /***/ (function(module, exports) { /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * * @typechecks static-only */ 'use strict'; /** * Memoizes the return value of a function that accepts one string argument. */ function memoizeStringOnly(callback) { var cache = {}; return function (string) { if (!cache.hasOwnProperty(string)) { cache[string] = callback.call(this, string); } return cache[string]; }; } module.exports = memoizeStringOnly; /***/ }), /* 107 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var DOMProperty = __webpack_require__(40); var ReactDOMComponentTree = __webpack_require__(38); var ReactInstrumentation = __webpack_require__(66); var quoteAttributeValueForBrowser = __webpack_require__(108); var warning = __webpack_require__(11); var VALID_ATTRIBUTE_NAME_REGEX = new RegExp('^[' + DOMProperty.ATTRIBUTE_NAME_START_CHAR + '][' + DOMProperty.ATTRIBUTE_NAME_CHAR + ']*$'); var illegalAttributeNameCache = {}; var validatedAttributeNameCache = {}; function isAttributeNameSafe(attributeName) { if (validatedAttributeNameCache.hasOwnProperty(attributeName)) { return true; } if (illegalAttributeNameCache.hasOwnProperty(attributeName)) { return false; } if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName)) { validatedAttributeNameCache[attributeName] = true; return true; } illegalAttributeNameCache[attributeName] = true; process.env.NODE_ENV !== 'production' ? warning(false, 'Invalid attribute name: `%s`', attributeName) : void 0; return false; } function shouldIgnoreValue(propertyInfo, value) { return value == null || propertyInfo.hasBooleanValue && !value || propertyInfo.hasNumericValue && isNaN(value) || propertyInfo.hasPositiveNumericValue && value < 1 || propertyInfo.hasOverloadedBooleanValue && value === false; } /** * Operations for dealing with DOM properties. */ var DOMPropertyOperations = { /** * Creates markup for the ID property. * * @param {string} id Unescaped ID. * @return {string} Markup string. */ createMarkupForID: function (id) { return DOMProperty.ID_ATTRIBUTE_NAME + '=' + quoteAttributeValueForBrowser(id); }, setAttributeForID: function (node, id) { node.setAttribute(DOMProperty.ID_ATTRIBUTE_NAME, id); }, createMarkupForRoot: function () { return DOMProperty.ROOT_ATTRIBUTE_NAME + '=""'; }, setAttributeForRoot: function (node) { node.setAttribute(DOMProperty.ROOT_ATTRIBUTE_NAME, ''); }, /** * Creates markup for a property. * * @param {string} name * @param {*} value * @return {?string} Markup string, or null if the property was invalid. */ createMarkupForProperty: function (name, value) { var propertyInfo = DOMProperty.properties.hasOwnProperty(name) ? DOMProperty.properties[name] : null; if (propertyInfo) { if (shouldIgnoreValue(propertyInfo, value)) { return ''; } var attributeName = propertyInfo.attributeName; if (propertyInfo.hasBooleanValue || propertyInfo.hasOverloadedBooleanValue && value === true) { return attributeName + '=""'; } return attributeName + '=' + quoteAttributeValueForBrowser(value); } else if (DOMProperty.isCustomAttribute(name)) { if (value == null) { return ''; } return name + '=' + quoteAttributeValueForBrowser(value); } return null; }, /** * Creates markup for a custom property. * * @param {string} name * @param {*} value * @return {string} Markup string, or empty string if the property was invalid. */ createMarkupForCustomAttribute: function (name, value) { if (!isAttributeNameSafe(name) || value == null) { return ''; } return name + '=' + quoteAttributeValueForBrowser(value); }, /** * Sets the value for a property on a node. * * @param {DOMElement} node * @param {string} name * @param {*} value */ setValueForProperty: function (node, name, value) { var propertyInfo = DOMProperty.properties.hasOwnProperty(name) ? DOMProperty.properties[name] : null; if (propertyInfo) { var mutationMethod = propertyInfo.mutationMethod; if (mutationMethod) { mutationMethod(node, value); } else if (shouldIgnoreValue(propertyInfo, value)) { this.deleteValueForProperty(node, name); return; } else if (propertyInfo.mustUseProperty) { // Contrary to `setAttribute`, object properties are properly // `toString`ed by IE8/9. node[propertyInfo.propertyName] = value; } else { var attributeName = propertyInfo.attributeName; var namespace = propertyInfo.attributeNamespace; // `setAttribute` with objects becomes only `[object]` in IE8/9, // ('' + value) makes it output the correct toString()-value. if (namespace) { node.setAttributeNS(namespace, attributeName, '' + value); } else if (propertyInfo.hasBooleanValue || propertyInfo.hasOverloadedBooleanValue && value === true) { node.setAttribute(attributeName, ''); } else { node.setAttribute(attributeName, '' + value); } } } else if (DOMProperty.isCustomAttribute(name)) { DOMPropertyOperations.setValueForAttribute(node, name, value); return; } if (process.env.NODE_ENV !== 'production') { var payload = {}; payload[name] = value; ReactInstrumentation.debugTool.onHostOperation({ instanceID: ReactDOMComponentTree.getInstanceFromNode(node)._debugID, type: 'update attribute', payload: payload }); } }, setValueForAttribute: function (node, name, value) { if (!isAttributeNameSafe(name)) { return; } if (value == null) { node.removeAttribute(name); } else { node.setAttribute(name, '' + value); } if (process.env.NODE_ENV !== 'production') { var payload = {}; payload[name] = value; ReactInstrumentation.debugTool.onHostOperation({ instanceID: ReactDOMComponentTree.getInstanceFromNode(node)._debugID, type: 'update attribute', payload: payload }); } }, /** * Deletes an attributes from a node. * * @param {DOMElement} node * @param {string} name */ deleteValueForAttribute: function (node, name) { node.removeAttribute(name); if (process.env.NODE_ENV !== 'production') { ReactInstrumentation.debugTool.onHostOperation({ instanceID: ReactDOMComponentTree.getInstanceFromNode(node)._debugID, type: 'remove attribute', payload: name }); } }, /** * Deletes the value for a property on a node. * * @param {DOMElement} node * @param {string} name */ deleteValueForProperty: function (node, name) { var propertyInfo = DOMProperty.properties.hasOwnProperty(name) ? DOMProperty.properties[name] : null; if (propertyInfo) { var mutationMethod = propertyInfo.mutationMethod; if (mutationMethod) { mutationMethod(node, undefined); } else if (propertyInfo.mustUseProperty) { var propName = propertyInfo.propertyName; if (propertyInfo.hasBooleanValue) { node[propName] = false; } else { node[propName] = ''; } } else { node.removeAttribute(propertyInfo.attributeName); } } else if (DOMProperty.isCustomAttribute(name)) { node.removeAttribute(name); } if (process.env.NODE_ENV !== 'production') { ReactInstrumentation.debugTool.onHostOperation({ instanceID: ReactDOMComponentTree.getInstanceFromNode(node)._debugID, type: 'remove attribute', payload: name }); } } }; module.exports = DOMPropertyOperations; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 108 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var escapeTextContentForBrowser = __webpack_require__(90); /** * Escapes attribute value to prevent scripting attacks. * * @param {*} value Value to escape. * @return {string} An escaped string. */ function quoteAttributeValueForBrowser(value) { return '"' + escapeTextContentForBrowser(value) + '"'; } module.exports = quoteAttributeValueForBrowser; /***/ }), /* 109 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _assign = __webpack_require__(4); var EventPluginRegistry = __webpack_require__(47); var ReactEventEmitterMixin = __webpack_require__(110); var ViewportMetrics = __webpack_require__(80); var getVendorPrefixedEventName = __webpack_require__(111); var isEventSupported = __webpack_require__(74); /** * Summary of `ReactBrowserEventEmitter` event handling: * * - Top-level delegation is used to trap most native browser events. This * may only occur in the main thread and is the responsibility of * ReactEventListener, which is injected and can therefore support pluggable * event sources. This is the only work that occurs in the main thread. * * - We normalize and de-duplicate events to account for browser quirks. This * may be done in the worker thread. * * - Forward these native events (with the associated top-level type used to * trap it) to `EventPluginHub`, which in turn will ask plugins if they want * to extract any synthetic events. * * - The `EventPluginHub` will then process each event by annotating them with * "dispatches", a sequence of listeners and IDs that care about that event. * * - The `EventPluginHub` then dispatches the events. * * Overview of React and the event system: * * +------------+ . * | DOM | . * +------------+ . * | . * v . * +------------+ . * | ReactEvent | . * | Listener | . * +------------+ . +-----------+ * | . +--------+|SimpleEvent| * | . | |Plugin | * +-----|------+ . v +-----------+ * | | | . +--------------+ +------------+ * | +-----------.--->|EventPluginHub| | Event | * | | . | | +-----------+ | Propagators| * | ReactEvent | . | | |TapEvent | |------------| * | Emitter | . | |<---+|Plugin | |other plugin| * | | . | | +-----------+ | utilities | * | +-----------.--->| | +------------+ * | | | . +--------------+ * +-----|------+ . ^ +-----------+ * | . | |Enter/Leave| * + . +-------+|Plugin | * +-------------+ . +-----------+ * | application | . * |-------------| . * | | . * | | . * +-------------+ . * . * React Core . General Purpose Event Plugin System */ var hasEventPageXY; var alreadyListeningTo = {}; var isMonitoringScrollValue = false; var reactTopListenersCounter = 0; // For events like 'submit' which don't consistently bubble (which we trap at a // lower node than `document`), binding at `document` would cause duplicate // events so we don't include them here var topEventMapping = { topAbort: 'abort', topAnimationEnd: getVendorPrefixedEventName('animationend') || 'animationend', topAnimationIteration: getVendorPrefixedEventName('animationiteration') || 'animationiteration', topAnimationStart: getVendorPrefixedEventName('animationstart') || 'animationstart', topBlur: 'blur', topCanPlay: 'canplay', topCanPlayThrough: 'canplaythrough', topChange: 'change', topClick: 'click', topCompositionEnd: 'compositionend', topCompositionStart: 'compositionstart', topCompositionUpdate: 'compositionupdate', topContextMenu: 'contextmenu', topCopy: 'copy', topCut: 'cut', topDoubleClick: 'dblclick', topDrag: 'drag', topDragEnd: 'dragend', topDragEnter: 'dragenter', topDragExit: 'dragexit', topDragLeave: 'dragleave', topDragOver: 'dragover', topDragStart: 'dragstart', topDrop: 'drop', topDurationChange: 'durationchange', topEmptied: 'emptied', topEncrypted: 'encrypted', topEnded: 'ended', topError: 'error', topFocus: 'focus', topInput: 'input', topKeyDown: 'keydown', topKeyPress: 'keypress', topKeyUp: 'keyup', topLoadedData: 'loadeddata', topLoadedMetadata: 'loadedmetadata', topLoadStart: 'loadstart', topMouseDown: 'mousedown', topMouseMove: 'mousemove', topMouseOut: 'mouseout', topMouseOver: 'mouseover', topMouseUp: 'mouseup', topPaste: 'paste', topPause: 'pause', topPlay: 'play', topPlaying: 'playing', topProgress: 'progress', topRateChange: 'ratechange', topScroll: 'scroll', topSeeked: 'seeked', topSeeking: 'seeking', topSelectionChange: 'selectionchange', topStalled: 'stalled', topSuspend: 'suspend', topTextInput: 'textInput', topTimeUpdate: 'timeupdate', topTouchCancel: 'touchcancel', topTouchEnd: 'touchend', topTouchMove: 'touchmove', topTouchStart: 'touchstart', topTransitionEnd: getVendorPrefixedEventName('transitionend') || 'transitionend', topVolumeChange: 'volumechange', topWaiting: 'waiting', topWheel: 'wheel' }; /** * To ensure no conflicts with other potential React instances on the page */ var topListenersIDKey = '_reactListenersID' + String(Math.random()).slice(2); function getListeningForDocument(mountAt) { // In IE8, `mountAt` is a host object and doesn't have `hasOwnProperty` // directly. if (!Object.prototype.hasOwnProperty.call(mountAt, topListenersIDKey)) { mountAt[topListenersIDKey] = reactTopListenersCounter++; alreadyListeningTo[mountAt[topListenersIDKey]] = {}; } return alreadyListeningTo[mountAt[topListenersIDKey]]; } /** * `ReactBrowserEventEmitter` is used to attach top-level event listeners. For * example: * * EventPluginHub.putListener('myID', 'onClick', myFunction); * * This would allocate a "registration" of `('onClick', myFunction)` on 'myID'. * * @internal */ var ReactBrowserEventEmitter = _assign({}, ReactEventEmitterMixin, { /** * Injectable event backend */ ReactEventListener: null, injection: { /** * @param {object} ReactEventListener */ injectReactEventListener: function (ReactEventListener) { ReactEventListener.setHandleTopLevel(ReactBrowserEventEmitter.handleTopLevel); ReactBrowserEventEmitter.ReactEventListener = ReactEventListener; } }, /** * Sets whether or not any created callbacks should be enabled. * * @param {boolean} enabled True if callbacks should be enabled. */ setEnabled: function (enabled) { if (ReactBrowserEventEmitter.ReactEventListener) { ReactBrowserEventEmitter.ReactEventListener.setEnabled(enabled); } }, /** * @return {boolean} True if callbacks are enabled. */ isEnabled: function () { return !!(ReactBrowserEventEmitter.ReactEventListener && ReactBrowserEventEmitter.ReactEventListener.isEnabled()); }, /** * We listen for bubbled touch events on the document object. * * Firefox v8.01 (and possibly others) exhibited strange behavior when * mounting `onmousemove` events at some node that was not the document * element. The symptoms were that if your mouse is not moving over something * contained within that mount point (for example on the background) the * top-level listeners for `onmousemove` won't be called. However, if you * register the `mousemove` on the document object, then it will of course * catch all `mousemove`s. This along with iOS quirks, justifies restricting * top-level listeners to the document object only, at least for these * movement types of events and possibly all events. * * @see http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html * * Also, `keyup`/`keypress`/`keydown` do not bubble to the window on IE, but * they bubble to document. * * @param {string} registrationName Name of listener (e.g. `onClick`). * @param {object} contentDocumentHandle Document which owns the container */ listenTo: function (registrationName, contentDocumentHandle) { var mountAt = contentDocumentHandle; var isListening = getListeningForDocument(mountAt); var dependencies = EventPluginRegistry.registrationNameDependencies[registrationName]; for (var i = 0; i < dependencies.length; i++) { var dependency = dependencies[i]; if (!(isListening.hasOwnProperty(dependency) && isListening[dependency])) { if (dependency === 'topWheel') { if (isEventSupported('wheel')) { ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent('topWheel', 'wheel', mountAt); } else if (isEventSupported('mousewheel')) { ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent('topWheel', 'mousewheel', mountAt); } else { // Firefox needs to capture a different mouse scroll event. // @see http://www.quirksmode.org/dom/events/tests/scroll.html ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent('topWheel', 'DOMMouseScroll', mountAt); } } else if (dependency === 'topScroll') { if (isEventSupported('scroll', true)) { ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent('topScroll', 'scroll', mountAt); } else { ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent('topScroll', 'scroll', ReactBrowserEventEmitter.ReactEventListener.WINDOW_HANDLE); } } else if (dependency === 'topFocus' || dependency === 'topBlur') { if (isEventSupported('focus', true)) { ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent('topFocus', 'focus', mountAt); ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent('topBlur', 'blur', mountAt); } else if (isEventSupported('focusin')) { // IE has `focusin` and `focusout` events which bubble. // @see http://www.quirksmode.org/blog/archives/2008/04/delegating_the.html ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent('topFocus', 'focusin', mountAt); ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent('topBlur', 'focusout', mountAt); } // to make sure blur and focus event listeners are only attached once isListening.topBlur = true; isListening.topFocus = true; } else if (topEventMapping.hasOwnProperty(dependency)) { ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(dependency, topEventMapping[dependency], mountAt); } isListening[dependency] = true; } } }, trapBubbledEvent: function (topLevelType, handlerBaseName, handle) { return ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelType, handlerBaseName, handle); }, trapCapturedEvent: function (topLevelType, handlerBaseName, handle) { return ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelType, handlerBaseName, handle); }, /** * Protect against document.createEvent() returning null * Some popup blocker extensions appear to do this: * https://github.com/facebook/react/issues/6887 */ supportsEventPageXY: function () { if (!document.createEvent) { return false; } var ev = document.createEvent('MouseEvent'); return ev != null && 'pageX' in ev; }, /** * Listens to window scroll and resize events. We cache scroll values so that * application code can access them without triggering reflows. * * ViewportMetrics is only used by SyntheticMouse/TouchEvent and only when * pageX/pageY isn't supported (legacy browsers). * * NOTE: Scroll events do not bubble. * * @see http://www.quirksmode.org/dom/events/scroll.html */ ensureScrollValueMonitoring: function () { if (hasEventPageXY === undefined) { hasEventPageXY = ReactBrowserEventEmitter.supportsEventPageXY(); } if (!hasEventPageXY && !isMonitoringScrollValue) { var refresh = ViewportMetrics.refreshScrollValues; ReactBrowserEventEmitter.ReactEventListener.monitorScrollValue(refresh); isMonitoringScrollValue = true; } } }); module.exports = ReactBrowserEventEmitter; /***/ }), /* 110 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var EventPluginHub = __webpack_require__(46); function runEventQueueInBatch(events) { EventPluginHub.enqueueEvents(events); EventPluginHub.processEventQueue(false); } var ReactEventEmitterMixin = { /** * Streams a fired top-level event to `EventPluginHub` where plugins have the * opportunity to create `ReactEvent`s to be dispatched. */ handleTopLevel: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { var events = EventPluginHub.extractEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget); runEventQueueInBatch(events); } }; module.exports = ReactEventEmitterMixin; /***/ }), /* 111 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var ExecutionEnvironment = __webpack_require__(52); /** * Generate a mapping of standard vendor prefixes using the defined style property and event name. * * @param {string} styleProp * @param {string} eventName * @returns {object} */ function makePrefixMap(styleProp, eventName) { var prefixes = {}; prefixes[styleProp.toLowerCase()] = eventName.toLowerCase(); prefixes['Webkit' + styleProp] = 'webkit' + eventName; prefixes['Moz' + styleProp] = 'moz' + eventName; prefixes['ms' + styleProp] = 'MS' + eventName; prefixes['O' + styleProp] = 'o' + eventName.toLowerCase(); return prefixes; } /** * A list of event names to a configurable list of vendor prefixes. */ var vendorPrefixes = { animationend: makePrefixMap('Animation', 'AnimationEnd'), animationiteration: makePrefixMap('Animation', 'AnimationIteration'), animationstart: makePrefixMap('Animation', 'AnimationStart'), transitionend: makePrefixMap('Transition', 'TransitionEnd') }; /** * Event names that have already been detected and prefixed (if applicable). */ var prefixedEventNames = {}; /** * Element to check for prefixes on. */ var style = {}; /** * Bootstrap if a DOM exists. */ if (ExecutionEnvironment.canUseDOM) { style = document.createElement('div').style; // On some platforms, in particular some releases of Android 4.x, // the un-prefixed "animation" and "transition" properties are defined on the // style object but the events that fire will still be prefixed, so we need // to check if the un-prefixed events are usable, and if not remove them from the map. if (!('AnimationEvent' in window)) { delete vendorPrefixes.animationend.animation; delete vendorPrefixes.animationiteration.animation; delete vendorPrefixes.animationstart.animation; } // Same as above if (!('TransitionEvent' in window)) { delete vendorPrefixes.transitionend.transition; } } /** * Attempts to determine the correct vendor prefixed event name. * * @param {string} eventName * @returns {string} */ 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 ''; } module.exports = getVendorPrefixedEventName; /***/ }), /* 112 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(39), _assign = __webpack_require__(4); var DOMPropertyOperations = __webpack_require__(107); var LinkedValueUtils = __webpack_require__(113); var ReactDOMComponentTree = __webpack_require__(38); var ReactUpdates = __webpack_require__(60); var invariant = __webpack_require__(8); var warning = __webpack_require__(11); var didWarnValueLink = false; var didWarnCheckedLink = false; var didWarnValueDefaultValue = false; var didWarnCheckedDefaultChecked = false; var didWarnControlledToUncontrolled = false; var didWarnUncontrolledToControlled = false; function forceUpdateIfMounted() { if (this._rootNodeID) { // DOM component is still mounted; update ReactDOMInput.updateWrapper(this); } } function isControlled(props) { var usesChecked = props.type === 'checkbox' || props.type === 'radio'; return usesChecked ? props.checked != null : props.value != null; } /** * Implements an <input> host component that allows setting these optional * props: `checked`, `value`, `defaultChecked`, and `defaultValue`. * * If `checked` or `value` are not supplied (or null/undefined), user actions * that affect the checked state or value will trigger updates to the element. * * If they are supplied (and not null/undefined), the rendered element will not * trigger updates to the element. Instead, the props must change in order for * the rendered element to be updated. * * The rendered element will be initialized as unchecked (or `defaultChecked`) * with an empty value (or `defaultValue`). * * @see http://www.w3.org/TR/2012/WD-html5-20121025/the-input-element.html */ var ReactDOMInput = { getHostProps: function (inst, props) { var value = LinkedValueUtils.getValue(props); var checked = LinkedValueUtils.getChecked(props); var hostProps = _assign({ // Make sure we set .type before any other properties (setting .value // before .type means .value is lost in IE11 and below) type: undefined, // Make sure we set .step before .value (setting .value before .step // means .value is rounded on mount, based upon step precision) step: undefined, // Make sure we set .min & .max before .value (to ensure proper order // in corner cases such as min or max deriving from value, e.g. Issue #7170) min: undefined, max: undefined }, props, { defaultChecked: undefined, defaultValue: undefined, value: value != null ? value : inst._wrapperState.initialValue, checked: checked != null ? checked : inst._wrapperState.initialChecked, onChange: inst._wrapperState.onChange }); return hostProps; }, mountWrapper: function (inst, props) { if (process.env.NODE_ENV !== 'production') { LinkedValueUtils.checkPropTypes('input', props, inst._currentElement._owner); var owner = inst._currentElement._owner; if (props.valueLink !== undefined && !didWarnValueLink) { process.env.NODE_ENV !== 'production' ? warning(false, '`valueLink` prop on `input` is deprecated; set `value` and `onChange` instead.') : void 0; didWarnValueLink = true; } if (props.checkedLink !== undefined && !didWarnCheckedLink) { process.env.NODE_ENV !== 'production' ? warning(false, '`checkedLink` prop on `input` is deprecated; set `value` and `onChange` instead.') : void 0; didWarnCheckedLink = true; } if (props.checked !== undefined && props.defaultChecked !== undefined && !didWarnCheckedDefaultChecked) { process.env.NODE_ENV !== 'production' ? warning(false, '%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://fb.me/react-controlled-components', owner && owner.getName() || 'A component', props.type) : void 0; didWarnCheckedDefaultChecked = true; } if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValueDefaultValue) { process.env.NODE_ENV !== 'production' ? warning(false, '%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://fb.me/react-controlled-components', owner && owner.getName() || 'A component', props.type) : void 0; didWarnValueDefaultValue = true; } } var defaultValue = props.defaultValue; inst._wrapperState = { initialChecked: props.checked != null ? props.checked : props.defaultChecked, initialValue: props.value != null ? props.value : defaultValue, listeners: null, onChange: _handleChange.bind(inst), controlled: isControlled(props) }; }, updateWrapper: function (inst) { var props = inst._currentElement.props; if (process.env.NODE_ENV !== 'production') { var controlled = isControlled(props); var owner = inst._currentElement._owner; if (!inst._wrapperState.controlled && controlled && !didWarnUncontrolledToControlled) { process.env.NODE_ENV !== 'production' ? warning(false, '%s is changing an uncontrolled input of type %s to be controlled. ' + 'Input elements should not switch from uncontrolled to controlled (or vice versa). ' + 'Decide between using a controlled or uncontrolled input ' + 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components', owner && owner.getName() || 'A component', props.type) : void 0; didWarnUncontrolledToControlled = true; } if (inst._wrapperState.controlled && !controlled && !didWarnControlledToUncontrolled) { process.env.NODE_ENV !== 'production' ? warning(false, '%s is changing a controlled input of type %s to be uncontrolled. ' + 'Input elements should not switch from controlled to uncontrolled (or vice versa). ' + 'Decide between using a controlled or uncontrolled input ' + 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components', owner && owner.getName() || 'A component', props.type) : void 0; didWarnControlledToUncontrolled = true; } } // TODO: Shouldn't this be getChecked(props)? var checked = props.checked; if (checked != null) { DOMPropertyOperations.setValueForProperty(ReactDOMComponentTree.getNodeFromInstance(inst), 'checked', checked || false); } var node = ReactDOMComponentTree.getNodeFromInstance(inst); var value = LinkedValueUtils.getValue(props); if (value != null) { if (value === 0 && node.value === '') { node.value = '0'; // Note: IE9 reports a number inputs as 'text', so check props instead. } else if (props.type === 'number') { // Simulate `input.valueAsNumber`. IE9 does not support it var valueAsNumber = parseFloat(node.value, 10) || 0; // eslint-disable-next-line if (value != valueAsNumber) { // Cast `value` to a string to ensure the value is set correctly. While // browsers typically do this as necessary, jsdom doesn't. node.value = '' + value; } // eslint-disable-next-line } else if (value != node.value) { // Cast `value` to a string to ensure the value is set correctly. While // browsers typically do this as necessary, jsdom doesn't. node.value = '' + value; } } else { if (props.value == null && props.defaultValue != null) { // In Chrome, assigning defaultValue to certain input types triggers input validation. // For number inputs, the display value loses trailing decimal points. For email inputs, // Chrome raises "The specified value <x> is not a valid email address". // // Here we check to see if the defaultValue has actually changed, avoiding these problems // when the user is inputting text // // https://github.com/facebook/react/issues/7253 if (node.defaultValue !== '' + props.defaultValue) { node.defaultValue = '' + props.defaultValue; } } if (props.checked == null && props.defaultChecked != null) { node.defaultChecked = !!props.defaultChecked; } } }, postMountWrapper: function (inst) { var props = inst._currentElement.props; // This is in postMount because we need access to the DOM node, which is not // available until after the component has mounted. var node = ReactDOMComponentTree.getNodeFromInstance(inst); // Detach value from defaultValue. We won't do anything if we're working on // submit or reset inputs as those values & defaultValues are linked. They // are not resetable nodes so this operation doesn't matter and actually // removes browser-default values (eg "Submit Query") when no value is // provided. switch (props.type) { case 'submit': case 'reset': break; case 'color': case 'date': case 'datetime': case 'datetime-local': case 'month': case 'time': case 'week': // This fixes the no-show issue on iOS Safari and Android Chrome: // https://github.com/facebook/react/issues/7233 node.value = ''; node.value = node.defaultValue; break; default: node.value = node.value; break; } // Normally, we'd just do `node.checked = node.checked` upon initial mount, less this bug // this is needed to work around a chrome bug where setting defaultChecked // will sometimes influence the value of checked (even after detachment). // Reference: https://bugs.chromium.org/p/chromium/issues/detail?id=608416 // We need to temporarily unset name to avoid disrupting radio button groups. var name = node.name; if (name !== '') { node.name = ''; } node.defaultChecked = !node.defaultChecked; node.defaultChecked = !node.defaultChecked; if (name !== '') { node.name = name; } } }; function _handleChange(event) { var props = this._currentElement.props; var returnValue = LinkedValueUtils.executeOnChange(props, event); // Here we use asap to wait until all updates have propagated, which // is important when using controlled components within layers: // https://github.com/facebook/react/issues/1698 ReactUpdates.asap(forceUpdateIfMounted, this); var name = props.name; if (props.type === 'radio' && name != null) { var rootNode = ReactDOMComponentTree.getNodeFromInstance(this); var queryRoot = rootNode; while (queryRoot.parentNode) { queryRoot = queryRoot.parentNode; } // If `rootNode.form` was non-null, then we could try `form.elements`, // but that sometimes behaves strangely in IE8. We could also try using // `form.getElementsByName`, but that will only return direct children // and won't include inputs that use the HTML5 `form=` attribute. Since // the input might not even be in a form, let's just use the global // `querySelectorAll` to ensure we don't miss anything. 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; } // This will throw if radio buttons rendered by different copies of React // and the same name are rendered into the same form (same as #1939). // That's probably okay; we don't support it just as we don't support // mixing React radio buttons with non-React ones. var otherInstance = ReactDOMComponentTree.getInstanceFromNode(otherNode); !otherInstance ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactDOMInput: Mixing React and non-React radio inputs with the same `name` is not supported.') : _prodInvariant('90') : void 0; // If this is a controlled radio button group, forcing the input that // was previously checked to update will cause it to be come re-checked // as appropriate. ReactUpdates.asap(forceUpdateIfMounted, otherInstance); } } return returnValue; } module.exports = ReactDOMInput; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 113 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(39); var ReactPropTypesSecret = __webpack_require__(114); var propTypesFactory = __webpack_require__(30); var React = __webpack_require__(2); var PropTypes = propTypesFactory(React.isValidElement); var invariant = __webpack_require__(8); var warning = __webpack_require__(11); var hasReadOnlyValue = { 'button': true, 'checkbox': true, 'image': true, 'hidden': true, 'radio': true, 'reset': true, 'submit': true }; function _assertSingleLink(inputProps) { !(inputProps.checkedLink == null || inputProps.valueLink == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Cannot provide a checkedLink and a valueLink. If you want to use checkedLink, you probably don\'t want to use valueLink and vice versa.') : _prodInvariant('87') : void 0; } function _assertValueLink(inputProps) { _assertSingleLink(inputProps); !(inputProps.value == null && inputProps.onChange == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Cannot provide a valueLink and a value or onChange event. If you want to use value or onChange, you probably don\'t want to use valueLink.') : _prodInvariant('88') : void 0; } function _assertCheckedLink(inputProps) { _assertSingleLink(inputProps); !(inputProps.checked == null && inputProps.onChange == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Cannot provide a checkedLink and a checked property or onChange event. If you want to use checked or onChange, you probably don\'t want to use checkedLink') : _prodInvariant('89') : void 0; } var propTypes = { value: function (props, propName, componentName) { if (!props[propName] || hasReadOnlyValue[props.type] || props.onChange || props.readOnly || props.disabled) { return null; } return new 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`.'); }, checked: function (props, propName, componentName) { if (!props[propName] || props.onChange || props.readOnly || props.disabled) { return null; } return new 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`.'); }, onChange: PropTypes.func }; var loggedTypeFailures = {}; function getDeclarationErrorAddendum(owner) { if (owner) { var name = owner.getName(); if (name) { return ' Check the render method of `' + name + '`.'; } } return ''; } /** * Provide a linked `value` attribute for controlled forms. You should not use * this outside of the ReactDOM controlled form components. */ var LinkedValueUtils = { checkPropTypes: function (tagName, props, owner) { for (var propName in propTypes) { if (propTypes.hasOwnProperty(propName)) { var error = propTypes[propName](props, propName, tagName, 'prop', null, ReactPropTypesSecret); } if (error instanceof Error && !(error.message in loggedTypeFailures)) { // Only monitor this failure once because there tends to be a lot of the // same error. loggedTypeFailures[error.message] = true; var addendum = getDeclarationErrorAddendum(owner); process.env.NODE_ENV !== 'production' ? warning(false, 'Failed form propType: %s%s', error.message, addendum) : void 0; } } }, /** * @param {object} inputProps Props for form component * @return {*} current value of the input either from value prop or link. */ getValue: function (inputProps) { if (inputProps.valueLink) { _assertValueLink(inputProps); return inputProps.valueLink.value; } return inputProps.value; }, /** * @param {object} inputProps Props for form component * @return {*} current checked status of the input either from checked prop * or link. */ getChecked: function (inputProps) { if (inputProps.checkedLink) { _assertCheckedLink(inputProps); return inputProps.checkedLink.value; } return inputProps.checked; }, /** * @param {object} inputProps Props for form component * @param {SyntheticEvent} event change event to handle */ executeOnChange: function (inputProps, event) { if (inputProps.valueLink) { _assertValueLink(inputProps); return inputProps.valueLink.requestChange(event.target.value); } else if (inputProps.checkedLink) { _assertCheckedLink(inputProps); return inputProps.checkedLink.requestChange(event.target.checked); } else if (inputProps.onChange) { return inputProps.onChange.call(undefined, event); } } }; module.exports = LinkedValueUtils; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 114 */ /***/ (function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'; module.exports = ReactPropTypesSecret; /***/ }), /* 115 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _assign = __webpack_require__(4); var React = __webpack_require__(2); var ReactDOMComponentTree = __webpack_require__(38); var ReactDOMSelect = __webpack_require__(116); var warning = __webpack_require__(11); var didWarnInvalidOptionChildren = false; function flattenChildren(children) { var content = ''; // Flatten children and warn if they aren't strings or numbers; // invalid types are ignored. React.Children.forEach(children, function (child) { if (child == null) { return; } if (typeof child === 'string' || typeof child === 'number') { content += child; } else if (!didWarnInvalidOptionChildren) { didWarnInvalidOptionChildren = true; process.env.NODE_ENV !== 'production' ? warning(false, 'Only strings and numbers are supported as <option> children.') : void 0; } }); return content; } /** * Implements an <option> host component that warns when `selected` is set. */ var ReactDOMOption = { mountWrapper: function (inst, props, hostParent) { // TODO (yungsters): Remove support for `selected` in <option>. if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(props.selected == null, 'Use the `defaultValue` or `value` props on <select> instead of ' + 'setting `selected` on <option>.') : void 0; } // Look up whether this option is 'selected' var selectValue = null; if (hostParent != null) { var selectParent = hostParent; if (selectParent._tag === 'optgroup') { selectParent = selectParent._hostParent; } if (selectParent != null && selectParent._tag === 'select') { selectValue = ReactDOMSelect.getSelectValueContext(selectParent); } } // If the value is null (e.g., no specified value or after initial mount) // or missing (e.g., for <datalist>), we don't change props.selected var selected = null; if (selectValue != null) { var value; if (props.value != null) { value = props.value + ''; } else { value = flattenChildren(props.children); } selected = false; if (Array.isArray(selectValue)) { // multiple for (var i = 0; i < selectValue.length; i++) { if ('' + selectValue[i] === value) { selected = true; break; } } } else { selected = '' + selectValue === value; } } inst._wrapperState = { selected: selected }; }, postMountWrapper: function (inst) { // value="" should make a value attribute (#6219) var props = inst._currentElement.props; if (props.value != null) { var node = ReactDOMComponentTree.getNodeFromInstance(inst); node.setAttribute('value', props.value); } }, getHostProps: function (inst, props) { var hostProps = _assign({ selected: undefined, children: undefined }, props); // Read state only from initial mount because <select> updates value // manually; we need the initial state only for server rendering if (inst._wrapperState.selected != null) { hostProps.selected = inst._wrapperState.selected; } var content = flattenChildren(props.children); if (content) { hostProps.children = content; } return hostProps; } }; module.exports = ReactDOMOption; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 116 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _assign = __webpack_require__(4); var LinkedValueUtils = __webpack_require__(113); var ReactDOMComponentTree = __webpack_require__(38); var ReactUpdates = __webpack_require__(60); var warning = __webpack_require__(11); var didWarnValueLink = false; var didWarnValueDefaultValue = false; function updateOptionsIfPendingUpdateAndMounted() { if (this._rootNodeID && this._wrapperState.pendingUpdate) { this._wrapperState.pendingUpdate = false; var props = this._currentElement.props; var value = LinkedValueUtils.getValue(props); if (value != null) { updateOptions(this, Boolean(props.multiple), value); } } } function getDeclarationErrorAddendum(owner) { if (owner) { var name = owner.getName(); if (name) { return ' Check the render method of `' + name + '`.'; } } return ''; } var valuePropNames = ['value', 'defaultValue']; /** * Validation function for `value` and `defaultValue`. * @private */ function checkSelectPropTypes(inst, props) { var owner = inst._currentElement._owner; LinkedValueUtils.checkPropTypes('select', props, owner); if (props.valueLink !== undefined && !didWarnValueLink) { process.env.NODE_ENV !== 'production' ? warning(false, '`valueLink` prop on `select` is deprecated; set `value` and `onChange` instead.') : void 0; didWarnValueLink = true; } for (var i = 0; i < valuePropNames.length; i++) { var propName = valuePropNames[i]; if (props[propName] == null) { continue; } var isArray = Array.isArray(props[propName]); if (props.multiple && !isArray) { process.env.NODE_ENV !== 'production' ? warning(false, 'The `%s` prop supplied to <select> must be an array if ' + '`multiple` is true.%s', propName, getDeclarationErrorAddendum(owner)) : void 0; } else if (!props.multiple && isArray) { process.env.NODE_ENV !== 'production' ? warning(false, 'The `%s` prop supplied to <select> must be a scalar ' + 'value if `multiple` is false.%s', propName, getDeclarationErrorAddendum(owner)) : void 0; } } } /** * @param {ReactDOMComponent} inst * @param {boolean} multiple * @param {*} propValue A stringable (with `multiple`, a list of stringables). * @private */ function updateOptions(inst, multiple, propValue) { var selectedValue, i; var options = ReactDOMComponentTree.getNodeFromInstance(inst).options; if (multiple) { selectedValue = {}; for (i = 0; i < propValue.length; i++) { selectedValue['' + propValue[i]] = true; } for (i = 0; i < options.length; i++) { var selected = selectedValue.hasOwnProperty(options[i].value); if (options[i].selected !== selected) { options[i].selected = selected; } } } else { // Do not set `select.value` as exact behavior isn't consistent across all // browsers for all cases. selectedValue = '' + propValue; for (i = 0; i < options.length; i++) { if (options[i].value === selectedValue) { options[i].selected = true; return; } } if (options.length) { options[0].selected = true; } } } /** * Implements a <select> host component that allows optionally setting the * props `value` and `defaultValue`. If `multiple` is false, the prop must be a * stringable. If `multiple` is true, the prop must be an array of stringables. * * If `value` is not supplied (or null/undefined), user actions that change the * selected option will trigger updates to the rendered options. * * If it is supplied (and not null/undefined), the rendered options will not * update in response to user actions. Instead, the `value` prop must change in * order for the rendered options to update. * * If `defaultValue` is provided, any options with the supplied values will be * selected. */ var ReactDOMSelect = { getHostProps: function (inst, props) { return _assign({}, props, { onChange: inst._wrapperState.onChange, value: undefined }); }, mountWrapper: function (inst, props) { if (process.env.NODE_ENV !== 'production') { checkSelectPropTypes(inst, props); } var value = LinkedValueUtils.getValue(props); inst._wrapperState = { pendingUpdate: false, initialValue: value != null ? value : props.defaultValue, listeners: null, onChange: _handleChange.bind(inst), wasMultiple: Boolean(props.multiple) }; if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValueDefaultValue) { process.env.NODE_ENV !== 'production' ? warning(false, '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://fb.me/react-controlled-components') : void 0; didWarnValueDefaultValue = true; } }, getSelectValueContext: function (inst) { // ReactDOMOption looks at this initial value so the initial generated // markup has correct `selected` attributes return inst._wrapperState.initialValue; }, postUpdateWrapper: function (inst) { var props = inst._currentElement.props; // After the initial mount, we control selected-ness manually so don't pass // this value down inst._wrapperState.initialValue = undefined; var wasMultiple = inst._wrapperState.wasMultiple; inst._wrapperState.wasMultiple = Boolean(props.multiple); var value = LinkedValueUtils.getValue(props); if (value != null) { inst._wrapperState.pendingUpdate = false; updateOptions(inst, Boolean(props.multiple), value); } else if (wasMultiple !== Boolean(props.multiple)) { // For simplicity, reapply `defaultValue` if `multiple` is toggled. if (props.defaultValue != null) { updateOptions(inst, Boolean(props.multiple), props.defaultValue); } else { // Revert the select back to its default unselected state. updateOptions(inst, Boolean(props.multiple), props.multiple ? [] : ''); } } } }; function _handleChange(event) { var props = this._currentElement.props; var returnValue = LinkedValueUtils.executeOnChange(props, event); if (this._rootNodeID) { this._wrapperState.pendingUpdate = true; } ReactUpdates.asap(updateOptionsIfPendingUpdateAndMounted, this); return returnValue; } module.exports = ReactDOMSelect; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 117 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(39), _assign = __webpack_require__(4); var LinkedValueUtils = __webpack_require__(113); var ReactDOMComponentTree = __webpack_require__(38); var ReactUpdates = __webpack_require__(60); var invariant = __webpack_require__(8); var warning = __webpack_require__(11); var didWarnValueLink = false; var didWarnValDefaultVal = false; function forceUpdateIfMounted() { if (this._rootNodeID) { // DOM component is still mounted; update ReactDOMTextarea.updateWrapper(this); } } /** * Implements a <textarea> host component that allows setting `value`, and * `defaultValue`. This differs from the traditional DOM API because value is * usually set as PCDATA children. * * If `value` is not supplied (or null/undefined), user actions that affect the * value will trigger updates to the element. * * If `value` is supplied (and not null/undefined), the rendered element will * not trigger updates to the element. Instead, the `value` prop must change in * order for the rendered element to be updated. * * The rendered element will be initialized with an empty value, the prop * `defaultValue` if specified, or the children content (deprecated). */ var ReactDOMTextarea = { getHostProps: function (inst, props) { !(props.dangerouslySetInnerHTML == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, '`dangerouslySetInnerHTML` does not make sense on <textarea>.') : _prodInvariant('91') : void 0; // Always set children to the same thing. In IE9, the selection range will // get reset if `textContent` is mutated. We could add a check in setTextContent // to only set the value if/when the value differs from the node value (which would // completely solve this IE9 bug), but Sebastian+Ben seemed to like this solution. // The value can be a boolean or object so that's why it's forced to be a string. var hostProps = _assign({}, props, { value: undefined, defaultValue: undefined, children: '' + inst._wrapperState.initialValue, onChange: inst._wrapperState.onChange }); return hostProps; }, mountWrapper: function (inst, props) { if (process.env.NODE_ENV !== 'production') { LinkedValueUtils.checkPropTypes('textarea', props, inst._currentElement._owner); if (props.valueLink !== undefined && !didWarnValueLink) { process.env.NODE_ENV !== 'production' ? warning(false, '`valueLink` prop on `textarea` is deprecated; set `value` and `onChange` instead.') : void 0; didWarnValueLink = true; } if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValDefaultVal) { process.env.NODE_ENV !== 'production' ? warning(false, '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://fb.me/react-controlled-components') : void 0; didWarnValDefaultVal = true; } } var value = LinkedValueUtils.getValue(props); var initialValue = value; // Only bother fetching default value if we're going to use it if (value == null) { var defaultValue = props.defaultValue; // TODO (yungsters): Remove support for children content in <textarea>. var children = props.children; if (children != null) { if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(false, 'Use the `defaultValue` or `value` props instead of setting ' + 'children on <textarea>.') : void 0; } !(defaultValue == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'If you supply `defaultValue` on a <textarea>, do not pass children.') : _prodInvariant('92') : void 0; if (Array.isArray(children)) { !(children.length <= 1) ? process.env.NODE_ENV !== 'production' ? invariant(false, '<textarea> can only have at most one child.') : _prodInvariant('93') : void 0; children = children[0]; } defaultValue = '' + children; } if (defaultValue == null) { defaultValue = ''; } initialValue = defaultValue; } inst._wrapperState = { initialValue: '' + initialValue, listeners: null, onChange: _handleChange.bind(inst) }; }, updateWrapper: function (inst) { var props = inst._currentElement.props; var node = ReactDOMComponentTree.getNodeFromInstance(inst); var value = LinkedValueUtils.getValue(props); if (value != null) { // Cast `value` to a string to ensure the value is set correctly. While // browsers typically do this as necessary, jsdom doesn't. var newValue = '' + value; // To avoid side effects (such as losing text selection), only set value if changed if (newValue !== node.value) { node.value = newValue; } if (props.defaultValue == null) { node.defaultValue = newValue; } } if (props.defaultValue != null) { node.defaultValue = props.defaultValue; } }, postMountWrapper: function (inst) { // This is in postMount because we need access to the DOM node, which is not // available until after the component has mounted. var node = ReactDOMComponentTree.getNodeFromInstance(inst); var textContent = node.textContent; // Only set node.value if textContent is equal to the expected // initial value. In IE10/IE11 there is a bug where the placeholder attribute // will populate textContent as well. // https://developer.microsoft.com/microsoft-edge/platform/issues/101525/ if (textContent === inst._wrapperState.initialValue) { node.value = textContent; } } }; function _handleChange(event) { var props = this._currentElement.props; var returnValue = LinkedValueUtils.executeOnChange(props, event); ReactUpdates.asap(forceUpdateIfMounted, this); return returnValue; } module.exports = ReactDOMTextarea; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 118 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(39); var ReactComponentEnvironment = __webpack_require__(119); var ReactInstanceMap = __webpack_require__(120); var ReactInstrumentation = __webpack_require__(66); var ReactCurrentOwner = __webpack_require__(10); var ReactReconciler = __webpack_require__(63); var ReactChildReconciler = __webpack_require__(121); var emptyFunction = __webpack_require__(12); var flattenChildren = __webpack_require__(136); var invariant = __webpack_require__(8); /** * Make an update for markup to be rendered and inserted at a supplied index. * * @param {string} markup Markup that renders into an element. * @param {number} toIndex Destination index. * @private */ function makeInsertMarkup(markup, afterNode, toIndex) { // NOTE: Null values reduce hidden classes. return { type: 'INSERT_MARKUP', content: markup, fromIndex: null, fromNode: null, toIndex: toIndex, afterNode: afterNode }; } /** * Make an update for moving an existing element to another index. * * @param {number} fromIndex Source index of the existing element. * @param {number} toIndex Destination index of the element. * @private */ function makeMove(child, afterNode, toIndex) { // NOTE: Null values reduce hidden classes. return { type: 'MOVE_EXISTING', content: null, fromIndex: child._mountIndex, fromNode: ReactReconciler.getHostNode(child), toIndex: toIndex, afterNode: afterNode }; } /** * Make an update for removing an element at an index. * * @param {number} fromIndex Index of the element to remove. * @private */ function makeRemove(child, node) { // NOTE: Null values reduce hidden classes. return { type: 'REMOVE_NODE', content: null, fromIndex: child._mountIndex, fromNode: node, toIndex: null, afterNode: null }; } /** * Make an update for setting the markup of a node. * * @param {string} markup Markup that renders into an element. * @private */ function makeSetMarkup(markup) { // NOTE: Null values reduce hidden classes. return { type: 'SET_MARKUP', content: markup, fromIndex: null, fromNode: null, toIndex: null, afterNode: null }; } /** * Make an update for setting the text content. * * @param {string} textContent Text content to set. * @private */ function makeTextContent(textContent) { // NOTE: Null values reduce hidden classes. return { type: 'TEXT_CONTENT', content: textContent, fromIndex: null, fromNode: null, toIndex: null, afterNode: null }; } /** * Push an update, if any, onto the queue. Creates a new queue if none is * passed and always returns the queue. Mutative. */ function enqueue(queue, update) { if (update) { queue = queue || []; queue.push(update); } return queue; } /** * Processes any enqueued updates. * * @private */ function processQueue(inst, updateQueue) { ReactComponentEnvironment.processChildrenUpdates(inst, updateQueue); } var setChildrenForInstrumentation = emptyFunction; if (process.env.NODE_ENV !== 'production') { var getDebugID = function (inst) { if (!inst._debugID) { // Check for ART-like instances. TODO: This is silly/gross. var internal; if (internal = ReactInstanceMap.get(inst)) { inst = internal; } } return inst._debugID; }; setChildrenForInstrumentation = function (children) { var debugID = getDebugID(this); // TODO: React Native empty components are also multichild. // This means they still get into this method but don't have _debugID. if (debugID !== 0) { ReactInstrumentation.debugTool.onSetChildren(debugID, children ? Object.keys(children).map(function (key) { return children[key]._debugID; }) : []); } }; } /** * ReactMultiChild are capable of reconciling multiple children. * * @class ReactMultiChild * @internal */ var ReactMultiChild = { /** * Provides common functionality for components that must reconcile multiple * children. This is used by `ReactDOMComponent` to mount, update, and * unmount child components. * * @lends {ReactMultiChild.prototype} */ Mixin: { _reconcilerInstantiateChildren: function (nestedChildren, transaction, context) { if (process.env.NODE_ENV !== 'production') { var selfDebugID = getDebugID(this); if (this._currentElement) { try { ReactCurrentOwner.current = this._currentElement._owner; return ReactChildReconciler.instantiateChildren(nestedChildren, transaction, context, selfDebugID); } finally { ReactCurrentOwner.current = null; } } } return ReactChildReconciler.instantiateChildren(nestedChildren, transaction, context); }, _reconcilerUpdateChildren: function (prevChildren, nextNestedChildrenElements, mountImages, removedNodes, transaction, context) { var nextChildren; var selfDebugID = 0; if (process.env.NODE_ENV !== 'production') { selfDebugID = getDebugID(this); if (this._currentElement) { try { ReactCurrentOwner.current = this._currentElement._owner; nextChildren = flattenChildren(nextNestedChildrenElements, selfDebugID); } finally { ReactCurrentOwner.current = null; } ReactChildReconciler.updateChildren(prevChildren, nextChildren, mountImages, removedNodes, transaction, this, this._hostContainerInfo, context, selfDebugID); return nextChildren; } } nextChildren = flattenChildren(nextNestedChildrenElements, selfDebugID); ReactChildReconciler.updateChildren(prevChildren, nextChildren, mountImages, removedNodes, transaction, this, this._hostContainerInfo, context, selfDebugID); return nextChildren; }, /** * Generates a "mount image" for each of the supplied children. In the case * of `ReactDOMComponent`, a mount image is a string of markup. * * @param {?object} nestedChildren Nested child maps. * @return {array} An array of mounted representations. * @internal */ mountChildren: function (nestedChildren, transaction, context) { var children = this._reconcilerInstantiateChildren(nestedChildren, transaction, context); this._renderedChildren = children; var mountImages = []; var index = 0; for (var name in children) { if (children.hasOwnProperty(name)) { var child = children[name]; var selfDebugID = 0; if (process.env.NODE_ENV !== 'production') { selfDebugID = getDebugID(this); } var mountImage = ReactReconciler.mountComponent(child, transaction, this, this._hostContainerInfo, context, selfDebugID); child._mountIndex = index++; mountImages.push(mountImage); } } if (process.env.NODE_ENV !== 'production') { setChildrenForInstrumentation.call(this, children); } return mountImages; }, /** * Replaces any rendered children with a text content string. * * @param {string} nextContent String of content. * @internal */ updateTextContent: function (nextContent) { var prevChildren = this._renderedChildren; // Remove any rendered children. ReactChildReconciler.unmountChildren(prevChildren, false); for (var name in prevChildren) { if (prevChildren.hasOwnProperty(name)) { true ? process.env.NODE_ENV !== 'production' ? invariant(false, 'updateTextContent called on non-empty component.') : _prodInvariant('118') : void 0; } } // Set new text content. var updates = [makeTextContent(nextContent)]; processQueue(this, updates); }, /** * Replaces any rendered children with a markup string. * * @param {string} nextMarkup String of markup. * @internal */ updateMarkup: function (nextMarkup) { var prevChildren = this._renderedChildren; // Remove any rendered children. ReactChildReconciler.unmountChildren(prevChildren, false); for (var name in prevChildren) { if (prevChildren.hasOwnProperty(name)) { true ? process.env.NODE_ENV !== 'production' ? invariant(false, 'updateTextContent called on non-empty component.') : _prodInvariant('118') : void 0; } } var updates = [makeSetMarkup(nextMarkup)]; processQueue(this, updates); }, /** * Updates the rendered children with new children. * * @param {?object} nextNestedChildrenElements Nested child element maps. * @param {ReactReconcileTransaction} transaction * @internal */ updateChildren: function (nextNestedChildrenElements, transaction, context) { // Hook used by React ART this._updateChildren(nextNestedChildrenElements, transaction, context); }, /** * @param {?object} nextNestedChildrenElements Nested child element maps. * @param {ReactReconcileTransaction} transaction * @final * @protected */ _updateChildren: function (nextNestedChildrenElements, transaction, context) { var prevChildren = this._renderedChildren; var removedNodes = {}; var mountImages = []; var nextChildren = this._reconcilerUpdateChildren(prevChildren, nextNestedChildrenElements, mountImages, removedNodes, transaction, context); if (!nextChildren && !prevChildren) { return; } var updates = null; var name; // `nextIndex` will increment for each child in `nextChildren`, but // `lastIndex` will be the last index visited in `prevChildren`. var nextIndex = 0; var lastIndex = 0; // `nextMountIndex` will increment for each newly mounted child. var nextMountIndex = 0; var lastPlacedNode = null; for (name in nextChildren) { if (!nextChildren.hasOwnProperty(name)) { continue; } var prevChild = prevChildren && prevChildren[name]; var nextChild = nextChildren[name]; if (prevChild === nextChild) { updates = enqueue(updates, this.moveChild(prevChild, lastPlacedNode, nextIndex, lastIndex)); lastIndex = Math.max(prevChild._mountIndex, lastIndex); prevChild._mountIndex = nextIndex; } else { if (prevChild) { // Update `lastIndex` before `_mountIndex` gets unset by unmounting. lastIndex = Math.max(prevChild._mountIndex, lastIndex); // The `removedNodes` loop below will actually remove the child. } // The child must be instantiated before it's mounted. updates = enqueue(updates, this._mountChildAtIndex(nextChild, mountImages[nextMountIndex], lastPlacedNode, nextIndex, transaction, context)); nextMountIndex++; } nextIndex++; lastPlacedNode = ReactReconciler.getHostNode(nextChild); } // Remove children that are no longer present. for (name in removedNodes) { if (removedNodes.hasOwnProperty(name)) { updates = enqueue(updates, this._unmountChild(prevChildren[name], removedNodes[name])); } } if (updates) { processQueue(this, updates); } this._renderedChildren = nextChildren; if (process.env.NODE_ENV !== 'production') { setChildrenForInstrumentation.call(this, nextChildren); } }, /** * Unmounts all rendered children. This should be used to clean up children * when this component is unmounted. It does not actually perform any * backend operations. * * @internal */ unmountChildren: function (safely) { var renderedChildren = this._renderedChildren; ReactChildReconciler.unmountChildren(renderedChildren, safely); this._renderedChildren = null; }, /** * Moves a child component to the supplied index. * * @param {ReactComponent} child Component to move. * @param {number} toIndex Destination index of the element. * @param {number} lastIndex Last index visited of the siblings of `child`. * @protected */ moveChild: function (child, afterNode, toIndex, lastIndex) { // If the index of `child` is less than `lastIndex`, then it needs to // be moved. Otherwise, we do not need to move it because a child will be // inserted or moved before `child`. if (child._mountIndex < lastIndex) { return makeMove(child, afterNode, toIndex); } }, /** * Creates a child component. * * @param {ReactComponent} child Component to create. * @param {string} mountImage Markup to insert. * @protected */ createChild: function (child, afterNode, mountImage) { return makeInsertMarkup(mountImage, afterNode, child._mountIndex); }, /** * Removes a child component. * * @param {ReactComponent} child Child to remove. * @protected */ removeChild: function (child, node) { return makeRemove(child, node); }, /** * Mounts a child with the supplied name. * * NOTE: This is part of `updateChildren` and is here for readability. * * @param {ReactComponent} child Component to mount. * @param {string} name Name of the child. * @param {number} index Index at which to insert the child. * @param {ReactReconcileTransaction} transaction * @private */ _mountChildAtIndex: function (child, mountImage, afterNode, index, transaction, context) { child._mountIndex = index; return this.createChild(child, afterNode, mountImage); }, /** * Unmounts a rendered child. * * NOTE: This is part of `updateChildren` and is here for readability. * * @param {ReactComponent} child Component to unmount. * @private */ _unmountChild: function (child, node) { var update = this.removeChild(child, node); child._mountIndex = null; return update; } } }; module.exports = ReactMultiChild; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 119 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var _prodInvariant = __webpack_require__(39); var invariant = __webpack_require__(8); var injected = false; var ReactComponentEnvironment = { /** * Optionally injectable hook for swapping out mount images in the middle of * the tree. */ replaceNodeWithMarkup: null, /** * Optionally injectable hook for processing a queue of child updates. Will * later move into MultiChildComponents. */ processChildrenUpdates: null, injection: { injectEnvironment: function (environment) { !!injected ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactCompositeComponent: injectEnvironment() can only be called once.') : _prodInvariant('104') : void 0; ReactComponentEnvironment.replaceNodeWithMarkup = environment.replaceNodeWithMarkup; ReactComponentEnvironment.processChildrenUpdates = environment.processChildrenUpdates; injected = true; } } }; module.exports = ReactComponentEnvironment; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 120 */ /***/ (function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; /** * `ReactInstanceMap` maintains a mapping from a public facing stateful * instance (key) and the internal representation (value). This allows public * methods to accept the user facing instance as an argument and map them back * to internal methods. */ // TODO: Replace this with ES6: var ReactInstanceMap = new Map(); var ReactInstanceMap = { /** * This API should be called `delete` but we'd have to make sure to always * transform these to strings for IE support. When this transform is fully * supported we can rename it. */ remove: function (key) { key._reactInternalInstance = undefined; }, get: function (key) { return key._reactInternalInstance; }, has: function (key) { return key._reactInternalInstance !== undefined; }, set: function (key, value) { key._reactInternalInstance = value; } }; module.exports = ReactInstanceMap; /***/ }), /* 121 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var ReactReconciler = __webpack_require__(63); var instantiateReactComponent = __webpack_require__(122); var KeyEscapeUtils = __webpack_require__(132); var shouldUpdateReactComponent = __webpack_require__(128); var traverseAllChildren = __webpack_require__(133); var warning = __webpack_require__(11); var ReactComponentTreeHook; if (typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'test') { // Temporary hack. // Inline requires don't work well with Jest: // https://github.com/facebook/react/issues/7240 // Remove the inline requires when we don't need them anymore: // https://github.com/facebook/react/pull/7178 ReactComponentTreeHook = __webpack_require__(26); } function instantiateChild(childInstances, child, name, selfDebugID) { // We found a component instance. var keyUnique = childInstances[name] === undefined; if (process.env.NODE_ENV !== 'production') { if (!ReactComponentTreeHook) { ReactComponentTreeHook = __webpack_require__(26); } if (!keyUnique) { process.env.NODE_ENV !== 'production' ? warning(false, 'flattenChildren(...): Encountered two children with the same key, ' + '`%s`. Child keys must be unique; when two children share a key, only ' + 'the first child will be used.%s', KeyEscapeUtils.unescape(name), ReactComponentTreeHook.getStackAddendumByID(selfDebugID)) : void 0; } } if (child != null && keyUnique) { childInstances[name] = instantiateReactComponent(child, true); } } /** * ReactChildReconciler provides helpers for initializing or updating a set of * children. Its output is suitable for passing it onto ReactMultiChild which * does diffed reordering and insertion. */ var ReactChildReconciler = { /** * Generates a "mount image" for each of the supplied children. In the case * of `ReactDOMComponent`, a mount image is a string of markup. * * @param {?object} nestedChildNodes Nested child maps. * @return {?object} A set of child instances. * @internal */ instantiateChildren: function (nestedChildNodes, transaction, context, selfDebugID // 0 in production and for roots ) { if (nestedChildNodes == null) { return null; } var childInstances = {}; if (process.env.NODE_ENV !== 'production') { traverseAllChildren(nestedChildNodes, function (childInsts, child, name) { return instantiateChild(childInsts, child, name, selfDebugID); }, childInstances); } else { traverseAllChildren(nestedChildNodes, instantiateChild, childInstances); } return childInstances; }, /** * Updates the rendered children and returns a new set of children. * * @param {?object} prevChildren Previously initialized set of children. * @param {?object} nextChildren Flat child element maps. * @param {ReactReconcileTransaction} transaction * @param {object} context * @return {?object} A new set of child instances. * @internal */ updateChildren: function (prevChildren, nextChildren, mountImages, removedNodes, transaction, hostParent, hostContainerInfo, context, selfDebugID // 0 in production and for roots ) { // We currently don't have a way to track moves here but if we use iterators // instead of for..in we can zip the iterators and check if an item has // moved. // TODO: If nothing has changed, return the prevChildren object so that we // can quickly bailout if nothing has changed. if (!nextChildren && !prevChildren) { return; } var name; var prevChild; for (name in nextChildren) { if (!nextChildren.hasOwnProperty(name)) { continue; } prevChild = prevChildren && prevChildren[name]; var prevElement = prevChild && prevChild._currentElement; var nextElement = nextChildren[name]; if (prevChild != null && shouldUpdateReactComponent(prevElement, nextElement)) { ReactReconciler.receiveComponent(prevChild, nextElement, transaction, context); nextChildren[name] = prevChild; } else { if (prevChild) { removedNodes[name] = ReactReconciler.getHostNode(prevChild); ReactReconciler.unmountComponent(prevChild, false); } // The child must be instantiated before it's mounted. var nextChildInstance = instantiateReactComponent(nextElement, true); nextChildren[name] = nextChildInstance; // Creating mount image now ensures refs are resolved in right order // (see https://github.com/facebook/react/pull/7101 for explanation). var nextChildMountImage = ReactReconciler.mountComponent(nextChildInstance, transaction, hostParent, hostContainerInfo, context, selfDebugID); mountImages.push(nextChildMountImage); } } // Unmount children that are no longer present. for (name in prevChildren) { if (prevChildren.hasOwnProperty(name) && !(nextChildren && nextChildren.hasOwnProperty(name))) { prevChild = prevChildren[name]; removedNodes[name] = ReactReconciler.getHostNode(prevChild); ReactReconciler.unmountComponent(prevChild, false); } } }, /** * Unmounts all rendered children. This should be used to clean up children * when this component is unmounted. * * @param {?object} renderedChildren Previously initialized set of children. * @internal */ unmountChildren: function (renderedChildren, safely) { for (var name in renderedChildren) { if (renderedChildren.hasOwnProperty(name)) { var renderedChild = renderedChildren[name]; ReactReconciler.unmountComponent(renderedChild, safely); } } } }; module.exports = ReactChildReconciler; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 122 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(39), _assign = __webpack_require__(4); var ReactCompositeComponent = __webpack_require__(123); var ReactEmptyComponent = __webpack_require__(129); var ReactHostComponent = __webpack_require__(130); var getNextDebugID = __webpack_require__(131); var invariant = __webpack_require__(8); var warning = __webpack_require__(11); // To avoid a cyclic dependency, we create the final class in this module var ReactCompositeComponentWrapper = function (element) { this.construct(element); }; function getDeclarationErrorAddendum(owner) { if (owner) { var name = owner.getName(); if (name) { return ' Check the render method of `' + name + '`.'; } } return ''; } /** * Check if the type reference is a known internal type. I.e. not a user * provided composite type. * * @param {function} type * @return {boolean} Returns true if this is a valid internal type. */ function isInternalComponentType(type) { return typeof type === 'function' && typeof type.prototype !== 'undefined' && typeof type.prototype.mountComponent === 'function' && typeof type.prototype.receiveComponent === 'function'; } /** * Given a ReactNode, create an instance that will actually be mounted. * * @param {ReactNode} node * @param {boolean} shouldHaveDebugID * @return {object} A new instance of the element's constructor. * @protected */ function instantiateReactComponent(node, shouldHaveDebugID) { var instance; if (node === null || node === false) { instance = ReactEmptyComponent.create(instantiateReactComponent); } else if (typeof node === 'object') { var element = node; var type = element.type; if (typeof type !== 'function' && typeof type !== 'string') { var info = ''; if (process.env.NODE_ENV !== 'production') { if (type === undefined || 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.'; } } info += getDeclarationErrorAddendum(element._owner); true ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s', type == null ? type : typeof type, info) : _prodInvariant('130', type == null ? type : typeof type, info) : void 0; } // Special case string values if (typeof element.type === 'string') { instance = ReactHostComponent.createInternalComponent(element); } else if (isInternalComponentType(element.type)) { // This is temporarily available for custom components that are not string // representations. I.e. ART. Once those are updated to use the string // representation, we can drop this code path. instance = new element.type(element); // We renamed this. Allow the old name for compat. :( if (!instance.getHostNode) { instance.getHostNode = instance.getNativeNode; } } else { instance = new ReactCompositeComponentWrapper(element); } } else if (typeof node === 'string' || typeof node === 'number') { instance = ReactHostComponent.createInstanceForText(node); } else { true ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Encountered invalid React node of type %s', typeof node) : _prodInvariant('131', typeof node) : void 0; } if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(typeof instance.mountComponent === 'function' && typeof instance.receiveComponent === 'function' && typeof instance.getHostNode === 'function' && typeof instance.unmountComponent === 'function', 'Only React Components can be mounted.') : void 0; } // These two fields are used by the DOM and ART diffing algorithms // respectively. Instead of using expandos on components, we should be // storing the state needed by the diffing algorithms elsewhere. instance._mountIndex = 0; instance._mountImage = null; if (process.env.NODE_ENV !== 'production') { instance._debugID = shouldHaveDebugID ? getNextDebugID() : 0; } // Internal instances should fully constructed at this point, so they should // not get any new fields added to them at this point. if (process.env.NODE_ENV !== 'production') { if (Object.preventExtensions) { Object.preventExtensions(instance); } } return instance; } _assign(ReactCompositeComponentWrapper.prototype, ReactCompositeComponent, { _instantiateReactComponent: instantiateReactComponent }); module.exports = instantiateReactComponent; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 123 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(39), _assign = __webpack_require__(4); var React = __webpack_require__(2); var ReactComponentEnvironment = __webpack_require__(119); var ReactCurrentOwner = __webpack_require__(10); var ReactErrorUtils = __webpack_require__(49); var ReactInstanceMap = __webpack_require__(120); var ReactInstrumentation = __webpack_require__(66); var ReactNodeTypes = __webpack_require__(124); var ReactReconciler = __webpack_require__(63); if (process.env.NODE_ENV !== 'production') { var checkReactTypeSpec = __webpack_require__(125); } var emptyObject = __webpack_require__(20); var invariant = __webpack_require__(8); var shallowEqual = __webpack_require__(127); var shouldUpdateReactComponent = __webpack_require__(128); var warning = __webpack_require__(11); var CompositeTypes = { ImpureClass: 0, PureClass: 1, StatelessFunctional: 2 }; function StatelessComponent(Component) {} StatelessComponent.prototype.render = function () { var Component = ReactInstanceMap.get(this)._currentElement.type; var element = Component(this.props, this.context, this.updater); warnIfInvalidElement(Component, element); return element; }; function warnIfInvalidElement(Component, element) { if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(element === null || element === false || React.isValidElement(element), '%s(...): A valid React element (or null) must be returned. You may have ' + 'returned undefined, an array or some other invalid object.', Component.displayName || Component.name || 'Component') : void 0; process.env.NODE_ENV !== 'production' ? warning(!Component.childContextTypes, '%s(...): childContextTypes cannot be defined on a functional component.', Component.displayName || Component.name || 'Component') : void 0; } } function shouldConstruct(Component) { return !!(Component.prototype && Component.prototype.isReactComponent); } function isPureComponent(Component) { return !!(Component.prototype && Component.prototype.isPureReactComponent); } // Separated into a function to contain deoptimizations caused by try/finally. function measureLifeCyclePerf(fn, debugID, timerType) { if (debugID === 0) { // Top-level wrappers (see ReactMount) and empty components (see // ReactDOMEmptyComponent) are invisible to hooks and devtools. // Both are implementation details that should go away in the future. return fn(); } ReactInstrumentation.debugTool.onBeginLifeCycleTimer(debugID, timerType); try { return fn(); } finally { ReactInstrumentation.debugTool.onEndLifeCycleTimer(debugID, timerType); } } /** * ------------------ The Life-Cycle of a Composite Component ------------------ * * - constructor: Initialization of state. The instance is now retained. * - componentWillMount * - render * - [children's constructors] * - [children's componentWillMount and render] * - [children's componentDidMount] * - componentDidMount * * Update Phases: * - componentWillReceiveProps (only called if parent updated) * - shouldComponentUpdate * - componentWillUpdate * - render * - [children's constructors or receive props phases] * - componentDidUpdate * * - componentWillUnmount * - [children's componentWillUnmount] * - [children destroyed] * - (destroyed): The instance is now blank, released by React and ready for GC. * * ----------------------------------------------------------------------------- */ /** * An incrementing ID assigned to each component when it is mounted. This is * used to enforce the order in which `ReactUpdates` updates dirty components. * * @private */ var nextMountID = 1; /** * @lends {ReactCompositeComponent.prototype} */ var ReactCompositeComponent = { /** * Base constructor for all composite component. * * @param {ReactElement} element * @final * @internal */ construct: function (element) { this._currentElement = element; this._rootNodeID = 0; this._compositeType = null; this._instance = null; this._hostParent = null; this._hostContainerInfo = null; // See ReactUpdateQueue this._updateBatchNumber = null; this._pendingElement = null; this._pendingStateQueue = null; this._pendingReplaceState = false; this._pendingForceUpdate = false; this._renderedNodeType = null; this._renderedComponent = null; this._context = null; this._mountOrder = 0; this._topLevelWrapper = null; // See ReactUpdates and ReactUpdateQueue. this._pendingCallbacks = null; // ComponentWillUnmount shall only be called once this._calledComponentWillUnmount = false; if (process.env.NODE_ENV !== 'production') { this._warnedAboutRefsInRender = false; } }, /** * Initializes the component, renders markup, and registers event listeners. * * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {?object} hostParent * @param {?object} hostContainerInfo * @param {?object} context * @return {?string} Rendered markup to be inserted into the DOM. * @final * @internal */ mountComponent: function (transaction, hostParent, hostContainerInfo, context) { var _this = this; this._context = context; this._mountOrder = nextMountID++; this._hostParent = hostParent; this._hostContainerInfo = hostContainerInfo; var publicProps = this._currentElement.props; var publicContext = this._processContext(context); var Component = this._currentElement.type; var updateQueue = transaction.getUpdateQueue(); // Initialize the public class var doConstruct = shouldConstruct(Component); var inst = this._constructComponent(doConstruct, publicProps, publicContext, updateQueue); var renderedElement; // Support functional components if (!doConstruct && (inst == null || inst.render == null)) { renderedElement = inst; warnIfInvalidElement(Component, renderedElement); !(inst === null || inst === false || React.isValidElement(inst)) ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s(...): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.', Component.displayName || Component.name || 'Component') : _prodInvariant('105', Component.displayName || Component.name || 'Component') : void 0; inst = new StatelessComponent(Component); this._compositeType = CompositeTypes.StatelessFunctional; } else { if (isPureComponent(Component)) { this._compositeType = CompositeTypes.PureClass; } else { this._compositeType = CompositeTypes.ImpureClass; } } if (process.env.NODE_ENV !== 'production') { // This will throw later in _renderValidatedComponent, but add an early // warning now to help debugging if (inst.render == null) { process.env.NODE_ENV !== 'production' ? warning(false, '%s(...): No `render` method found on the returned component ' + 'instance: you may have forgotten to define `render`.', Component.displayName || Component.name || 'Component') : void 0; } var propsMutated = inst.props !== publicProps; var componentName = Component.displayName || Component.name || 'Component'; process.env.NODE_ENV !== 'production' ? warning(inst.props === undefined || !propsMutated, '%s(...): When calling super() in `%s`, make sure to pass ' + 'up the same props that your component\'s constructor was passed.', componentName, componentName) : void 0; } // These should be set up in the constructor, but as a convenience for // simpler class abstractions, we set them up after the fact. inst.props = publicProps; inst.context = publicContext; inst.refs = emptyObject; inst.updater = updateQueue; this._instance = inst; // Store a reference from the instance back to the internal representation ReactInstanceMap.set(inst, this); if (process.env.NODE_ENV !== 'production') { // Since plain JS classes are defined without any special initialization // logic, we can not catch common errors early. Therefore, we have to // catch them here, at initialization time, instead. process.env.NODE_ENV !== 'production' ? warning(!inst.getInitialState || inst.getInitialState.isReactClassApproved || inst.state, '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?', this.getName() || 'a component') : void 0; process.env.NODE_ENV !== 'production' ? warning(!inst.getDefaultProps || inst.getDefaultProps.isReactClassApproved, '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.', this.getName() || 'a component') : void 0; process.env.NODE_ENV !== 'production' ? warning(!inst.propTypes, 'propTypes was defined as an instance property on %s. Use a static ' + 'property to define propTypes instead.', this.getName() || 'a component') : void 0; process.env.NODE_ENV !== 'production' ? warning(!inst.contextTypes, 'contextTypes was defined as an instance property on %s. Use a ' + 'static property to define contextTypes instead.', this.getName() || 'a component') : void 0; process.env.NODE_ENV !== 'production' ? warning(typeof inst.componentShouldUpdate !== 'function', '%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.', this.getName() || 'A component') : void 0; process.env.NODE_ENV !== 'production' ? warning(typeof inst.componentDidUnmount !== 'function', '%s has a method called ' + 'componentDidUnmount(). But there is no such lifecycle method. ' + 'Did you mean componentWillUnmount()?', this.getName() || 'A component') : void 0; process.env.NODE_ENV !== 'production' ? warning(typeof inst.componentWillRecieveProps !== 'function', '%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', this.getName() || 'A component') : void 0; } var initialState = inst.state; if (initialState === undefined) { inst.state = initialState = null; } !(typeof initialState === 'object' && !Array.isArray(initialState)) ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s.state: must be set to an object or null', this.getName() || 'ReactCompositeComponent') : _prodInvariant('106', this.getName() || 'ReactCompositeComponent') : void 0; this._pendingStateQueue = null; this._pendingReplaceState = false; this._pendingForceUpdate = false; var markup; if (inst.unstable_handleError) { markup = this.performInitialMountWithErrorHandling(renderedElement, hostParent, hostContainerInfo, transaction, context); } else { markup = this.performInitialMount(renderedElement, hostParent, hostContainerInfo, transaction, context); } if (inst.componentDidMount) { if (process.env.NODE_ENV !== 'production') { transaction.getReactMountReady().enqueue(function () { measureLifeCyclePerf(function () { return inst.componentDidMount(); }, _this._debugID, 'componentDidMount'); }); } else { transaction.getReactMountReady().enqueue(inst.componentDidMount, inst); } } return markup; }, _constructComponent: function (doConstruct, publicProps, publicContext, updateQueue) { if (process.env.NODE_ENV !== 'production') { ReactCurrentOwner.current = this; try { return this._constructComponentWithoutOwner(doConstruct, publicProps, publicContext, updateQueue); } finally { ReactCurrentOwner.current = null; } } else { return this._constructComponentWithoutOwner(doConstruct, publicProps, publicContext, updateQueue); } }, _constructComponentWithoutOwner: function (doConstruct, publicProps, publicContext, updateQueue) { var Component = this._currentElement.type; if (doConstruct) { if (process.env.NODE_ENV !== 'production') { return measureLifeCyclePerf(function () { return new Component(publicProps, publicContext, updateQueue); }, this._debugID, 'ctor'); } else { return new Component(publicProps, publicContext, updateQueue); } } // This can still be an instance in case of factory components // but we'll count this as time spent rendering as the more common case. if (process.env.NODE_ENV !== 'production') { return measureLifeCyclePerf(function () { return Component(publicProps, publicContext, updateQueue); }, this._debugID, 'render'); } else { return Component(publicProps, publicContext, updateQueue); } }, performInitialMountWithErrorHandling: function (renderedElement, hostParent, hostContainerInfo, transaction, context) { var markup; var checkpoint = transaction.checkpoint(); try { markup = this.performInitialMount(renderedElement, hostParent, hostContainerInfo, transaction, context); } catch (e) { // Roll back to checkpoint, handle error (which may add items to the transaction), and take a new checkpoint transaction.rollback(checkpoint); this._instance.unstable_handleError(e); if (this._pendingStateQueue) { this._instance.state = this._processPendingState(this._instance.props, this._instance.context); } checkpoint = transaction.checkpoint(); this._renderedComponent.unmountComponent(true); transaction.rollback(checkpoint); // Try again - we've informed the component about the error, so they can render an error message this time. // If this throws again, the error will bubble up (and can be caught by a higher error boundary). markup = this.performInitialMount(renderedElement, hostParent, hostContainerInfo, transaction, context); } return markup; }, performInitialMount: function (renderedElement, hostParent, hostContainerInfo, transaction, context) { var inst = this._instance; var debugID = 0; if (process.env.NODE_ENV !== 'production') { debugID = this._debugID; } if (inst.componentWillMount) { if (process.env.NODE_ENV !== 'production') { measureLifeCyclePerf(function () { return inst.componentWillMount(); }, debugID, 'componentWillMount'); } else { inst.componentWillMount(); } // When mounting, calls to `setState` by `componentWillMount` will set // `this._pendingStateQueue` without triggering a re-render. if (this._pendingStateQueue) { inst.state = this._processPendingState(inst.props, inst.context); } } // If not a stateless component, we now render if (renderedElement === undefined) { renderedElement = this._renderValidatedComponent(); } var nodeType = ReactNodeTypes.getType(renderedElement); this._renderedNodeType = nodeType; var child = this._instantiateReactComponent(renderedElement, nodeType !== ReactNodeTypes.EMPTY /* shouldHaveDebugID */ ); this._renderedComponent = child; var markup = ReactReconciler.mountComponent(child, transaction, hostParent, hostContainerInfo, this._processChildContext(context), debugID); if (process.env.NODE_ENV !== 'production') { if (debugID !== 0) { var childDebugIDs = child._debugID !== 0 ? [child._debugID] : []; ReactInstrumentation.debugTool.onSetChildren(debugID, childDebugIDs); } } return markup; }, getHostNode: function () { return ReactReconciler.getHostNode(this._renderedComponent); }, /** * Releases any resources allocated by `mountComponent`. * * @final * @internal */ unmountComponent: function (safely) { if (!this._renderedComponent) { return; } var inst = this._instance; if (inst.componentWillUnmount && !inst._calledComponentWillUnmount) { inst._calledComponentWillUnmount = true; if (safely) { var name = this.getName() + '.componentWillUnmount()'; ReactErrorUtils.invokeGuardedCallback(name, inst.componentWillUnmount.bind(inst)); } else { if (process.env.NODE_ENV !== 'production') { measureLifeCyclePerf(function () { return inst.componentWillUnmount(); }, this._debugID, 'componentWillUnmount'); } else { inst.componentWillUnmount(); } } } if (this._renderedComponent) { ReactReconciler.unmountComponent(this._renderedComponent, safely); this._renderedNodeType = null; this._renderedComponent = null; this._instance = null; } // Reset pending fields // Even if this component is scheduled for another update in ReactUpdates, // it would still be ignored because these fields are reset. this._pendingStateQueue = null; this._pendingReplaceState = false; this._pendingForceUpdate = false; this._pendingCallbacks = null; this._pendingElement = null; // These fields do not really need to be reset since this object is no // longer accessible. this._context = null; this._rootNodeID = 0; this._topLevelWrapper = null; // Delete the reference from the instance to this internal representation // which allow the internals to be properly cleaned up even if the user // leaks a reference to the public instance. ReactInstanceMap.remove(inst); // Some existing components rely on inst.props even after they've been // destroyed (in event handlers). // TODO: inst.props = null; // TODO: inst.state = null; // TODO: inst.context = null; }, /** * Filters the context object to only contain keys specified in * `contextTypes` * * @param {object} context * @return {?object} * @private */ _maskContext: function (context) { var Component = this._currentElement.type; var contextTypes = Component.contextTypes; if (!contextTypes) { return emptyObject; } var maskedContext = {}; for (var contextName in contextTypes) { maskedContext[contextName] = context[contextName]; } return maskedContext; }, /** * Filters the context object to only contain keys specified in * `contextTypes`, and asserts that they are valid. * * @param {object} context * @return {?object} * @private */ _processContext: function (context) { var maskedContext = this._maskContext(context); if (process.env.NODE_ENV !== 'production') { var Component = this._currentElement.type; if (Component.contextTypes) { this._checkContextTypes(Component.contextTypes, maskedContext, 'context'); } } return maskedContext; }, /** * @param {object} currentContext * @return {object} * @private */ _processChildContext: function (currentContext) { var Component = this._currentElement.type; var inst = this._instance; var childContext; if (inst.getChildContext) { if (process.env.NODE_ENV !== 'production') { ReactInstrumentation.debugTool.onBeginProcessingChildContext(); try { childContext = inst.getChildContext(); } finally { ReactInstrumentation.debugTool.onEndProcessingChildContext(); } } else { childContext = inst.getChildContext(); } } if (childContext) { !(typeof Component.childContextTypes === 'object') ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s.getChildContext(): childContextTypes must be defined in order to use getChildContext().', this.getName() || 'ReactCompositeComponent') : _prodInvariant('107', this.getName() || 'ReactCompositeComponent') : void 0; if (process.env.NODE_ENV !== 'production') { this._checkContextTypes(Component.childContextTypes, childContext, 'child context'); } for (var name in childContext) { !(name in Component.childContextTypes) ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s.getChildContext(): key "%s" is not defined in childContextTypes.', this.getName() || 'ReactCompositeComponent', name) : _prodInvariant('108', this.getName() || 'ReactCompositeComponent', name) : void 0; } return _assign({}, currentContext, childContext); } return currentContext; }, /** * Assert that the context types are valid * * @param {object} typeSpecs Map of context field to a ReactPropType * @param {object} values Runtime values that need to be type-checked * @param {string} location e.g. "prop", "context", "child context" * @private */ _checkContextTypes: function (typeSpecs, values, location) { if (process.env.NODE_ENV !== 'production') { checkReactTypeSpec(typeSpecs, values, location, this.getName(), null, this._debugID); } }, receiveComponent: function (nextElement, transaction, nextContext) { var prevElement = this._currentElement; var prevContext = this._context; this._pendingElement = null; this.updateComponent(transaction, prevElement, nextElement, prevContext, nextContext); }, /** * If any of `_pendingElement`, `_pendingStateQueue`, or `_pendingForceUpdate` * is set, update the component. * * @param {ReactReconcileTransaction} transaction * @internal */ performUpdateIfNecessary: function (transaction) { if (this._pendingElement != null) { ReactReconciler.receiveComponent(this, this._pendingElement, transaction, this._context); } else if (this._pendingStateQueue !== null || this._pendingForceUpdate) { this.updateComponent(transaction, this._currentElement, this._currentElement, this._context, this._context); } else { this._updateBatchNumber = null; } }, /** * Perform an update to a mounted component. The componentWillReceiveProps and * shouldComponentUpdate methods are called, then (assuming the update isn't * skipped) the remaining update lifecycle methods are called and the DOM * representation is updated. * * By default, this implements React's rendering and reconciliation algorithm. * Sophisticated clients may wish to override this. * * @param {ReactReconcileTransaction} transaction * @param {ReactElement} prevParentElement * @param {ReactElement} nextParentElement * @internal * @overridable */ updateComponent: function (transaction, prevParentElement, nextParentElement, prevUnmaskedContext, nextUnmaskedContext) { var inst = this._instance; !(inst != null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Attempted to update component `%s` that has already been unmounted (or failed to mount).', this.getName() || 'ReactCompositeComponent') : _prodInvariant('136', this.getName() || 'ReactCompositeComponent') : void 0; var willReceive = false; var nextContext; // Determine if the context has changed or not if (this._context === nextUnmaskedContext) { nextContext = inst.context; } else { nextContext = this._processContext(nextUnmaskedContext); willReceive = true; } var prevProps = prevParentElement.props; var nextProps = nextParentElement.props; // Not a simple state update but a props update if (prevParentElement !== nextParentElement) { willReceive = true; } // An update here will schedule an update but immediately set // _pendingStateQueue which will ensure that any state updates gets // immediately reconciled instead of waiting for the next batch. if (willReceive && inst.componentWillReceiveProps) { if (process.env.NODE_ENV !== 'production') { measureLifeCyclePerf(function () { return inst.componentWillReceiveProps(nextProps, nextContext); }, this._debugID, 'componentWillReceiveProps'); } else { inst.componentWillReceiveProps(nextProps, nextContext); } } var nextState = this._processPendingState(nextProps, nextContext); var shouldUpdate = true; if (!this._pendingForceUpdate) { if (inst.shouldComponentUpdate) { if (process.env.NODE_ENV !== 'production') { shouldUpdate = measureLifeCyclePerf(function () { return inst.shouldComponentUpdate(nextProps, nextState, nextContext); }, this._debugID, 'shouldComponentUpdate'); } else { shouldUpdate = inst.shouldComponentUpdate(nextProps, nextState, nextContext); } } else { if (this._compositeType === CompositeTypes.PureClass) { shouldUpdate = !shallowEqual(prevProps, nextProps) || !shallowEqual(inst.state, nextState); } } } if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(shouldUpdate !== undefined, '%s.shouldComponentUpdate(): Returned undefined instead of a ' + 'boolean value. Make sure to return true or false.', this.getName() || 'ReactCompositeComponent') : void 0; } this._updateBatchNumber = null; if (shouldUpdate) { this._pendingForceUpdate = false; // Will set `this.props`, `this.state` and `this.context`. this._performComponentUpdate(nextParentElement, nextProps, nextState, nextContext, transaction, nextUnmaskedContext); } else { // If it's determined that a component should not update, we still want // to set props and state but we shortcut the rest of the update. this._currentElement = nextParentElement; this._context = nextUnmaskedContext; inst.props = nextProps; inst.state = nextState; inst.context = nextContext; } }, _processPendingState: function (props, context) { var inst = this._instance; var queue = this._pendingStateQueue; var replace = this._pendingReplaceState; this._pendingReplaceState = false; this._pendingStateQueue = null; if (!queue) { return inst.state; } if (replace && queue.length === 1) { return queue[0]; } var nextState = _assign({}, replace ? queue[0] : inst.state); for (var i = replace ? 1 : 0; i < queue.length; i++) { var partial = queue[i]; _assign(nextState, typeof partial === 'function' ? partial.call(inst, nextState, props, context) : partial); } return nextState; }, /** * Merges new props and state, notifies delegate methods of update and * performs update. * * @param {ReactElement} nextElement Next element * @param {object} nextProps Next public object to set as properties. * @param {?object} nextState Next object to set as state. * @param {?object} nextContext Next public object to set as context. * @param {ReactReconcileTransaction} transaction * @param {?object} unmaskedContext * @private */ _performComponentUpdate: function (nextElement, nextProps, nextState, nextContext, transaction, unmaskedContext) { var _this2 = this; var inst = this._instance; var hasComponentDidUpdate = Boolean(inst.componentDidUpdate); var prevProps; var prevState; var prevContext; if (hasComponentDidUpdate) { prevProps = inst.props; prevState = inst.state; prevContext = inst.context; } if (inst.componentWillUpdate) { if (process.env.NODE_ENV !== 'production') { measureLifeCyclePerf(function () { return inst.componentWillUpdate(nextProps, nextState, nextContext); }, this._debugID, 'componentWillUpdate'); } else { inst.componentWillUpdate(nextProps, nextState, nextContext); } } this._currentElement = nextElement; this._context = unmaskedContext; inst.props = nextProps; inst.state = nextState; inst.context = nextContext; this._updateRenderedComponent(transaction, unmaskedContext); if (hasComponentDidUpdate) { if (process.env.NODE_ENV !== 'production') { transaction.getReactMountReady().enqueue(function () { measureLifeCyclePerf(inst.componentDidUpdate.bind(inst, prevProps, prevState, prevContext), _this2._debugID, 'componentDidUpdate'); }); } else { transaction.getReactMountReady().enqueue(inst.componentDidUpdate.bind(inst, prevProps, prevState, prevContext), inst); } } }, /** * Call the component's `render` method and update the DOM accordingly. * * @param {ReactReconcileTransaction} transaction * @internal */ _updateRenderedComponent: function (transaction, context) { var prevComponentInstance = this._renderedComponent; var prevRenderedElement = prevComponentInstance._currentElement; var nextRenderedElement = this._renderValidatedComponent(); var debugID = 0; if (process.env.NODE_ENV !== 'production') { debugID = this._debugID; } if (shouldUpdateReactComponent(prevRenderedElement, nextRenderedElement)) { ReactReconciler.receiveComponent(prevComponentInstance, nextRenderedElement, transaction, this._processChildContext(context)); } else { var oldHostNode = ReactReconciler.getHostNode(prevComponentInstance); ReactReconciler.unmountComponent(prevComponentInstance, false); var nodeType = ReactNodeTypes.getType(nextRenderedElement); this._renderedNodeType = nodeType; var child = this._instantiateReactComponent(nextRenderedElement, nodeType !== ReactNodeTypes.EMPTY /* shouldHaveDebugID */ ); this._renderedComponent = child; var nextMarkup = ReactReconciler.mountComponent(child, transaction, this._hostParent, this._hostContainerInfo, this._processChildContext(context), debugID); if (process.env.NODE_ENV !== 'production') { if (debugID !== 0) { var childDebugIDs = child._debugID !== 0 ? [child._debugID] : []; ReactInstrumentation.debugTool.onSetChildren(debugID, childDebugIDs); } } this._replaceNodeWithMarkup(oldHostNode, nextMarkup, prevComponentInstance); } }, /** * Overridden in shallow rendering. * * @protected */ _replaceNodeWithMarkup: function (oldHostNode, nextMarkup, prevInstance) { ReactComponentEnvironment.replaceNodeWithMarkup(oldHostNode, nextMarkup, prevInstance); }, /** * @protected */ _renderValidatedComponentWithoutOwnerOrContext: function () { var inst = this._instance; var renderedElement; if (process.env.NODE_ENV !== 'production') { renderedElement = measureLifeCyclePerf(function () { return inst.render(); }, this._debugID, 'render'); } else { renderedElement = inst.render(); } if (process.env.NODE_ENV !== 'production') { // We allow auto-mocks to proceed as if they're returning null. if (renderedElement === undefined && inst.render._isMockFunction) { // This is probably bad practice. Consider warning here and // deprecating this convenience. renderedElement = null; } } return renderedElement; }, /** * @private */ _renderValidatedComponent: function () { var renderedElement; if (process.env.NODE_ENV !== 'production' || this._compositeType !== CompositeTypes.StatelessFunctional) { ReactCurrentOwner.current = this; try { renderedElement = this._renderValidatedComponentWithoutOwnerOrContext(); } finally { ReactCurrentOwner.current = null; } } else { renderedElement = this._renderValidatedComponentWithoutOwnerOrContext(); } !( // TODO: An `isValidNode` function would probably be more appropriate renderedElement === null || renderedElement === false || React.isValidElement(renderedElement)) ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s.render(): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.', this.getName() || 'ReactCompositeComponent') : _prodInvariant('109', this.getName() || 'ReactCompositeComponent') : void 0; return renderedElement; }, /** * Lazily allocates the refs object and stores `component` as `ref`. * * @param {string} ref Reference name. * @param {component} component Component to store as `ref`. * @final * @private */ attachRef: function (ref, component) { var inst = this.getPublicInstance(); !(inst != null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Stateless function components cannot have refs.') : _prodInvariant('110') : void 0; var publicComponentInstance = component.getPublicInstance(); if (process.env.NODE_ENV !== 'production') { var componentName = component && component.getName ? component.getName() : 'a component'; process.env.NODE_ENV !== 'production' ? warning(publicComponentInstance != null || component._compositeType !== CompositeTypes.StatelessFunctional, 'Stateless function components cannot be given refs ' + '(See ref "%s" in %s created by %s). ' + 'Attempts to access this ref will fail.', ref, componentName, this.getName()) : void 0; } var refs = inst.refs === emptyObject ? inst.refs = {} : inst.refs; refs[ref] = publicComponentInstance; }, /** * Detaches a reference name. * * @param {string} ref Name to dereference. * @final * @private */ detachRef: function (ref) { var refs = this.getPublicInstance().refs; delete refs[ref]; }, /** * Get a text description of the component that can be used to identify it * in error messages. * @return {string} The name or null. * @internal */ getName: function () { var type = this._currentElement.type; var constructor = this._instance && this._instance.constructor; return type.displayName || constructor && constructor.displayName || type.name || constructor && constructor.name || null; }, /** * Get the publicly accessible representation of this component - i.e. what * is exposed by refs and returned by render. Can be null for stateless * components. * * @return {ReactComponent} the public component instance. * @internal */ getPublicInstance: function () { var inst = this._instance; if (this._compositeType === CompositeTypes.StatelessFunctional) { return null; } return inst; }, // Stub _instantiateReactComponent: null }; module.exports = ReactCompositeComponent; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 124 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var _prodInvariant = __webpack_require__(39); var React = __webpack_require__(2); var invariant = __webpack_require__(8); var ReactNodeTypes = { HOST: 0, COMPOSITE: 1, EMPTY: 2, getType: function (node) { if (node === null || node === false) { return ReactNodeTypes.EMPTY; } else if (React.isValidElement(node)) { if (typeof node.type === 'function') { return ReactNodeTypes.COMPOSITE; } else { return ReactNodeTypes.HOST; } } true ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Unexpected node: %s', node) : _prodInvariant('26', node) : void 0; } }; module.exports = ReactNodeTypes; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 125 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(39); var ReactPropTypeLocationNames = __webpack_require__(126); var ReactPropTypesSecret = __webpack_require__(114); var invariant = __webpack_require__(8); var warning = __webpack_require__(11); var ReactComponentTreeHook; if (typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'test') { // Temporary hack. // Inline requires don't work well with Jest: // https://github.com/facebook/react/issues/7240 // Remove the inline requires when we don't need them anymore: // https://github.com/facebook/react/pull/7178 ReactComponentTreeHook = __webpack_require__(26); } var loggedTypeFailures = {}; /** * Assert that the values match with the type specs. * Error messages are memorized and will only be shown once. * * @param {object} typeSpecs Map of name to a ReactPropType * @param {object} values Runtime values that need to be type-checked * @param {string} location e.g. "prop", "context", "child context" * @param {string} componentName Name of the component for error messages. * @param {?object} element The React element that is being type-checked * @param {?number} debugID The React component instance that is being type-checked * @private */ function checkReactTypeSpec(typeSpecs, values, location, componentName, element, debugID) { for (var typeSpecName in typeSpecs) { if (typeSpecs.hasOwnProperty(typeSpecName)) { var error; // Prop type validation may throw. In case they do, we don't want to // fail the render phase where it didn't fail before. So we log it. // After these have been cleaned up, we'll let them throw. try { // This is intentionally an invariant that gets caught. It's the same // behavior as without this statement except with a better message. !(typeof typeSpecs[typeSpecName] === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s: %s type `%s` is invalid; it must be a function, usually from React.PropTypes.', componentName || 'React class', ReactPropTypeLocationNames[location], typeSpecName) : _prodInvariant('84', componentName || 'React class', ReactPropTypeLocationNames[location], typeSpecName) : void 0; error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret); } catch (ex) { error = ex; } process.env.NODE_ENV !== 'production' ? warning(!error || error instanceof 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', ReactPropTypeLocationNames[location], typeSpecName, typeof error) : void 0; if (error instanceof Error && !(error.message in loggedTypeFailures)) { // Only monitor this failure once because there tends to be a lot of the // same error. loggedTypeFailures[error.message] = true; var componentStackInfo = ''; if (process.env.NODE_ENV !== 'production') { if (!ReactComponentTreeHook) { ReactComponentTreeHook = __webpack_require__(26); } if (debugID !== null) { componentStackInfo = ReactComponentTreeHook.getStackAddendumByID(debugID); } else if (element !== null) { componentStackInfo = ReactComponentTreeHook.getCurrentStackAddendum(element); } } process.env.NODE_ENV !== 'production' ? warning(false, 'Failed %s type: %s%s', location, error.message, componentStackInfo) : void 0; } } } } module.exports = checkReactTypeSpec; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 126 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var ReactPropTypeLocationNames = {}; if (process.env.NODE_ENV !== 'production') { ReactPropTypeLocationNames = { prop: 'prop', context: 'context', childContext: 'child context' }; } module.exports = ReactPropTypeLocationNames; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 127 */ /***/ (function(module, exports) { /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks * */ /*eslint-disable no-self-compare */ 'use strict'; var hasOwnProperty = Object.prototype.hasOwnProperty; /** * inlined Object.is polyfill to avoid requiring consumers ship their own * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is */ function is(x, y) { // SameValue algorithm if (x === y) { // Steps 1-5, 7-10 // Steps 6.b-6.e: +0 != -0 // Added the nonzero y check to make Flow happy, but it is redundant return x !== 0 || y !== 0 || 1 / x === 1 / y; } else { // Step 6.a: NaN == NaN return x !== x && y !== y; } } /** * Performs equality by iterating through keys on an object and returning false * when any key has values which are not strictly equal between the arguments. * Returns true when the values of all keys are strictly equal. */ function shallowEqual(objA, objB) { if (is(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; } // Test for A's keys different from B. for (var i = 0; i < keysA.length; i++) { if (!hasOwnProperty.call(objB, keysA[i]) || !is(objA[keysA[i]], objB[keysA[i]])) { return false; } } return true; } module.exports = shallowEqual; /***/ }), /* 128 */ /***/ (function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; /** * Given a `prevElement` and `nextElement`, determines if the existing * instance should be updated as opposed to being destroyed or replaced by a new * instance. Both arguments are elements. This ensures that this logic can * operate on stateless trees without any backing instance. * * @param {?object} prevElement * @param {?object} nextElement * @return {boolean} True if the existing instance should be updated. * @protected */ function shouldUpdateReactComponent(prevElement, nextElement) { var prevEmpty = prevElement === null || prevElement === false; var nextEmpty = nextElement === null || nextElement === false; if (prevEmpty || nextEmpty) { return prevEmpty === nextEmpty; } var prevType = typeof prevElement; var nextType = typeof nextElement; if (prevType === 'string' || prevType === 'number') { return nextType === 'string' || nextType === 'number'; } else { return nextType === 'object' && prevElement.type === nextElement.type && prevElement.key === nextElement.key; } } module.exports = shouldUpdateReactComponent; /***/ }), /* 129 */ /***/ (function(module, exports) { /** * Copyright 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var emptyComponentFactory; var ReactEmptyComponentInjection = { injectEmptyComponentFactory: function (factory) { emptyComponentFactory = factory; } }; var ReactEmptyComponent = { create: function (instantiate) { return emptyComponentFactory(instantiate); } }; ReactEmptyComponent.injection = ReactEmptyComponentInjection; module.exports = ReactEmptyComponent; /***/ }), /* 130 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(39); var invariant = __webpack_require__(8); var genericComponentClass = null; var textComponentClass = null; var ReactHostComponentInjection = { // This accepts a class that receives the tag string. This is a catch all // that can render any kind of tag. injectGenericComponentClass: function (componentClass) { genericComponentClass = componentClass; }, // This accepts a text component class that takes the text string to be // rendered as props. injectTextComponentClass: function (componentClass) { textComponentClass = componentClass; } }; /** * Get a host internal component class for a specific tag. * * @param {ReactElement} element The element to create. * @return {function} The internal class constructor function. */ function createInternalComponent(element) { !genericComponentClass ? process.env.NODE_ENV !== 'production' ? invariant(false, 'There is no registered component for the tag %s', element.type) : _prodInvariant('111', element.type) : void 0; return new genericComponentClass(element); } /** * @param {ReactText} text * @return {ReactComponent} */ function createInstanceForText(text) { return new textComponentClass(text); } /** * @param {ReactComponent} component * @return {boolean} */ function isTextComponent(component) { return component instanceof textComponentClass; } var ReactHostComponent = { createInternalComponent: createInternalComponent, createInstanceForText: createInstanceForText, isTextComponent: isTextComponent, injection: ReactHostComponentInjection }; module.exports = ReactHostComponent; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 131 */ /***/ (function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var nextDebugID = 1; function getNextDebugID() { return nextDebugID++; } module.exports = getNextDebugID; /***/ }), /* 132 */ /***/ (function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; /** * Escape and wrap key so it is safe to use as a reactid * * @param {string} key to be escaped. * @return {string} the escaped key. */ function escape(key) { var escapeRegex = /[=:]/g; var escaperLookup = { '=': '=0', ':': '=2' }; var escapedString = ('' + key).replace(escapeRegex, function (match) { return escaperLookup[match]; }); return '$' + escapedString; } /** * Unescape and unwrap key for human-readable display * * @param {string} key to unescape. * @return {string} the unescaped key. */ function unescape(key) { var unescapeRegex = /(=0|=2)/g; var unescaperLookup = { '=0': '=', '=2': ':' }; var keySubstring = key[0] === '.' && key[1] === '$' ? key.substring(2) : key.substring(1); return ('' + keySubstring).replace(unescapeRegex, function (match) { return unescaperLookup[match]; }); } var KeyEscapeUtils = { escape: escape, unescape: unescape }; module.exports = KeyEscapeUtils; /***/ }), /* 133 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(39); var ReactCurrentOwner = __webpack_require__(10); var REACT_ELEMENT_TYPE = __webpack_require__(134); var getIteratorFn = __webpack_require__(135); var invariant = __webpack_require__(8); var KeyEscapeUtils = __webpack_require__(132); var warning = __webpack_require__(11); var SEPARATOR = '.'; var SUBSEPARATOR = ':'; /** * This is inlined from ReactElement since this file is shared between * isomorphic and renderers. We could extract this to a * */ /** * TODO: Test that a single child and an array with one item have the same key * pattern. */ var didWarnAboutMaps = false; /** * Generate a key string that identifies a component within a set. * * @param {*} component A component that could contain a manual key. * @param {number} index Index that is used if a manual key is not provided. * @return {string} */ function getComponentKey(component, index) { // Do some typechecking here since we call this blindly. We want to ensure // that we don't block potential future ES APIs. if (component && typeof component === 'object' && component.key != null) { // Explicit key return KeyEscapeUtils.escape(component.key); } // Implicit key determined by the index in the set return index.toString(36); } /** * @param {?*} children Children tree container. * @param {!string} nameSoFar Name of the key path so far. * @param {!function} callback Callback to invoke with each child found. * @param {?*} traverseContext Used to pass information throughout the traversal * process. * @return {!number} The number of children in this subtree. */ function traverseAllChildrenImpl(children, nameSoFar, callback, traverseContext) { var type = typeof children; if (type === 'undefined' || type === 'boolean') { // All of the above are perceived as null. children = null; } if (children === null || type === 'string' || type === 'number' || // The following is inlined from ReactElement. This means we can optimize // some checks. React Fiber also inlines this logic for similar purposes. type === 'object' && children.$$typeof === REACT_ELEMENT_TYPE) { callback(traverseContext, children, // If it's the only child, treat the name as if it was wrapped in an array // so that it's consistent if the number of children grows. nameSoFar === '' ? SEPARATOR + getComponentKey(children, 0) : nameSoFar); return 1; } var child; var nextName; var subtreeCount = 0; // Count of children found in the current subtree. var nextNamePrefix = nameSoFar === '' ? SEPARATOR : nameSoFar + SUBSEPARATOR; if (Array.isArray(children)) { for (var i = 0; i < children.length; i++) { child = children[i]; nextName = nextNamePrefix + getComponentKey(child, i); subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext); } } else { var iteratorFn = getIteratorFn(children); if (iteratorFn) { var iterator = iteratorFn.call(children); var step; if (iteratorFn !== children.entries) { var ii = 0; while (!(step = iterator.next()).done) { child = step.value; nextName = nextNamePrefix + getComponentKey(child, ii++); subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext); } } else { if (process.env.NODE_ENV !== 'production') { var mapsAsChildrenAddendum = ''; if (ReactCurrentOwner.current) { var mapsAsChildrenOwnerName = ReactCurrentOwner.current.getName(); if (mapsAsChildrenOwnerName) { mapsAsChildrenAddendum = ' Check the render method of `' + mapsAsChildrenOwnerName + '`.'; } } process.env.NODE_ENV !== 'production' ? warning(didWarnAboutMaps, 'Using Maps as children is not yet fully supported. It is an ' + 'experimental feature that might be removed. Convert it to a ' + 'sequence / iterable of keyed ReactElements instead.%s', mapsAsChildrenAddendum) : void 0; didWarnAboutMaps = true; } // Iterator will provide entry [k,v] tuples rather than values. while (!(step = iterator.next()).done) { var entry = step.value; if (entry) { child = entry[1]; nextName = nextNamePrefix + KeyEscapeUtils.escape(entry[0]) + SUBSEPARATOR + getComponentKey(child, 0); subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext); } } } } else if (type === 'object') { var addendum = ''; if (process.env.NODE_ENV !== 'production') { addendum = ' If you meant to render a collection of children, use an array ' + 'instead or wrap the object using createFragment(object) from the ' + 'React add-ons.'; if (children._isReactElement) { addendum = ' It looks like you\'re using an element created by a different ' + 'version of React. Make sure to use only one copy of React.'; } if (ReactCurrentOwner.current) { var name = ReactCurrentOwner.current.getName(); if (name) { addendum += ' Check the render method of `' + name + '`.'; } } } var childrenString = String(children); true ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Objects are not valid as a React child (found: %s).%s', childrenString === '[object Object]' ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString, addendum) : _prodInvariant('31', childrenString === '[object Object]' ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString, addendum) : void 0; } } return subtreeCount; } /** * Traverses children that are typically specified as `props.children`, but * might also be specified through attributes: * * - `traverseAllChildren(this.props.children, ...)` * - `traverseAllChildren(this.props.leftPanelChildren, ...)` * * The `traverseContext` is an optional argument that is passed through the * entire traversal. It can be used to store accumulations or anything else that * the callback might find relevant. * * @param {?*} children Children tree object. * @param {!function} callback To invoke upon traversing each child. * @param {?*} traverseContext Context for traversal. * @return {!number} The number of children in this subtree. */ function traverseAllChildren(children, callback, traverseContext) { if (children == null) { return 0; } return traverseAllChildrenImpl(children, '', callback, traverseContext); } module.exports = traverseAllChildren; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 134 */ /***/ (function(module, exports) { /** * Copyright 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; // The Symbol used to tag the ReactElement type. If there is no native Symbol // nor polyfill, then a plain number is used for performance. var REACT_ELEMENT_TYPE = typeof Symbol === 'function' && Symbol['for'] && Symbol['for']('react.element') || 0xeac7; module.exports = REACT_ELEMENT_TYPE; /***/ }), /* 135 */ /***/ (function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; /* global Symbol */ var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator; var FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec. /** * Returns the iterator method function contained on the iterable object. * * Be sure to invoke the function with the iterable as context: * * var iteratorFn = getIteratorFn(myIterable); * if (iteratorFn) { * var iterator = iteratorFn.call(myIterable); * ... * } * * @param {?object} maybeIterable * @return {?function} */ function getIteratorFn(maybeIterable) { var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]); if (typeof iteratorFn === 'function') { return iteratorFn; } } module.exports = getIteratorFn; /***/ }), /* 136 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var KeyEscapeUtils = __webpack_require__(132); var traverseAllChildren = __webpack_require__(133); var warning = __webpack_require__(11); var ReactComponentTreeHook; if (typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'test') { // Temporary hack. // Inline requires don't work well with Jest: // https://github.com/facebook/react/issues/7240 // Remove the inline requires when we don't need them anymore: // https://github.com/facebook/react/pull/7178 ReactComponentTreeHook = __webpack_require__(26); } /** * @param {function} traverseContext Context passed through traversal. * @param {?ReactComponent} child React child component. * @param {!string} name String name of key path to child. * @param {number=} selfDebugID Optional debugID of the current internal instance. */ function flattenSingleChildIntoContext(traverseContext, child, name, selfDebugID) { // We found a component instance. if (traverseContext && typeof traverseContext === 'object') { var result = traverseContext; var keyUnique = result[name] === undefined; if (process.env.NODE_ENV !== 'production') { if (!ReactComponentTreeHook) { ReactComponentTreeHook = __webpack_require__(26); } if (!keyUnique) { process.env.NODE_ENV !== 'production' ? warning(false, 'flattenChildren(...): Encountered two children with the same key, ' + '`%s`. Child keys must be unique; when two children share a key, only ' + 'the first child will be used.%s', KeyEscapeUtils.unescape(name), ReactComponentTreeHook.getStackAddendumByID(selfDebugID)) : void 0; } } if (keyUnique && child != null) { result[name] = child; } } } /** * Flattens children that are typically specified as `props.children`. Any null * children will not be included in the resulting object. * @return {!object} flattened children keyed by name. */ function flattenChildren(children, selfDebugID) { if (children == null) { return children; } var result = {}; if (process.env.NODE_ENV !== 'production') { traverseAllChildren(children, function (traverseContext, child, name) { return flattenSingleChildIntoContext(traverseContext, child, name, selfDebugID); }, result); } else { traverseAllChildren(children, flattenSingleChildIntoContext, result); } return result; } module.exports = flattenChildren; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 137 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _assign = __webpack_require__(4); var PooledClass = __webpack_require__(54); var Transaction = __webpack_require__(72); var ReactInstrumentation = __webpack_require__(66); var ReactServerUpdateQueue = __webpack_require__(138); /** * Executed within the scope of the `Transaction` instance. Consider these as * being member methods, but with an implied ordering while being isolated from * each other. */ var TRANSACTION_WRAPPERS = []; if (process.env.NODE_ENV !== 'production') { TRANSACTION_WRAPPERS.push({ initialize: ReactInstrumentation.debugTool.onBeginFlush, close: ReactInstrumentation.debugTool.onEndFlush }); } var noopCallbackQueue = { enqueue: function () {} }; /** * @class ReactServerRenderingTransaction * @param {boolean} renderToStaticMarkup */ function ReactServerRenderingTransaction(renderToStaticMarkup) { this.reinitializeTransaction(); this.renderToStaticMarkup = renderToStaticMarkup; this.useCreateElement = false; this.updateQueue = new ReactServerUpdateQueue(this); } var Mixin = { /** * @see Transaction * @abstract * @final * @return {array} Empty list of operation wrap procedures. */ getTransactionWrappers: function () { return TRANSACTION_WRAPPERS; }, /** * @return {object} The queue to collect `onDOMReady` callbacks with. */ getReactMountReady: function () { return noopCallbackQueue; }, /** * @return {object} The queue to collect React async events. */ getUpdateQueue: function () { return this.updateQueue; }, /** * `PooledClass` looks for this, and will invoke this before allowing this * instance to be reused. */ destructor: function () {}, checkpoint: function () {}, rollback: function () {} }; _assign(ReactServerRenderingTransaction.prototype, Transaction, Mixin); PooledClass.addPoolingTo(ReactServerRenderingTransaction); module.exports = ReactServerRenderingTransaction; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 138 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var ReactUpdateQueue = __webpack_require__(139); var warning = __webpack_require__(11); function warnNoop(publicInstance, callerName) { if (process.env.NODE_ENV !== 'production') { var constructor = publicInstance.constructor; process.env.NODE_ENV !== 'production' ? warning(false, '%s(...): Can only update a mounting component. ' + 'This usually means you called %s() outside componentWillMount() on the server. ' + 'This is a no-op. Please check the code for the %s component.', callerName, callerName, constructor && (constructor.displayName || constructor.name) || 'ReactClass') : void 0; } } /** * This is the update queue used for server rendering. * It delegates to ReactUpdateQueue while server rendering is in progress and * switches to ReactNoopUpdateQueue after the transaction has completed. * @class ReactServerUpdateQueue * @param {Transaction} transaction */ var ReactServerUpdateQueue = function () { function ReactServerUpdateQueue(transaction) { _classCallCheck(this, ReactServerUpdateQueue); this.transaction = transaction; } /** * Checks whether or not this composite component is mounted. * @param {ReactClass} publicInstance The instance we want to test. * @return {boolean} True if mounted, false otherwise. * @protected * @final */ ReactServerUpdateQueue.prototype.isMounted = function isMounted(publicInstance) { return false; }; /** * Enqueue a callback that will be executed after all the pending updates * have processed. * * @param {ReactClass} publicInstance The instance to use as `this` context. * @param {?function} callback Called after state is updated. * @internal */ ReactServerUpdateQueue.prototype.enqueueCallback = function enqueueCallback(publicInstance, callback, callerName) { if (this.transaction.isInTransaction()) { ReactUpdateQueue.enqueueCallback(publicInstance, callback, callerName); } }; /** * Forces an update. This should only be invoked when it is known with * certainty that we are **not** in a DOM transaction. * * You may want to call this when you know that some deeper aspect of the * component's state has changed but `setState` was not called. * * This will not invoke `shouldComponentUpdate`, but it will invoke * `componentWillUpdate` and `componentDidUpdate`. * * @param {ReactClass} publicInstance The instance that should rerender. * @internal */ ReactServerUpdateQueue.prototype.enqueueForceUpdate = function enqueueForceUpdate(publicInstance) { if (this.transaction.isInTransaction()) { ReactUpdateQueue.enqueueForceUpdate(publicInstance); } else { warnNoop(publicInstance, 'forceUpdate'); } }; /** * Replaces all of the state. Always use this or `setState` to mutate state. * You should treat `this.state` as immutable. * * There is no guarantee that `this.state` will be immediately updated, so * accessing `this.state` after calling this method may return the old value. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object|function} completeState Next state. * @internal */ ReactServerUpdateQueue.prototype.enqueueReplaceState = function enqueueReplaceState(publicInstance, completeState) { if (this.transaction.isInTransaction()) { ReactUpdateQueue.enqueueReplaceState(publicInstance, completeState); } else { warnNoop(publicInstance, 'replaceState'); } }; /** * Sets a subset of the state. This only exists because _pendingState is * internal. This provides a merging strategy that is not available to deep * properties which is confusing. TODO: Expose pendingState or don't use it * during the merge. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object|function} partialState Next partial state to be merged with state. * @internal */ ReactServerUpdateQueue.prototype.enqueueSetState = function enqueueSetState(publicInstance, partialState) { if (this.transaction.isInTransaction()) { ReactUpdateQueue.enqueueSetState(publicInstance, partialState); } else { warnNoop(publicInstance, 'setState'); } }; return ReactServerUpdateQueue; }(); module.exports = ReactServerUpdateQueue; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 139 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ <|fim▁hole|> var ReactCurrentOwner = __webpack_require__(10); var ReactInstanceMap = __webpack_require__(120); var ReactInstrumentation = __webpack_require__(66); var ReactUpdates = __webpack_require__(60); var invariant = __webpack_require__(8); var warning = __webpack_require__(11); function enqueueUpdate(internalInstance) { ReactUpdates.enqueueUpdate(internalInstance); } function formatUnexpectedArgument(arg) { var type = typeof arg; if (type !== 'object') { return type; } var displayName = arg.constructor && arg.constructor.name || type; var keys = Object.keys(arg); if (keys.length > 0 && keys.length < 20) { return displayName + ' (keys: ' + keys.join(', ') + ')'; } return displayName; } function getInternalInstanceReadyForUpdate(publicInstance, callerName) { var internalInstance = ReactInstanceMap.get(publicInstance); if (!internalInstance) { if (process.env.NODE_ENV !== 'production') { var ctor = publicInstance.constructor; // Only warn when we have a callerName. Otherwise we should be silent. // We're probably calling from enqueueCallback. We don't want to warn // there because we already warned for the corresponding lifecycle method. process.env.NODE_ENV !== 'production' ? warning(!callerName, '%s(...): Can only update a mounted or mounting component. ' + 'This usually means you called %s() on an unmounted component. ' + 'This is a no-op. Please check the code for the %s component.', callerName, callerName, ctor && (ctor.displayName || ctor.name) || 'ReactClass') : void 0; } return null; } if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(ReactCurrentOwner.current == null, '%s(...): Cannot update during an existing state transition (such as ' + 'within `render` or another component\'s constructor). Render methods ' + 'should be a pure function of props and state; constructor ' + 'side-effects are an anti-pattern, but can be moved to ' + '`componentWillMount`.', callerName) : void 0; } return internalInstance; } /** * ReactUpdateQueue allows for state updates to be scheduled into a later * reconciliation step. */ var ReactUpdateQueue = { /** * Checks whether or not this composite component is mounted. * @param {ReactClass} publicInstance The instance we want to test. * @return {boolean} True if mounted, false otherwise. * @protected * @final */ isMounted: function (publicInstance) { if (process.env.NODE_ENV !== 'production') { var owner = ReactCurrentOwner.current; if (owner !== null) { process.env.NODE_ENV !== 'production' ? warning(owner._warnedAboutRefsInRender, '%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.', owner.getName() || 'A component') : void 0; owner._warnedAboutRefsInRender = true; } } var internalInstance = ReactInstanceMap.get(publicInstance); if (internalInstance) { // During componentWillMount and render this will still be null but after // that will always render to something. At least for now. So we can use // this hack. return !!internalInstance._renderedComponent; } else { return false; } }, /** * Enqueue a callback that will be executed after all the pending updates * have processed. * * @param {ReactClass} publicInstance The instance to use as `this` context. * @param {?function} callback Called after state is updated. * @param {string} callerName Name of the calling function in the public API. * @internal */ enqueueCallback: function (publicInstance, callback, callerName) { ReactUpdateQueue.validateCallback(callback, callerName); var internalInstance = getInternalInstanceReadyForUpdate(publicInstance); // Previously we would throw an error if we didn't have an internal // instance. Since we want to make it a no-op instead, we mirror the same // behavior we have in other enqueue* methods. // We also need to ignore callbacks in componentWillMount. See // enqueueUpdates. if (!internalInstance) { return null; } if (internalInstance._pendingCallbacks) { internalInstance._pendingCallbacks.push(callback); } else { internalInstance._pendingCallbacks = [callback]; } // TODO: The callback here is ignored when setState is called from // componentWillMount. Either fix it or disallow doing so completely in // favor of getInitialState. Alternatively, we can disallow // componentWillMount during server-side rendering. enqueueUpdate(internalInstance); }, enqueueCallbackInternal: function (internalInstance, callback) { if (internalInstance._pendingCallbacks) { internalInstance._pendingCallbacks.push(callback); } else { internalInstance._pendingCallbacks = [callback]; } enqueueUpdate(internalInstance); }, /** * Forces an update. This should only be invoked when it is known with * certainty that we are **not** in a DOM transaction. * * You may want to call this when you know that some deeper aspect of the * component's state has changed but `setState` was not called. * * This will not invoke `shouldComponentUpdate`, but it will invoke * `componentWillUpdate` and `componentDidUpdate`. * * @param {ReactClass} publicInstance The instance that should rerender. * @internal */ enqueueForceUpdate: function (publicInstance) { var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'forceUpdate'); if (!internalInstance) { return; } internalInstance._pendingForceUpdate = true; enqueueUpdate(internalInstance); }, /** * Replaces all of the state. Always use this or `setState` to mutate state. * You should treat `this.state` as immutable. * * There is no guarantee that `this.state` will be immediately updated, so * accessing `this.state` after calling this method may return the old value. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} completeState Next state. * @internal */ enqueueReplaceState: function (publicInstance, completeState, callback) { var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'replaceState'); if (!internalInstance) { return; } internalInstance._pendingStateQueue = [completeState]; internalInstance._pendingReplaceState = true; // Future-proof 15.5 if (callback !== undefined && callback !== null) { ReactUpdateQueue.validateCallback(callback, 'replaceState'); if (internalInstance._pendingCallbacks) { internalInstance._pendingCallbacks.push(callback); } else { internalInstance._pendingCallbacks = [callback]; } } enqueueUpdate(internalInstance); }, /** * Sets a subset of the state. This only exists because _pendingState is * internal. This provides a merging strategy that is not available to deep * properties which is confusing. TODO: Expose pendingState or don't use it * during the merge. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} partialState Next partial state to be merged with state. * @internal */ enqueueSetState: function (publicInstance, partialState) { if (process.env.NODE_ENV !== 'production') { ReactInstrumentation.debugTool.onSetState(); process.env.NODE_ENV !== 'production' ? warning(partialState != null, 'setState(...): You passed an undefined or null state object; ' + 'instead, use forceUpdate().') : void 0; } var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'setState'); if (!internalInstance) { return; } var queue = internalInstance._pendingStateQueue || (internalInstance._pendingStateQueue = []); queue.push(partialState); enqueueUpdate(internalInstance); }, enqueueElementInternal: function (internalInstance, nextElement, nextContext) { internalInstance._pendingElement = nextElement; // TODO: introduce _pendingContext instead of setting it directly. internalInstance._context = nextContext; enqueueUpdate(internalInstance); }, validateCallback: function (callback, callerName) { !(!callback || typeof callback === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s(...): Expected the last optional `callback` argument to be a function. Instead received: %s.', callerName, formatUnexpectedArgument(callback)) : _prodInvariant('122', callerName, formatUnexpectedArgument(callback)) : void 0; } }; module.exports = ReactUpdateQueue; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 140 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _assign = __webpack_require__(4); var emptyFunction = __webpack_require__(12); var warning = __webpack_require__(11); var validateDOMNesting = emptyFunction; if (process.env.NODE_ENV !== 'production') { // This validation code was written based on the HTML5 parsing spec: // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope // // Note: this does not catch all invalid nesting, nor does it try to (as it's // not clear what practical benefit doing so provides); instead, we warn only // for cases where the parser will give a parse tree differing from what React // intended. For example, <b><div></div></b> is invalid but we don't warn // because it still parses correctly; we do warn for other cases like nested // <p> tags where the beginning of the second element implicitly closes the // first, causing a confusing mess. // https://html.spec.whatwg.org/multipage/syntax.html#special 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']; // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope var inScopeTags = ['applet', 'caption', 'html', 'table', 'td', 'th', 'marquee', 'object', 'template', // https://html.spec.whatwg.org/multipage/syntax.html#html-integration-point // TODO: Distinguish by namespace here -- for <title>, including it here // errs on the side of fewer warnings 'foreignObject', 'desc', 'title']; // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-button-scope var buttonScopeTags = inScopeTags.concat(['button']); // https://html.spec.whatwg.org/multipage/syntax.html#generate-implied-end-tags 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 }; var updatedAncestorInfo = function (oldInfo, tag, instance) { var ancestorInfo = _assign({}, oldInfo || emptyAncestorInfo); var info = { tag: tag, instance: instance }; if (inScopeTags.indexOf(tag) !== -1) { ancestorInfo.aTagInScope = null; ancestorInfo.buttonTagInScope = null; ancestorInfo.nobrTagInScope = null; } if (buttonScopeTags.indexOf(tag) !== -1) { ancestorInfo.pTagInButtonScope = null; } // See rules for 'li', 'dd', 'dt' start tags in // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody 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; }; /** * Returns whether */ var isTagValidWithParent = function (tag, parentTag) { // First, let's check if we're in an unusual parsing mode... switch (parentTag) { // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inselect case 'select': return tag === 'option' || tag === 'optgroup' || tag === '#text'; case 'optgroup': return tag === 'option' || tag === '#text'; // Strictly speaking, seeing an <option> doesn't mean we're in a <select> // but case 'option': return tag === '#text'; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intd // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incaption // No special behavior since these rules fall back to "in body" mode for // all except special table nodes which cause bad parsing behavior anyway. // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intr case 'tr': return tag === 'th' || tag === 'td' || tag === 'style' || tag === 'script' || tag === 'template'; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intbody case 'tbody': case 'thead': case 'tfoot': return tag === 'tr' || tag === 'style' || tag === 'script' || tag === 'template'; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incolgroup case 'colgroup': return tag === 'col' || tag === 'template'; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intable case 'table': return tag === 'caption' || tag === 'colgroup' || tag === 'tbody' || tag === 'tfoot' || tag === 'thead' || tag === 'style' || tag === 'script' || tag === 'template'; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inhead 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'; // https://html.spec.whatwg.org/multipage/semantics.html#the-html-element case 'html': return tag === 'head' || tag === 'body'; case '#document': return tag === 'html'; } // Probably in the "in body" parsing mode, so we outlaw only tag combos // where the parsing rules cause implicit opens or closes to be added. // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody 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 'frame': case 'head': case 'html': case 'tbody': case 'td': case 'tfoot': case 'th': case 'thead': case 'tr': // These tags are only valid with a few parents that have special child // parsing rules -- if we're down here, then none of those matched and // so we allow it only if we don't know what the parent is, as all other // cases are invalid. return parentTag == null; } return true; }; /** * Returns whether */ 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': // Spec says something about storing a list of markers, but it sounds // equivalent to this check. return ancestorInfo.aTagInScope; case 'nobr': return ancestorInfo.nobrTagInScope; } return null; }; /** * Given a ReactCompositeComponent instance, return a list of its recursive * owners, starting at the root and ending with the instance itself. */ var findOwnerStack = function (instance) { if (!instance) { return []; } var stack = []; do { stack.push(instance); } while (instance = instance._currentElement._owner); stack.reverse(); return stack; }; var didWarn = {}; validateDOMNesting = function (childTag, childText, childInstance, ancestorInfo) { ancestorInfo = ancestorInfo || emptyAncestorInfo; var parentInfo = ancestorInfo.current; var parentTag = parentInfo && parentInfo.tag; if (childText != null) { process.env.NODE_ENV !== 'production' ? warning(childTag == null, 'validateDOMNesting: when childText is passed, childTag should be null') : void 0; childTag = '#text'; } var invalidParent = isTagValidWithParent(childTag, parentTag) ? null : parentInfo; var invalidAncestor = invalidParent ? null : findInvalidAncestorForTag(childTag, ancestorInfo); var problematic = invalidParent || invalidAncestor; if (problematic) { var ancestorTag = problematic.tag; var ancestorInstance = problematic.instance; var childOwner = childInstance && childInstance._currentElement._owner; var ancestorOwner = ancestorInstance && ancestorInstance._currentElement._owner; var childOwners = findOwnerStack(childOwner); var ancestorOwners = findOwnerStack(ancestorOwner); var minStackLen = Math.min(childOwners.length, ancestorOwners.length); var i; var deepestCommon = -1; for (i = 0; i < minStackLen; i++) { if (childOwners[i] === ancestorOwners[i]) { deepestCommon = i; } else { break; } } var UNKNOWN = '(unknown)'; var childOwnerNames = childOwners.slice(deepestCommon + 1).map(function (inst) { return inst.getName() || UNKNOWN; }); var ancestorOwnerNames = ancestorOwners.slice(deepestCommon + 1).map(function (inst) { return inst.getName() || UNKNOWN; }); var ownerInfo = [].concat( // If the parent and child instances have a common owner ancestor, start // with that -- otherwise we just start with the parent's owners. deepestCommon !== -1 ? childOwners[deepestCommon].getName() || UNKNOWN : [], ancestorOwnerNames, ancestorTag, // If we're warning about an invalid (non-parent) ancestry, add '...' invalidAncestor ? ['...'] : [], childOwnerNames, childTag).join(' > '); var warnKey = !!invalidParent + '|' + childTag + '|' + ancestorTag + '|' + ownerInfo; if (didWarn[warnKey]) { return; } didWarn[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> to your code to match the DOM tree generated by ' + 'the browser.'; } process.env.NODE_ENV !== 'production' ? warning(false, 'validateDOMNesting(...): %s cannot appear as a child of <%s>.%s ' + 'See %s.%s', tagDisplayName, ancestorTag, whitespaceInfo, ownerInfo, info) : void 0; } else { process.env.NODE_ENV !== 'production' ? warning(false, 'validateDOMNesting(...): %s cannot appear as a descendant of ' + '<%s>. See %s.', tagDisplayName, ancestorTag, ownerInfo) : void 0; } } }; validateDOMNesting.updatedAncestorInfo = updatedAncestorInfo; // For testing validateDOMNesting.isTagValidInContext = function (tag, ancestorInfo) { ancestorInfo = ancestorInfo || emptyAncestorInfo; var parentInfo = ancestorInfo.current; var parentTag = parentInfo && parentInfo.tag; return isTagValidWithParent(tag, parentTag) && !findInvalidAncestorForTag(tag, ancestorInfo); }; } module.exports = validateDOMNesting; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 141 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _assign = __webpack_require__(4); var DOMLazyTree = __webpack_require__(85); var ReactDOMComponentTree = __webpack_require__(38); var ReactDOMEmptyComponent = function (instantiate) { // ReactCompositeComponent uses this: this._currentElement = null; // ReactDOMComponentTree uses these: this._hostNode = null; this._hostParent = null; this._hostContainerInfo = null; this._domID = 0; }; _assign(ReactDOMEmptyComponent.prototype, { mountComponent: function (transaction, hostParent, hostContainerInfo, context) { var domID = hostContainerInfo._idCounter++; this._domID = domID; this._hostParent = hostParent; this._hostContainerInfo = hostContainerInfo; var nodeValue = ' react-empty: ' + this._domID + ' '; if (transaction.useCreateElement) { var ownerDocument = hostContainerInfo._ownerDocument; var node = ownerDocument.createComment(nodeValue); ReactDOMComponentTree.precacheNode(this, node); return DOMLazyTree(node); } else { if (transaction.renderToStaticMarkup) { // Normally we'd insert a comment node, but since this is a situation // where React won't take over (static pages), we can simply return // nothing. return ''; } return '<!--' + nodeValue + '-->'; } }, receiveComponent: function () {}, getHostNode: function () { return ReactDOMComponentTree.getNodeFromInstance(this); }, unmountComponent: function () { ReactDOMComponentTree.uncacheNode(this); } }); module.exports = ReactDOMEmptyComponent; /***/ }), /* 142 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(39); var invariant = __webpack_require__(8); /** * Return the lowest common ancestor of A and B, or null if they are in * different trees. */ function getLowestCommonAncestor(instA, instB) { !('_hostNode' in instA) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'getNodeFromInstance: Invalid argument.') : _prodInvariant('33') : void 0; !('_hostNode' in instB) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'getNodeFromInstance: Invalid argument.') : _prodInvariant('33') : void 0; var depthA = 0; for (var tempA = instA; tempA; tempA = tempA._hostParent) { depthA++; } var depthB = 0; for (var tempB = instB; tempB; tempB = tempB._hostParent) { depthB++; } // If A is deeper, crawl up. while (depthA - depthB > 0) { instA = instA._hostParent; depthA--; } // If B is deeper, crawl up. while (depthB - depthA > 0) { instB = instB._hostParent; depthB--; } // Walk in lockstep until we find a match. var depth = depthA; while (depth--) { if (instA === instB) { return instA; } instA = instA._hostParent; instB = instB._hostParent; } return null; } /** * Return if A is an ancestor of B. */ function isAncestor(instA, instB) { !('_hostNode' in instA) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'isAncestor: Invalid argument.') : _prodInvariant('35') : void 0; !('_hostNode' in instB) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'isAncestor: Invalid argument.') : _prodInvariant('35') : void 0; while (instB) { if (instB === instA) { return true; } instB = instB._hostParent; } return false; } /** * Return the parent instance of the passed-in instance. */ function getParentInstance(inst) { !('_hostNode' in inst) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'getParentInstance: Invalid argument.') : _prodInvariant('36') : void 0; return inst._hostParent; } /** * Simulates the traversal of a two-phase, capture/bubble event dispatch. */ function traverseTwoPhase(inst, fn, arg) { var path = []; while (inst) { path.push(inst); inst = inst._hostParent; } var i; for (i = path.length; i-- > 0;) { fn(path[i], 'captured', arg); } for (i = 0; i < path.length; i++) { fn(path[i], 'bubbled', arg); } } /** * Traverses the ID hierarchy and invokes the supplied `cb` on any IDs that * should would receive a `mouseEnter` or `mouseLeave` event. * * Does not invoke the callback on the nearest common ancestor because nothing * "entered" or "left" that element. */ function traverseEnterLeave(from, to, fn, argFrom, argTo) { var common = from && to ? getLowestCommonAncestor(from, to) : null; var pathFrom = []; while (from && from !== common) { pathFrom.push(from); from = from._hostParent; } var pathTo = []; while (to && to !== common) { pathTo.push(to); to = to._hostParent; } var i; for (i = 0; i < pathFrom.length; i++) { fn(pathFrom[i], 'bubbled', argFrom); } for (i = pathTo.length; i-- > 0;) { fn(pathTo[i], 'captured', argTo); } } module.exports = { isAncestor: isAncestor, getLowestCommonAncestor: getLowestCommonAncestor, getParentInstance: getParentInstance, traverseTwoPhase: traverseTwoPhase, traverseEnterLeave: traverseEnterLeave }; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 143 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(39), _assign = __webpack_require__(4); var DOMChildrenOperations = __webpack_require__(84); var DOMLazyTree = __webpack_require__(85); var ReactDOMComponentTree = __webpack_require__(38); var escapeTextContentForBrowser = __webpack_require__(90); var invariant = __webpack_require__(8); var validateDOMNesting = __webpack_require__(140); /** * Text nodes violate a couple assumptions that React makes about components: * * - When mounting text into the DOM, adjacent text nodes are merged. * - Text nodes cannot be assigned a React root ID. * * This component is used to wrap strings between comment nodes so that they * can undergo the same reconciliation that is applied to elements. * * TODO: Investigate representing React components in the DOM with text nodes. * * @class ReactDOMTextComponent * @extends ReactComponent * @internal */ var ReactDOMTextComponent = function (text) { // TODO: This is really a ReactText (ReactNode), not a ReactElement this._currentElement = text; this._stringText = '' + text; // ReactDOMComponentTree uses these: this._hostNode = null; this._hostParent = null; // Properties this._domID = 0; this._mountIndex = 0; this._closingComment = null; this._commentNodes = null; }; _assign(ReactDOMTextComponent.prototype, { /** * Creates the markup for this text node. This node is not intended to have * any features besides containing text content. * * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @return {string} Markup for this text node. * @internal */ mountComponent: function (transaction, hostParent, hostContainerInfo, context) { if (process.env.NODE_ENV !== 'production') { var parentInfo; if (hostParent != null) { parentInfo = hostParent._ancestorInfo; } else if (hostContainerInfo != null) { parentInfo = hostContainerInfo._ancestorInfo; } if (parentInfo) { // parentInfo should always be present except for the top-level // component when server rendering validateDOMNesting(null, this._stringText, this, parentInfo); } } var domID = hostContainerInfo._idCounter++; var openingValue = ' react-text: ' + domID + ' '; var closingValue = ' /react-text '; this._domID = domID; this._hostParent = hostParent; if (transaction.useCreateElement) { var ownerDocument = hostContainerInfo._ownerDocument; var openingComment = ownerDocument.createComment(openingValue); var closingComment = ownerDocument.createComment(closingValue); var lazyTree = DOMLazyTree(ownerDocument.createDocumentFragment()); DOMLazyTree.queueChild(lazyTree, DOMLazyTree(openingComment)); if (this._stringText) { DOMLazyTree.queueChild(lazyTree, DOMLazyTree(ownerDocument.createTextNode(this._stringText))); } DOMLazyTree.queueChild(lazyTree, DOMLazyTree(closingComment)); ReactDOMComponentTree.precacheNode(this, openingComment); this._closingComment = closingComment; return lazyTree; } else { var escapedText = escapeTextContentForBrowser(this._stringText); if (transaction.renderToStaticMarkup) { // Normally we'd wrap this between comment nodes for the reasons stated // above, but since this is a situation where React won't take over // (static pages), we can simply return the text as it is. return escapedText; } return '<!--' + openingValue + '-->' + escapedText + '<!--' + closingValue + '-->'; } }, /** * Updates this component by updating the text content. * * @param {ReactText} nextText The next text content * @param {ReactReconcileTransaction} transaction * @internal */ receiveComponent: function (nextText, transaction) { if (nextText !== this._currentElement) { this._currentElement = nextText; var nextStringText = '' + nextText; if (nextStringText !== this._stringText) { // TODO: Save this as pending props and use performUpdateIfNecessary // and/or updateComponent to do the actual update for consistency with // other component types? this._stringText = nextStringText; var commentNodes = this.getHostNode(); DOMChildrenOperations.replaceDelimitedText(commentNodes[0], commentNodes[1], nextStringText); } } }, getHostNode: function () { var hostNode = this._commentNodes; if (hostNode) { return hostNode; } if (!this._closingComment) { var openingComment = ReactDOMComponentTree.getNodeFromInstance(this); var node = openingComment.nextSibling; while (true) { !(node != null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Missing closing comment for text component %s', this._domID) : _prodInvariant('67', this._domID) : void 0; if (node.nodeType === 8 && node.nodeValue === ' /react-text ') { this._closingComment = node; break; } node = node.nextSibling; } } hostNode = [this._hostNode, this._closingComment]; this._commentNodes = hostNode; return hostNode; }, unmountComponent: function () { this._closingComment = null; this._commentNodes = null; ReactDOMComponentTree.uncacheNode(this); } }); module.exports = ReactDOMTextComponent; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 144 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _assign = __webpack_require__(4); var ReactUpdates = __webpack_require__(60); var Transaction = __webpack_require__(72); var emptyFunction = __webpack_require__(12); var RESET_BATCHED_UPDATES = { initialize: emptyFunction, close: function () { ReactDefaultBatchingStrategy.isBatchingUpdates = false; } }; var FLUSH_BATCHED_UPDATES = { initialize: emptyFunction, close: ReactUpdates.flushBatchedUpdates.bind(ReactUpdates) }; var TRANSACTION_WRAPPERS = [FLUSH_BATCHED_UPDATES, RESET_BATCHED_UPDATES]; function ReactDefaultBatchingStrategyTransaction() { this.reinitializeTransaction(); } _assign(ReactDefaultBatchingStrategyTransaction.prototype, Transaction, { getTransactionWrappers: function () { return TRANSACTION_WRAPPERS; } }); var transaction = new ReactDefaultBatchingStrategyTransaction(); var ReactDefaultBatchingStrategy = { isBatchingUpdates: false, /** * Call the provided function in a context within which calls to `setState` * and friends are batched such that components aren't updated unnecessarily. */ batchedUpdates: function (callback, a, b, c, d, e) { var alreadyBatchingUpdates = ReactDefaultBatchingStrategy.isBatchingUpdates; ReactDefaultBatchingStrategy.isBatchingUpdates = true; // The code is written this way to avoid extra allocations if (alreadyBatchingUpdates) { return callback(a, b, c, d, e); } else { return transaction.perform(callback, null, a, b, c, d, e); } } }; module.exports = ReactDefaultBatchingStrategy; /***/ }), /* 145 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _assign = __webpack_require__(4); var EventListener = __webpack_require__(146); var ExecutionEnvironment = __webpack_require__(52); var PooledClass = __webpack_require__(54); var ReactDOMComponentTree = __webpack_require__(38); var ReactUpdates = __webpack_require__(60); var getEventTarget = __webpack_require__(73); var getUnboundedScrollPosition = __webpack_require__(147); /** * Find the deepest React component completely containing the root of the * passed-in instance (for use when entire React trees are nested within each * other). If React trees are not nested, returns null. */ function findParent(inst) { // TODO: It may be a good idea to cache this to prevent unnecessary DOM // traversal, but caching is difficult to do correctly without using a // mutation observer to listen for all DOM changes. while (inst._hostParent) { inst = inst._hostParent; } var rootNode = ReactDOMComponentTree.getNodeFromInstance(inst); var container = rootNode.parentNode; return ReactDOMComponentTree.getClosestInstanceFromNode(container); } // Used to store ancestor hierarchy in top level callback function TopLevelCallbackBookKeeping(topLevelType, nativeEvent) { this.topLevelType = topLevelType; this.nativeEvent = nativeEvent; this.ancestors = []; } _assign(TopLevelCallbackBookKeeping.prototype, { destructor: function () { this.topLevelType = null; this.nativeEvent = null; this.ancestors.length = 0; } }); PooledClass.addPoolingTo(TopLevelCallbackBookKeeping, PooledClass.twoArgumentPooler); function handleTopLevelImpl(bookKeeping) { var nativeEventTarget = getEventTarget(bookKeeping.nativeEvent); var targetInst = ReactDOMComponentTree.getClosestInstanceFromNode(nativeEventTarget); // Loop through the hierarchy, in case there's any nested components. // It's important that we build the array of ancestors before calling any // event handlers, because event handlers can modify the DOM, leading to // inconsistencies with ReactMount's node cache. See #1105. var ancestor = targetInst; do { bookKeeping.ancestors.push(ancestor); ancestor = ancestor && findParent(ancestor); } while (ancestor); for (var i = 0; i < bookKeeping.ancestors.length; i++) { targetInst = bookKeeping.ancestors[i]; ReactEventListener._handleTopLevel(bookKeeping.topLevelType, targetInst, bookKeeping.nativeEvent, getEventTarget(bookKeeping.nativeEvent)); } } function scrollValueMonitor(cb) { var scrollPosition = getUnboundedScrollPosition(window); cb(scrollPosition); } var ReactEventListener = { _enabled: true, _handleTopLevel: null, WINDOW_HANDLE: ExecutionEnvironment.canUseDOM ? window : null, setHandleTopLevel: function (handleTopLevel) { ReactEventListener._handleTopLevel = handleTopLevel; }, setEnabled: function (enabled) { ReactEventListener._enabled = !!enabled; }, isEnabled: function () { return ReactEventListener._enabled; }, /** * Traps top-level events by using event bubbling. * * @param {string} topLevelType Record from `EventConstants`. * @param {string} handlerBaseName Event name (e.g. "click"). * @param {object} element Element on which to attach listener. * @return {?object} An object with a remove function which will forcefully * remove the listener. * @internal */ trapBubbledEvent: function (topLevelType, handlerBaseName, element) { if (!element) { return null; } return EventListener.listen(element, handlerBaseName, ReactEventListener.dispatchEvent.bind(null, topLevelType)); }, /** * Traps a top-level event by using event capturing. * * @param {string} topLevelType Record from `EventConstants`. * @param {string} handlerBaseName Event name (e.g. "click"). * @param {object} element Element on which to attach listener. * @return {?object} An object with a remove function which will forcefully * remove the listener. * @internal */ trapCapturedEvent: function (topLevelType, handlerBaseName, element) { if (!element) { return null; } return EventListener.capture(element, handlerBaseName, ReactEventListener.dispatchEvent.bind(null, topLevelType)); }, monitorScrollValue: function (refresh) { var callback = scrollValueMonitor.bind(null, refresh); EventListener.listen(window, 'scroll', callback); }, dispatchEvent: function (topLevelType, nativeEvent) { if (!ReactEventListener._enabled) { return; } var bookKeeping = TopLevelCallbackBookKeeping.getPooled(topLevelType, nativeEvent); try { // Event queue being processed in the same cycle allows // `preventDefault`. ReactUpdates.batchedUpdates(handleTopLevelImpl, bookKeeping); } finally { TopLevelCallbackBookKeeping.release(bookKeeping); } } }; module.exports = ReactEventListener; /***/ }), /* 146 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {'use strict'; /** * Copyright (c) 2013-present, Facebook, 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. * * @typechecks */ var emptyFunction = __webpack_require__(12); /** * Upstream version of event listener. Does not take into account specific * nature of platform. */ var EventListener = { /** * Listen to DOM events during the bubble phase. * * @param {DOMEventTarget} target DOM element to register listener on. * @param {string} eventType Event type, e.g. 'click' or 'mouseover'. * @param {function} callback Callback function. * @return {object} Object with a `remove` method. */ listen: function listen(target, eventType, callback) { if (target.addEventListener) { target.addEventListener(eventType, callback, false); return { remove: function remove() { target.removeEventListener(eventType, callback, false); } }; } else if (target.attachEvent) { target.attachEvent('on' + eventType, callback); return { remove: function remove() { target.detachEvent('on' + eventType, callback); } }; } }, /** * Listen to DOM events during the capture phase. * * @param {DOMEventTarget} target DOM element to register listener on. * @param {string} eventType Event type, e.g. 'click' or 'mouseover'. * @param {function} callback Callback function. * @return {object} Object with a `remove` method. */ capture: function capture(target, eventType, callback) { if (target.addEventListener) { target.addEventListener(eventType, callback, true); return { remove: function remove() { target.removeEventListener(eventType, callback, true); } }; } else { if (process.env.NODE_ENV !== 'production') { console.error('Attempted to listen to events during the capture phase on a ' + 'browser that does not support the capture phase. Your application ' + 'will not receive some events.'); } return { remove: emptyFunction }; } }, registerDefault: function registerDefault() {} }; module.exports = EventListener; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 147 */ /***/ (function(module, exports) { /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ 'use strict'; /** * Gets the scroll position of the supplied element or window. * * The return values are unbounded, unlike `getScrollPosition`. This means they * may be negative or exceed the element boundaries (which is possible using * inertial scrolling). * * @param {DOMWindow|DOMElement} scrollable * @return {object} Map with `x` and `y` keys. */ function getUnboundedScrollPosition(scrollable) { if (scrollable.Window && scrollable instanceof scrollable.Window) { return { x: scrollable.pageXOffset || scrollable.document.documentElement.scrollLeft, y: scrollable.pageYOffset || scrollable.document.documentElement.scrollTop }; } return { x: scrollable.scrollLeft, y: scrollable.scrollTop }; } module.exports = getUnboundedScrollPosition; /***/ }), /* 148 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var DOMProperty = __webpack_require__(40); var EventPluginHub = __webpack_require__(46); var EventPluginUtils = __webpack_require__(48); var ReactComponentEnvironment = __webpack_require__(119); var ReactEmptyComponent = __webpack_require__(129); var ReactBrowserEventEmitter = __webpack_require__(109); var ReactHostComponent = __webpack_require__(130); var ReactUpdates = __webpack_require__(60); var ReactInjection = { Component: ReactComponentEnvironment.injection, DOMProperty: DOMProperty.injection, EmptyComponent: ReactEmptyComponent.injection, EventPluginHub: EventPluginHub.injection, EventPluginUtils: EventPluginUtils.injection, EventEmitter: ReactBrowserEventEmitter.injection, HostComponent: ReactHostComponent.injection, Updates: ReactUpdates.injection }; module.exports = ReactInjection; /***/ }), /* 149 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _assign = __webpack_require__(4); var CallbackQueue = __webpack_require__(61); var PooledClass = __webpack_require__(54); var ReactBrowserEventEmitter = __webpack_require__(109); var ReactInputSelection = __webpack_require__(150); var ReactInstrumentation = __webpack_require__(66); var Transaction = __webpack_require__(72); var ReactUpdateQueue = __webpack_require__(139); /** * Ensures that, when possible, the selection range (currently selected text * input) is not disturbed by performing the transaction. */ var SELECTION_RESTORATION = { /** * @return {Selection} Selection information. */ initialize: ReactInputSelection.getSelectionInformation, /** * @param {Selection} sel Selection information returned from `initialize`. */ close: ReactInputSelection.restoreSelection }; /** * Suppresses events (blur/focus) that could be inadvertently dispatched due to * high level DOM manipulations (like temporarily removing a text input from the * DOM). */ var EVENT_SUPPRESSION = { /** * @return {boolean} The enabled status of `ReactBrowserEventEmitter` before * the reconciliation. */ initialize: function () { var currentlyEnabled = ReactBrowserEventEmitter.isEnabled(); ReactBrowserEventEmitter.setEnabled(false); return currentlyEnabled; }, /** * @param {boolean} previouslyEnabled Enabled status of * `ReactBrowserEventEmitter` before the reconciliation occurred. `close` * restores the previous value. */ close: function (previouslyEnabled) { ReactBrowserEventEmitter.setEnabled(previouslyEnabled); } }; /** * Provides a queue for collecting `componentDidMount` and * `componentDidUpdate` callbacks during the transaction. */ var ON_DOM_READY_QUEUEING = { /** * Initializes the internal `onDOMReady` queue. */ initialize: function () { this.reactMountReady.reset(); }, /** * After DOM is flushed, invoke all registered `onDOMReady` callbacks. */ close: function () { this.reactMountReady.notifyAll(); } }; /** * Executed within the scope of the `Transaction` instance. Consider these as * being member methods, but with an implied ordering while being isolated from * each other. */ var TRANSACTION_WRAPPERS = [SELECTION_RESTORATION, EVENT_SUPPRESSION, ON_DOM_READY_QUEUEING]; if (process.env.NODE_ENV !== 'production') { TRANSACTION_WRAPPERS.push({ initialize: ReactInstrumentation.debugTool.onBeginFlush, close: ReactInstrumentation.debugTool.onEndFlush }); } /** * Currently: * - The order that these are listed in the transaction is critical: * - Suppresses events. * - Restores selection range. * * Future: * - Restore document/overflow scroll positions that were unintentionally * modified via DOM insertions above the top viewport boundary. * - Implement/integrate with customized constraint based layout system and keep * track of which dimensions must be remeasured. * * @class ReactReconcileTransaction */ function ReactReconcileTransaction(useCreateElement) { this.reinitializeTransaction(); // Only server-side rendering really needs this option (see // `ReactServerRendering`), but server-side uses // `ReactServerRenderingTransaction` instead. This option is here so that it's // accessible and defaults to false when `ReactDOMComponent` and // `ReactDOMTextComponent` checks it in `mountComponent`.` this.renderToStaticMarkup = false; this.reactMountReady = CallbackQueue.getPooled(null); this.useCreateElement = useCreateElement; } var Mixin = { /** * @see Transaction * @abstract * @final * @return {array<object>} List of operation wrap procedures. * TODO: convert to array<TransactionWrapper> */ getTransactionWrappers: function () { return TRANSACTION_WRAPPERS; }, /** * @return {object} The queue to collect `onDOMReady` callbacks with. */ getReactMountReady: function () { return this.reactMountReady; }, /** * @return {object} The queue to collect React async events. */ getUpdateQueue: function () { return ReactUpdateQueue; }, /** * Save current transaction state -- if the return value from this method is * passed to `rollback`, the transaction will be reset to that state. */ checkpoint: function () { // reactMountReady is the our only stateful wrapper return this.reactMountReady.checkpoint(); }, rollback: function (checkpoint) { this.reactMountReady.rollback(checkpoint); }, /** * `PooledClass` looks for this, and will invoke this before allowing this * instance to be reused. */ destructor: function () { CallbackQueue.release(this.reactMountReady); this.reactMountReady = null; } }; _assign(ReactReconcileTransaction.prototype, Transaction, Mixin); PooledClass.addPoolingTo(ReactReconcileTransaction); module.exports = ReactReconcileTransaction; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 150 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var ReactDOMSelection = __webpack_require__(151); var containsNode = __webpack_require__(153); var focusNode = __webpack_require__(98); var getActiveElement = __webpack_require__(156); function isInDocument(node) { return containsNode(document.documentElement, node); } /** * @ReactInputSelection: React input selection module. Based on Selection.js, * but modified to be suitable for react and has a couple of bug fixes (doesn't * assume buttons have range selections allowed). * Input selection module for React. */ var ReactInputSelection = { hasSelectionCapabilities: function (elem) { var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase(); return nodeName && (nodeName === 'input' && elem.type === 'text' || nodeName === 'textarea' || elem.contentEditable === 'true'); }, getSelectionInformation: function () { var focusedElem = getActiveElement(); return { focusedElem: focusedElem, selectionRange: ReactInputSelection.hasSelectionCapabilities(focusedElem) ? ReactInputSelection.getSelection(focusedElem) : null }; }, /** * @restoreSelection: If any selection information was potentially lost, * restore it. This is useful when performing operations that could remove dom * nodes and place them back in, resulting in focus being lost. */ restoreSelection: function (priorSelectionInformation) { var curFocusedElem = getActiveElement(); var priorFocusedElem = priorSelectionInformation.focusedElem; var priorSelectionRange = priorSelectionInformation.selectionRange; if (curFocusedElem !== priorFocusedElem && isInDocument(priorFocusedElem)) { if (ReactInputSelection.hasSelectionCapabilities(priorFocusedElem)) { ReactInputSelection.setSelection(priorFocusedElem, priorSelectionRange); } focusNode(priorFocusedElem); } }, /** * @getSelection: Gets the selection bounds of a focused textarea, input or * contentEditable node. * -@input: Look up selection bounds of this input * -@return {start: selectionStart, end: selectionEnd} */ getSelection: function (input) { var selection; if ('selectionStart' in input) { // Modern browser with input or textarea. selection = { start: input.selectionStart, end: input.selectionEnd }; } else if (document.selection && input.nodeName && input.nodeName.toLowerCase() === 'input') { // IE8 input. var range = document.selection.createRange(); // There can only be one selection per document in IE, so it must // be in our element. if (range.parentElement() === input) { selection = { start: -range.moveStart('character', -input.value.length), end: -range.moveEnd('character', -input.value.length) }; } } else { // Content editable or old IE textarea. selection = ReactDOMSelection.getOffsets(input); } return selection || { start: 0, end: 0 }; }, /** * @setSelection: Sets the selection bounds of a textarea or input and focuses * the input. * -@input Set selection bounds of this input or textarea * -@offsets Object of same form that is returned from get* */ setSelection: function (input, offsets) { var start = offsets.start; var end = offsets.end; if (end === undefined) { end = start; } if ('selectionStart' in input) { input.selectionStart = start; input.selectionEnd = Math.min(end, input.value.length); } else if (document.selection && input.nodeName && input.nodeName.toLowerCase() === 'input') { var range = input.createTextRange(); range.collapse(true); range.moveStart('character', start); range.moveEnd('character', end - start); range.select(); } else { ReactDOMSelection.setOffsets(input, offsets); } } }; module.exports = ReactInputSelection; /***/ }), /* 151 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var ExecutionEnvironment = __webpack_require__(52); var getNodeForCharacterOffset = __webpack_require__(152); var getTextContentAccessor = __webpack_require__(55); /** * While `isCollapsed` is available on the Selection object and `collapsed` * is available on the Range object, IE11 sometimes gets them wrong. * If the anchor/focus nodes and offsets are the same, the range is collapsed. */ function isCollapsed(anchorNode, anchorOffset, focusNode, focusOffset) { return anchorNode === focusNode && anchorOffset === focusOffset; } /** * Get the appropriate anchor and focus node/offset pairs for IE. * * The catch here is that IE's selection API doesn't provide information * about whether the selection is forward or backward, so we have to * behave as though it's always forward. * * IE text differs from modern selection in that it behaves as though * block elements end with a new line. This means character offsets will * differ between the two APIs. * * @param {DOMElement} node * @return {object} */ function getIEOffsets(node) { var selection = document.selection; var selectedRange = selection.createRange(); var selectedLength = selectedRange.text.length; // Duplicate selection so we can move range without breaking user selection. var fromStart = selectedRange.duplicate(); fromStart.moveToElementText(node); fromStart.setEndPoint('EndToStart', selectedRange); var startOffset = fromStart.text.length; var endOffset = startOffset + selectedLength; return { start: startOffset, end: endOffset }; } /** * @param {DOMElement} node * @return {?object} */ function getModernOffsets(node) { var selection = window.getSelection && window.getSelection(); if (!selection || selection.rangeCount === 0) { return null; } var anchorNode = selection.anchorNode; var anchorOffset = selection.anchorOffset; var focusNode = selection.focusNode; var focusOffset = selection.focusOffset; var currentRange = selection.getRangeAt(0); // In Firefox, range.startContainer and range.endContainer can be "anonymous // divs", e.g. the up/down buttons on an <input type="number">. Anonymous // divs do not seem to expose properties, triggering a "Permission denied // error" if any of its properties are accessed. The only seemingly possible // way to avoid erroring is to access a property that typically works for // non-anonymous divs and catch any error that may otherwise arise. See // https://bugzilla.mozilla.org/show_bug.cgi?id=208427 try { /* eslint-disable no-unused-expressions */ currentRange.startContainer.nodeType; currentRange.endContainer.nodeType; /* eslint-enable no-unused-expressions */ } catch (e) { return null; } // If the node and offset values are the same, the selection is collapsed. // `Selection.isCollapsed` is available natively, but IE sometimes gets // this value wrong. var isSelectionCollapsed = isCollapsed(selection.anchorNode, selection.anchorOffset, selection.focusNode, selection.focusOffset); var rangeLength = isSelectionCollapsed ? 0 : currentRange.toString().length; var tempRange = currentRange.cloneRange(); tempRange.selectNodeContents(node); tempRange.setEnd(currentRange.startContainer, currentRange.startOffset); var isTempRangeCollapsed = isCollapsed(tempRange.startContainer, tempRange.startOffset, tempRange.endContainer, tempRange.endOffset); var start = isTempRangeCollapsed ? 0 : tempRange.toString().length; var end = start + rangeLength; // Detect whether the selection is backward. var detectionRange = document.createRange(); detectionRange.setStart(anchorNode, anchorOffset); detectionRange.setEnd(focusNode, focusOffset); var isBackward = detectionRange.collapsed; return { start: isBackward ? end : start, end: isBackward ? start : end }; } /** * @param {DOMElement|DOMTextNode} node * @param {object} offsets */ function setIEOffsets(node, offsets) { var range = document.selection.createRange().duplicate(); var start, end; if (offsets.end === undefined) { start = offsets.start; end = start; } else if (offsets.start > offsets.end) { start = offsets.end; end = offsets.start; } else { start = offsets.start; end = offsets.end; } range.moveToElementText(node); range.moveStart('character', start); range.setEndPoint('EndToStart', range); range.moveEnd('character', end - start); range.select(); } /** * In modern non-IE browsers, we can support both forward and backward * selections. * * Note: IE10+ supports the Selection object, but it does not support * the `extend` method, which means that even in modern IE, it's not possible * to programmatically create a backward selection. Thus, for all IE * versions, we use the old IE API to create our selections. * * @param {DOMElement|DOMTextNode} node * @param {object} offsets */ function setModernOffsets(node, offsets) { if (!window.getSelection) { return; } var selection = window.getSelection(); var length = node[getTextContentAccessor()].length; var start = Math.min(offsets.start, length); var end = offsets.end === undefined ? start : Math.min(offsets.end, length); // IE 11 uses modern selection, but doesn't support the extend method. // Flip backward selections, so we can set with a single range. 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) { var range = document.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); } } } var useIEOffsets = ExecutionEnvironment.canUseDOM && 'selection' in document && !('getSelection' in window); var ReactDOMSelection = { /** * @param {DOMElement} node */ getOffsets: useIEOffsets ? getIEOffsets : getModernOffsets, /** * @param {DOMElement|DOMTextNode} node * @param {object} offsets */ setOffsets: useIEOffsets ? setIEOffsets : setModernOffsets }; module.exports = ReactDOMSelection; /***/ }), /* 152 */ /***/ (function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; /** * Given any node return the first leaf node without children. * * @param {DOMElement|DOMTextNode} node * @return {DOMElement|DOMTextNode} */ function getLeafNode(node) { while (node && node.firstChild) { node = node.firstChild; } return node; } /** * Get the next sibling within a container. This will walk up the * DOM if a node's siblings have been exhausted. * * @param {DOMElement|DOMTextNode} node * @return {?DOMElement|DOMTextNode} */ function getSiblingNode(node) { while (node) { if (node.nextSibling) { return node.nextSibling; } node = node.parentNode; } } /** * Get object describing the nodes which contain characters at offset. * * @param {DOMElement|DOMTextNode} root * @param {number} offset * @return {?object} */ function getNodeForCharacterOffset(root, offset) { var node = getLeafNode(root); var nodeStart = 0; var nodeEnd = 0; while (node) { if (node.nodeType === 3) { nodeEnd = nodeStart + node.textContent.length; if (nodeStart <= offset && nodeEnd >= offset) { return { node: node, offset: offset - nodeStart }; } nodeStart = nodeEnd; } node = getLeafNode(getSiblingNode(node)); } } module.exports = getNodeForCharacterOffset; /***/ }), /* 153 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ var isTextNode = __webpack_require__(154); /*eslint-disable no-bitwise */ /** * Checks if a given DOM node contains or is another DOM 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; } } module.exports = containsNode; /***/ }), /* 154 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ var isNode = __webpack_require__(155); /** * @param {*} object The object to check. * @return {boolean} Whether or not the object is a DOM text node. */ function isTextNode(object) { return isNode(object) && object.nodeType == 3; } module.exports = isTextNode; /***/ }), /* 155 */ /***/ (function(module, exports) { 'use strict'; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ /** * @param {*} object The object to check. * @return {boolean} Whether or not the object is a DOM node. */ function isNode(object) { var doc = object ? object.ownerDocument || object : document; var defaultView = doc.defaultView || window; return !!(object && (typeof defaultView.Node === 'function' ? object instanceof defaultView.Node : typeof object === 'object' && typeof object.nodeType === 'number' && typeof object.nodeName === 'string')); } module.exports = isNode; /***/ }), /* 156 */ /***/ (function(module, exports) { 'use strict'; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ /* eslint-disable fb-www/typeof-undefined */ /** * Same as document.activeElement but wraps in a try-catch block. In IE it is * not safe to call document.activeElement if there is nothing focused. * * The activeElement will be null only if the document or document body is not * yet defined. * * @param {?DOMDocument} doc Defaults to current document. * @return {?DOMElement} */ function getActiveElement(doc) /*?DOMElement*/{ doc = doc || (typeof document !== 'undefined' ? document : undefined); if (typeof doc === 'undefined') { return null; } try { return doc.activeElement || doc.body; } catch (e) { return doc.body; } } module.exports = getActiveElement; /***/ }), /* 157 */ /***/ (function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var NS = { xlink: 'http://www.w3.org/1999/xlink', xml: 'http://www.w3.org/XML/1998/namespace' }; // We use attributes for everything SVG so let's avoid some duplication and run // code instead. // The following are all specified in the HTML config already so we exclude here. // - class (as className) // - color // - height // - id // - lang // - max // - media // - method // - min // - name // - style // - target // - type // - width var ATTRS = { accentHeight: 'accent-height', accumulate: 0, additive: 0, alignmentBaseline: 'alignment-baseline', allowReorder: 'allowReorder', alphabetic: 0, amplitude: 0, arabicForm: 'arabic-form', ascent: 0, attributeName: 'attributeName', attributeType: 'attributeType', autoReverse: 'autoReverse', azimuth: 0, baseFrequency: 'baseFrequency', baseProfile: 'baseProfile', baselineShift: 'baseline-shift', bbox: 0, begin: 0, bias: 0, by: 0, calcMode: 'calcMode', capHeight: 'cap-height', clip: 0, clipPath: 'clip-path', clipRule: 'clip-rule', clipPathUnits: 'clipPathUnits', colorInterpolation: 'color-interpolation', colorInterpolationFilters: 'color-interpolation-filters', colorProfile: 'color-profile', colorRendering: 'color-rendering', contentScriptType: 'contentScriptType', contentStyleType: 'contentStyleType', cursor: 0, cx: 0, cy: 0, d: 0, decelerate: 0, descent: 0, diffuseConstant: 'diffuseConstant', direction: 0, display: 0, divisor: 0, dominantBaseline: 'dominant-baseline', dur: 0, dx: 0, dy: 0, edgeMode: 'edgeMode', elevation: 0, enableBackground: 'enable-background', end: 0, exponent: 0, externalResourcesRequired: 'externalResourcesRequired', fill: 0, fillOpacity: 'fill-opacity', fillRule: 'fill-rule', filter: 0, filterRes: 'filterRes', filterUnits: 'filterUnits', floodColor: 'flood-color', floodOpacity: 'flood-opacity', focusable: 0, fontFamily: 'font-family', fontSize: 'font-size', fontSizeAdjust: 'font-size-adjust', fontStretch: 'font-stretch', fontStyle: 'font-style', fontVariant: 'font-variant', fontWeight: 'font-weight', format: 0, from: 0, fx: 0, fy: 0, g1: 0, g2: 0, glyphName: 'glyph-name', glyphOrientationHorizontal: 'glyph-orientation-horizontal', glyphOrientationVertical: 'glyph-orientation-vertical', glyphRef: 'glyphRef', gradientTransform: 'gradientTransform', gradientUnits: 'gradientUnits', hanging: 0, horizAdvX: 'horiz-adv-x', horizOriginX: 'horiz-origin-x', ideographic: 0, imageRendering: 'image-rendering', 'in': 0, in2: 0, intercept: 0, k: 0, k1: 0, k2: 0, k3: 0, k4: 0, kernelMatrix: 'kernelMatrix', kernelUnitLength: 'kernelUnitLength', kerning: 0, keyPoints: 'keyPoints', keySplines: 'keySplines', keyTimes: 'keyTimes', lengthAdjust: 'lengthAdjust', letterSpacing: 'letter-spacing', lightingColor: 'lighting-color', limitingConeAngle: 'limitingConeAngle', local: 0, markerEnd: 'marker-end', markerMid: 'marker-mid', markerStart: 'marker-start', markerHeight: 'markerHeight', markerUnits: 'markerUnits', markerWidth: 'markerWidth', mask: 0, maskContentUnits: 'maskContentUnits', maskUnits: 'maskUnits', mathematical: 0, mode: 0, numOctaves: 'numOctaves', offset: 0, opacity: 0, operator: 0, order: 0, orient: 0, orientation: 0, origin: 0, overflow: 0, overlinePosition: 'overline-position', overlineThickness: 'overline-thickness', paintOrder: 'paint-order', panose1: 'panose-1', pathLength: 'pathLength', patternContentUnits: 'patternContentUnits', patternTransform: 'patternTransform', patternUnits: 'patternUnits', pointerEvents: 'pointer-events', points: 0, pointsAtX: 'pointsAtX', pointsAtY: 'pointsAtY', pointsAtZ: 'pointsAtZ', preserveAlpha: 'preserveAlpha', preserveAspectRatio: 'preserveAspectRatio', primitiveUnits: 'primitiveUnits', r: 0, radius: 0, refX: 'refX', refY: 'refY', renderingIntent: 'rendering-intent', repeatCount: 'repeatCount', repeatDur: 'repeatDur', requiredExtensions: 'requiredExtensions', requiredFeatures: 'requiredFeatures', restart: 0, result: 0, rotate: 0, rx: 0, ry: 0, scale: 0, seed: 0, shapeRendering: 'shape-rendering', slope: 0, spacing: 0, specularConstant: 'specularConstant', specularExponent: 'specularExponent', speed: 0, spreadMethod: 'spreadMethod', startOffset: 'startOffset', stdDeviation: 'stdDeviation', stemh: 0, stemv: 0, stitchTiles: 'stitchTiles', stopColor: 'stop-color', stopOpacity: 'stop-opacity', strikethroughPosition: 'strikethrough-position', strikethroughThickness: 'strikethrough-thickness', string: 0, stroke: 0, strokeDasharray: 'stroke-dasharray', strokeDashoffset: 'stroke-dashoffset', strokeLinecap: 'stroke-linecap', strokeLinejoin: 'stroke-linejoin', strokeMiterlimit: 'stroke-miterlimit', strokeOpacity: 'stroke-opacity', strokeWidth: 'stroke-width', surfaceScale: 'surfaceScale', systemLanguage: 'systemLanguage', tableValues: 'tableValues', targetX: 'targetX', targetY: 'targetY', textAnchor: 'text-anchor', textDecoration: 'text-decoration', textRendering: 'text-rendering', textLength: 'textLength', to: 0, transform: 0, u1: 0, u2: 0, underlinePosition: 'underline-position', underlineThickness: 'underline-thickness', unicode: 0, unicodeBidi: 'unicode-bidi', unicodeRange: 'unicode-range', unitsPerEm: 'units-per-em', vAlphabetic: 'v-alphabetic', vHanging: 'v-hanging', vIdeographic: 'v-ideographic', vMathematical: 'v-mathematical', values: 0, vectorEffect: 'vector-effect', version: 0, vertAdvY: 'vert-adv-y', vertOriginX: 'vert-origin-x', vertOriginY: 'vert-origin-y', viewBox: 'viewBox', viewTarget: 'viewTarget', visibility: 0, widths: 0, wordSpacing: 'word-spacing', writingMode: 'writing-mode', x: 0, xHeight: 'x-height', x1: 0, x2: 0, xChannelSelector: 'xChannelSelector', xlinkActuate: 'xlink:actuate', xlinkArcrole: 'xlink:arcrole', xlinkHref: 'xlink:href', xlinkRole: 'xlink:role', xlinkShow: 'xlink:show', xlinkTitle: 'xlink:title', xlinkType: 'xlink:type', xmlBase: 'xml:base', xmlns: 0, xmlnsXlink: 'xmlns:xlink', xmlLang: 'xml:lang', xmlSpace: 'xml:space', y: 0, y1: 0, y2: 0, yChannelSelector: 'yChannelSelector', z: 0, zoomAndPan: 'zoomAndPan' }; var SVGDOMPropertyConfig = { Properties: {}, DOMAttributeNamespaces: { xlinkActuate: NS.xlink, xlinkArcrole: NS.xlink, xlinkHref: NS.xlink, xlinkRole: NS.xlink, xlinkShow: NS.xlink, xlinkTitle: NS.xlink, xlinkType: NS.xlink, xmlBase: NS.xml, xmlLang: NS.xml, xmlSpace: NS.xml }, DOMAttributeNames: {} }; Object.keys(ATTRS).forEach(function (key) { SVGDOMPropertyConfig.Properties[key] = 0; if (ATTRS[key]) { SVGDOMPropertyConfig.DOMAttributeNames[key] = ATTRS[key]; } }); module.exports = SVGDOMPropertyConfig; /***/ }), /* 158 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var EventPropagators = __webpack_require__(45); var ExecutionEnvironment = __webpack_require__(52); var ReactDOMComponentTree = __webpack_require__(38); var ReactInputSelection = __webpack_require__(150); var SyntheticEvent = __webpack_require__(57); var getActiveElement = __webpack_require__(156); var isTextInputElement = __webpack_require__(75); var shallowEqual = __webpack_require__(127); var skipSelectionChangeEvent = ExecutionEnvironment.canUseDOM && 'documentMode' in document && document.documentMode <= 11; var eventTypes = { select: { phasedRegistrationNames: { bubbled: 'onSelect', captured: 'onSelectCapture' }, dependencies: ['topBlur', 'topContextMenu', 'topFocus', 'topKeyDown', 'topKeyUp', 'topMouseDown', 'topMouseUp', 'topSelectionChange'] } }; var activeElement = null; var activeElementInst = null; var lastSelection = null; var mouseDown = false; // Track whether a listener exists for this plugin. If none exist, we do // not extract events. See #3639. var hasListener = false; /** * Get an object which is a unique representation of the current selection. * * The return value will not be consistent across nodes or browsers, but * two identical selections on the same node will return identical objects. * * @param {DOMElement} node * @return {object} */ function getSelection(node) { if ('selectionStart' in node && ReactInputSelection.hasSelectionCapabilities(node)) { return { start: node.selectionStart, end: node.selectionEnd }; } else if (window.getSelection) { var selection = window.getSelection(); return { anchorNode: selection.anchorNode, anchorOffset: selection.anchorOffset, focusNode: selection.focusNode, focusOffset: selection.focusOffset }; } else if (document.selection) { var range = document.selection.createRange(); return { parentElement: range.parentElement(), text: range.text, top: range.boundingTop, left: range.boundingLeft }; } } /** * Poll selection to see whether it's changed. * * @param {object} nativeEvent * @return {?SyntheticEvent} */ function constructSelectEvent(nativeEvent, nativeEventTarget) { // Ensure we have the right element, and that the user is not dragging a // selection (this matches native `select` event behavior). In HTML5, select // fires only on input and textarea thus if there's no focused element we // won't dispatch. if (mouseDown || activeElement == null || activeElement !== getActiveElement()) { return null; } // Only fire when selection has actually changed. var currentSelection = getSelection(activeElement); if (!lastSelection || !shallowEqual(lastSelection, currentSelection)) { lastSelection = currentSelection; var syntheticEvent = SyntheticEvent.getPooled(eventTypes.select, activeElementInst, nativeEvent, nativeEventTarget); syntheticEvent.type = 'select'; syntheticEvent.target = activeElement; EventPropagators.accumulateTwoPhaseDispatches(syntheticEvent); return syntheticEvent; } return null; } /** * This plugin creates an `onSelect` event that normalizes select events * across form elements. * * Supported elements are: * - input (see `isTextInputElement`) * - textarea * - contentEditable * * This differs from native browser implementations in the following ways: * - Fires on contentEditable fields as well as inputs. * - Fires for collapsed selection. * - Fires after user input. */ var SelectEventPlugin = { eventTypes: eventTypes, extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { if (!hasListener) { return null; } var targetNode = targetInst ? ReactDOMComponentTree.getNodeFromInstance(targetInst) : window; switch (topLevelType) { // Track the input node that has focus. case 'topFocus': if (isTextInputElement(targetNode) || targetNode.contentEditable === 'true') { activeElement = targetNode; activeElementInst = targetInst; lastSelection = null; } break; case 'topBlur': activeElement = null; activeElementInst = null; lastSelection = null; break; // Don't fire the event while the user is dragging. This matches the // semantics of the native select event. case 'topMouseDown': mouseDown = true; break; case 'topContextMenu': case 'topMouseUp': mouseDown = false; return constructSelectEvent(nativeEvent, nativeEventTarget); // Chrome and IE fire non-standard event when selection is changed (and // sometimes when it hasn't). IE's event fires out of order with respect // to key and input events on deletion, so we discard it. // // Firefox doesn't support selectionchange, so check selection status // after each key entry. The selection changes after keydown and before // keyup, but we check on keydown as well in the case of holding down a // key, when multiple keydown events are fired but only one keyup is. // This is also our approach for IE handling, for the reason above. case 'topSelectionChange': if (skipSelectionChangeEvent) { break; } // falls through case 'topKeyDown': case 'topKeyUp': return constructSelectEvent(nativeEvent, nativeEventTarget); } return null; }, didPutListener: function (inst, registrationName, listener) { if (registrationName === 'onSelect') { hasListener = true; } } }; module.exports = SelectEventPlugin; /***/ }), /* 159 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var _prodInvariant = __webpack_require__(39); var EventListener = __webpack_require__(146); var EventPropagators = __webpack_require__(45); var ReactDOMComponentTree = __webpack_require__(38); var SyntheticAnimationEvent = __webpack_require__(160); var SyntheticClipboardEvent = __webpack_require__(161); var SyntheticEvent = __webpack_require__(57); var SyntheticFocusEvent = __webpack_require__(162); var SyntheticKeyboardEvent = __webpack_require__(163); var SyntheticMouseEvent = __webpack_require__(78); var SyntheticDragEvent = __webpack_require__(166); var SyntheticTouchEvent = __webpack_require__(167); var SyntheticTransitionEvent = __webpack_require__(168); var SyntheticUIEvent = __webpack_require__(79); var SyntheticWheelEvent = __webpack_require__(169); var emptyFunction = __webpack_require__(12); var getEventCharCode = __webpack_require__(164); var invariant = __webpack_require__(8); /** * Turns * ['abort', ...] * into * eventTypes = { * 'abort': { * phasedRegistrationNames: { * bubbled: 'onAbort', * captured: 'onAbortCapture', * }, * dependencies: ['topAbort'], * }, * ... * }; * topLevelEventsToDispatchConfig = { * 'topAbort': { sameConfig } * }; */ var eventTypes = {}; var topLevelEventsToDispatchConfig = {}; ['abort', 'animationEnd', 'animationIteration', 'animationStart', 'blur', 'canPlay', 'canPlayThrough', 'click', 'contextMenu', 'copy', 'cut', 'doubleClick', 'drag', 'dragEnd', 'dragEnter', 'dragExit', 'dragLeave', 'dragOver', 'dragStart', 'drop', 'durationChange', 'emptied', 'encrypted', 'ended', 'error', 'focus', 'input', 'invalid', 'keyDown', 'keyPress', 'keyUp', 'load', 'loadedData', 'loadedMetadata', 'loadStart', 'mouseDown', 'mouseMove', 'mouseOut', 'mouseOver', 'mouseUp', 'paste', 'pause', 'play', 'playing', 'progress', 'rateChange', 'reset', 'scroll', 'seeked', 'seeking', 'stalled', 'submit', 'suspend', 'timeUpdate', 'touchCancel', 'touchEnd', 'touchMove', 'touchStart', 'transitionEnd', 'volumeChange', 'waiting', 'wheel'].forEach(function (event) { var capitalizedEvent = event[0].toUpperCase() + event.slice(1); var onEvent = 'on' + capitalizedEvent; var topEvent = 'top' + capitalizedEvent; var type = { phasedRegistrationNames: { bubbled: onEvent, captured: onEvent + 'Capture' }, dependencies: [topEvent] }; eventTypes[event] = type; topLevelEventsToDispatchConfig[topEvent] = type; }); var onClickListeners = {}; function getDictionaryKey(inst) { // Prevents V8 performance issue: // https://github.com/facebook/react/pull/7232 return '.' + inst._rootNodeID; } function isInteractive(tag) { return tag === 'button' || tag === 'input' || tag === 'select' || tag === 'textarea'; } var SimpleEventPlugin = { eventTypes: eventTypes, extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { var dispatchConfig = topLevelEventsToDispatchConfig[topLevelType]; if (!dispatchConfig) { return null; } var EventConstructor; switch (topLevelType) { case 'topAbort': case 'topCanPlay': case 'topCanPlayThrough': case 'topDurationChange': case 'topEmptied': case 'topEncrypted': case 'topEnded': case 'topError': case 'topInput': case 'topInvalid': case 'topLoad': case 'topLoadedData': case 'topLoadedMetadata': case 'topLoadStart': case 'topPause': case 'topPlay': case 'topPlaying': case 'topProgress': case 'topRateChange': case 'topReset': case 'topSeeked': case 'topSeeking': case 'topStalled': case 'topSubmit': case 'topSuspend': case 'topTimeUpdate': case 'topVolumeChange': case 'topWaiting': // HTML Events // @see http://www.w3.org/TR/html5/index.html#events-0 EventConstructor = SyntheticEvent; break; case 'topKeyPress': // Firefox creates a keypress event for function keys too. This removes // the unwanted keypress events. Enter is however both printable and // non-printable. One would expect Tab to be as well (but it isn't). if (getEventCharCode(nativeEvent) === 0) { return null; } /* falls through */ case 'topKeyDown': case 'topKeyUp': EventConstructor = SyntheticKeyboardEvent; break; case 'topBlur': case 'topFocus': EventConstructor = SyntheticFocusEvent; break; case 'topClick': // Firefox creates a click event on right mouse clicks. This removes the // unwanted click events. if (nativeEvent.button === 2) { return null; } /* falls through */ case 'topDoubleClick': case 'topMouseDown': case 'topMouseMove': case 'topMouseUp': // TODO: Disabled elements should not respond to mouse events /* falls through */ case 'topMouseOut': case 'topMouseOver': case 'topContextMenu': EventConstructor = SyntheticMouseEvent; break; case 'topDrag': case 'topDragEnd': case 'topDragEnter': case 'topDragExit': case 'topDragLeave': case 'topDragOver': case 'topDragStart': case 'topDrop': EventConstructor = SyntheticDragEvent; break; case 'topTouchCancel': case 'topTouchEnd': case 'topTouchMove': case 'topTouchStart': EventConstructor = SyntheticTouchEvent; break; case 'topAnimationEnd': case 'topAnimationIteration': case 'topAnimationStart': EventConstructor = SyntheticAnimationEvent; break; case 'topTransitionEnd': EventConstructor = SyntheticTransitionEvent; break; case 'topScroll': EventConstructor = SyntheticUIEvent; break; case 'topWheel': EventConstructor = SyntheticWheelEvent; break; case 'topCopy': case 'topCut': case 'topPaste': EventConstructor = SyntheticClipboardEvent; break; } !EventConstructor ? process.env.NODE_ENV !== 'production' ? invariant(false, 'SimpleEventPlugin: Unhandled event type, `%s`.', topLevelType) : _prodInvariant('86', topLevelType) : void 0; var event = EventConstructor.getPooled(dispatchConfig, targetInst, nativeEvent, nativeEventTarget); EventPropagators.accumulateTwoPhaseDispatches(event); return event; }, didPutListener: function (inst, registrationName, listener) { // Mobile Safari does not fire properly bubble click events on // non-interactive elements, which means delegated click listeners do not // fire. The workaround for this bug involves attaching an empty click // listener on the target node. // http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html if (registrationName === 'onClick' && !isInteractive(inst._tag)) { var key = getDictionaryKey(inst); var node = ReactDOMComponentTree.getNodeFromInstance(inst); if (!onClickListeners[key]) { onClickListeners[key] = EventListener.listen(node, 'click', emptyFunction); } } }, willDeleteListener: function (inst, registrationName) { if (registrationName === 'onClick' && !isInteractive(inst._tag)) { var key = getDictionaryKey(inst); onClickListeners[key].remove(); delete onClickListeners[key]; } } }; module.exports = SimpleEventPlugin; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 160 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var SyntheticEvent = __webpack_require__(57); /** * @interface Event * @see http://www.w3.org/TR/css3-animations/#AnimationEvent-interface * @see https://developer.mozilla.org/en-US/docs/Web/API/AnimationEvent */ var AnimationEventInterface = { animationName: null, elapsedTime: null, pseudoElement: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticEvent} */ function SyntheticAnimationEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticEvent.augmentClass(SyntheticAnimationEvent, AnimationEventInterface); module.exports = SyntheticAnimationEvent; /***/ }), /* 161 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var SyntheticEvent = __webpack_require__(57); /** * @interface Event * @see http://www.w3.org/TR/clipboard-apis/ */ var ClipboardEventInterface = { clipboardData: function (event) { return 'clipboardData' in event ? event.clipboardData : window.clipboardData; } }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticClipboardEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticEvent.augmentClass(SyntheticClipboardEvent, ClipboardEventInterface); module.exports = SyntheticClipboardEvent; /***/ }), /* 162 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var SyntheticUIEvent = __webpack_require__(79); /** * @interface FocusEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var FocusEventInterface = { relatedTarget: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticFocusEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticUIEvent.augmentClass(SyntheticFocusEvent, FocusEventInterface); module.exports = SyntheticFocusEvent; /***/ }), /* 163 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var SyntheticUIEvent = __webpack_require__(79); var getEventCharCode = __webpack_require__(164); var getEventKey = __webpack_require__(165); var getEventModifierState = __webpack_require__(81); /** * @interface KeyboardEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var KeyboardEventInterface = { key: getEventKey, location: null, ctrlKey: null, shiftKey: null, altKey: null, metaKey: null, repeat: null, locale: null, getModifierState: getEventModifierState, // Legacy Interface charCode: function (event) { // `charCode` is the result of a KeyPress event and represents the value of // the actual printable character. // KeyPress is deprecated, but its replacement is not yet final and not // implemented in any major browser. Only KeyPress has charCode. if (event.type === 'keypress') { return getEventCharCode(event); } return 0; }, keyCode: function (event) { // `keyCode` is the result of a KeyDown/Up event and represents the value of // physical keyboard key. // The actual meaning of the value depends on the users' keyboard layout // which cannot be detected. Assuming that it is a US keyboard layout // provides a surprisingly accurate mapping for US and European users. // Due to this, it is left to the user to implement at this time. if (event.type === 'keydown' || event.type === 'keyup') { return event.keyCode; } return 0; }, which: function (event) { // `which` is an alias for either `keyCode` or `charCode` depending on the // type of the event. if (event.type === 'keypress') { return getEventCharCode(event); } if (event.type === 'keydown' || event.type === 'keyup') { return event.keyCode; } return 0; } }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticKeyboardEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticUIEvent.augmentClass(SyntheticKeyboardEvent, KeyboardEventInterface); module.exports = SyntheticKeyboardEvent; /***/ }), /* 164 */ /***/ (function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; /** * `charCode` represents the actual "character code" and is safe to use with * `String.fromCharCode`. As such, only keys that correspond to printable * characters produce a valid `charCode`, the only exception to this is Enter. * The Tab-key is considered non-printable and does not have a `charCode`, * presumably because it does not produce a tab-character in browsers. * * @param {object} nativeEvent Native browser event. * @return {number} Normalized `charCode` property. */ function getEventCharCode(nativeEvent) { var charCode; var keyCode = nativeEvent.keyCode; if ('charCode' in nativeEvent) { charCode = nativeEvent.charCode; // FF does not set `charCode` for the Enter-key, check against `keyCode`. if (charCode === 0 && keyCode === 13) { charCode = 13; } } else { // IE8 does not implement `charCode`, but `keyCode` has the correct value. charCode = keyCode; } // Some non-printable keys are reported in `charCode`/`keyCode`, discard them. // Must not discard the (non-)printable Enter-key. if (charCode >= 32 || charCode === 13) { return charCode; } return 0; } module.exports = getEventCharCode; /***/ }), /* 165 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var getEventCharCode = __webpack_require__(164); /** * Normalization of deprecated HTML5 `key` values * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names */ 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' }; /** * Translation from legacy `keyCode` to HTML5 `key` * Only special keys supported, all others depend on keyboard layout or browser * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names */ 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' }; /** * @param {object} nativeEvent Native browser event. * @return {string} Normalized `key` property. */ function getEventKey(nativeEvent) { if (nativeEvent.key) { // Normalize inconsistent values reported by browsers due to // implementations of a working draft specification. // FireFox implements `key` but returns `MozPrintableKey` for all // printable characters (normalized to `Unidentified`), ignore it. var key = normalizeKey[nativeEvent.key] || nativeEvent.key; if (key !== 'Unidentified') { return key; } } // Browser does not implement `key`, polyfill as much of it as we can. if (nativeEvent.type === 'keypress') { var charCode = getEventCharCode(nativeEvent); // The enter-key is technically both printable and non-printable and can // thus be captured by `keypress`, no other non-printable key should. return charCode === 13 ? 'Enter' : String.fromCharCode(charCode); } if (nativeEvent.type === 'keydown' || nativeEvent.type === 'keyup') { // While user keyboard layout determines the actual meaning of each // `keyCode` value, almost all function keys have a universal value. return translateToKey[nativeEvent.keyCode] || 'Unidentified'; } return ''; } module.exports = getEventKey; /***/ }), /* 166 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var SyntheticMouseEvent = __webpack_require__(78); /** * @interface DragEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var DragEventInterface = { dataTransfer: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticDragEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticMouseEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticMouseEvent.augmentClass(SyntheticDragEvent, DragEventInterface); module.exports = SyntheticDragEvent; /***/ }), /* 167 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var SyntheticUIEvent = __webpack_require__(79); var getEventModifierState = __webpack_require__(81); /** * @interface TouchEvent * @see http://www.w3.org/TR/touch-events/ */ var TouchEventInterface = { touches: null, targetTouches: null, changedTouches: null, altKey: null, metaKey: null, ctrlKey: null, shiftKey: null, getModifierState: getEventModifierState }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticTouchEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticUIEvent.augmentClass(SyntheticTouchEvent, TouchEventInterface); module.exports = SyntheticTouchEvent; /***/ }), /* 168 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var SyntheticEvent = __webpack_require__(57); /** * @interface Event * @see http://www.w3.org/TR/2009/WD-css3-transitions-20090320/#transition-events- * @see https://developer.mozilla.org/en-US/docs/Web/API/TransitionEvent */ var TransitionEventInterface = { propertyName: null, elapsedTime: null, pseudoElement: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticEvent} */ function SyntheticTransitionEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticEvent.augmentClass(SyntheticTransitionEvent, TransitionEventInterface); module.exports = SyntheticTransitionEvent; /***/ }), /* 169 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var SyntheticMouseEvent = __webpack_require__(78); /** * @interface WheelEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var WheelEventInterface = { deltaX: function (event) { return 'deltaX' in event ? event.deltaX : // Fallback to `wheelDeltaX` for Webkit and normalize (right is positive). 'wheelDeltaX' in event ? -event.wheelDeltaX : 0; }, deltaY: function (event) { return 'deltaY' in event ? event.deltaY : // Fallback to `wheelDeltaY` for Webkit and normalize (down is positive). 'wheelDeltaY' in event ? -event.wheelDeltaY : // Fallback to `wheelDelta` for IE<9 and normalize (down is positive). 'wheelDelta' in event ? -event.wheelDelta : 0; }, deltaZ: null, // Browsers without "deltaMode" is reporting in raw wheel delta where one // notch on the scroll is always +/- 120, roughly equivalent to pixels. // A good approximation of DOM_DELTA_LINE (1) is 5% of viewport size or // ~40 pixels, for DOM_DELTA_SCREEN (2) it is 87.5% of viewport size. deltaMode: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticMouseEvent} */ function SyntheticWheelEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticMouseEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticMouseEvent.augmentClass(SyntheticWheelEvent, WheelEventInterface); module.exports = SyntheticWheelEvent; /***/ }), /* 170 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(39); var DOMLazyTree = __webpack_require__(85); var DOMProperty = __webpack_require__(40); var React = __webpack_require__(2); var ReactBrowserEventEmitter = __webpack_require__(109); var ReactCurrentOwner = __webpack_require__(10); var ReactDOMComponentTree = __webpack_require__(38); var ReactDOMContainerInfo = __webpack_require__(171); var ReactDOMFeatureFlags = __webpack_require__(172); var ReactFeatureFlags = __webpack_require__(62); var ReactInstanceMap = __webpack_require__(120); var ReactInstrumentation = __webpack_require__(66); var ReactMarkupChecksum = __webpack_require__(173); var ReactReconciler = __webpack_require__(63); var ReactUpdateQueue = __webpack_require__(139); var ReactUpdates = __webpack_require__(60); var emptyObject = __webpack_require__(20); var instantiateReactComponent = __webpack_require__(122); var invariant = __webpack_require__(8); var setInnerHTML = __webpack_require__(87); var shouldUpdateReactComponent = __webpack_require__(128); var warning = __webpack_require__(11); var ATTR_NAME = DOMProperty.ID_ATTRIBUTE_NAME; var ROOT_ATTR_NAME = DOMProperty.ROOT_ATTRIBUTE_NAME; var ELEMENT_NODE_TYPE = 1; var DOC_NODE_TYPE = 9; var DOCUMENT_FRAGMENT_NODE_TYPE = 11; var instancesByReactRootID = {}; /** * Finds the index of the first character * that's not common between the two given strings. * * @return {number} the index of the character where the strings diverge */ function firstDifferenceIndex(string1, string2) { var minLen = Math.min(string1.length, string2.length); for (var i = 0; i < minLen; i++) { if (string1.charAt(i) !== string2.charAt(i)) { return i; } } return string1.length === string2.length ? -1 : minLen; } /** * @param {DOMElement|DOMDocument} container DOM element that may contain * a React component * @return {?*} DOM element that may have the reactRoot ID, or null. */ function getReactRootElementInContainer(container) { if (!container) { return null; } if (container.nodeType === DOC_NODE_TYPE) { return container.documentElement; } else { return container.firstChild; } } function internalGetID(node) { // If node is something like a window, document, or text node, none of // which support attributes or a .getAttribute method, gracefully return // the empty string, as if the attribute were missing. return node.getAttribute && node.getAttribute(ATTR_NAME) || ''; } /** * Mounts this component and inserts it into the DOM. * * @param {ReactComponent} componentInstance The instance to mount. * @param {DOMElement} container DOM element to mount into. * @param {ReactReconcileTransaction} transaction * @param {boolean} shouldReuseMarkup If true, do not insert markup */ function mountComponentIntoNode(wrapperInstance, container, transaction, shouldReuseMarkup, context) { var markerName; if (ReactFeatureFlags.logTopLevelRenders) { var wrappedElement = wrapperInstance._currentElement.props.child; var type = wrappedElement.type; markerName = 'React mount: ' + (typeof type === 'string' ? type : type.displayName || type.name); console.time(markerName); } var markup = ReactReconciler.mountComponent(wrapperInstance, transaction, null, ReactDOMContainerInfo(wrapperInstance, container), context, 0 /* parentDebugID */ ); if (markerName) { console.timeEnd(markerName); } wrapperInstance._renderedComponent._topLevelWrapper = wrapperInstance; ReactMount._mountImageIntoNode(markup, container, wrapperInstance, shouldReuseMarkup, transaction); } /** * Batched mount. * * @param {ReactComponent} componentInstance The instance to mount. * @param {DOMElement} container DOM element to mount into. * @param {boolean} shouldReuseMarkup If true, do not insert markup */ function batchedMountComponentIntoNode(componentInstance, container, shouldReuseMarkup, context) { var transaction = ReactUpdates.ReactReconcileTransaction.getPooled( /* useCreateElement */ !shouldReuseMarkup && ReactDOMFeatureFlags.useCreateElement); transaction.perform(mountComponentIntoNode, null, componentInstance, container, transaction, shouldReuseMarkup, context); ReactUpdates.ReactReconcileTransaction.release(transaction); } /** * Unmounts a component and removes it from the DOM. * * @param {ReactComponent} instance React component instance. * @param {DOMElement} container DOM element to unmount from. * @final * @internal * @see {ReactMount.unmountComponentAtNode} */ function unmountComponentFromNode(instance, container, safely) { if (process.env.NODE_ENV !== 'production') { ReactInstrumentation.debugTool.onBeginFlush(); } ReactReconciler.unmountComponent(instance, safely); if (process.env.NODE_ENV !== 'production') { ReactInstrumentation.debugTool.onEndFlush(); } if (container.nodeType === DOC_NODE_TYPE) { container = container.documentElement; } // http://jsperf.com/emptying-a-node while (container.lastChild) { container.removeChild(container.lastChild); } } /** * True if the supplied DOM node has a direct React-rendered child that is * not a React root element. Useful for warning in `render`, * `unmountComponentAtNode`, etc. * * @param {?DOMElement} node The candidate DOM node. * @return {boolean} True if the DOM element contains a direct child that was * rendered by React but is not a root element. * @internal */ function hasNonRootReactChild(container) { var rootEl = getReactRootElementInContainer(container); if (rootEl) { var inst = ReactDOMComponentTree.getInstanceFromNode(rootEl); return !!(inst && inst._hostParent); } } /** * True if the supplied DOM node is a React DOM element and * it has been rendered by another copy of React. * * @param {?DOMElement} node The candidate DOM node. * @return {boolean} True if the DOM has been rendered by another copy of React * @internal */ function nodeIsRenderedByOtherInstance(container) { var rootEl = getReactRootElementInContainer(container); return !!(rootEl && isReactNode(rootEl) && !ReactDOMComponentTree.getInstanceFromNode(rootEl)); } /** * True if the supplied DOM node is a valid node element. * * @param {?DOMElement} node The candidate DOM node. * @return {boolean} True if the DOM is a valid DOM node. * @internal */ function isValidContainer(node) { return !!(node && (node.nodeType === ELEMENT_NODE_TYPE || node.nodeType === DOC_NODE_TYPE || node.nodeType === DOCUMENT_FRAGMENT_NODE_TYPE)); } /** * True if the supplied DOM node is a valid React node element. * * @param {?DOMElement} node The candidate DOM node. * @return {boolean} True if the DOM is a valid React DOM node. * @internal */ function isReactNode(node) { return isValidContainer(node) && (node.hasAttribute(ROOT_ATTR_NAME) || node.hasAttribute(ATTR_NAME)); } function getHostRootInstanceInContainer(container) { var rootEl = getReactRootElementInContainer(container); var prevHostInstance = rootEl && ReactDOMComponentTree.getInstanceFromNode(rootEl); return prevHostInstance && !prevHostInstance._hostParent ? prevHostInstance : null; } function getTopLevelWrapperInContainer(container) { var root = getHostRootInstanceInContainer(container); return root ? root._hostContainerInfo._topLevelWrapper : null; } /** * Temporary (?) hack so that we can store all top-level pending updates on * composites instead of having to worry about different types of components * here. */ var topLevelRootCounter = 1; var TopLevelWrapper = function () { this.rootID = topLevelRootCounter++; }; TopLevelWrapper.prototype.isReactComponent = {}; if (process.env.NODE_ENV !== 'production') { TopLevelWrapper.displayName = 'TopLevelWrapper'; } TopLevelWrapper.prototype.render = function () { return this.props.child; }; TopLevelWrapper.isReactTopLevelWrapper = true; /** * Mounting is the process of initializing a React component by creating its * representative DOM elements and inserting them into a supplied `container`. * Any prior content inside `container` is destroyed in the process. * * ReactMount.render( * component, * document.getElementById('container') * ); * * <div id="container"> <-- Supplied `container`. * <div data-reactid=".3"> <-- Rendered reactRoot of React * // ... component. * </div> * </div> * * Inside of `container`, the first element rendered is the "reactRoot". */ var ReactMount = { TopLevelWrapper: TopLevelWrapper, /** * Used by devtools. The keys are not important. */ _instancesByReactRootID: instancesByReactRootID, /** * This is a hook provided to support rendering React components while * ensuring that the apparent scroll position of its `container` does not * change. * * @param {DOMElement} container The `container` being rendered into. * @param {function} renderCallback This must be called once to do the render. */ scrollMonitor: function (container, renderCallback) { renderCallback(); }, /** * Take a component that's already mounted into the DOM and replace its props * @param {ReactComponent} prevComponent component instance already in the DOM * @param {ReactElement} nextElement component instance to render * @param {DOMElement} container container to render into * @param {?function} callback function triggered on completion */ _updateRootComponent: function (prevComponent, nextElement, nextContext, container, callback) { ReactMount.scrollMonitor(container, function () { ReactUpdateQueue.enqueueElementInternal(prevComponent, nextElement, nextContext); if (callback) { ReactUpdateQueue.enqueueCallbackInternal(prevComponent, callback); } }); return prevComponent; }, /** * Render a new component into the DOM. Hooked by hooks! * * @param {ReactElement} nextElement element to render * @param {DOMElement} container container to render into * @param {boolean} shouldReuseMarkup if we should skip the markup insertion * @return {ReactComponent} nextComponent */ _renderNewRootComponent: function (nextElement, container, shouldReuseMarkup, context) { // Various parts of our code (such as ReactCompositeComponent's // _renderValidatedComponent) assume that calls to render aren't nested; // verify that that's the case. process.env.NODE_ENV !== 'production' ? warning(ReactCurrentOwner.current == null, '_renderNewRootComponent(): 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. Check the render method of %s.', ReactCurrentOwner.current && ReactCurrentOwner.current.getName() || 'ReactCompositeComponent') : void 0; !isValidContainer(container) ? process.env.NODE_ENV !== 'production' ? invariant(false, '_registerComponent(...): Target container is not a DOM element.') : _prodInvariant('37') : void 0; ReactBrowserEventEmitter.ensureScrollValueMonitoring(); var componentInstance = instantiateReactComponent(nextElement, false); // The initial render is synchronous but any updates that happen during // rendering, in componentWillMount or componentDidMount, will be batched // according to the current batching strategy. ReactUpdates.batchedUpdates(batchedMountComponentIntoNode, componentInstance, container, shouldReuseMarkup, context); var wrapperID = componentInstance._instance.rootID; instancesByReactRootID[wrapperID] = componentInstance; return componentInstance; }, /** * Renders a React component into the DOM in the supplied `container`. * * If the React component was previously rendered into `container`, this will * perform an update on it and only mutate the DOM as necessary to reflect the * latest React component. * * @param {ReactComponent} parentComponent The conceptual parent of this render tree. * @param {ReactElement} nextElement Component element to render. * @param {DOMElement} container DOM element to render into. * @param {?function} callback function triggered on completion * @return {ReactComponent} Component instance rendered in `container`. */ renderSubtreeIntoContainer: function (parentComponent, nextElement, container, callback) { !(parentComponent != null && ReactInstanceMap.has(parentComponent)) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'parentComponent must be a valid React Component') : _prodInvariant('38') : void 0; return ReactMount._renderSubtreeIntoContainer(parentComponent, nextElement, container, callback); }, _renderSubtreeIntoContainer: function (parentComponent, nextElement, container, callback) { ReactUpdateQueue.validateCallback(callback, 'ReactDOM.render'); !React.isValidElement(nextElement) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactDOM.render(): Invalid component element.%s', typeof nextElement === 'string' ? ' Instead of passing a string like \'div\', pass ' + 'React.createElement(\'div\') or <div />.' : typeof nextElement === 'function' ? ' Instead of passing a class like Foo, pass ' + 'React.createElement(Foo) or <Foo />.' : // Check if it quacks like an element nextElement != null && nextElement.props !== undefined ? ' This may be caused by unintentionally loading two independent ' + 'copies of React.' : '') : _prodInvariant('39', typeof nextElement === 'string' ? ' Instead of passing a string like \'div\', pass ' + 'React.createElement(\'div\') or <div />.' : typeof nextElement === 'function' ? ' Instead of passing a class like Foo, pass ' + 'React.createElement(Foo) or <Foo />.' : nextElement != null && nextElement.props !== undefined ? ' This may be caused by unintentionally loading two independent ' + 'copies of React.' : '') : void 0; process.env.NODE_ENV !== 'production' ? warning(!container || !container.tagName || container.tagName.toUpperCase() !== 'BODY', '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.') : void 0; var nextWrappedElement = React.createElement(TopLevelWrapper, { child: nextElement }); var nextContext; if (parentComponent) { var parentInst = ReactInstanceMap.get(parentComponent); nextContext = parentInst._processChildContext(parentInst._context); } else { nextContext = emptyObject; } var prevComponent = getTopLevelWrapperInContainer(container); if (prevComponent) { var prevWrappedElement = prevComponent._currentElement; var prevElement = prevWrappedElement.props.child; if (shouldUpdateReactComponent(prevElement, nextElement)) { var publicInst = prevComponent._renderedComponent.getPublicInstance(); var updatedCallback = callback && function () { callback.call(publicInst); }; ReactMount._updateRootComponent(prevComponent, nextWrappedElement, nextContext, container, updatedCallback); return publicInst; } else { ReactMount.unmountComponentAtNode(container); } } var reactRootElement = getReactRootElementInContainer(container); var containerHasReactMarkup = reactRootElement && !!internalGetID(reactRootElement); var containerHasNonRootReactChild = hasNonRootReactChild(container); if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(!containerHasNonRootReactChild, '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.') : void 0; if (!containerHasReactMarkup || reactRootElement.nextSibling) { var rootElementSibling = reactRootElement; while (rootElementSibling) { if (internalGetID(rootElementSibling)) { process.env.NODE_ENV !== 'production' ? warning(false, '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.') : void 0; break; } rootElementSibling = rootElementSibling.nextSibling; } } } var shouldReuseMarkup = containerHasReactMarkup && !prevComponent && !containerHasNonRootReactChild; var component = ReactMount._renderNewRootComponent(nextWrappedElement, container, shouldReuseMarkup, nextContext)._renderedComponent.getPublicInstance(); if (callback) { callback.call(component); } return component; }, /** * Renders a React component into the DOM in the supplied `container`. * See https://facebook.github.io/react/docs/top-level-api.html#reactdom.render * * If the React component was previously rendered into `container`, this will * perform an update on it and only mutate the DOM as necessary to reflect the * latest React component. * * @param {ReactElement} nextElement Component element to render. * @param {DOMElement} container DOM element to render into. * @param {?function} callback function triggered on completion * @return {ReactComponent} Component instance rendered in `container`. */ render: function (nextElement, container, callback) { return ReactMount._renderSubtreeIntoContainer(null, nextElement, container, callback); }, /** * Unmounts and destroys the React component rendered in the `container`. * See https://facebook.github.io/react/docs/top-level-api.html#reactdom.unmountcomponentatnode * * @param {DOMElement} container DOM element containing a React component. * @return {boolean} True if a component was found in and unmounted from * `container` */ unmountComponentAtNode: function (container) { // Various parts of our code (such as ReactCompositeComponent's // _renderValidatedComponent) assume that calls to render aren't nested; // verify that that's the case. (Strictly speaking, unmounting won't cause a // render but we still don't expect to be in a render call here.) process.env.NODE_ENV !== 'production' ? warning(ReactCurrentOwner.current == null, 'unmountComponentAtNode(): 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. Check the render method of %s.', ReactCurrentOwner.current && ReactCurrentOwner.current.getName() || 'ReactCompositeComponent') : void 0; !isValidContainer(container) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'unmountComponentAtNode(...): Target container is not a DOM element.') : _prodInvariant('40') : void 0; if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(!nodeIsRenderedByOtherInstance(container), 'unmountComponentAtNode(): The node you\'re attempting to unmount ' + 'was rendered by another copy of React.') : void 0; } var prevComponent = getTopLevelWrapperInContainer(container); if (!prevComponent) { // Check if the node being unmounted was rendered by React, but isn't a // root node. var containerHasNonRootReactChild = hasNonRootReactChild(container); // Check if the container itself is a React root node. var isContainerReactRoot = container.nodeType === 1 && container.hasAttribute(ROOT_ATTR_NAME); if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(!containerHasNonRootReactChild, '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.') : void 0; } return false; } delete instancesByReactRootID[prevComponent._instance.rootID]; ReactUpdates.batchedUpdates(unmountComponentFromNode, prevComponent, container, false); return true; }, _mountImageIntoNode: function (markup, container, instance, shouldReuseMarkup, transaction) { !isValidContainer(container) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'mountComponentIntoNode(...): Target container is not valid.') : _prodInvariant('41') : void 0; if (shouldReuseMarkup) { var rootElement = getReactRootElementInContainer(container); if (ReactMarkupChecksum.canReuseMarkup(markup, rootElement)) { ReactDOMComponentTree.precacheNode(instance, rootElement); return; } else { var checksum = rootElement.getAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME); rootElement.removeAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME); var rootMarkup = rootElement.outerHTML; rootElement.setAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME, checksum); var normalizedMarkup = markup; if (process.env.NODE_ENV !== 'production') { // because rootMarkup is retrieved from the DOM, various normalizations // will have occurred which will not be present in `markup`. Here, // insert markup into a <div> or <iframe> depending on the container // type to perform the same normalizations before comparing. var normalizer; if (container.nodeType === ELEMENT_NODE_TYPE) { normalizer = document.createElement('div'); normalizer.innerHTML = markup; normalizedMarkup = normalizer.innerHTML; } else { normalizer = document.createElement('iframe'); document.body.appendChild(normalizer); normalizer.contentDocument.write(markup); normalizedMarkup = normalizer.contentDocument.documentElement.outerHTML; document.body.removeChild(normalizer); } } var diffIndex = firstDifferenceIndex(normalizedMarkup, rootMarkup); var difference = ' (client) ' + normalizedMarkup.substring(diffIndex - 20, diffIndex + 20) + '\n (server) ' + rootMarkup.substring(diffIndex - 20, diffIndex + 20); !(container.nodeType !== DOC_NODE_TYPE) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'You\'re trying to render a component to the document using server rendering but the checksum was invalid. This usually means you rendered a different component type or props on the client from the one on the server, or your render() methods are impure. React cannot handle this case due to cross-browser quirks by rendering at the document root. You should look for environment dependent code in your components and ensure the props are the same client and server side:\n%s', difference) : _prodInvariant('42', difference) : void 0; if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(false, 'React attempted to reuse markup in a container but the ' + 'checksum was invalid. This generally means that you are ' + 'using server rendering and the markup generated on the ' + 'server was not what the client was expecting. React injected ' + 'new markup to compensate which works but you have lost many ' + 'of the benefits of server rendering. Instead, figure out ' + 'why the markup being generated is different on the client ' + 'or server:\n%s', difference) : void 0; } } } !(container.nodeType !== DOC_NODE_TYPE) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'You\'re trying to render a component to the document but you didn\'t use server rendering. We can\'t do this without using server rendering due to cross-browser quirks. See ReactDOMServer.renderToString() for server rendering.') : _prodInvariant('43') : void 0; if (transaction.useCreateElement) { while (container.lastChild) { container.removeChild(container.lastChild); } DOMLazyTree.insertTreeBefore(container, markup, null); } else { setInnerHTML(container, markup); ReactDOMComponentTree.precacheNode(instance, container.firstChild); } if (process.env.NODE_ENV !== 'production') { var hostNode = ReactDOMComponentTree.getInstanceFromNode(container.firstChild); if (hostNode._debugID !== 0) { ReactInstrumentation.debugTool.onHostOperation({ instanceID: hostNode._debugID, type: 'mount', payload: markup.toString() }); } } } }; module.exports = ReactMount; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 171 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var validateDOMNesting = __webpack_require__(140); var DOC_NODE_TYPE = 9; function ReactDOMContainerInfo(topLevelWrapper, node) { var info = { _topLevelWrapper: topLevelWrapper, _idCounter: 1, _ownerDocument: node ? node.nodeType === DOC_NODE_TYPE ? node : node.ownerDocument : null, _node: node, _tag: node ? node.nodeName.toLowerCase() : null, _namespaceURI: node ? node.namespaceURI : null }; if (process.env.NODE_ENV !== 'production') { info._ancestorInfo = node ? validateDOMNesting.updatedAncestorInfo(null, info._tag, null) : null; } return info; } module.exports = ReactDOMContainerInfo; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 172 */ /***/ (function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var ReactDOMFeatureFlags = { useCreateElement: true, useFiber: false }; module.exports = ReactDOMFeatureFlags; /***/ }), /* 173 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var adler32 = __webpack_require__(174); var TAG_END = /\/?>/; var COMMENT_START = /^<\!\-\-/; var ReactMarkupChecksum = { CHECKSUM_ATTR_NAME: 'data-react-checksum', /** * @param {string} markup Markup string * @return {string} Markup string with checksum attribute attached */ addChecksumToMarkup: function (markup) { var checksum = adler32(markup); // Add checksum (handle both parent tags, comments and self-closing tags) if (COMMENT_START.test(markup)) { return markup; } else { return markup.replace(TAG_END, ' ' + ReactMarkupChecksum.CHECKSUM_ATTR_NAME + '="' + checksum + '"$&'); } }, /** * @param {string} markup to use * @param {DOMElement} element root React element * @returns {boolean} whether or not the markup is the same */ canReuseMarkup: function (markup, element) { var existingChecksum = element.getAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME); existingChecksum = existingChecksum && parseInt(existingChecksum, 10); var markupChecksum = adler32(markup); return markupChecksum === existingChecksum; } }; module.exports = ReactMarkupChecksum; /***/ }), /* 174 */ /***/ (function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var MOD = 65521; // adler32 is not cryptographically strong, and is only used to sanity check that // markup generated on the server matches the markup generated on the client. // This implementation (a modified version of the SheetJS version) has been optimized // for our use case, at the expense of conforming to the adler32 specification // for non-ascii inputs. function adler32(data) { var a = 1; var b = 0; var i = 0; var l = data.length; var m = l & ~0x3; while (i < m) { var n = Math.min(i + 4096, m); for (; i < n; i += 4) { b += (a += data.charCodeAt(i)) + (a += data.charCodeAt(i + 1)) + (a += data.charCodeAt(i + 2)) + (a += data.charCodeAt(i + 3)); } a %= MOD; b %= MOD; } for (; i < l; i++) { b += a += data.charCodeAt(i); } a %= MOD; b %= MOD; return a | b << 16; } module.exports = adler32; /***/ }), /* 175 */ /***/ (function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; module.exports = '15.5.4'; /***/ }), /* 176 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(39); var ReactCurrentOwner = __webpack_require__(10); var ReactDOMComponentTree = __webpack_require__(38); var ReactInstanceMap = __webpack_require__(120); var getHostComponentFromComposite = __webpack_require__(177); var invariant = __webpack_require__(8); var warning = __webpack_require__(11); /** * Returns the DOM node rendered by this element. * * See https://facebook.github.io/react/docs/top-level-api.html#reactdom.finddomnode * * @param {ReactComponent|DOMElement} componentOrElement * @return {?DOMElement} The root node of this element. */ function findDOMNode(componentOrElement) { if (process.env.NODE_ENV !== 'production') { var owner = ReactCurrentOwner.current; if (owner !== null) { process.env.NODE_ENV !== 'production' ? warning(owner._warnedAboutRefsInRender, '%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.', owner.getName() || 'A component') : void 0; owner._warnedAboutRefsInRender = true; } } if (componentOrElement == null) { return null; } if (componentOrElement.nodeType === 1) { return componentOrElement; } var inst = ReactInstanceMap.get(componentOrElement); if (inst) { inst = getHostComponentFromComposite(inst); return inst ? ReactDOMComponentTree.getNodeFromInstance(inst) : null; } if (typeof componentOrElement.render === 'function') { true ? process.env.NODE_ENV !== 'production' ? invariant(false, 'findDOMNode was called on an unmounted component.') : _prodInvariant('44') : void 0; } else { true ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Element appears to be neither ReactComponent nor DOMNode (keys: %s)', Object.keys(componentOrElement)) : _prodInvariant('45', Object.keys(componentOrElement)) : void 0; } } module.exports = findDOMNode; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 177 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var ReactNodeTypes = __webpack_require__(124); function getHostComponentFromComposite(inst) { var type; while ((type = inst._renderedNodeType) === ReactNodeTypes.COMPOSITE) { inst = inst._renderedComponent; } if (type === ReactNodeTypes.HOST) { return inst._renderedComponent; } else if (type === ReactNodeTypes.EMPTY) { return null; } } module.exports = getHostComponentFromComposite; /***/ }), /* 178 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var ReactMount = __webpack_require__(170); module.exports = ReactMount.renderSubtreeIntoContainer; /***/ }), /* 179 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var DOMProperty = __webpack_require__(40); var EventPluginRegistry = __webpack_require__(47); var ReactComponentTreeHook = __webpack_require__(26); var warning = __webpack_require__(11); if (process.env.NODE_ENV !== 'production') { var reactProps = { children: true, dangerouslySetInnerHTML: true, key: true, ref: true, autoFocus: true, defaultValue: true, valueLink: true, defaultChecked: true, checkedLink: true, innerHTML: true, suppressContentEditableWarning: true, onFocusIn: true, onFocusOut: true }; var warnedProperties = {}; var validateProperty = function (tagName, name, debugID) { if (DOMProperty.properties.hasOwnProperty(name) || DOMProperty.isCustomAttribute(name)) { return true; } if (reactProps.hasOwnProperty(name) && reactProps[name] || warnedProperties.hasOwnProperty(name) && warnedProperties[name]) { return true; } if (EventPluginRegistry.registrationNameModules.hasOwnProperty(name)) { return true; } warnedProperties[name] = true; var lowerCasedName = name.toLowerCase(); // data-* attributes should be lowercase; suggest the lowercase version var standardName = DOMProperty.isCustomAttribute(lowerCasedName) ? lowerCasedName : DOMProperty.getPossibleStandardName.hasOwnProperty(lowerCasedName) ? DOMProperty.getPossibleStandardName[lowerCasedName] : null; var registrationName = EventPluginRegistry.possibleRegistrationNames.hasOwnProperty(lowerCasedName) ? EventPluginRegistry.possibleRegistrationNames[lowerCasedName] : null; if (standardName != null) { process.env.NODE_ENV !== 'production' ? warning(false, 'Unknown DOM property %s. Did you mean %s?%s', name, standardName, ReactComponentTreeHook.getStackAddendumByID(debugID)) : void 0; return true; } else if (registrationName != null) { process.env.NODE_ENV !== 'production' ? warning(false, 'Unknown event handler property %s. Did you mean `%s`?%s', name, registrationName, ReactComponentTreeHook.getStackAddendumByID(debugID)) : void 0; return true; } else { // We were unable to guess which prop the user intended. // It is likely that the user was just blindly spreading/forwarding props // Components should be careful to only render valid props/attributes. // Warning will be invoked in warnUnknownProperties to allow grouping. return false; } }; } var warnUnknownProperties = function (debugID, element) { var unknownProps = []; for (var key in element.props) { var isValid = validateProperty(element.type, key, debugID); if (!isValid) { unknownProps.push(key); } } var unknownPropString = unknownProps.map(function (prop) { return '`' + prop + '`'; }).join(', '); if (unknownProps.length === 1) { process.env.NODE_ENV !== 'production' ? warning(false, 'Unknown prop %s on <%s> tag. Remove this prop from the element. ' + 'For details, see https://fb.me/react-unknown-prop%s', unknownPropString, element.type, ReactComponentTreeHook.getStackAddendumByID(debugID)) : void 0; } else if (unknownProps.length > 1) { process.env.NODE_ENV !== 'production' ? warning(false, 'Unknown props %s on <%s> tag. Remove these props from the element. ' + 'For details, see https://fb.me/react-unknown-prop%s', unknownPropString, element.type, ReactComponentTreeHook.getStackAddendumByID(debugID)) : void 0; } }; function handleElement(debugID, element) { if (element == null || typeof element.type !== 'string') { return; } if (element.type.indexOf('-') >= 0 || element.props.is) { return; } warnUnknownProperties(debugID, element); } var ReactDOMUnknownPropertyHook = { onBeforeMountComponent: function (debugID, element) { handleElement(debugID, element); }, onBeforeUpdateComponent: function (debugID, element) { handleElement(debugID, element); } }; module.exports = ReactDOMUnknownPropertyHook; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 180 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var ReactComponentTreeHook = __webpack_require__(26); var warning = __webpack_require__(11); var didWarnValueNull = false; function handleElement(debugID, element) { if (element == null) { return; } if (element.type !== 'input' && element.type !== 'textarea' && element.type !== 'select') { return; } if (element.props != null && element.props.value === null && !didWarnValueNull) { process.env.NODE_ENV !== 'production' ? warning(false, '`value` prop on `%s` should not be null. ' + 'Consider using the empty string to clear the component or `undefined` ' + 'for uncontrolled components.%s', element.type, ReactComponentTreeHook.getStackAddendumByID(debugID)) : void 0; didWarnValueNull = true; } } var ReactDOMNullInputValuePropHook = { onBeforeMountComponent: function (debugID, element) { handleElement(debugID, element); }, onBeforeUpdateComponent: function (debugID, element) { handleElement(debugID, element); } }; module.exports = ReactDOMNullInputValuePropHook; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 181 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var DOMProperty = __webpack_require__(40); var ReactComponentTreeHook = __webpack_require__(26); var warning = __webpack_require__(11); var warnedProperties = {}; var rARIA = new RegExp('^(aria)-[' + DOMProperty.ATTRIBUTE_NAME_CHAR + ']*$'); function validateProperty(tagName, name, debugID) { if (warnedProperties.hasOwnProperty(name) && warnedProperties[name]) { return true; } if (rARIA.test(name)) { var lowerCasedName = name.toLowerCase(); var standardName = DOMProperty.getPossibleStandardName.hasOwnProperty(lowerCasedName) ? DOMProperty.getPossibleStandardName[lowerCasedName] : null; // If this is an aria-* attribute, but is not listed in the known DOM // DOM properties, then it is an invalid aria-* attribute. if (standardName == null) { warnedProperties[name] = true; return false; } // aria-* attributes should be lowercase; suggest the lowercase version. if (name !== standardName) { process.env.NODE_ENV !== 'production' ? warning(false, 'Unknown ARIA attribute %s. Did you mean %s?%s', name, standardName, ReactComponentTreeHook.getStackAddendumByID(debugID)) : void 0; warnedProperties[name] = true; return true; } } return true; } function warnInvalidARIAProps(debugID, element) { var invalidProps = []; for (var key in element.props) { var isValid = validateProperty(element.type, key, debugID); if (!isValid) { invalidProps.push(key); } } var unknownPropString = invalidProps.map(function (prop) { return '`' + prop + '`'; }).join(', '); if (invalidProps.length === 1) { process.env.NODE_ENV !== 'production' ? warning(false, 'Invalid aria prop %s on <%s> tag. ' + 'For details, see https://fb.me/invalid-aria-prop%s', unknownPropString, element.type, ReactComponentTreeHook.getStackAddendumByID(debugID)) : void 0; } else if (invalidProps.length > 1) { process.env.NODE_ENV !== 'production' ? warning(false, 'Invalid aria props %s on <%s> tag. ' + 'For details, see https://fb.me/invalid-aria-prop%s', unknownPropString, element.type, ReactComponentTreeHook.getStackAddendumByID(debugID)) : void 0; } } function handleElement(debugID, element) { if (element == null || typeof element.type !== 'string') { return; } if (element.type.indexOf('-') >= 0 || element.props.is) { return; } warnInvalidARIAProps(debugID, element); } var ReactDOMInvalidARIAHook = { onBeforeMountComponent: function (debugID, element) { if (process.env.NODE_ENV !== 'production') { handleElement(debugID, element); } }, onBeforeUpdateComponent: function (debugID, element) { if (process.env.NODE_ENV !== 'production') { handleElement(debugID, element); } } }; module.exports = ReactDOMInvalidARIAHook; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 182 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _shield = __webpack_require__(183); var _shield2 = _interopRequireDefault(_shield); var _react = __webpack_require__(1); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var Member = function (_Component) { _inherits(Member, _Component); function Member() { _classCallCheck(this, Member); return _possibleConstructorReturn(this, (Member.__proto__ || Object.getPrototypeOf(Member)).apply(this, arguments)); } _createClass(Member, [{ key: 'render', value: function render() { var _props = this.props, name = _props.name, thumbnail = _props.thumbnail, email = _props.email, admin = _props.admin, makeAdmin = _props.makeAdmin; return React.createElement( 'div', { className: 'member' }, React.createElement( 'h1', null, name, ' ', admin ? React.createElement(_shield2.default, null) : null ), React.createElement( 'a', { onClick: makeAdmin }, 'Make admin ' ), React.createElement('img', { src: thumbnail, alt: 'profile picture' }), React.createElement( 'p', null, React.createElement( 'a', { href: 'mailto:' + rmail }, email ) ) ); } }]); return Member; }(_react.Component); exports.default = Member; /***/ }), /* 183 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _reactIconBase = __webpack_require__(184); var _reactIconBase2 = _interopRequireDefault(_reactIconBase); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var FaShield = function FaShield(props) { return _react2.default.createElement( _reactIconBase2.default, _extends({ viewBox: '0 0 40 40' }, props), _react2.default.createElement( 'g', null, _react2.default.createElement('path', { d: 'm29.8 21.4v-14.3h-10v25.4q2.6-1.4 4.7-3 5.3-4.1 5.3-8.1z m4.3-17.1v17.1q0 2-0.8 3.8t-1.8 3.4-2.7 2.8-2.8 2.3-2.7 1.8-2 1.1-0.9 0.4q-0.3 0.1-0.6 0.1t-0.6-0.1q-0.4-0.2-0.9-0.4t-2-1.1-2.7-1.8-2.9-2.3-2.6-2.8-1.9-3.4-0.7-3.8v-17.1q0-0.6 0.4-1t1-0.4h25.7q0.6 0 1 0.4t0.5 1z' }) ) ); }; exports.default = FaShield; module.exports = exports['default']; /***/ }), /* 184 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(185); var _propTypes2 = _interopRequireDefault(_propTypes); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } var IconBase = function IconBase(_ref, _ref2) { var children = _ref.children; var color = _ref.color; var size = _ref.size; var style = _ref.style; var props = _objectWithoutProperties(_ref, ['children', 'color', 'size', 'style']); var _ref2$reactIconBase = _ref2.reactIconBase; var reactIconBase = _ref2$reactIconBase === undefined ? {} : _ref2$reactIconBase; var computedSize = size || reactIconBase.size || '1em'; return _react2.default.createElement('svg', _extends({ children: children, fill: 'currentColor', preserveAspectRatio: 'xMidYMid meet', height: computedSize, width: computedSize }, reactIconBase, props, { style: _extends({ verticalAlign: 'middle', color: color || reactIconBase.color }, reactIconBase.style || {}, style) })); }; IconBase.propTypes = { color: _propTypes2.default.string, size: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.number]), style: _propTypes2.default.object }; IconBase.contextTypes = { reactIconBase: _propTypes2.default.shape(IconBase.propTypes) }; exports.default = IconBase; module.exports = exports['default']; /***/ }), /* 185 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ if (process.env.NODE_ENV !== 'production') { var REACT_ELEMENT_TYPE = (typeof Symbol === 'function' && Symbol.for && Symbol.for('react.element')) || 0xeac7; var isValidElement = function(object) { return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; }; // By explicitly using `prop-types` you are opting into new development behavior. // http://fb.me/prop-types-in-prod var throwOnDirectAccess = true; module.exports = __webpack_require__(186)(isValidElement, throwOnDirectAccess); } else { // By explicitly using `prop-types` you are opting into new production behavior. // http://fb.me/prop-types-in-prod module.exports = __webpack_require__(189)(); } /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 186 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ 'use strict'; var emptyFunction = __webpack_require__(12); var invariant = __webpack_require__(8); var warning = __webpack_require__(11); var ReactPropTypesSecret = __webpack_require__(187); var checkPropTypes = __webpack_require__(188); module.exports = function(isValidElement, throwOnDirectAccess) { /* global Symbol */ var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator; var FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec. /** * Returns the iterator method function contained on the iterable object. * * Be sure to invoke the function with the iterable as context: * * var iteratorFn = getIteratorFn(myIterable); * if (iteratorFn) { * var iterator = iteratorFn.call(myIterable); * ... * } * * @param {?object} maybeIterable * @return {?function} */ function getIteratorFn(maybeIterable) { var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]); if (typeof iteratorFn === 'function') { return iteratorFn; } } /** * Collection of methods that allow declaration and validation of props that are * supplied to React components. Example usage: * * var Props = require('ReactPropTypes'); * var MyArticle = React.createClass({ * propTypes: { * // An optional string prop named "description". * description: Props.string, * * // A required enum prop named "category". * category: Props.oneOf(['News','Photos']).isRequired, * * // A prop named "dialog" that requires an instance of Dialog. * dialog: Props.instanceOf(Dialog).isRequired * }, * render: function() { ... } * }); * * A more formal specification of how these methods are used: * * type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...) * decl := ReactPropTypes.{type}(.isRequired)? * * Each and every declaration produces a function with the same signature. This * allows the creation of custom validation functions. For example: * * var MyLink = React.createClass({ * propTypes: { * // An optional string or URI prop named "href". * href: function(props, propName, componentName) { * var propValue = props[propName]; * if (propValue != null && typeof propValue !== 'string' && * !(propValue instanceof URI)) { * return new Error( * 'Expected a string or an URI for ' + propName + ' in ' + * componentName * ); * } * } * }, * render: function() {...} * }); * * @internal */ var ANONYMOUS = '<<anonymous>>'; // Important! // Keep this list in sync with production version in `./factoryWithThrowingShims.js`. var ReactPropTypes = { array: createPrimitiveTypeChecker('array'), bool: createPrimitiveTypeChecker('boolean'), func: createPrimitiveTypeChecker('function'), number: createPrimitiveTypeChecker('number'), object: createPrimitiveTypeChecker('object'), string: createPrimitiveTypeChecker('string'), symbol: createPrimitiveTypeChecker('symbol'), any: createAnyTypeChecker(), arrayOf: createArrayOfTypeChecker, element: createElementTypeChecker(), instanceOf: createInstanceTypeChecker, node: createNodeChecker(), objectOf: createObjectOfTypeChecker, oneOf: createEnumTypeChecker, oneOfType: createUnionTypeChecker, shape: createShapeTypeChecker }; /** * inlined Object.is polyfill to avoid requiring consumers ship their own * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is */ /*eslint-disable no-self-compare*/ function is(x, y) { // SameValue algorithm if (x === y) { // Steps 1-5, 7-10 // Steps 6.b-6.e: +0 != -0 return x !== 0 || 1 / x === 1 / y; } else { // Step 6.a: NaN == NaN return x !== x && y !== y; } } /*eslint-enable no-self-compare*/ /** * We use an Error-like object for backward compatibility as people may call * PropTypes directly and inspect their output. However, we don't use real * Errors anymore. We don't inspect their stack anyway, and creating them * is prohibitively expensive if they are created too often, such as what * happens in oneOfType() for any type before the one that matched. */ function PropTypeError(message) { this.message = message; this.stack = ''; } // Make `instanceof Error` still work for returned errors. PropTypeError.prototype = Error.prototype; function createChainableTypeChecker(validate) { if (process.env.NODE_ENV !== 'production') { var manualPropTypeCallCache = {}; var manualPropTypeWarningCount = 0; } function checkType(isRequired, props, propName, componentName, location, propFullName, secret) { componentName = componentName || ANONYMOUS; propFullName = propFullName || propName; if (secret !== ReactPropTypesSecret) { if (throwOnDirectAccess) { // New behavior only for users of `prop-types` package invariant( false, 'Calling PropTypes validators directly is not supported by the `prop-types` package. ' + 'Use `PropTypes.checkPropTypes()` to call them. ' + 'Read more at http://fb.me/use-check-prop-types' ); } else if (process.env.NODE_ENV !== 'production' && typeof console !== 'undefined') { // Old behavior for people using React.PropTypes var cacheKey = componentName + ':' + propName; if ( !manualPropTypeCallCache[cacheKey] && // Avoid spamming the console because they are often not actionable except for lib authors manualPropTypeWarningCount < 3 ) { warning( false, 'You are manually calling a React.PropTypes validation ' + 'function for the `%s` prop on `%s`. This is deprecated ' + 'and will throw in the standalone `prop-types` package. ' + 'You may be seeing this warning due to a third-party PropTypes ' + 'library. See https://fb.me/react-warning-dont-call-proptypes ' + 'for details.', propFullName, componentName ); manualPropTypeCallCache[cacheKey] = true; manualPropTypeWarningCount++; } } } if (props[propName] == null) { if (isRequired) { if (props[propName] === null) { return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required ' + ('in `' + componentName + '`, but its value is `null`.')); } return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required in ' + ('`' + componentName + '`, but its value is `undefined`.')); } return null; } else { return validate(props, propName, componentName, location, propFullName); } } var chainedCheckType = checkType.bind(null, false); chainedCheckType.isRequired = checkType.bind(null, true); return chainedCheckType; } function createPrimitiveTypeChecker(expectedType) { function validate(props, propName, componentName, location, propFullName, secret) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== expectedType) { // `propValue` being instance of, say, date/regexp, pass the 'object' // check, but we can offer a more precise error message here rather than // 'of type `object`'. var preciseType = getPreciseType(propValue); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + preciseType + '` supplied to `' + componentName + '`, expected ') + ('`' + expectedType + '`.')); } return null; } return createChainableTypeChecker(validate); } function createAnyTypeChecker() { return createChainableTypeChecker(emptyFunction.thatReturnsNull); } function createArrayOfTypeChecker(typeChecker) { function validate(props, propName, componentName, location, propFullName) { if (typeof typeChecker !== 'function') { return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside arrayOf.'); } var propValue = props[propName]; if (!Array.isArray(propValue)) { var propType = getPropType(propValue); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an array.')); } for (var i = 0; i < propValue.length; i++) { var error = typeChecker(propValue, i, componentName, location, propFullName + '[' + i + ']', ReactPropTypesSecret); if (error instanceof Error) { return error; } } return null; } return createChainableTypeChecker(validate); } function createElementTypeChecker() { function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; if (!isValidElement(propValue)) { var propType = getPropType(propValue); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected a single ReactElement.')); } return null; } return createChainableTypeChecker(validate); } function createInstanceTypeChecker(expectedClass) { function validate(props, propName, componentName, location, propFullName) { if (!(props[propName] instanceof expectedClass)) { var expectedClassName = expectedClass.name || ANONYMOUS; var actualClassName = getClassName(props[propName]); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + actualClassName + '` supplied to `' + componentName + '`, expected ') + ('instance of `' + expectedClassName + '`.')); } return null; } return createChainableTypeChecker(validate); } function createEnumTypeChecker(expectedValues) { if (!Array.isArray(expectedValues)) { process.env.NODE_ENV !== 'production' ? warning(false, 'Invalid argument supplied to oneOf, expected an instance of array.') : void 0; return emptyFunction.thatReturnsNull; } function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; for (var i = 0; i < expectedValues.length; i++) { if (is(propValue, expectedValues[i])) { return null; } } var valuesString = JSON.stringify(expectedValues); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of value `' + propValue + '` ' + ('supplied to `' + componentName + '`, expected one of ' + valuesString + '.')); } return createChainableTypeChecker(validate); } function createObjectOfTypeChecker(typeChecker) { function validate(props, propName, componentName, location, propFullName) { if (typeof typeChecker !== 'function') { return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside objectOf.'); } var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== 'object') { return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an object.')); } for (var key in propValue) { if (propValue.hasOwnProperty(key)) { var error = typeChecker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret); if (error instanceof Error) { return error; } } } return null; } return createChainableTypeChecker(validate); } function createUnionTypeChecker(arrayOfTypeCheckers) { if (!Array.isArray(arrayOfTypeCheckers)) { process.env.NODE_ENV !== 'production' ? warning(false, 'Invalid argument supplied to oneOfType, expected an instance of array.') : void 0; return emptyFunction.thatReturnsNull; } function validate(props, propName, componentName, location, propFullName) { for (var i = 0; i < arrayOfTypeCheckers.length; i++) { var checker = arrayOfTypeCheckers[i]; if (checker(props, propName, componentName, location, propFullName, ReactPropTypesSecret) == null) { return null; } } return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`.')); } return createChainableTypeChecker(validate); } function createNodeChecker() { function validate(props, propName, componentName, location, propFullName) { if (!isNode(props[propName])) { return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`, expected a ReactNode.')); } return null; } return createChainableTypeChecker(validate); } function createShapeTypeChecker(shapeTypes) { function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== 'object') { return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.')); } for (var key in shapeTypes) { var checker = shapeTypes[key]; if (!checker) { continue; } var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret); if (error) { return error; } } return null; } return createChainableTypeChecker(validate); } function isNode(propValue) { switch (typeof propValue) { case 'number': case 'string': case 'undefined': return true; case 'boolean': return !propValue; case 'object': if (Array.isArray(propValue)) { return propValue.every(isNode); } if (propValue === null || isValidElement(propValue)) { return true; } var iteratorFn = getIteratorFn(propValue); if (iteratorFn) { var iterator = iteratorFn.call(propValue); var step; if (iteratorFn !== propValue.entries) { while (!(step = iterator.next()).done) { if (!isNode(step.value)) { return false; } } } else { // Iterator will provide entry [k,v] tuples rather than values. while (!(step = iterator.next()).done) { var entry = step.value; if (entry) { if (!isNode(entry[1])) { return false; } } } } } else { return false; } return true; default: return false; } } function isSymbol(propType, propValue) { // Native Symbol. if (propType === 'symbol') { return true; } // 19.4.3.5 Symbol.prototype[@@toStringTag] === 'Symbol' if (propValue['@@toStringTag'] === 'Symbol') { return true; } // Fallback for non-spec compliant Symbols which are polyfilled. if (typeof Symbol === 'function' && propValue instanceof Symbol) { return true; } return false; } // Equivalent of `typeof` but with special handling for array and regexp. function getPropType(propValue) { var propType = typeof propValue; if (Array.isArray(propValue)) { return 'array'; } if (propValue instanceof RegExp) { // Old webkits (at least until Android 4.0) return 'function' rather than // 'object' for typeof a RegExp. We'll normalize this here so that /bla/ // passes PropTypes.object. return 'object'; } if (isSymbol(propType, propValue)) { return 'symbol'; } return propType; } // This handles more types than `getPropType`. Only used for error messages. // See `createPrimitiveTypeChecker`. function getPreciseType(propValue) { var propType = getPropType(propValue); if (propType === 'object') { if (propValue instanceof Date) { return 'date'; } else if (propValue instanceof RegExp) { return 'regexp'; } } return propType; } // Returns class name of the object, if any. function getClassName(propValue) { if (!propValue.constructor || !propValue.constructor.name) { return ANONYMOUS; } return propValue.constructor.name; } ReactPropTypes.checkPropTypes = checkPropTypes; ReactPropTypes.PropTypes = ReactPropTypes; return ReactPropTypes; }; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 187 */ /***/ (function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ 'use strict'; var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'; module.exports = ReactPropTypesSecret; /***/ }), /* 188 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ 'use strict'; if (process.env.NODE_ENV !== 'production') { var invariant = __webpack_require__(8); var warning = __webpack_require__(11); var ReactPropTypesSecret = __webpack_require__(187); var loggedTypeFailures = {}; } /** * Assert that the values match with the type specs. * Error messages are memorized and will only be shown once. * * @param {object} typeSpecs Map of name to a ReactPropType * @param {object} values Runtime values that need to be type-checked * @param {string} location e.g. "prop", "context", "child context" * @param {string} componentName Name of the component for error messages. * @param {?Function} getStack Returns the component stack. * @private */ function checkPropTypes(typeSpecs, values, location, componentName, getStack) { if (process.env.NODE_ENV !== 'production') { for (var typeSpecName in typeSpecs) { if (typeSpecs.hasOwnProperty(typeSpecName)) { var error; // Prop type validation may throw. In case they do, we don't want to // fail the render phase where it didn't fail before. So we log it. // After these have been cleaned up, we'll let them throw. try { // This is intentionally an invariant that gets caught. It's the same // behavior as without this statement except with a better message. invariant(typeof typeSpecs[typeSpecName] === 'function', '%s: %s type `%s` is invalid; it must be a function, usually from ' + 'React.PropTypes.', componentName || 'React class', location, typeSpecName); error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret); } catch (ex) { error = ex; } warning(!error || error instanceof 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); if (error instanceof Error && !(error.message in loggedTypeFailures)) { // Only monitor this failure once because there tends to be a lot of the // same error. loggedTypeFailures[error.message] = true; var stack = getStack ? getStack() : ''; warning(false, 'Failed %s type: %s%s', location, error.message, stack != null ? stack : ''); } } } } } module.exports = checkPropTypes; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }), /* 189 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ 'use strict'; var emptyFunction = __webpack_require__(12); var invariant = __webpack_require__(8); module.exports = function() { // Important! // Keep this list in sync with production version in `./factoryWithTypeCheckers.js`. function shim() { invariant( false, 'Calling PropTypes validators directly is not supported by the `prop-types` package. ' + 'Use PropTypes.checkPropTypes() to call them. ' + 'Read more at http://fb.me/use-check-prop-types' ); }; shim.isRequired = shim; function getShim() { return shim; }; var ReactPropTypes = { array: shim, bool: shim, func: shim, number: shim, object: shim, string: shim, symbol: shim, any: shim, arrayOf: getShim, element: shim, instanceOf: getShim, node: shim, objectOf: getShim, oneOf: getShim, oneOfType: getShim, shape: getShim }; ReactPropTypes.checkPropTypes = emptyFunction; ReactPropTypes.PropTypes = ReactPropTypes; return ReactPropTypes; }; /***/ }) /******/ ]);<|fim▁end|>
'use strict'; var _prodInvariant = __webpack_require__(39);
<|file_name|>service_callback_api_schema.py<|end_file_name|><|fim▁begin|>from app.schema_validation.definitions import https_url, uuid create_service_callback_api_schema = { "$schema": "http://json-schema.org/draft-04/schema#", "description": "POST service callback/inbound api schema", "type": "object", "title": "Create service callback/inbound api", "properties": { "url": https_url, "bearer_token": {"type": "string", "minLength": 10}, "updated_by_id": uuid }, "required": ["url", "bearer_token", "updated_by_id"] } update_service_callback_api_schema = { "$schema": "http://json-schema.org/draft-04/schema#", "description": "POST service callback/inbound api schema", "type": "object", "title": "Create service callback/inbound api", "properties": { "url": https_url, "bearer_token": {"type": "string", "minLength": 10}, "updated_by_id": uuid },<|fim▁hole|><|fim▁end|>
"required": ["updated_by_id"] }
<|file_name|>jy_serv.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env jython import sys #sys.path.append("/usr/share/java/itextpdf-5.4.1.jar") sys.path.append("itextpdf-5.4.1.jar") #sys.path.append("/usr/share/java/itext-2.0.7.jar") #sys.path.append("/usr/share/java/xercesImpl.jar") #sys.path.append("/usr/share/java/xml-apis.jar") from java.io import FileOutputStream from com.itextpdf.text.pdf import PdfReader,PdfStamper,BaseFont #from com.lowagie.text.pdf import PdfReader,PdfStamper,BaseFont #import re<|fim▁hole|>import time #import xmlrpclib from SimpleXMLRPCServer import SimpleXMLRPCServer def pdf_fill(orig_pdf,new_pdf,vals): #print "pdf_fill",orig_pdf,new_pdf,vals t0=time.time() #print orig_pdf rd=PdfReader(orig_pdf) #print new_pdf #print t0 st=PdfStamper(rd,FileOutputStream(new_pdf)) font=BaseFont.createFont("/usr/share/fonts/truetype/thai/Garuda.ttf",BaseFont.IDENTITY_H,BaseFont.EMBEDDED) form=st.getAcroFields() for k,v in vals.items(): try: form.setFieldProperty(k,"textfont",font,None) form.setField(k,v.decode('utf-8')) except Exception,e: raise Exception("Field %s: %s"%(k,str(e))) st.setFormFlattening(True) st.close() t1=time.time() #print "finished in %.2fs"%(t1-t0) return True def pdf_merge(pdf1,pdf2): #print "pdf_merge",orig_pdf,vals t0=time.time() pdf=pdf1 t1=time.time() #print "finished in %.2fs"%(t1-t0) return pdf serv=SimpleXMLRPCServer(("localhost",9999)) serv.register_function(pdf_fill,"pdf_fill") serv.register_function(pdf_merge,"pdf_merge") print "waiting for requests..." serv.serve_forever()<|fim▁end|>
<|file_name|>groupjoin.ts<|end_file_name|><|fim▁begin|>import { IterableX } from '../../iterable/iterablex'; import { groupJoin } from '../../iterable/operators/groupjoin'; /** * @ignore */ export function groupJoinProto<TOuter, TInner, TKey, TResult>( this: IterableX<TOuter>, inner: Iterable<TInner>, outerSelector: (value: TOuter) => TKey, innerSelector: (value: TInner) => TKey, resultSelector: (outer: TOuter, inner: Iterable<TInner>) => TResult ): IterableX<TResult> { return groupJoin(inner, outerSelector, innerSelector, resultSelector)(this); } <|fim▁hole|> groupJoin: typeof groupJoinProto; } }<|fim▁end|>
IterableX.prototype.groupJoin = groupJoinProto; declare module '../../iterable/iterablex' { interface IterableX<T> {
<|file_name|>SortOrderSelectionDialog.java<|end_file_name|><|fim▁begin|>package de.thomas.dreja.ec.musicquiz.gui.dialog; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.DialogFragment; import android.content.DialogInterface; import android.os.Bundle; import de.thomas.dreja.ec.musicquiz.R; import de.thomas.dreja.ec.musicquiz.ctrl.PlaylistResolver.SortOrder; public class SortOrderSelectionDialog extends DialogFragment { private SortOrderSelectionListener listener; @Override public Dialog onCreateDialog(Bundle savedInstanceState) { String[] items = new String[SortOrder.values().length]; for(int i=0; i<items.length; i++) { items[i] = SortOrder.values()[i].getName(getResources()); } AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle(R.string.sort_by) .setItems(items, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { listener.onSortOrderSelected(SortOrder.values()[which]); <|fim▁hole|> }); return builder.create(); } public interface SortOrderSelectionListener { public void onSortOrderSelected(SortOrder order); } @Override public void onAttach(Activity activity) { super.onAttach(activity); // Verify that the host activity implements the callback interface try { // Instantiate the NoticeDialogListener so we can send events to the host listener = (SortOrderSelectionListener) activity; } catch (ClassCastException e) { // The activity doesn't implement the interface, throw exception throw new ClassCastException(activity.toString() + " must implement SortOrderSelectionListener"); } } }<|fim▁end|>
}
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>//------------------------------------------------------------------------------- // URL: //------------------------------------------------------------------------------- <|fim▁hole|> use time; use reader; pub const ID: i32 = 8; pub const DIR: &str = "array/dutchflag"; //------------------------------------------------------------------------------- // O(n) time, O(1) extra space //------------------------------------------------------------------------------- pub fn first(data_path: &Path) -> Box<Fn() -> u64> { // Reading input let mut data = reader::read_all_lines(data_path); let count: usize = reader::first_usize(&mut data); let elements: Vec<i64> = reader::all_i64(&mut data, count); reader::skip_empty_line(&mut data); // Reading desired output let expected: Vec<i64> = reader::all_i64(&mut data, count); Box::new(move || -> u64 { // Setup let mut elements = elements.clone(); // Measure let start = time::precise_time_ns(); first_algorithm(&mut elements); let end = time::precise_time_ns(); // Validate if elements.len() != expected.len() { panic!("Result has different length than expected!"); } else { let mut index = 0; let total = elements.len() - 1; loop { if elements[index] != expected[index] { panic!("Result is different from expected!"); } if index < total { index += 1; } else { break; } } } // Result end - start }) } fn first_algorithm(elements: &mut Vec<i64>) { let mut low = 0; let mut mid = 0; let mut high = elements.len() - 1; while mid <= high { let element = elements[mid]; if element == 0 { elements[mid] = elements[low]; elements[low] = element; low += 1; mid += 1; } else if element == 1 { mid += 1; } else { elements[mid] = elements[high]; elements[high] = element; high -= 1; } } }<|fim▁end|>
use std::path::Path;
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|>
from . import test_stock_location_empty
<|file_name|>SpeedSearch.java<|end_file_name|><|fim▁begin|>/* * Copyright 2000-2017 JetBrains s.r.o.<|fim▁hole|> * 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 com.intellij.ui.speedSearch; import com.intellij.openapi.keymap.KeymapUtil; import com.intellij.openapi.util.TextRange; import com.intellij.psi.codeStyle.AllOccurrencesMatcher; import com.intellij.psi.codeStyle.FixingLayoutMatcher; import com.intellij.psi.codeStyle.MinusculeMatcher; import com.intellij.psi.codeStyle.NameUtil; import com.intellij.util.text.Matcher; import com.intellij.util.ui.UIUtil; import kava.beans.PropertyChangeListener; import kava.beans.PropertyChangeSupport; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; public class SpeedSearch extends SpeedSearchSupply implements KeyListener { public static final String PUNCTUATION_MARKS = "*_-\"'/.#$>: ,;?!@%^&"; private final PropertyChangeSupport myChangeSupport = new PropertyChangeSupport(this); private final boolean myMatchAllOccurrences; private String myString = ""; private boolean myEnabled; private Matcher myMatcher; public SpeedSearch() { this(false); } public SpeedSearch(boolean matchAllOccurrences) { myMatchAllOccurrences = matchAllOccurrences; } public void type(String letter) { updatePattern(myString + letter); } public void backspace() { if (myString.length() > 0) { updatePattern(myString.substring(0, myString.length() - 1)); } } public boolean shouldBeShowing(String string) { return string == null || myString.length() == 0 || (myMatcher != null && myMatcher.matches(string)); } public void processKeyEvent(KeyEvent e) { if (e.isConsumed() || !myEnabled) return; String old = myString; if (e.getID() == KeyEvent.KEY_PRESSED) { if (KeymapUtil.isEventForAction(e, "EditorDeleteToWordStart")) { if (isHoldingFilter()) { while (!myString.isEmpty() && !Character.isWhitespace(myString.charAt(myString.length() - 1))) { backspace(); } e.consume(); } } else if (e.getKeyCode() == KeyEvent.VK_BACK_SPACE) { backspace(); e.consume(); } else if (e.getKeyCode() == KeyEvent.VK_ESCAPE) { if (isHoldingFilter()) { updatePattern(""); e.consume(); } } } else if (e.getID() == KeyEvent.KEY_TYPED) { if (!UIUtil.isReallyTypedEvent(e)) return; // key-char is good only on KEY_TYPED // for example: key-char on ctrl-J PRESSED is \n // see https://en.wikipedia.org/wiki/Control_character char ch = e.getKeyChar(); if (Character.isLetterOrDigit(ch) || !startedWithWhitespace(ch) && PUNCTUATION_MARKS.indexOf(ch) != -1) { type(Character.toString(ch)); e.consume(); } } if (!old.equalsIgnoreCase(myString)) { update(); } } private boolean startedWithWhitespace(char ch) { return !isHoldingFilter() && Character.isWhitespace(ch); } public void update() { } public void noHits() { } public boolean isHoldingFilter() { return myEnabled && myString.length() > 0; } public void setEnabled(boolean enabled) { myEnabled = enabled; } public void reset() { if (isHoldingFilter()) { updatePattern(""); } if (myEnabled) { update(); } } public String getFilter() { return myString; } public void updatePattern(final String string) { String prevString = myString; myString = string; try { String pattern = "*" + string; NameUtil.MatchingCaseSensitivity caseSensitivity = NameUtil.MatchingCaseSensitivity.NONE; String separators = ""; myMatcher = myMatchAllOccurrences ? AllOccurrencesMatcher.create(pattern, caseSensitivity, separators) : new FixingLayoutMatcher(pattern, caseSensitivity, separators); } catch (Exception e) { myMatcher = null; } fireStateChanged(prevString); } @Nullable public Matcher getMatcher() { return myMatcher; } @Nullable @Override public Iterable<TextRange> matchingFragments(@Nonnull String text) { if (myMatcher instanceof MinusculeMatcher) { return ((MinusculeMatcher)myMatcher).matchingFragments(text); } return null; } @Override public void refreshSelection() { } @Override public boolean isPopupActive() { return isHoldingFilter(); } @Nullable @Override public String getEnteredPrefix() { return myString; } @Override public void addChangeListener(@Nonnull PropertyChangeListener listener) { myChangeSupport.addPropertyChangeListener(listener); } @Override public void removeChangeListener(@Nonnull PropertyChangeListener listener) { myChangeSupport.removePropertyChangeListener(listener); } private void fireStateChanged(String prevString) { myChangeSupport.firePropertyChange(SpeedSearchSupply.ENTERED_PREFIX_PROPERTY_NAME, prevString, getEnteredPrefix()); } @Override public void findAndSelectElement(@Nonnull String searchQuery) { } @Override public void keyTyped(KeyEvent e) { processKeyEvent(e); } @Override public void keyPressed(KeyEvent e) { processKeyEvent(e); } @Override public void keyReleased(KeyEvent e) { processKeyEvent(e); } }<|fim▁end|>
* * Licensed under the Apache License, Version 2.0 (the "License");
<|file_name|>filesearch.rs<|end_file_name|><|fim▁begin|>// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![allow(non_camel_case_types)] pub use self::FileMatch::*; use std::cell::RefCell; use std::collections::HashSet; use std::io::fs::PathExtensions; use std::io::fs; use std::os; use util::fs as myfs; pub enum FileMatch { FileMatches, FileDoesntMatch, } impl Copy for FileMatch {} // A module for searching for libraries // FIXME (#2658): I'm not happy how this module turned out. Should // probably just be folded into cstore. /// Functions with type `pick` take a parent directory as well as /// a file found in that directory. pub type pick<'a> = |path: &Path|: 'a -> FileMatch; pub struct FileSearch<'a> { pub sysroot: &'a Path, pub addl_lib_search_paths: &'a RefCell<Vec<Path>>, pub triple: &'a str, } impl<'a> FileSearch<'a> { pub fn for_each_lib_search_path(&self, f: |&Path| -> FileMatch) { let mut visited_dirs = HashSet::new(); let mut found = false; debug!("filesearch: searching additional lib search paths [{}]", self.addl_lib_search_paths.borrow().len()); for path in self.addl_lib_search_paths.borrow().iter() { match f(path) { FileMatches => found = true, FileDoesntMatch => () } visited_dirs.insert(path.as_vec().to_vec()); } debug!("filesearch: searching lib path"); let tlib_path = make_target_lib_path(self.sysroot, self.triple); if !visited_dirs.contains(tlib_path.as_vec()) { match f(&tlib_path) { FileMatches => found = true, FileDoesntMatch => () } } visited_dirs.insert(tlib_path.as_vec().to_vec()); // Try RUST_PATH if !found { let rustpath = rust_path(); for path in rustpath.iter() { let tlib_path = make_rustpkg_lib_path( self.sysroot, path, self.triple); debug!("is {} in visited_dirs? {}", tlib_path.display(), visited_dirs.contains(&tlib_path.as_vec().to_vec())); if !visited_dirs.contains(tlib_path.as_vec()) { visited_dirs.insert(tlib_path.as_vec().to_vec()); // Don't keep searching the RUST_PATH if one match turns up -- // if we did, we'd get a "multiple matching crates" error match f(&tlib_path) { FileMatches => { break; } FileDoesntMatch => () } } } } } pub fn get_lib_path(&self) -> Path { make_target_lib_path(self.sysroot, self.triple) } pub fn search(&self, pick: pick) { self.for_each_lib_search_path(|lib_search_path| { debug!("searching {}", lib_search_path.display()); match fs::readdir(lib_search_path) { Ok(files) => { let mut rslt = FileDoesntMatch; fn is_rlib(p: & &Path) -> bool { p.extension_str() == Some("rlib") } // Reading metadata out of rlibs is faster, and if we find both // an rlib and a dylib we only read one of the files of // metadata, so in the name of speed, bring all rlib files to // the front of the search list. let files1 = files.iter().filter(|p| is_rlib(p)); let files2 = files.iter().filter(|p| !is_rlib(p)); for path in files1.chain(files2) { debug!("testing {}", path.display()); let maybe_picked = pick(path); match maybe_picked { FileMatches => { debug!("picked {}", path.display()); rslt = FileMatches; } FileDoesntMatch => { debug!("rejected {}", path.display()); } } } rslt } Err(..) => FileDoesntMatch, } }); } pub fn new(sysroot: &'a Path, triple: &'a str, addl_lib_search_paths: &'a RefCell<Vec<Path>>) -> FileSearch<'a> { debug!("using sysroot = {}, triple = {}", sysroot.display(), triple); FileSearch { sysroot: sysroot, addl_lib_search_paths: addl_lib_search_paths, triple: triple, } } // Returns a list of directories where target-specific dylibs might be located. pub fn get_dylib_search_paths(&self) -> Vec<Path> { let mut paths = Vec::new(); self.for_each_lib_search_path(|lib_search_path| { paths.push(lib_search_path.clone()); FileDoesntMatch }); paths } // Returns a list of directories where target-specific tool binaries are located.<|fim▁hole|> p.push(rustlibdir()); p.push(self.triple); p.push("bin"); vec![p] } } pub fn relative_target_lib_path(sysroot: &Path, target_triple: &str) -> Path { let mut p = Path::new(find_libdir(sysroot)); assert!(p.is_relative()); p.push(rustlibdir()); p.push(target_triple); p.push("lib"); p } fn make_target_lib_path(sysroot: &Path, target_triple: &str) -> Path { sysroot.join(&relative_target_lib_path(sysroot, target_triple)) } fn make_rustpkg_lib_path(sysroot: &Path, dir: &Path, triple: &str) -> Path { let mut p = dir.join(find_libdir(sysroot)); p.push(triple); p } pub fn get_or_default_sysroot() -> Path { // Follow symlinks. If the resolved path is relative, make it absolute. fn canonicalize(path: Option<Path>) -> Option<Path> { path.and_then(|path| match myfs::realpath(&path) { Ok(canon) => Some(canon), Err(e) => panic!("failed to get realpath: {}", e), }) } match canonicalize(os::self_exe_name()) { Some(mut p) => { p.pop(); p.pop(); p } None => panic!("can't determine value for sysroot") } } #[cfg(windows)] static PATH_ENTRY_SEPARATOR: &'static str = ";"; #[cfg(not(windows))] static PATH_ENTRY_SEPARATOR: &'static str = ":"; /// Returns RUST_PATH as a string, without default paths added pub fn get_rust_path() -> Option<String> { os::getenv("RUST_PATH").map(|x| x.to_string()) } /// Returns the value of RUST_PATH, as a list /// of Paths. Includes default entries for, if they exist: /// $HOME/.rust /// DIR/.rust for any DIR that's the current working directory /// or an ancestor of it pub fn rust_path() -> Vec<Path> { let mut env_rust_path: Vec<Path> = match get_rust_path() { Some(env_path) => { let env_path_components = env_path.split_str(PATH_ENTRY_SEPARATOR); env_path_components.map(|s| Path::new(s)).collect() } None => Vec::new() }; let mut cwd = os::getcwd().unwrap(); // now add in default entries let cwd_dot_rust = cwd.join(".rust"); if !env_rust_path.contains(&cwd_dot_rust) { env_rust_path.push(cwd_dot_rust); } if !env_rust_path.contains(&cwd) { env_rust_path.push(cwd.clone()); } loop { if { let f = cwd.filename(); f.is_none() || f.unwrap() == b".." } { break } cwd.set_filename(".rust"); if !env_rust_path.contains(&cwd) && cwd.exists() { env_rust_path.push(cwd.clone()); } cwd.pop(); } let h = os::homedir(); for h in h.iter() { let p = h.join(".rust"); if !env_rust_path.contains(&p) && p.exists() { env_rust_path.push(p); } } env_rust_path } // The name of the directory rustc expects libraries to be located. // On Unix should be "lib", on windows "bin" #[cfg(unix)] fn find_libdir(sysroot: &Path) -> String { // FIXME: This is a quick hack to make the rustc binary able to locate // Rust libraries in Linux environments where libraries might be installed // to lib64/lib32. This would be more foolproof by basing the sysroot off // of the directory where librustc is located, rather than where the rustc // binary is. //If --libdir is set during configuration to the value other than // "lib" (i.e. non-default), this value is used (see issue #16552). match option_env!("CFG_LIBDIR_RELATIVE") { Some(libdir) if libdir != "lib" => return libdir.to_string(), _ => if sysroot.join(primary_libdir_name()).join(rustlibdir()).exists() { return primary_libdir_name(); } else { return secondary_libdir_name(); } } #[cfg(target_word_size = "64")] fn primary_libdir_name() -> String { "lib64".to_string() } #[cfg(target_word_size = "32")] fn primary_libdir_name() -> String { "lib32".to_string() } fn secondary_libdir_name() -> String { "lib".to_string() } } #[cfg(windows)] fn find_libdir(_sysroot: &Path) -> String { "bin".to_string() } // The name of rustc's own place to organize libraries. // Used to be "rustc", now the default is "rustlib" pub fn rustlibdir() -> String { "rustlib".to_string() }<|fim▁end|>
pub fn get_tools_search_paths(&self) -> Vec<Path> { let mut p = Path::new(self.sysroot); p.push(find_libdir(self.sysroot));
<|file_name|>client_agent_endpoint.go<|end_file_name|><|fim▁begin|>package nomad import ( "bytes" "context" "errors" "fmt" "io" "net" "time" log "github.com/hashicorp/go-hclog" sframer "github.com/hashicorp/nomad/client/lib/streamframer" cstructs "github.com/hashicorp/nomad/client/structs" "github.com/hashicorp/nomad/command/agent/host" "github.com/hashicorp/nomad/command/agent/monitor" "github.com/hashicorp/nomad/command/agent/pprof" "github.com/hashicorp/nomad/helper" "github.com/hashicorp/nomad/nomad/structs" "github.com/hashicorp/go-msgpack/codec" ) type Agent struct { srv *Server } func (a *Agent) register() { a.srv.streamingRpcs.Register("Agent.Monitor", a.monitor) } func (a *Agent) Profile(args *structs.AgentPprofRequest, reply *structs.AgentPprofResponse) error { // Check ACL for agent write aclObj, err := a.srv.ResolveToken(args.AuthToken) if err != nil { return err } else if aclObj != nil && !aclObj.AllowAgentWrite() { return structs.ErrPermissionDenied } // Forward to different region if necessary // this would typically be done in a.srv.forward() but since // we are targeting a specific server, not just the leader // we must manually handle region forwarding here. region := args.RequestRegion() if region == "" { return fmt.Errorf("missing target RPC") } if region != a.srv.config.Region { // Mark that we are forwarding args.SetForwarded() return a.srv.forwardRegion(region, "Agent.Profile", args, reply) } // Targeting a node, forward request to node if args.NodeID != "" { return a.forwardProfileClient(args, reply) } // Handle serverID not equal to ours if args.ServerID != "" { serverToFwd, err := a.forwardFor(args.ServerID, region) if err != nil { return err } if serverToFwd != nil { return a.srv.forwardServer(serverToFwd, "Agent.Profile", args, reply) } } // If ACLs are disabled, EnableDebug must be enabled if aclObj == nil && !a.srv.config.EnableDebug { return structs.ErrPermissionDenied } // Process the request on this server var resp []byte var headers map[string]string // Determine which profile to run and generate profile. // Blocks for args.Seconds // Our RPC endpoints currently don't support context // or request cancellation so using server shutdownCtx as a // best effort. switch args.ReqType { case pprof.CPUReq: resp, headers, err = pprof.CPUProfile(a.srv.shutdownCtx, args.Seconds) case pprof.CmdReq: resp, headers, err = pprof.Cmdline() case pprof.LookupReq: resp, headers, err = pprof.Profile(args.Profile, args.Debug, args.GC) case pprof.TraceReq: resp, headers, err = pprof.Trace(a.srv.shutdownCtx, args.Seconds) default: err = structs.NewErrRPCCoded(404, "Unknown profile request type") } if err != nil { if pprof.IsErrProfileNotFound(err) { return structs.NewErrRPCCoded(404, err.Error()) } return structs.NewErrRPCCoded(500, err.Error()) } // Copy profile response to reply reply.Payload = resp reply.HTTPHeaders = headers reply.AgentID = a.srv.serf.LocalMember().Name return nil } func (a *Agent) monitor(conn io.ReadWriteCloser) { defer conn.Close() // Decode args var args cstructs.MonitorRequest decoder := codec.NewDecoder(conn, structs.MsgpackHandle) encoder := codec.NewEncoder(conn, structs.MsgpackHandle) if err := decoder.Decode(&args); err != nil { handleStreamResultError(err, helper.Int64ToPtr(500), encoder) return } // Check agent read permissions if aclObj, err := a.srv.ResolveToken(args.AuthToken); err != nil { handleStreamResultError(err, nil, encoder) return } else if aclObj != nil && !aclObj.AllowAgentRead() { handleStreamResultError(structs.ErrPermissionDenied, helper.Int64ToPtr(403), encoder) return } logLevel := log.LevelFromString(args.LogLevel) if args.LogLevel == "" { logLevel = log.LevelFromString("INFO") } if logLevel == log.NoLevel { handleStreamResultError(errors.New("Unknown log level"), helper.Int64ToPtr(400), encoder) return } // Targeting a node, forward request to node if args.NodeID != "" { a.forwardMonitorClient(conn, args, encoder, decoder) // forwarded request has ended, return return } region := args.RequestRegion() if region == "" { handleStreamResultError(fmt.Errorf("missing target RPC"), helper.Int64ToPtr(400), encoder) return } if region != a.srv.config.Region { // Mark that we are forwarding args.SetForwarded() } // Try to forward request to remote region/server if args.ServerID != "" { serverToFwd, err := a.forwardFor(args.ServerID, region) if err != nil { handleStreamResultError(err, helper.Int64ToPtr(400), encoder) return } if serverToFwd != nil { a.forwardMonitorServer(conn, serverToFwd, args, encoder, decoder) return } } // NodeID was empty, ServerID was equal to this server, monitor this server ctx, cancel := context.WithCancel(context.Background()) defer cancel() monitor := monitor.New(512, a.srv.logger, &log.LoggerOptions{ Level: logLevel, JSONFormat: args.LogJSON, }) frames := make(chan *sframer.StreamFrame, 32) errCh := make(chan error) var buf bytes.Buffer frameCodec := codec.NewEncoder(&buf, structs.JsonHandle) framer := sframer.NewStreamFramer(frames, 1*time.Second, 200*time.Millisecond, 1024) framer.Run() defer framer.Destroy() // goroutine to detect remote side closing go func() { if _, err := conn.Read(nil); err != nil { // One end of the pipe explicitly closed, exit cancel() return } <-ctx.Done() }() logCh := monitor.Start() defer monitor.Stop() initialOffset := int64(0) // receive logs and build frames go func() { defer framer.Destroy() LOOP: for { select { case log := <-logCh: if err := framer.Send("", "log", log, initialOffset); err != nil { select { case errCh <- err: case <-ctx.Done(): } break LOOP } case <-ctx.Done(): break LOOP } }<|fim▁hole|> for { select { case frame, ok := <-frames: if !ok { // frame may have been closed when an error // occurred. Check once more for an error. select { case streamErr = <-errCh: // There was a pending error! default: // No error, continue on } break OUTER } var resp cstructs.StreamErrWrapper if args.PlainText { resp.Payload = frame.Data } else { if err := frameCodec.Encode(frame); err != nil { streamErr = err break OUTER } resp.Payload = buf.Bytes() buf.Reset() } if err := encoder.Encode(resp); err != nil { streamErr = err break OUTER } encoder.Reset(conn) case <-ctx.Done(): break OUTER } } if streamErr != nil { handleStreamResultError(streamErr, helper.Int64ToPtr(500), encoder) return } } // forwardFor returns a serverParts for a request to be forwarded to. // A response of nil, nil indicates that the current server is equal to the // serverID and region so the request should not be forwarded. func (a *Agent) forwardFor(serverID, region string) (*serverParts, error) { var target *serverParts var err error if serverID == "leader" { isLeader, remoteLeader := a.srv.getLeader() if !isLeader && remoteLeader != nil { target = remoteLeader } else if !isLeader && remoteLeader == nil { return nil, structs.ErrNoLeader } else if isLeader { // This server is current leader do not forward return nil, nil } } else { target, err = a.srv.getServer(region, serverID) if err != nil { return nil, err } } // Unable to find a server if target == nil { return nil, fmt.Errorf("unknown nomad server %s", serverID) } // ServerID is this current server, // No need to forward request if target.Name == a.srv.LocalMember().Name { return nil, nil } return target, nil } func (a *Agent) forwardMonitorClient(conn io.ReadWriteCloser, args cstructs.MonitorRequest, encoder *codec.Encoder, decoder *codec.Decoder) { // Get the Connection to the client either by fowarding to another server // or creating direct stream state, srv, err := a.findClientConn(args.NodeID) if err != nil { handleStreamResultError(err, helper.Int64ToPtr(500), encoder) return } var clientConn net.Conn if state == nil { conn, err := a.srv.streamingRpc(srv, "Agent.Monitor") if err != nil { handleStreamResultError(err, nil, encoder) return } clientConn = conn } else { stream, err := NodeStreamingRpc(state.Session, "Agent.Monitor") if err != nil { handleStreamResultError(err, nil, encoder) return } clientConn = stream } defer clientConn.Close() // Send the Request outEncoder := codec.NewEncoder(clientConn, structs.MsgpackHandle) if err := outEncoder.Encode(args); err != nil { handleStreamResultError(err, nil, encoder) return } structs.Bridge(conn, clientConn) } func (a *Agent) forwardMonitorServer(conn io.ReadWriteCloser, server *serverParts, args cstructs.MonitorRequest, encoder *codec.Encoder, decoder *codec.Decoder) { // empty ServerID to prevent forwarding loop args.ServerID = "" serverConn, err := a.srv.streamingRpc(server, "Agent.Monitor") if err != nil { handleStreamResultError(err, helper.Int64ToPtr(500), encoder) return } defer serverConn.Close() // Send the Request outEncoder := codec.NewEncoder(serverConn, structs.MsgpackHandle) if err := outEncoder.Encode(args); err != nil { handleStreamResultError(err, helper.Int64ToPtr(500), encoder) return } structs.Bridge(conn, serverConn) } func (a *Agent) forwardProfileClient(args *structs.AgentPprofRequest, reply *structs.AgentPprofResponse) error { state, srv, err := a.findClientConn(args.NodeID) if err != nil { return err } if srv != nil { return a.srv.forwardServer(srv, "Agent.Profile", args, reply) } // NodeRpc rpcErr := NodeRpc(state.Session, "Agent.Profile", args, reply) if rpcErr != nil { return rpcErr } return nil } // Host returns data about the agent's host system for the `debug` command. func (a *Agent) Host(args *structs.HostDataRequest, reply *structs.HostDataResponse) error { aclObj, err := a.srv.ResolveToken(args.AuthToken) if err != nil { return err } if (aclObj != nil && !aclObj.AllowAgentRead()) || (aclObj == nil && !a.srv.config.EnableDebug) { return structs.ErrPermissionDenied } // Forward to different region if necessary // this would typically be done in a.srv.forward() but since // we are targeting a specific server, not just the leader // we must manually handle region forwarding here. region := args.RequestRegion() if region == "" { return fmt.Errorf("missing target RPC") } if region != a.srv.config.Region { // Mark that we are forwarding args.SetForwarded() return a.srv.forwardRegion(region, "Agent.Host", args, reply) } // Targeting a client node, forward request to node if args.NodeID != "" { client, srv, err := a.findClientConn(args.NodeID) if err != nil { return err } if srv != nil { return a.srv.forwardServer(srv, "Agent.Host", args, reply) } return NodeRpc(client.Session, "Agent.Host", args, reply) } // Handle serverID not equal to ours if args.ServerID != "" { srv, err := a.forwardFor(args.ServerID, region) if err != nil { return err } if srv != nil { return a.srv.forwardServer(srv, "Agent.Host", args, reply) } } data, err := host.MakeHostData() if err != nil { return err } reply.AgentID = a.srv.serf.LocalMember().Name reply.HostData = data return nil } // findClientConn is a helper that returns a connection to the client node or, if the client // is connected to a different server, a serverParts describing the server to which the // client bound RPC should be forwarded. func (a *Agent) findClientConn(nodeID string) (*nodeConnState, *serverParts, error) { snap, err := a.srv.State().Snapshot() if err != nil { return nil, nil, structs.NewErrRPCCoded(500, err.Error()) } node, err := snap.NodeByID(nil, nodeID) if err != nil { return nil, nil, structs.NewErrRPCCoded(500, err.Error()) } if node == nil { err := fmt.Errorf("Unknown node %q", nodeID) return nil, nil, structs.NewErrRPCCoded(404, err.Error()) } if err := nodeSupportsRpc(node); err != nil { return nil, nil, structs.NewErrRPCCoded(400, err.Error()) } // Get the Connection to the client either by fowarding to another server // or creating direct stream state, ok := a.srv.getNodeConn(nodeID) if ok { return state, nil, nil } // Determine the server that has a connection to the node srv, err := a.srv.serverWithNodeConn(nodeID, a.srv.Region()) if err != nil { code := 500 if structs.IsErrNoNodeConn(err) { code = 404 } return nil, nil, structs.NewErrRPCCoded(code, err.Error()) } return nil, srv, nil }<|fim▁end|>
}() var streamErr error OUTER:
<|file_name|>main.go<|end_file_name|><|fim▁begin|>package main import ( "fmt" "io/ioutil"<|fim▁hole|> "os" ) func main() { dat, err := ioutil.ReadFile("data/simple.txt") if err != nil { fmt.Println(err) os.Exit(1) } fmt.Print(string(dat)) }<|fim▁end|>
<|file_name|>stack_fwd.hh<|end_file_name|><|fim▁begin|>/** \file "util/STL/stack_fwd.hh" Forward declaration of std::stack. No wrapping. $Id: stack_fwd.hh,v 1.6 2006/04/23 07:37:29 fang Exp $ */ #ifndef __UTIL_STL_STACK_FWD_HH__ #define __UTIL_STL_STACK_FWD_HH__ #include "util/STL/deque_fwd.hh" BEGIN_NAMESPACE_STD // doesn't like redeclaring default template arguments... // template <class T, class Alloc = std::allocator<T> > template <class T, class Seq><|fim▁hole|>class stack; template <class T> struct default_stack { typedef stack<T, typename default_deque<T>::type> type; template <class S> struct rebind : public default_stack<S> { }; }; // end struct default_stack END_NAMESPACE_STD #endif // __UTIL_STL_STACK_FWD_HH__<|fim▁end|>
<|file_name|>descriptor.py<|end_file_name|><|fim▁begin|>""" This module implements atom/bond/structure-wise descriptor calculated from pretrained megnet model """ import os from typing import Dict, Union import numpy as np from tensorflow.keras.models import Model from megnet.models import GraphModel, MEGNetModel from megnet.utils.typing import StructureOrMolecule DEFAULT_MODEL = os.path.join(os.path.dirname(__file__), "../../mvl_models/mp-2019.4.1/formation_energy.hdf5") class MEGNetDescriptor: """ MEGNet descriptors. This class takes a trained model and then compute the intermediate outputs as structure features """ def __init__(self, model_name: Union[str, GraphModel, MEGNetModel] = DEFAULT_MODEL, use_cache: bool = True): """ Args: model_name (str or MEGNetModel): trained model. If it is str, then only models in mvl_models are used. use_cache (bool): whether to use cache for structure graph calculations """ if isinstance(model_name, str): model = MEGNetModel.from_file(model_name) elif isinstance(model_name, GraphModel): model = model_name else: raise ValueError("model_name only support str or GraphModel object") layers = model.layers important_prefix = ["meg", "set", "concatenate"] all_names = [i.name for i in layers if any(i.name.startswith(j) for j in important_prefix)] if any(i.startswith("megnet") for i in all_names): self.version = "v2" else: self.version = "v1" valid_outputs = [i.output for i in layers if any(i.name.startswith(j) for j in important_prefix)] outputs = [] valid_names = [] for i, j in zip(all_names, valid_outputs): if isinstance(j, list): for k, l in enumerate(j): valid_names.append(i + f"_{k}") outputs.append(l) else: valid_names.append(i) outputs.append(j) full_model = Model(inputs=model.inputs, outputs=outputs) model.model = full_model self.model = model self.valid_names = valid_names self._cache: Dict[str, float] = {} self.use_cache = use_cache def _predict_structure(self, structure: StructureOrMolecule) -> np.ndarray: graph = self.model.graph_converter.convert(structure) inp = self.model.graph_converter.graph_to_input(graph) return self.model.predict(inp) def _predict_feature(self, structure: StructureOrMolecule) -> np.ndarray: if not self.use_cache: return self._predict_structure(structure) s = str(structure) if s in self._cache: return self._cache[s] result = self._predict_structure(structure) self._cache[s] = result return result def _get_features(self, structure: StructureOrMolecule, prefix: str, level: int, index: int = None) -> np.ndarray: name = prefix if level is not None: name = f"{prefix}_{level}" if index is not None: name += f"_{index}" if name not in self.valid_names: raise ValueError(f"{name} not in original megnet model") ind = self.valid_names.index(name) out_all = self._predict_feature(structure) return out_all[ind][0] def _get_updated_prefix_level(self, prefix: str, level: int): mapping = { "meg_net_layer": ["megnet", level - 1], "set2_set": ["set2set_atom" if level == 1 else "set2set_bond", None], "concatenate": ["concatenate", None], } if self.version == "v2": return mapping[prefix][0], mapping[prefix][1] # type: ignore return prefix, level def get_atom_features(self, structure: StructureOrMolecule, level: int = 3) -> np.ndarray: """ Get megnet atom features from structure Args: structure: pymatgen structure or molecule level: int, indicating the block number of megnet, starting from 1 Returns: nxm atomic feature matrix """ prefix, level = self._get_updated_prefix_level("meg_net_layer", level) return self._get_features(structure, prefix=prefix, level=level, index=0) def get_bond_features(self, structure: StructureOrMolecule, level: int = 3) -> np.ndarray: """ Get bond features at megnet block level Args: structure: pymatgen structure level: int Returns: n_bond x m bond feature matrix """ prefix, level = self._get_updated_prefix_level("meg_net_layer", level) return self._get_features(structure, prefix=prefix, level=level, index=1) def get_global_features(self, structure: StructureOrMolecule, level: int = 2) -> np.ndarray: """ Get state features at megnet block level Args: structure: pymatgen structure or molecule level: int Returns: 1 x m_g global feature vector<|fim▁hole|> def get_set2set(self, structure: StructureOrMolecule, ftype: str = "atom") -> np.ndarray: """ Get set2set output as features Args: structure (StructureOrMolecule): pymatgen structure or molecule ftype (str): atom or bond Returns: feature matrix, each row is a vector for an atom or bond """ mapping = {"atom": 1, "bond": 2} prefix, level = self._get_updated_prefix_level("set2_set", level=mapping[ftype]) return self._get_features(structure, prefix=prefix, level=level) def get_structure_features(self, structure: StructureOrMolecule) -> np.ndarray: """ Get structure level feature vector Args: structure (StructureOrMolecule): pymatgen structure or molecule Returns: one feature vector for the structure """ prefix, level = self._get_updated_prefix_level("concatenate", level=1) return self._get_features(structure, prefix=prefix, level=level)<|fim▁end|>
""" prefix, level = self._get_updated_prefix_level("meg_net_layer", level) return self._get_features(structure, prefix=prefix, level=level, index=2)
<|file_name|>test_evalf.py<|end_file_name|><|fim▁begin|>from sympy.core.evalf import PrecisionExhausted, complex_accuracy from sympy import pi, I, Symbol, Add, Rational, exp, sqrt, sin, cos, \ fibonacci, Integral, oo, E, atan, log, integrate, floor, ceiling, \ factorial, binomial, Sum, zeta, Catalan, Pow, GoldenRatio, sympify, \ sstr, Function, Eq, Mul, Pow, Derivative from sympy.mpmath.libmp.libmpf import from_float from sympy.utilities.pytest import raises x = Symbol('x') y = Symbol('y') n = Symbol('n') def NS(e, n=15, **options): return sstr(sympify(e).evalf(n, **options), full_prec=True) def test_evalf_helpers(): assert complex_accuracy((from_float(2.0),None,35,None)) == 35 assert complex_accuracy((from_float(2.0),from_float(10.0),35,100)) == 37 assert complex_accuracy((from_float(2.0),from_float(1000.0),35,100)) == 43 assert complex_accuracy((from_float(2.0),from_float(10.0),100,35)) == 35 assert complex_accuracy((from_float(2.0),from_float(1000.0),100,35)) == 35 def test_evalf_basic(): assert NS('pi',15) == '3.14159265358979' assert NS('2/3',10) == '0.6666666667' assert NS('355/113-pi',6) == '2.66764e-7' assert NS('16*atan(1/5)-4*atan(1/239)', 15) == '3.14159265358979' def test_cancellation(): assert NS(Add(pi,Rational(1,10**1000),-pi,evaluate=False),15,maxn=1200) == '1.00000000000000e-1000' def test_evalf_powers(): assert NS('pi**(10**20)',10) == '1.339148777e+49714987269413385435' assert NS(pi**(10**100),10) == ('4.946362032e+4971498726941338543512682882' '9089887365167832438044244613405349992494711208' '95526746555473864642912223') assert NS('2**(1/10**50)',15) == '1.00000000000000' assert NS('2**(1/10**50)-1',15) == '6.93147180559945e-51' # Evaluation of Rump's ill-conditioned polynomial def test_evalf_rump(): a = 1335*y**6/4+x**2*(11*x**2*y**2-y**6-121*y**4-2)+11*y**8/2+x/(2*y) assert NS(a, 15, subs={x:77617, y:33096}) == '-0.827396059946821' def test_evalf_complex(): assert NS('2*sqrt(pi)*I',10) == '3.544907702*I' assert NS('3+3*I',15) == '3.00000000000000 + 3.00000000000000*I' assert NS('E+pi*I',15) == '2.71828182845905 + 3.14159265358979*I' assert NS('pi * (3+4*I)',15) == '9.42477796076938 + 12.5663706143592*I' assert NS('I*(2+I)',15) == '-1.00000000000000 + 2.00000000000000*I' #assert NS('(pi+E*I)*(E+pi*I)',15) in ('.0e-15 + 17.25866050002*I', '.0e-17 + 17.25866050002*I', '-.0e-17 + 17.25866050002*I') assert NS('(pi+E*I)*(E+pi*I)',15,chop=True) == '17.2586605000200*I' def test_evalf_complex_powers(): assert NS('(E+pi*I)**100000000000000000') == \ '-3.58896782867793e+61850354284995199 + 4.58581754997159e+61850354284995199*I' # XXX: rewrite if a+a*I simplification introduced in sympy #assert NS('(pi + pi*I)**2') in ('.0e-15 + 19.7392088021787*I', '.0e-16 + 19.7392088021787*I') assert NS('(pi + pi*I)**2', chop=True) == '19.7392088021787*I' assert NS('(pi + 1/10**8 + pi*I)**2') == '6.2831853e-8 + 19.7392088650106*I' assert NS('(pi + 1/10**12 + pi*I)**2') == '6.283e-12 + 19.7392088021850*I' #assert NS('(pi + pi*I)**4') == '-389.63636413601 + .0e-14*I' assert NS('(pi + pi*I)**4', chop=True) == '-389.636364136010' assert NS('(pi + 1/10**8 + pi*I)**4') == '-389.636366616512 + 2.4805021e-6*I' assert NS('(pi + 1/10**12 + pi*I)**4') == '-389.636364136258 + 2.481e-10*I' assert NS('(10000*pi + 10000*pi*I)**4', chop=True) == '-3.89636364136010e+18' def test_evalf_exponentiation(): assert NS(sqrt(-pi)) == '1.77245385090552*I' assert NS(Pow(pi*I, Rational(1,2), evaluate=False)) == '1.25331413731550 + 1.25331413731550*I' assert NS(pi**I) == '0.413292116101594 + 0.910598499212615*I' assert NS(pi**(E+I/3)) == '20.8438653991931 + 8.36343473930031*I' assert NS((pi+I/3)**(E+I/3)) == '17.2442906093590 + 13.6839376767037*I' assert NS(exp(pi)) == '23.1406926327793' assert NS(exp(pi+E*I)) == '-21.0981542849657 + 9.50576358282422*I' assert NS(pi**pi) == '36.4621596072079' assert NS((-pi)**pi) == '-32.9138577418939 - 15.6897116534332*I' assert NS((-pi)**(-pi)) == '-0.0247567717232697 + 0.0118013091280262*I' # An example from Smith, "Multiple Precision Complex Arithmetic and Functions" def test_evalf_complex_cancellation(): A = Rational('63287/100000') B = Rational('52498/100000') C = Rational('69301/100000') D = Rational('83542/100000') F = Rational('2231321613/2500000000') # XXX: the number of returned mantissa digits in the real part could # change with the implementation. What matters is that the returned digits are # correct. assert NS((A+B*I)*(C+D*I),6) == '6.44862e-6 + 0.892529*I' assert NS((A+B*I)*(C+D*I),10) == '6.447099821e-6 + 0.8925286452*I'<|fim▁hole|> assert NS("log(pi*I)", 15) == '1.14472988584940 + 1.57079632679490*I' def test_evalf_trig(): assert NS('sin(1)',15) == '0.841470984807897' assert NS('cos(1)',15) == '0.540302305868140' assert NS('sin(10**-6)',15) == '9.99999999999833e-7' assert NS('cos(10**-6)',15) == '0.999999999999500' assert NS('sin(E*10**100)',15) == '0.409160531722613' # Some input near roots assert NS(sin(exp(pi*sqrt(163))*pi), 15) == '-2.35596641936785e-12' assert NS(sin(pi*10**100 + Rational(7,10**5), evaluate=False), 15, maxn=120) == \ '6.99999999428333e-5' assert NS(sin(Rational(7,10**5), evaluate=False), 15) == \ '6.99999999428333e-5' # Check detection of various false identities def test_evalf_near_integers(): # Binet's formula f = lambda n: ((1+sqrt(5))**n)/(2**n * sqrt(5)) assert NS(f(5000) - fibonacci(5000), 10, maxn=1500) == '5.156009964e-1046' # Some near-integer identities from # http://mathworld.wolfram.com/AlmostInteger.html assert NS('sin(2017*2**(1/5))',15) == '-1.00000000000000' assert NS('sin(2017*2**(1/5))',20) == '-0.99999999999999997857' assert NS('1+sin(2017*2**(1/5))',15) == '2.14322287389390e-17' assert NS('45 - 613*E/37 + 35/991', 15) == '6.03764498766326e-11' def test_evalf_ramanujan(): assert NS(exp(pi*sqrt(163)) - 640320**3 - 744, 10) == '-7.499274028e-13' # A related identity A = 262537412640768744*exp(-pi*sqrt(163)) B = 196884*exp(-2*pi*sqrt(163)) C = 103378831900730205293632*exp(-3*pi*sqrt(163)) assert NS(1-A-B+C,10) == '1.613679005e-59' # Input that for various reasons have failed at some point def test_evalf_bugs(): assert NS(sin(1)+exp(-10**10),10) == NS(sin(1),10) assert NS(exp(10**10)+sin(1),10) == NS(exp(10**10),10) assert NS('log(1+1/10**50)',20) == '1.0000000000000000000e-50' assert NS('log(10**100,10)',10) == '100.0000000' assert NS('log(2)',10) == '0.6931471806' assert NS('(sin(x)-x)/x**3', 15, subs={x:'1/10**50'}) == '-0.166666666666667' assert NS(sin(1)+Rational(1,10**100)*I,15) == '0.841470984807897 + 1.00000000000000e-100*I' assert x.evalf() == x assert NS((1+I)**2*I,6) == '-2.00000 + 2.32831e-10*I' d={n: (-1)**Rational(6,7), y: (-1)**Rational(4,7), x: (-1)**Rational(2,7)} assert NS((x*(1+y*(1 + n))).subs(d).evalf(),6) == '0.346011 + 0.433884*I' assert NS(((-I-sqrt(2)*I)**2).evalf()) == '-5.82842712474619' assert NS((1+I)**2*I,15) == '-2.00000000000000 + 2.16840434497101e-19*I' #1659 (1/2): assert NS(pi.evalf(69) - pi) == '-4.43863937855894e-71' #1659 (2/2): With the bug present, this still only fails if the # terms are in the order given here. This is not generally the case, # because the order depends on the hashes of the terms. assert NS(20 - 5008329267844*n**25 - 477638700*n**37 - 19*n, subs={n:.01}) == '19.8100000000000' def test_evalf_integer_parts(): a = floor(log(8)/log(2) - exp(-1000), evaluate=False) b = floor(log(8)/log(2), evaluate=False) raises(PrecisionExhausted, "a.evalf()") assert a.evalf(chop=True) == 3 assert a.evalf(maxn=500) == 2 raises(PrecisionExhausted, "b.evalf()") raises(PrecisionExhausted, "b.evalf(maxn=500)") assert b.evalf(chop=True) == 3 assert int(floor(factorial(50)/E,evaluate=False).evalf()) == \ 11188719610782480504630258070757734324011354208865721592720336800L assert int(ceiling(factorial(50)/E,evaluate=False).evalf()) == \ 11188719610782480504630258070757734324011354208865721592720336801L assert int(floor((GoldenRatio**999 / sqrt(5) + Rational(1,2))).evalf(1000)) == fibonacci(999) assert int(floor((GoldenRatio**1000 / sqrt(5) + Rational(1,2))).evalf(1000)) == fibonacci(1000) def test_evalf_trig_zero_detection(): a = sin(160*pi, evaluate=False) t = a.evalf(maxn=100) assert abs(t) < 1e-100 assert t._prec < 2 assert a.evalf(chop=True) == 0 raises(PrecisionExhausted, "a.evalf(strict=True)") def test_evalf_divergent_series(): n = Symbol('n', integer=True) raises(ValueError, 'Sum(1/n, (n, 1, oo)).evalf()') raises(ValueError, 'Sum(n/(n**2+1), (n, 1, oo)).evalf()') raises(ValueError, 'Sum((-1)**n, (n, 1, oo)).evalf()') raises(ValueError, 'Sum((-1)**n, (n, 1, oo)).evalf()') raises(ValueError, 'Sum(n**2, (n, 1, oo)).evalf()') raises(ValueError, 'Sum(2**n, (n, 1, oo)).evalf()') raises(ValueError, 'Sum((-2)**n, (n, 1, oo)).evalf()') raises(ValueError, 'Sum((2*n+3)/(3*n**2+4), (n,0, oo)).evalf()') raises(ValueError, 'Sum((0.5*n**3)/(n**4+1),(n,0,oo)).evalf()') def test_evalf_py_methods(): assert abs(float(pi+1) - 4.1415926535897932) < 1e-10 assert abs(complex(pi+1) - 4.1415926535897932) < 1e-10 assert abs(complex(pi+E*I) - (3.1415926535897931+2.7182818284590451j)) < 1e-10 raises(ValueError, "float(pi+x)") raises(ValueError, "complex(pi+x)") def test_evalf_power_subs_bugs(): assert (x**2).evalf(subs={x:0}) == 0 assert sqrt(x).evalf(subs={x:0}) == 0 assert (x**Rational(2,3)).evalf(subs={x:0}) == 0 assert (x**x).evalf(subs={x:0}) == 1 assert (3**x).evalf(subs={x:0}) == 1 assert exp(x).evalf(subs={x:0}) == 1 assert ((2+I)**x).evalf(subs={x:0}) == 1 assert (0**x).evalf(subs={x:0}) == 1 def test_evalf_arguments(): raises(TypeError, 'pi.evalf(method="garbage")') def test_implemented_function_evalf(): from sympy.utilities.lambdify import implemented_function f = Function('f') x = Symbol('x') f = implemented_function(f, lambda x: x + 1) assert str(f(x)) == "f(x)" assert str(f(2)) == "f(2)" assert f(2).evalf() == 3 assert f(x).evalf() == f(x) del f._imp_ # XXX: due to caching _imp_ would influence all other tests def test_evaluate_false(): for no in [[], 0, False, None]: assert Add(3, 2, evaluate=no).is_Add assert Mul(3, 2, evaluate=no).is_Mul assert Pow(3, 2, evaluate=no).is_Pow assert Pow(y, 2, evaluate=True) - Pow(y, 2, evaluate=True) == 0 def test_evalf_relational(): assert Eq(x/5, y/10).evalf() == Eq(0.2*x, 0.1*y) def test_issue_2387(): assert not cos(sqrt(0.5 + I)).n().is_Function def test_issue_2387_bug(): from sympy import I, Expr assert abs(Expr._from_mpmath(I._to_mpmath(15), 15) - I) < 1.0e-15<|fim▁end|>
assert NS((A+B*I)*(C+D*I) - F*I, 5) in ('6.4471e-6 - .0e-15*I', '6.4471e-6 + .0e-15*I') def test_evalf_logs(): assert NS("log(3+pi*I)", 15) == '1.46877619736226 + 0.808448792630022*I'
<|file_name|>RecordTimer.py<|end_file_name|><|fim▁begin|>from enigma import eEPGCache, getBestPlayableServiceReference, \ eServiceReference, iRecordableService, quitMainloop from Components.config import config from Components.UsageConfig import defaultMoviePath from Components.TimerSanityCheck import TimerSanityCheck from Screens.MessageBox import MessageBox import Screens.Standby from Tools import Directories, Notifications, ASCIItranslit, Trashcan from Tools.XMLTools import stringToXML import timer import xml.etree.cElementTree import NavigationInstance from ServiceReference import ServiceReference from time import localtime, strftime, ctime, time from bisect import insort # ok, for descriptions etc we have: # service reference (to get the service name) # name (title) # description (description) # event data (ONLY for time adjustments etc.) # parses an event, and gives out a (begin, end, name, duration, eit)-tuple. # begin and end will be corrected def parseEvent(ev, description = True): if description: name = ev.getEventName() description = ev.getShortDescription() if description == "": description = ev.getExtendedDescription() else: name = "" description = "" begin = ev.getBeginTime() end = begin + ev.getDuration() eit = ev.getEventId() begin -= config.recording.margin_before.value * 60 end += config.recording.margin_after.value * 60 return (begin, end, name, description, eit) class AFTEREVENT: NONE = 0 STANDBY = 1 DEEPSTANDBY = 2 AUTO = 3 # please do not translate log messages class RecordTimerEntry(timer.TimerEntry, object): ######### the following static methods and members are only in use when the box is in (soft) standby receiveRecordEvents = False @staticmethod def shutdown(): quitMainloop(1) @staticmethod def staticGotRecordEvent(recservice, event): if event == iRecordableService.evEnd: print "RecordTimer.staticGotRecordEvent(iRecordableService.evEnd)" recordings = NavigationInstance.instance.getRecordings() if not recordings: # no more recordings exist rec_time = NavigationInstance.instance.RecordTimer.getNextRecordingTime() if rec_time > 0 and (rec_time - time()) < 360: print "another recording starts in", rec_time - time(), "seconds... do not shutdown yet" else: print "no starting records in the next 360 seconds... immediate shutdown" RecordTimerEntry.shutdown() # immediate shutdown elif event == iRecordableService.evStart: print "RecordTimer.staticGotRecordEvent(iRecordableService.evStart)" @staticmethod def stopTryQuitMainloop(): print "RecordTimer.stopTryQuitMainloop" NavigationInstance.instance.record_event.remove(RecordTimerEntry.staticGotRecordEvent) RecordTimerEntry.receiveRecordEvents = False @staticmethod def TryQuitMainloop(default_yes = True): if not RecordTimerEntry.receiveRecordEvents: print "RecordTimer.TryQuitMainloop" NavigationInstance.instance.record_event.append(RecordTimerEntry.staticGotRecordEvent) RecordTimerEntry.receiveRecordEvents = True # send fake event.. to check if another recordings are running or # other timers start in a few seconds RecordTimerEntry.staticGotRecordEvent(None, iRecordableService.evEnd) # send normal notification for the case the user leave the standby now.. Notifications.AddNotification(Screens.Standby.TryQuitMainloop, 1, onSessionOpenCallback=RecordTimerEntry.stopTryQuitMainloop, default_yes = default_yes) ################################################################# def __init__(self, serviceref, begin, end, name, description, eit, disabled = False, justplay = False, afterEvent = AFTEREVENT.AUTO, checkOldTimers = False, dirname = None, tags = None): timer.TimerEntry.__init__(self, int(begin), int(end)) if checkOldTimers == True: if self.begin < time() - 1209600: self.begin = int(time()) if self.end < self.begin: self.end = self.begin assert isinstance(serviceref, ServiceReference) if serviceref.isRecordable(): self.service_ref = serviceref else: self.service_ref = ServiceReference(None) self.eit = eit self.dontSave = False self.name = name self.description = description self.disabled = disabled self.timer = None self.__record_service = None self.start_prepare = 0 self.justplay = justplay self.afterEvent = afterEvent self.dirname = dirname self.dirnameHadToFallback = False self.autoincrease = False self.autoincreasetime = 3600 * 24 # 1 day self.tags = tags or [] self.log_entries = [] self.resetState() def log(self, code, msg): self.log_entries.append((int(time()), code, msg)) print "[TIMER]", msg def calculateFilename(self): service_name = self.service_ref.getServiceName() begin_date = strftime("%Y%m%d %H%M", localtime(self.begin)) begin_shortdate = strftime("%Y%m%d", localtime(self.begin)) print "begin_date: ", begin_date print "service_name: ", service_name print "name:", self.name print "description: ", self.description filename = begin_date + " - " + service_name if self.name: if config.usage.setup_level.index >= 2: # expert+ if config.recording.filename_composition.value == "short": filename = begin_shortdate + " - " + self.name elif config.recording.filename_composition.value == "long": filename += " - " + self.name + " - " + self.description else: filename += " - " + self.name # standard else: filename += " - " + self.name if config.recording.ascii_filenames.value: filename = ASCIItranslit.legacyEncode(filename) if not self.dirname or not Directories.fileExists(self.dirname, 'w'): if self.dirname: self.dirnameHadToFallback = True dirname = defaultMoviePath() else: dirname = self.dirname self.Filename = Directories.getRecordingFilename(filename, dirname) self.log(0, "Filename calculated as: '%s'" % self.Filename) #begin_date + " - " + service_name + description) def tryPrepare(self): if self.justplay: return True else: self.calculateFilename() rec_ref = self.service_ref and self.service_ref.ref if rec_ref and rec_ref.flags & eServiceReference.isGroup: rec_ref = getBestPlayableServiceReference(rec_ref, eServiceReference()) if not rec_ref: self.log(1, "'get best playable service for group... record' failed") return False self.record_service = rec_ref and NavigationInstance.instance.recordService(rec_ref) if not self.record_service: self.log(1, "'record service' failed") return False if self.repeated: epgcache = eEPGCache.getInstance() queryTime=self.begin+(self.end-self.begin)/2 evt = epgcache.lookupEventTime(rec_ref, queryTime) if evt: self.description = evt.getShortDescription() if self.description == "": description = evt.getExtendedDescription() event_id = evt.getEventId() else: event_id = -1 else: event_id = self.eit if event_id is None: event_id = -1 prep_res=self.record_service.prepare(self.Filename + ".ts", self.begin, self.end, event_id, self.name.replace("\n", ""), self.description.replace("\n", ""), ' '.join(self.tags)) if prep_res: if prep_res == -255: self.log(4, "failed to write meta information") else: self.log(2, "'prepare' failed: error %d" % prep_res) # we must calc nur start time before stopRecordService call because in Screens/Standby.py TryQuitMainloop tries to get # the next start time in evEnd event handler... self.do_backoff() self.start_prepare = time() + self.backoff NavigationInstance.instance.stopRecordService(self.record_service) self.record_service = None return False return True def do_backoff(self): if self.backoff == 0: self.backoff = 5 else: self.backoff *= 2 if self.backoff > 100: self.backoff = 100 self.log(10, "backoff: retry in %d seconds" % self.backoff) def activate(self): next_state = self.state + 1 self.log(5, "activating state %d" % next_state) if next_state == self.StatePrepared: if self.tryPrepare(): self.log(6, "prepare ok, waiting for begin") # create file to "reserve" the filename # because another recording at the same time on another service can try to record the same event # i.e. cable / sat.. then the second recording needs an own extension... when we create the file # here than calculateFilename is happy if not self.justplay: open(self.Filename + ".ts", "w").close() # Give the Trashcan a chance to clean up try: Trashcan.instance.cleanIfIdle() except Exception, e: print "[TIMER] Failed to call Trashcan.instance.cleanIfIdle()" print "[TIMER] Error:", e # fine. it worked, resources are allocated. self.next_activation = self.begin self.backoff = 0 return True self.log(7, "prepare failed") if self.first_try_prepare: self.first_try_prepare = False cur_ref = NavigationInstance.instance.getCurrentlyPlayingServiceReference() if cur_ref and not cur_ref.getPath(): if not config.recording.asktozap.value: self.log(8, "asking user to zap away") Notifications.AddNotificationWithCallback(self.failureCB, MessageBox, _("A timer failed to record!\nDisable TV and try again?\n"), timeout=20) else: # zap without asking self.log(9, "zap without asking") Notifications.AddNotification(MessageBox, _("In order to record a timer, the TV was switched to the recording service!\n"), type=MessageBox.TYPE_INFO, timeout=20) self.failureCB(True) elif cur_ref: self.log(8, "currently running service is not a live service.. so stop it makes no sense") else: self.log(8, "currently no service running... so we dont need to stop it") return False elif next_state == self.StateRunning: # if this timer has been cancelled, just go to "end" state. if self.cancelled: return True if self.justplay: if Screens.Standby.inStandby: self.log(11, "wakeup and zap") #set service to zap after standby Screens.Standby.inStandby.prev_running_service = self.service_ref.ref #wakeup standby Screens.Standby.inStandby.Power() else: self.log(11, "zapping") NavigationInstance.instance.playService(self.service_ref.ref) return True else: self.log(11, "start recording") record_res = self.record_service.start() if record_res: self.log(13, "start record returned %d" % record_res) self.do_backoff() # retry self.begin = time() + self.backoff return False return True elif next_state == self.StateEnded: old_end = self.end if self.setAutoincreaseEnd(): self.log(12, "autoincrase recording %d minute(s)" % int((self.end - old_end)/60)) self.state -= 1 return True self.log(12, "stop recording") if not self.justplay: NavigationInstance.instance.stopRecordService(self.record_service) self.record_service = None if self.afterEvent == AFTEREVENT.STANDBY: if not Screens.Standby.inStandby: # not already in standby Notifications.AddNotificationWithCallback(self.sendStandbyNotification, MessageBox, _("A finished record timer wants to set your\nBox to standby. Do that now?"), timeout = 20) elif self.afterEvent == AFTEREVENT.DEEPSTANDBY: if not Screens.Standby.inTryQuitMainloop: # not a shutdown messagebox is open if Screens.Standby.inStandby: # in standby RecordTimerEntry.TryQuitMainloop() # start shutdown handling without screen else: Notifications.AddNotificationWithCallback(self.sendTryQuitMainloopNotification, MessageBox, _("A finished record timer wants to shut down\nyour Box. Shutdown now?"), timeout = 20) return True def setAutoincreaseEnd(self, entry = None): if not self.autoincrease: return False if entry is None: new_end = int(time()) + self.autoincreasetime else: new_end = entry.begin -30<|fim▁hole|> dummyentry = RecordTimerEntry(self.service_ref, self.begin, new_end, self.name, self.description, self.eit, disabled=True, justplay = self.justplay, afterEvent = self.afterEvent, dirname = self.dirname, tags = self.tags) dummyentry.disabled = self.disabled timersanitycheck = TimerSanityCheck(NavigationInstance.instance.RecordTimer.timer_list, dummyentry) if not timersanitycheck.check(): simulTimerList = timersanitycheck.getSimulTimerList() new_end = simulTimerList[1].begin del simulTimerList new_end -= 30 # 30 Sekunden Prepare-Zeit lassen del dummyentry if new_end <= time(): return False self.end = new_end return True def sendStandbyNotification(self, answer): if answer: Notifications.AddNotification(Screens.Standby.Standby) def sendTryQuitMainloopNotification(self, answer): if answer: Notifications.AddNotification(Screens.Standby.TryQuitMainloop, 1) def getNextActivation(self): if self.state == self.StateEnded: return self.end next_state = self.state + 1 return {self.StatePrepared: self.start_prepare, self.StateRunning: self.begin, self.StateEnded: self.end }[next_state] def failureCB(self, answer): if answer == True: self.log(13, "ok, zapped away") #NavigationInstance.instance.stopUserServices() NavigationInstance.instance.playService(self.service_ref.ref) else: self.log(14, "user didn't want to zap away, record will probably fail") def timeChanged(self): old_prepare = self.start_prepare self.start_prepare = self.begin - self.prepare_time self.backoff = 0 if int(old_prepare) != int(self.start_prepare): self.log(15, "record time changed, start prepare is now: %s" % ctime(self.start_prepare)) def gotRecordEvent(self, record, event): # TODO: this is not working (never true), please fix. (comparing two swig wrapped ePtrs) if self.__record_service.__deref__() != record.__deref__(): return self.log(16, "record event %d" % event) if event == iRecordableService.evRecordWriteError: print "WRITE ERROR on recording, disk full?" # show notification. the 'id' will make sure that it will be # displayed only once, even if more timers are failing at the # same time. (which is very likely in case of disk fullness) Notifications.AddPopup(text = _("Write error while recording. Disk full?\n"), type = MessageBox.TYPE_ERROR, timeout = 0, id = "DiskFullMessage") # ok, the recording has been stopped. we need to properly note # that in our state, with also keeping the possibility to re-try. # TODO: this has to be done. elif event == iRecordableService.evStart: text = _("A record has been started:\n%s") % self.name if self.dirnameHadToFallback: text = '\n'.join((text, _("Please note that the previously selected media could not be accessed and therefore the default directory is being used instead."))) if config.usage.show_message_when_recording_starts.value: Notifications.AddPopup(text = text, type = MessageBox.TYPE_INFO, timeout = 8) # we have record_service as property to automatically subscribe to record service events def setRecordService(self, service): if self.__record_service is not None: print "[remove callback]" NavigationInstance.instance.record_event.remove(self.gotRecordEvent) self.__record_service = service if self.__record_service is not None: print "[add callback]" NavigationInstance.instance.record_event.append(self.gotRecordEvent) record_service = property(lambda self: self.__record_service, setRecordService) def createTimer(xml): begin = int(xml.get("begin")) end = int(xml.get("end")) serviceref = ServiceReference(xml.get("serviceref").encode("utf-8")) description = xml.get("description").encode("utf-8") repeated = xml.get("repeated").encode("utf-8") disabled = long(xml.get("disabled") or "0") justplay = long(xml.get("justplay") or "0") afterevent = str(xml.get("afterevent") or "nothing") afterevent = { "nothing": AFTEREVENT.NONE, "standby": AFTEREVENT.STANDBY, "deepstandby": AFTEREVENT.DEEPSTANDBY, "auto": AFTEREVENT.AUTO }[afterevent] eit = xml.get("eit") if eit and eit != "None": eit = long(eit); else: eit = None location = xml.get("location") if location and location != "None": location = location.encode("utf-8") else: location = None tags = xml.get("tags") if tags and tags != "None": tags = tags.encode("utf-8").split(' ') else: tags = None name = xml.get("name").encode("utf-8") #filename = xml.get("filename").encode("utf-8") entry = RecordTimerEntry(serviceref, begin, end, name, description, eit, disabled, justplay, afterevent, dirname = location, tags = tags) entry.repeated = int(repeated) for l in xml.findall("log"): time = int(l.get("time")) code = int(l.get("code")) msg = l.text.strip().encode("utf-8") entry.log_entries.append((time, code, msg)) return entry class RecordTimer(timer.Timer): def __init__(self): timer.Timer.__init__(self) self.Filename = Directories.resolveFilename(Directories.SCOPE_CONFIG, "timers.xml") try: self.loadTimer() except IOError: print "unable to load timers from file!" def doActivate(self, w): # when activating a timer which has already passed, # simply abort the timer. don't run trough all the stages. if w.shouldSkip(): w.state = RecordTimerEntry.StateEnded else: # when active returns true, this means "accepted". # otherwise, the current state is kept. # the timer entry itself will fix up the delay then. if w.activate(): w.state += 1 self.timer_list.remove(w) # did this timer reached the last state? if w.state < RecordTimerEntry.StateEnded: # no, sort it into active list insort(self.timer_list, w) else: # yes. Process repeated, and re-add. if w.repeated: w.processRepeated() w.state = RecordTimerEntry.StateWaiting self.addTimerEntry(w) else: # Remove old timers as set in config self.cleanupDaily(config.recording.keep_timers.value) insort(self.processed_timers, w) self.stateChanged(w) def isRecording(self): isRunning = False for timer in self.timer_list: if timer.isRunning() and not timer.justplay: isRunning = True return isRunning def loadTimer(self): # TODO: PATH! if not Directories.fileExists(self.Filename): return try: doc = xml.etree.cElementTree.parse(self.Filename) except SyntaxError: from Tools.Notifications import AddPopup from Screens.MessageBox import MessageBox AddPopup(_("The timer file (timers.xml) is corrupt and could not be loaded."), type = MessageBox.TYPE_ERROR, timeout = 0, id = "TimerLoadFailed") print "timers.xml failed to load!" try: import os os.rename(self.Filename, self.Filename + "_old") except (IOError, OSError): print "renaming broken timer failed" return except IOError: print "timers.xml not found!" return root = doc.getroot() # put out a message when at least one timer overlaps checkit = True for timer in root.findall("timer"): newTimer = createTimer(timer) if (self.record(newTimer, True, dosave=False) is not None) and (checkit == True): from Tools.Notifications import AddPopup from Screens.MessageBox import MessageBox AddPopup(_("Timer overlap in timers.xml detected!\nPlease recheck it!"), type = MessageBox.TYPE_ERROR, timeout = 0, id = "TimerLoadFailed") checkit = False # at moment it is enough when the message is displayed one time def saveTimer(self): #root_element = xml.etree.cElementTree.Element('timers') #root_element.text = "\n" #for timer in self.timer_list + self.processed_timers: # some timers (instant records) don't want to be saved. # skip them #if timer.dontSave: #continue #t = xml.etree.cElementTree.SubElement(root_element, 'timers') #t.set("begin", str(int(timer.begin))) #t.set("end", str(int(timer.end))) #t.set("serviceref", str(timer.service_ref)) #t.set("repeated", str(timer.repeated)) #t.set("name", timer.name) #t.set("description", timer.description) #t.set("afterevent", str({ # AFTEREVENT.NONE: "nothing", # AFTEREVENT.STANDBY: "standby", # AFTEREVENT.DEEPSTANDBY: "deepstandby", # AFTEREVENT.AUTO: "auto"})) #if timer.eit is not None: # t.set("eit", str(timer.eit)) #if timer.dirname is not None: # t.set("location", str(timer.dirname)) #t.set("disabled", str(int(timer.disabled))) #t.set("justplay", str(int(timer.justplay))) #t.text = "\n" #t.tail = "\n" #for time, code, msg in timer.log_entries: #l = xml.etree.cElementTree.SubElement(t, 'log') #l.set("time", str(time)) #l.set("code", str(code)) #l.text = str(msg) #l.tail = "\n" #doc = xml.etree.cElementTree.ElementTree(root_element) #doc.write(self.Filename) list = [] list.append('<?xml version="1.0" ?>\n') list.append('<timers>\n') for timer in self.timer_list + self.processed_timers: if timer.dontSave: continue list.append('<timer') list.append(' begin="' + str(int(timer.begin)) + '"') list.append(' end="' + str(int(timer.end)) + '"') list.append(' serviceref="' + stringToXML(str(timer.service_ref)) + '"') list.append(' repeated="' + str(int(timer.repeated)) + '"') list.append(' name="' + str(stringToXML(timer.name)) + '"') list.append(' description="' + str(stringToXML(timer.description)) + '"') list.append(' afterevent="' + str(stringToXML({ AFTEREVENT.NONE: "nothing", AFTEREVENT.STANDBY: "standby", AFTEREVENT.DEEPSTANDBY: "deepstandby", AFTEREVENT.AUTO: "auto" }[timer.afterEvent])) + '"') if timer.eit is not None: list.append(' eit="' + str(timer.eit) + '"') if timer.dirname is not None: list.append(' location="' + str(stringToXML(timer.dirname)) + '"') if timer.tags is not None: list.append(' tags="' + str(stringToXML(' '.join(timer.tags))) + '"') list.append(' disabled="' + str(int(timer.disabled)) + '"') list.append(' justplay="' + str(int(timer.justplay)) + '"') list.append('>\n') if config.recording.debug.value: for time, code, msg in timer.log_entries: list.append('<log') list.append(' code="' + str(code) + '"') list.append(' time="' + str(time) + '"') list.append('>') list.append(str(stringToXML(msg))) list.append('</log>\n') list.append('</timer>\n') list.append('</timers>\n') file = open(self.Filename, "w") for x in list: file.write(x) file.close() def getNextZapTime(self): now = time() for timer in self.timer_list: if not timer.justplay or timer.begin < now: continue return timer.begin return -1 def getNextRecordingTime(self): now = time() for timer in self.timer_list: next_act = timer.getNextActivation() if timer.justplay or next_act < now: continue return next_act return -1 def isNextRecordAfterEventActionAuto(self): now = time() t = None for timer in self.timer_list: if timer.justplay or timer.begin < now: continue if t is None or t.begin == timer.begin: t = timer if t.afterEvent == AFTEREVENT.AUTO: return True return False def record(self, entry, ignoreTSC=False, dosave=True): #wird von loadTimer mit dosave=False aufgerufen timersanitycheck = TimerSanityCheck(self.timer_list,entry) if not timersanitycheck.check(): if ignoreTSC != True: print "timer conflict detected!" print timersanitycheck.getSimulTimerList() return timersanitycheck.getSimulTimerList() else: print "ignore timer conflict" elif timersanitycheck.doubleCheck(): print "ignore double timer" return None entry.timeChanged() print "[Timer] Record " + str(entry) entry.Timer = self self.addTimerEntry(entry) if dosave: self.saveTimer() return None def isInTimer(self, eventid, begin, duration, service): time_match = 0 chktime = None chktimecmp = None chktimecmp_end = None end = begin + duration refstr = str(service) for x in self.timer_list: check = x.service_ref.ref.toString() == refstr if not check: sref = x.service_ref.ref parent_sid = sref.getUnsignedData(5) parent_tsid = sref.getUnsignedData(6) if parent_sid and parent_tsid: # check for subservice sid = sref.getUnsignedData(1) tsid = sref.getUnsignedData(2) sref.setUnsignedData(1, parent_sid) sref.setUnsignedData(2, parent_tsid) sref.setUnsignedData(5, 0) sref.setUnsignedData(6, 0) check = sref.toCompareString() == refstr num = 0 if check: check = False event = eEPGCache.getInstance().lookupEventId(sref, eventid) num = event and event.getNumOfLinkageServices() or 0 sref.setUnsignedData(1, sid) sref.setUnsignedData(2, tsid) sref.setUnsignedData(5, parent_sid) sref.setUnsignedData(6, parent_tsid) for cnt in range(num): subservice = event.getLinkageService(sref, cnt) if sref.toCompareString() == subservice.toCompareString(): check = True break if check: if x.repeated != 0: if chktime is None: chktime = localtime(begin) chktimecmp = chktime.tm_wday * 1440 + chktime.tm_hour * 60 + chktime.tm_min chktimecmp_end = chktimecmp + (duration / 60) time = localtime(x.begin) for y in (0, 1, 2, 3, 4, 5, 6): if x.repeated & (1 << y) and (x.begin <= begin or begin <= x.begin <= end): timecmp = y * 1440 + time.tm_hour * 60 + time.tm_min if timecmp <= chktimecmp < (timecmp + ((x.end - x.begin) / 60)): time_match = ((timecmp + ((x.end - x.begin) / 60)) - chktimecmp) * 60 elif chktimecmp <= timecmp < chktimecmp_end: time_match = (chktimecmp_end - timecmp) * 60 else: #if x.eit is None: if begin <= x.begin <= end: diff = end - x.begin if time_match < diff: time_match = diff elif x.begin <= begin <= x.end: diff = x.end - begin if time_match < diff: time_match = diff if time_match: break return time_match def removeEntry(self, entry): print "[Timer] Remove " + str(entry) # avoid re-enqueuing entry.repeated = False # abort timer. # this sets the end time to current time, so timer will be stopped. entry.autoincrease = False entry.abort() if entry.state != entry.StateEnded: self.timeChanged(entry) print "state: ", entry.state print "in processed: ", entry in self.processed_timers print "in running: ", entry in self.timer_list # autoincrease instanttimer if possible if not entry.dontSave: for x in self.timer_list: if x.setAutoincreaseEnd(): self.timeChanged(x) # now the timer should be in the processed_timers list. remove it from there. self.processed_timers.remove(entry) self.saveTimer() def shutdown(self): self.saveTimer()<|fim▁end|>
<|file_name|>zone.py<|end_file_name|><|fim▁begin|><|fim▁hole|>Support for the definition of zones. For more details about this component, please refer to the documentation at https://home-assistant.io/components/zone/ """ import logging import voluptuous as vol from homeassistant.const import ( ATTR_HIDDEN, ATTR_LATITUDE, ATTR_LONGITUDE, CONF_NAME, CONF_LATITUDE, CONF_LONGITUDE, CONF_ICON) from homeassistant.helpers import config_per_platform from homeassistant.helpers.entity import Entity, generate_entity_id from homeassistant.util.location import distance import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) ATTR_PASSIVE = 'passive' ATTR_RADIUS = 'radius' CONF_PASSIVE = 'passive' CONF_RADIUS = 'radius' DEFAULT_NAME = 'Unnamed zone' DEFAULT_PASSIVE = False DEFAULT_RADIUS = 100 DOMAIN = 'zone' ENTITY_ID_FORMAT = 'zone.{}' ENTITY_ID_HOME = ENTITY_ID_FORMAT.format('home') ICON_HOME = 'mdi:home' ICON_IMPORT = 'mdi:import' STATE = 'zoning' # The config that zone accepts is the same as if it has platforms. PLATFORM_SCHEMA = vol.Schema({ vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Required(CONF_LATITUDE): cv.latitude, vol.Required(CONF_LONGITUDE): cv.longitude, vol.Optional(CONF_RADIUS, default=DEFAULT_RADIUS): vol.Coerce(float), vol.Optional(CONF_PASSIVE, default=DEFAULT_PASSIVE): cv.boolean, vol.Optional(CONF_ICON): cv.icon, }) def active_zone(hass, latitude, longitude, radius=0): """Find the active zone for given latitude, longitude.""" # Sort entity IDs so that we are deterministic if equal distance to 2 zones zones = (hass.states.get(entity_id) for entity_id in sorted(hass.states.entity_ids(DOMAIN))) min_dist = None closest = None for zone in zones: if zone.attributes.get(ATTR_PASSIVE): continue zone_dist = distance( latitude, longitude, zone.attributes[ATTR_LATITUDE], zone.attributes[ATTR_LONGITUDE]) within_zone = zone_dist - radius < zone.attributes[ATTR_RADIUS] closer_zone = closest is None or zone_dist < min_dist smaller_zone = (zone_dist == min_dist and zone.attributes[ATTR_RADIUS] < closest.attributes[ATTR_RADIUS]) if within_zone and (closer_zone or smaller_zone): min_dist = zone_dist closest = zone return closest def in_zone(zone, latitude, longitude, radius=0): """Test if given latitude, longitude is in given zone.""" zone_dist = distance( latitude, longitude, zone.attributes[ATTR_LATITUDE], zone.attributes[ATTR_LONGITUDE]) return zone_dist - radius < zone.attributes[ATTR_RADIUS] def setup(hass, config): """Setup zone.""" entities = set() for _, entry in config_per_platform(config, DOMAIN): name = entry.get(CONF_NAME) zone = Zone(hass, name, entry[CONF_LATITUDE], entry[CONF_LONGITUDE], entry.get(CONF_RADIUS), entry.get(CONF_ICON), entry.get(CONF_PASSIVE)) zone.entity_id = generate_entity_id(ENTITY_ID_FORMAT, name, entities) zone.update_ha_state() entities.add(zone.entity_id) if ENTITY_ID_HOME not in entities: zone = Zone(hass, hass.config.location_name, hass.config.latitude, hass.config.longitude, DEFAULT_RADIUS, ICON_HOME, False) zone.entity_id = ENTITY_ID_HOME zone.update_ha_state() return True class Zone(Entity): """Representation of a Zone.""" # pylint: disable=too-many-arguments, too-many-instance-attributes def __init__(self, hass, name, latitude, longitude, radius, icon, passive): """Initialize the zone.""" self.hass = hass self._name = name self._latitude = latitude self._longitude = longitude self._radius = radius self._icon = icon self._passive = passive @property def name(self): """Return the name of the zone.""" return self._name @property def state(self): """Return the state property really does nothing for a zone.""" return STATE @property def icon(self): """Return the icon if any.""" return self._icon @property def state_attributes(self): """Return the state attributes of the zone.""" data = { ATTR_HIDDEN: True, ATTR_LATITUDE: self._latitude, ATTR_LONGITUDE: self._longitude, ATTR_RADIUS: self._radius, } if self._passive: data[ATTR_PASSIVE] = self._passive return data<|fim▁end|>
"""
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>// Copyright 2014 The html5ever Project Developers. See the // COPYRIGHT file at the top-level directory of this distribution. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! The HTML5 tokenizer. #![allow(unused_imports)] pub use self::interface::{Doctype, Attribute, TagKind, StartTag, EndTag, Tag}; pub use self::interface::{Token, DoctypeToken, TagToken, CommentToken}; pub use self::interface::{CharacterTokens, NullCharacterToken, EOFToken, ParseError}; pub use self::interface::TokenSink; use self::states::{RawLessThanSign, RawEndTagOpen, RawEndTagName}; use self::states::{Rcdata, Rawtext, ScriptData, ScriptDataEscaped}; use self::states::{Escaped, DoubleEscaped}; use self::states::{Unquoted, SingleQuoted, DoubleQuoted}; use self::states::{DoctypeIdKind, Public, System}; use self::char_ref::{CharRef, CharRefTokenizer}; use self::buffer_queue::{BufferQueue, SetResult, FromSet, NotFromSet}; use util::str::lower_ascii_letter; use util::smallcharset::SmallCharSet; use std::ascii::AsciiExt; use std::mem::replace; use std::default::Default; use std::borrow::Cow::{self, Borrowed}; use std::collections::BTreeMap; use string_cache::{Atom, QualName}; use tendril::StrTendril; pub mod states; mod interface; mod char_ref; mod buffer_queue; fn option_push(opt_str: &mut Option<StrTendril>, c: char) { match *opt_str { Some(ref mut s) => s.push_char(c), None => *opt_str = Some(StrTendril::from_char(c)), } } /// Tokenizer options, with an impl for `Default`. #[derive(Clone)] pub struct TokenizerOpts { /// Report all parse errors described in the spec, at some /// performance penalty? Default: false pub exact_errors: bool, /// Discard a `U+FEFF BYTE ORDER MARK` if we see one at the beginning /// of the stream? Default: true pub discard_bom: bool, /// Keep a record of how long we spent in each state? Printed /// when `end()` is called. Default: false pub profile: bool, /// Initial state override. Only the test runner should use /// a non-`None` value! pub initial_state: Option<states::State>, /// Last start tag. Only the test runner should use a /// non-`None` value! /// /// FIXME: Can't use Tendril because we want TokenizerOpts /// to be Send. pub last_start_tag_name: Option<String>, } impl Default for TokenizerOpts { fn default() -> TokenizerOpts { TokenizerOpts { exact_errors: false, discard_bom: true, profile: false, initial_state: None, last_start_tag_name: None, } } } /// The HTML tokenizer. pub struct Tokenizer<Sink> { /// Options controlling the behavior of the tokenizer. opts: TokenizerOpts, /// Destination for tokens we emit. sink: Sink, /// The abstract machine state as described in the spec. state: states::State, /// Input ready to be tokenized. input_buffers: BufferQueue, /// Are we at the end of the file, once buffers have been processed /// completely? This affects whether we will wait for lookahead or not. at_eof: bool, /// Tokenizer for character references, if we're tokenizing /// one at the moment. char_ref_tokenizer: Option<Box<CharRefTokenizer>>, /// Current input character. Just consumed, may reconsume. current_char: char, /// Should we reconsume the current input character? reconsume: bool, /// Did we just consume \r, translating it to \n? In that case we need /// to ignore the next character if it's \n. ignore_lf: bool, /// Discard a U+FEFF BYTE ORDER MARK if we see one? Only done at the /// beginning of the stream. discard_bom: bool, /// Current tag kind. current_tag_kind: TagKind, /// Current tag name. current_tag_name: StrTendril, /// Current tag is self-closing? current_tag_self_closing: bool, /// Current tag attributes. current_tag_attrs: Vec<Attribute>, /// Current attribute name. current_attr_name: StrTendril, /// Current attribute value. current_attr_value: StrTendril, /// Current comment. current_comment: StrTendril, /// Current doctype token. current_doctype: Doctype, /// Last start tag name, for use in checking "appropriate end tag". last_start_tag_name: Option<Atom>, /// The "temporary buffer" mentioned in the spec. temp_buf: StrTendril, /// Record of how many ns we spent in each state, if profiling is enabled. state_profile: BTreeMap<states::State, u64>, /// Record of how many ns we spent in the token sink. time_in_sink: u64, } impl<Sink: TokenSink> Tokenizer<Sink> { /// Create a new tokenizer which feeds tokens to a particular `TokenSink`. pub fn new(sink: Sink, mut opts: TokenizerOpts) -> Tokenizer<Sink> { let start_tag_name = opts.last_start_tag_name.take() .map(|s| Atom::from(&*s)); let state = opts.initial_state.unwrap_or(states::Data); let discard_bom = opts.discard_bom; Tokenizer { opts: opts, sink: sink, state: state, char_ref_tokenizer: None, input_buffers: BufferQueue::new(), at_eof: false, current_char: '\0', reconsume: false, ignore_lf: false, discard_bom: discard_bom, current_tag_kind: StartTag, current_tag_name: StrTendril::new(), current_tag_self_closing: false, current_tag_attrs: vec!(), current_attr_name: StrTendril::new(), current_attr_value: StrTendril::new(), current_comment: StrTendril::new(), current_doctype: Doctype::new(), last_start_tag_name: start_tag_name, temp_buf: StrTendril::new(), state_profile: BTreeMap::new(), time_in_sink: 0, } } pub fn unwrap(self) -> Sink { self.sink } pub fn sink<'a>(&'a self) -> &'a Sink { &self.sink } pub fn sink_mut<'a>(&'a mut self) -> &'a mut Sink { &mut self.sink } /// Feed an input string into the tokenizer. pub fn feed(&mut self, mut input: StrTendril) { if input.is_empty() { return; } if self.discard_bom && input.starts_with("\u{feff}") { input.pop_front(3); }; self.input_buffers.push_back(input); self.run(); } pub fn set_plaintext_state(&mut self) { self.state = states::Plaintext; } fn process_token(&mut self, token: Token) { if self.opts.profile { let (_, dt) = time!(self.sink.process_token(token)); self.time_in_sink += dt; } else { self.sink.process_token(token); } } //§ preprocessing-the-input-stream // Get the next input character, which might be the character // 'c' that we already consumed from the buffers. fn get_preprocessed_char(&mut self, mut c: char) -> Option<char> { if self.ignore_lf { self.ignore_lf = false; if c == '\n' { c = unwrap_or_return!(self.input_buffers.next(), None); } } if c == '\r' { self.ignore_lf = true; c = '\n'; } if self.opts.exact_errors && match c as u32 { 0x01...0x08 | 0x0B | 0x0E...0x1F | 0x7F...0x9F | 0xFDD0...0xFDEF => true, n if (n & 0xFFFE) == 0xFFFE => true, _ => false, } { let msg = format!("Bad character {}", c); self.emit_error(Cow::Owned(msg)); } debug!("got character {}", c); self.current_char = c; Some(c) } //§ tokenization // Get the next input character, if one is available. fn get_char(&mut self) -> Option<char> { if self.reconsume { self.reconsume = false; Some(self.current_char) } else { self.input_buffers.next() .and_then(|c| self.get_preprocessed_char(c)) } } fn pop_except_from(&mut self, set: SmallCharSet) -> Option<SetResult> { // Bail to the slow path for various corner cases. // This means that `FromSet` can contain characters not in the set! // It shouldn't matter because the fallback `FromSet` case should // always do the same thing as the `NotFromSet` case. if self.opts.exact_errors || self.reconsume || self.ignore_lf { return self.get_char().map(|x| FromSet(x)); } let d = self.input_buffers.pop_except_from(set); debug!("got characters {:?}", d); match d { Some(FromSet(c)) => self.get_preprocessed_char(c).map(|x| FromSet(x)), // NB: We don't set self.current_char for a run of characters not // in the set. It shouldn't matter for the codepaths that use // this. _ => d } } // Check if the next characters are an ASCII case-insensitive match. See // BufferQueue::eat. // // NB: this doesn't do input stream preprocessing or set the current input // character. fn eat(&mut self, pat: &str, eq: fn(&u8, &u8) -> bool) -> Option<bool> { match self.input_buffers.eat(pat, eq) { None if self.at_eof => Some(false), r => r, } } /// Run the state machine for as long as we can. pub fn run(&mut self) { if self.opts.profile { loop { let state = self.state; let old_sink = self.time_in_sink; let (run, mut dt) = time!(self.step()); dt -= (self.time_in_sink - old_sink); let new = match self.state_profile.get_mut(&state) { Some(x) => { *x += dt; false } None => true, }; if new { // do this here because of borrow shenanigans self.state_profile.insert(state, dt); } if !run { break; } } } else { while self.step() { } } } fn bad_char_error(&mut self) { let msg = format_if!( self.opts.exact_errors, "Bad character", "Saw {} in state {:?}", self.current_char, self.state); self.emit_error(msg); } fn bad_eof_error(&mut self) { let msg = format_if!( self.opts.exact_errors, "Unexpected EOF", "Saw EOF in state {:?}", self.state); self.emit_error(msg); } fn emit_char(&mut self, c: char) { self.process_token(match c { '\0' => NullCharacterToken, _ => CharacterTokens(StrTendril::from_char(c)), }); } // The string must not contain '\0'! fn emit_chars(&mut self, b: StrTendril) { self.process_token(CharacterTokens(b)); } fn emit_current_tag(&mut self) { self.finish_attribute(); let name = Atom::from(&*self.current_tag_name); self.current_tag_name.clear(); match self.current_tag_kind { StartTag => { self.last_start_tag_name = Some(name.clone()); } EndTag => { if !self.current_tag_attrs.is_empty() { self.emit_error(Borrowed("Attributes on an end tag")); } if self.current_tag_self_closing { self.emit_error(Borrowed("Self-closing end tag")); } } } let token = TagToken(Tag { kind: self.current_tag_kind, name: name, self_closing: self.current_tag_self_closing, attrs: replace(&mut self.current_tag_attrs, vec!()), }); self.process_token(token); match self.sink.query_state_change() { None => (), Some(s) => self.state = s, } } fn emit_temp_buf(&mut self) { // FIXME: Make sure that clearing on emit is spec-compatible. let buf = replace(&mut self.temp_buf, StrTendril::new()); self.emit_chars(buf); } fn clear_temp_buf(&mut self) { // Do this without a new allocation. self.temp_buf.clear(); } fn emit_current_comment(&mut self) { let comment = replace(&mut self.current_comment, StrTendril::new()); self.process_token(CommentToken(comment)); } fn discard_tag(&mut self) { self.current_tag_name.clear(); self.current_tag_self_closing = false; self.current_tag_attrs = vec!(); } fn create_tag(&mut self, kind: TagKind, c: char) { self.discard_tag(); self.current_tag_name.push_char(c); self.current_tag_kind = kind; } fn have_appropriate_end_tag(&self) -> bool { match self.last_start_tag_name.as_ref() { Some(last) => (self.current_tag_kind == EndTag) && (*self.current_tag_name == **last), None => false, } } fn create_attribute(&mut self, c: char) { self.finish_attribute(); self.current_attr_name.push_char(c); } fn finish_attribute(&mut self) { if self.current_attr_name.len() == 0 { return; } // Check for a duplicate attribute. // FIXME: the spec says we should error as soon as the name is finished. // FIXME: linear time search, do we care? let dup = { let name = &*self.current_attr_name; self.current_tag_attrs.iter().any(|a| &*a.name.local == name) }; if dup { self.emit_error(Borrowed("Duplicate attribute")); self.current_attr_name.clear(); self.current_attr_value.clear(); } else { let name = Atom::from(&*self.current_attr_name); self.current_attr_name.clear(); self.current_tag_attrs.push(Attribute { // The tree builder will adjust the namespace if necessary. // This only happens in foreign elements. name: QualName::new(ns!(), name), value: replace(&mut self.current_attr_value, StrTendril::new()), }); } } fn emit_current_doctype(&mut self) { let doctype = replace(&mut self.current_doctype, Doctype::new()); self.process_token(DoctypeToken(doctype)); } fn doctype_id<'a>(&'a mut self, kind: DoctypeIdKind) -> &'a mut Option<StrTendril> { match kind { Public => &mut self.current_doctype.public_id, System => &mut self.current_doctype.system_id, } } fn clear_doctype_id(&mut self, kind: DoctypeIdKind) { let id = self.doctype_id(kind); match *id { Some(ref mut s) => s.clear(), None => *id = Some(StrTendril::new()), } } fn consume_char_ref(&mut self, addnl_allowed: Option<char>) { // NB: The char ref tokenizer assumes we have an additional allowed // character iff we're tokenizing in an attribute value. self.char_ref_tokenizer = Some(Box::new(CharRefTokenizer::new(addnl_allowed))); } fn emit_eof(&mut self) { self.process_token(EOFToken); } fn peek(&mut self) -> Option<char> { if self.reconsume { Some(self.current_char) } else { self.input_buffers.peek() } } fn discard_char(&mut self) { let c = self.get_char(); assert!(c.is_some()); } fn unconsume(&mut self, buf: StrTendril) { self.input_buffers.push_front(buf); } fn emit_error(&mut self, error: Cow<'static, str>) { self.process_token(ParseError(error)); } } //§ END // Shorthand for common state machine behaviors. macro_rules! shorthand ( ( $me:ident : emit $c:expr ) => ( $me.emit_char($c); ); ( $me:ident : create_tag $kind:ident $c:expr ) => ( $me.create_tag($kind, $c); ); ( $me:ident : push_tag $c:expr ) => ( $me.current_tag_name.push_char($c); ); ( $me:ident : discard_tag ) => ( $me.discard_tag(); ); ( $me:ident : discard_char ) => ( $me.discard_char(); ); ( $me:ident : push_temp $c:expr ) => ( $me.temp_buf.push_char($c); ); ( $me:ident : emit_temp ) => ( $me.emit_temp_buf(); ); ( $me:ident : clear_temp ) => ( $me.clear_temp_buf(); ); ( $me:ident : create_attr $c:expr ) => ( $me.create_attribute($c); ); ( $me:ident : push_name $c:expr ) => ( $me.current_attr_name.push_char($c); ); ( $me:ident : push_value $c:expr ) => ( $me.current_attr_value.push_char($c); ); ( $me:ident : append_value $c:expr ) => ( $me.current_attr_value.push_tendril($c); ); ( $me:ident : push_comment $c:expr ) => ( $me.current_comment.push_char($c); ); ( $me:ident : append_comment $c:expr ) => ( $me.current_comment.push_slice($c); ); ( $me:ident : emit_comment ) => ( $me.emit_current_comment(); ); ( $me:ident : clear_comment ) => ( $me.current_comment.clear(); ); ( $me:ident : create_doctype ) => ( $me.current_doctype = Doctype::new(); ); ( $me:ident : push_doctype_name $c:expr ) => ( option_push(&mut $me.current_doctype.name, $c); ); ( $me:ident : push_doctype_id $k:ident $c:expr ) => ( option_push($me.doctype_id($k), $c); ); ( $me:ident : clear_doctype_id $k:ident ) => ( $me.clear_doctype_id($k); ); ( $me:ident : force_quirks ) => ( $me.current_doctype.force_quirks = true; ); ( $me:ident : emit_doctype ) => ( $me.emit_current_doctype(); ); ( $me:ident : error ) => ( $me.bad_char_error(); ); ( $me:ident : error_eof ) => ( $me.bad_eof_error(); ); ); // Tracing of tokenizer actions. This adds significant bloat and compile time, // so it's behind a cfg flag. #[cfg(trace_tokenizer)] macro_rules! sh_trace ( ( $me:ident : $($cmds:tt)* ) => ({ debug!(" {:s}", stringify!($($cmds)*)); shorthand!($me:expr : $($cmds)*); })); #[cfg(not(trace_tokenizer))] macro_rules! sh_trace ( ( $me:ident : $($cmds:tt)* ) => ( shorthand!($me: $($cmds)*) ) ); // A little DSL for sequencing shorthand actions. macro_rules! go ( // A pattern like $($cmd:tt)* ; $($rest:tt)* causes parse ambiguity. // We have to tell the parser how much lookahead we need. ( $me:ident : $a:tt ; $($rest:tt)* ) => ({ sh_trace!($me: $a); go!($me: $($rest)*); }); ( $me:ident : $a:tt $b:tt ; $($rest:tt)* ) => ({ sh_trace!($me: $a $b); go!($me: $($rest)*); }); ( $me:ident : $a:tt $b:tt $c:tt ; $($rest:tt)* ) => ({ sh_trace!($me: $a $b $c); go!($me: $($rest)*); }); ( $me:ident : $a:tt $b:tt $c:tt $d:tt ; $($rest:tt)* ) => ({ sh_trace!($me: $a $b $c $d); go!($me: $($rest)*); }); // These can only come at the end. ( $me:ident : to $s:ident ) => ({ $me.state = states::$s; return true; }); ( $me:ident : to $s:ident $k1:expr ) => ({ $me.state = states::$s($k1); return true; }); ( $me:ident : to $s:ident $k1:ident $k2:expr ) => ({ $me.state = states::$s($k1($k2)); return true; }); ( $me:ident : reconsume $s:ident ) => ({ $me.reconsume = true; go!($me: to $s); }); ( $me:ident : reconsume $s:ident $k1:expr ) => ({ $me.reconsume = true; go!($me: to $s $k1); }); ( $me:ident : reconsume $s:ident $k1:ident $k2:expr ) => ({ $me.reconsume = true; go!($me: to $s $k1 $k2); }); ( $me:ident : consume_char_ref ) => ({ $me.consume_char_ref(None); return true; }); ( $me:ident : consume_char_ref $addnl:expr ) => ({ $me.consume_char_ref(Some($addnl)); return true; }); // We have a default next state after emitting a tag, but the sink can override. ( $me:ident : emit_tag $s:ident ) => ({ $me.state = states::$s; $me.emit_current_tag(); return true; }); ( $me:ident : eof ) => ({ $me.emit_eof(); return false; }); // If nothing else matched, it's a single command ( $me:ident : $($cmd:tt)+ ) => ( sh_trace!($me: $($cmd)+); ); // or nothing. ( $me:ident : ) => (()); ); macro_rules! go_match ( ( $me:ident : $x:expr, $($pats:pat),+ => $($cmds:tt)* ) => ( match $x { $($pats)|+ => go!($me: $($cmds)*), _ => (), } )); // This is a macro because it can cause early return // from the function where it is used. macro_rules! get_char ( ($me:expr) => ( unwrap_or_return!($me.get_char(), false) )); macro_rules! peek ( ($me:expr) => ( unwrap_or_return!($me.peek(), false) )); macro_rules! pop_except_from ( ($me:expr, $set:expr) => ( unwrap_or_return!($me.pop_except_from($set), false) )); macro_rules! eat ( ($me:expr, $pat:expr) => ( unwrap_or_return!($me.eat($pat, u8::eq_ignore_ascii_case), false) )); macro_rules! eat_exact ( ($me:expr, $pat:expr) => ( unwrap_or_return!($me.eat($pat, u8::eq), false) )); impl<Sink: TokenSink> Tokenizer<Sink> { // Run the state machine for a while. // Return true if we should be immediately re-invoked // (this just simplifies control flow vs. break / continue). fn step(&mut self) -> bool { if self.char_ref_tokenizer.is_some() { return self.step_char_ref_tokenizer(); } debug!("processing in state {:?}", self.state); match self.state { // Reachable only through `query_state_change`. The tree builder wants // the tokenizer to suspend processing. states::Quiescent => { self.state = states::Data; return false; } //§ data-state states::Data => loop { match pop_except_from!(self, small_char_set!('\r' '\0' '&' '<')) { FromSet('\0') => go!(self: error; emit '\0'), FromSet('&') => go!(self: consume_char_ref), FromSet('<') => go!(self: to TagOpen), FromSet(c) => go!(self: emit c), NotFromSet(b) => self.emit_chars(b), } }, //§ rcdata-state states::RawData(Rcdata) => loop { match pop_except_from!(self, small_char_set!('\r' '\0' '&' '<')) { FromSet('\0') => go!(self: error; emit '\u{fffd}'), FromSet('&') => go!(self: consume_char_ref), FromSet('<') => go!(self: to RawLessThanSign Rcdata), FromSet(c) => go!(self: emit c), NotFromSet(b) => self.emit_chars(b), } }, //§ rawtext-state states::RawData(Rawtext) => loop { match pop_except_from!(self, small_char_set!('\r' '\0' '<')) { FromSet('\0') => go!(self: error; emit '\u{fffd}'), FromSet('<') => go!(self: to RawLessThanSign Rawtext), FromSet(c) => go!(self: emit c), NotFromSet(b) => self.emit_chars(b), } }, //§ script-data-state states::RawData(ScriptData) => loop { match pop_except_from!(self, small_char_set!('\r' '\0' '<')) { FromSet('\0') => go!(self: error; emit '\u{fffd}'), FromSet('<') => go!(self: to RawLessThanSign ScriptData), FromSet(c) => go!(self: emit c), NotFromSet(b) => self.emit_chars(b), } }, //§ script-data-escaped-state states::RawData(ScriptDataEscaped(Escaped)) => loop { match pop_except_from!(self, small_char_set!('\r' '\0' '-' '<')) { FromSet('\0') => go!(self: error; emit '\u{fffd}'), FromSet('-') => go!(self: emit '-'; to ScriptDataEscapedDash Escaped), FromSet('<') => go!(self: to RawLessThanSign ScriptDataEscaped Escaped), FromSet(c) => go!(self: emit c), NotFromSet(b) => self.emit_chars(b), } }, //§ script-data-double-escaped-state states::RawData(ScriptDataEscaped(DoubleEscaped)) => loop { match pop_except_from!(self, small_char_set!('\r' '\0' '-' '<')) { FromSet('\0') => go!(self: error; emit '\u{fffd}'), FromSet('-') => go!(self: emit '-'; to ScriptDataEscapedDash DoubleEscaped), FromSet('<') => go!(self: emit '<'; to RawLessThanSign ScriptDataEscaped DoubleEscaped), FromSet(c) => go!(self: emit c), NotFromSet(b) => self.emit_chars(b), } }, //§ plaintext-state states::Plaintext => loop { match pop_except_from!(self, small_char_set!('\r' '\0')) { FromSet('\0') => go!(self: error; emit '\u{fffd}'), FromSet(c) => go!(self: emit c), NotFromSet(b) => self.emit_chars(b), } }, //§ tag-open-state states::TagOpen => loop { match get_char!(self) { '!' => go!(self: to MarkupDeclarationOpen), '/' => go!(self: to EndTagOpen), '?' => go!(self: error; clear_comment; push_comment '?'; to BogusComment), c => match lower_ascii_letter(c) { Some(cl) => go!(self: create_tag StartTag cl; to TagName), None => go!(self: error; emit '<'; reconsume Data), } }}, //§ end-tag-open-state states::EndTagOpen => loop { match get_char!(self) { '>' => go!(self: error; to Data), '\0' => go!(self: error; clear_comment; push_comment '\u{fffd}'; to BogusComment), c => match lower_ascii_letter(c) { Some(cl) => go!(self: create_tag EndTag cl; to TagName), None => go!(self: error; clear_comment; push_comment c; to BogusComment), } }}, //§ tag-name-state states::TagName => loop { match get_char!(self) { '\t' | '\n' | '\x0C' | ' ' => go!(self: to BeforeAttributeName), '/' => go!(self: to SelfClosingStartTag), '>' => go!(self: emit_tag Data), '\0' => go!(self: error; push_tag '\u{fffd}'), c => go!(self: push_tag (c.to_ascii_lowercase())), }}, //§ script-data-escaped-less-than-sign-state states::RawLessThanSign(ScriptDataEscaped(Escaped)) => loop { match get_char!(self) { '/' => go!(self: clear_temp; to RawEndTagOpen ScriptDataEscaped Escaped), c => match lower_ascii_letter(c) { Some(cl) => go!(self: clear_temp; push_temp cl; emit '<'; emit c; to ScriptDataEscapeStart DoubleEscaped), None => go!(self: emit '<'; reconsume RawData ScriptDataEscaped Escaped), } }}, //§ script-data-double-escaped-less-than-sign-state states::RawLessThanSign(ScriptDataEscaped(DoubleEscaped)) => loop { match get_char!(self) { '/' => go!(self: clear_temp; emit '/'; to ScriptDataDoubleEscapeEnd), _ => go!(self: reconsume RawData ScriptDataEscaped DoubleEscaped), }}, //§ rcdata-less-than-sign-state rawtext-less-than-sign-state script-data-less-than-sign-state // otherwise states::RawLessThanSign(kind) => loop { match get_char!(self) { '/' => go!(self: clear_temp; to RawEndTagOpen kind), '!' if kind == ScriptData => go!(self: emit '<'; emit '!'; to ScriptDataEscapeStart Escaped), _ => go!(self: emit '<'; reconsume RawData kind), }}, //§ rcdata-end-tag-open-state rawtext-end-tag-open-state script-data-end-tag-open-state script-data-escaped-end-tag-open-state states::RawEndTagOpen(kind) => loop { let c = get_char!(self); match lower_ascii_letter(c) { Some(cl) => go!(self: create_tag EndTag cl; push_temp c; to RawEndTagName kind), None => go!(self: emit '<'; emit '/'; reconsume RawData kind), } }, //§ rcdata-end-tag-name-state rawtext-end-tag-name-state script-data-end-tag-name-state script-data-escaped-end-tag-name-state states::RawEndTagName(kind) => loop { let c = get_char!(self); if self.have_appropriate_end_tag() { match c { '\t' | '\n' | '\x0C' | ' ' => go!(self: to BeforeAttributeName), '/' => go!(self: to SelfClosingStartTag), '>' => go!(self: emit_tag Data), _ => (), } } match lower_ascii_letter(c) { Some(cl) => go!(self: push_tag cl; push_temp c), None => go!(self: discard_tag; emit '<'; emit '/'; emit_temp; reconsume RawData kind), } }, //§ script-data-double-escape-start-state states::ScriptDataEscapeStart(DoubleEscaped) => loop { let c = get_char!(self); match c { '\t' | '\n' | '\x0C' | ' ' | '/' | '>' => { let esc = if &*self.temp_buf == "script" { DoubleEscaped } else { Escaped }; go!(self: emit c; to RawData ScriptDataEscaped esc); } _ => match lower_ascii_letter(c) { Some(cl) => go!(self: push_temp cl; emit c), None => go!(self: reconsume RawData ScriptDataEscaped Escaped), } } }, //§ script-data-escape-start-state states::ScriptDataEscapeStart(Escaped) => loop { match get_char!(self) { '-' => go!(self: emit '-'; to ScriptDataEscapeStartDash), _ => go!(self: reconsume RawData ScriptData), }}, //§ script-data-escape-start-dash-state states::ScriptDataEscapeStartDash => loop { match get_char!(self) { '-' => go!(self: emit '-'; to ScriptDataEscapedDashDash Escaped), _ => go!(self: reconsume RawData ScriptData), }}, //§ script-data-escaped-dash-state script-data-double-escaped-dash-state states::ScriptDataEscapedDash(kind) => loop { match get_char!(self) { '-' => go!(self: emit '-'; to ScriptDataEscapedDashDash kind), '<' => { if kind == DoubleEscaped { go!(self: emit '<'); } go!(self: to RawLessThanSign ScriptDataEscaped kind); } '\0' => go!(self: error; emit '\u{fffd}'; to RawData ScriptDataEscaped kind), c => go!(self: emit c; to RawData ScriptDataEscaped kind), }}, //§ script-data-escaped-dash-dash-state script-data-double-escaped-dash-dash-state states::ScriptDataEscapedDashDash(kind) => loop { match get_char!(self) { '-' => go!(self: emit '-'), '<' => { if kind == DoubleEscaped { go!(self: emit '<'); } go!(self: to RawLessThanSign ScriptDataEscaped kind); } '>' => go!(self: emit '>'; to RawData ScriptData), '\0' => go!(self: error; emit '\u{fffd}'; to RawData ScriptDataEscaped kind), c => go!(self: emit c; to RawData ScriptDataEscaped kind), }}, //§ script-data-double-escape-end-state states::ScriptDataDoubleEscapeEnd => loop { let c = get_char!(self); match c { '\t' | '\n' | '\x0C' | ' ' | '/' | '>' => { let esc = if &*self.temp_buf == "script" { Escaped } else { DoubleEscaped }; go!(self: emit c; to RawData ScriptDataEscaped esc); }<|fim▁hole|> } } }, //§ before-attribute-name-state states::BeforeAttributeName => loop { match get_char!(self) { '\t' | '\n' | '\x0C' | ' ' => (), '/' => go!(self: to SelfClosingStartTag), '>' => go!(self: emit_tag Data), '\0' => go!(self: error; create_attr '\u{fffd}'; to AttributeName), c => match lower_ascii_letter(c) { Some(cl) => go!(self: create_attr cl; to AttributeName), None => { go_match!(self: c, '"' , '\'' , '<' , '=' => error); go!(self: create_attr c; to AttributeName); } } }}, //§ attribute-name-state states::AttributeName => loop { match get_char!(self) { '\t' | '\n' | '\x0C' | ' ' => go!(self: to AfterAttributeName), '/' => go!(self: to SelfClosingStartTag), '=' => go!(self: to BeforeAttributeValue), '>' => go!(self: emit_tag Data), '\0' => go!(self: error; push_name '\u{fffd}'), c => match lower_ascii_letter(c) { Some(cl) => go!(self: push_name cl), None => { go_match!(self: c, '"' , '\'' , '<' => error); go!(self: push_name c); } } }}, //§ after-attribute-name-state states::AfterAttributeName => loop { match get_char!(self) { '\t' | '\n' | '\x0C' | ' ' => (), '/' => go!(self: to SelfClosingStartTag), '=' => go!(self: to BeforeAttributeValue), '>' => go!(self: emit_tag Data), '\0' => go!(self: error; create_attr '\u{fffd}'; to AttributeName), c => match lower_ascii_letter(c) { Some(cl) => go!(self: create_attr cl; to AttributeName), None => { go_match!(self: c, '"' , '\'' , '<' => error); go!(self: create_attr c; to AttributeName); } } }}, //§ before-attribute-value-state // Use peek so we can handle the first attr character along with the rest, // hopefully in the same zero-copy buffer. states::BeforeAttributeValue => loop { match peek!(self) { '\t' | '\n' | '\r' | '\x0C' | ' ' => go!(self: discard_char), '"' => go!(self: discard_char; to AttributeValue DoubleQuoted), '&' => go!(self: to AttributeValue Unquoted), '\'' => go!(self: discard_char; to AttributeValue SingleQuoted), '\0' => go!(self: discard_char; error; push_value '\u{fffd}'; to AttributeValue Unquoted), '>' => go!(self: discard_char; error; emit_tag Data), _ => go!(self: to AttributeValue Unquoted), }}, //§ attribute-value-(double-quoted)-state states::AttributeValue(DoubleQuoted) => loop { match pop_except_from!(self, small_char_set!('\r' '"' '&' '\0')) { FromSet('"') => go!(self: to AfterAttributeValueQuoted), FromSet('&') => go!(self: consume_char_ref '"'), FromSet('\0') => go!(self: error; push_value '\u{fffd}'), FromSet(c) => go!(self: push_value c), NotFromSet(ref b) => go!(self: append_value b), } }, //§ attribute-value-(single-quoted)-state states::AttributeValue(SingleQuoted) => loop { match pop_except_from!(self, small_char_set!('\r' '\'' '&' '\0')) { FromSet('\'') => go!(self: to AfterAttributeValueQuoted), FromSet('&') => go!(self: consume_char_ref '\''), FromSet('\0') => go!(self: error; push_value '\u{fffd}'), FromSet(c) => go!(self: push_value c), NotFromSet(ref b) => go!(self: append_value b), } }, //§ attribute-value-(unquoted)-state states::AttributeValue(Unquoted) => loop { match pop_except_from!(self, small_char_set!('\r' '\t' '\n' '\x0C' ' ' '&' '>' '\0')) { FromSet('\t') | FromSet('\n') | FromSet('\x0C') | FromSet(' ') => go!(self: to BeforeAttributeName), FromSet('&') => go!(self: consume_char_ref '>'), FromSet('>') => go!(self: emit_tag Data), FromSet('\0') => go!(self: error; push_value '\u{fffd}'), FromSet(c) => { go_match!(self: c, '"' , '\'' , '<' , '=' , '`' => error); go!(self: push_value c); } NotFromSet(ref b) => go!(self: append_value b), } }, //§ after-attribute-value-(quoted)-state states::AfterAttributeValueQuoted => loop { match get_char!(self) { '\t' | '\n' | '\x0C' | ' ' => go!(self: to BeforeAttributeName), '/' => go!(self: to SelfClosingStartTag), '>' => go!(self: emit_tag Data), _ => go!(self: error; reconsume BeforeAttributeName), }}, //§ self-closing-start-tag-state states::SelfClosingStartTag => loop { match get_char!(self) { '>' => { self.current_tag_self_closing = true; go!(self: emit_tag Data); } _ => go!(self: error; reconsume BeforeAttributeName), }}, //§ comment-start-state states::CommentStart => loop { match get_char!(self) { '-' => go!(self: to CommentStartDash), '\0' => go!(self: error; push_comment '\u{fffd}'; to Comment), '>' => go!(self: error; emit_comment; to Data), c => go!(self: push_comment c; to Comment), }}, //§ comment-start-dash-state states::CommentStartDash => loop { match get_char!(self) { '-' => go!(self: to CommentEnd), '\0' => go!(self: error; append_comment "-\u{fffd}"; to Comment), '>' => go!(self: error; emit_comment; to Data), c => go!(self: push_comment '-'; push_comment c; to Comment), }}, //§ comment-state states::Comment => loop { match get_char!(self) { '-' => go!(self: to CommentEndDash), '\0' => go!(self: error; push_comment '\u{fffd}'), c => go!(self: push_comment c), }}, //§ comment-end-dash-state states::CommentEndDash => loop { match get_char!(self) { '-' => go!(self: to CommentEnd), '\0' => go!(self: error; append_comment "-\u{fffd}"; to Comment), c => go!(self: push_comment '-'; push_comment c; to Comment), }}, //§ comment-end-state states::CommentEnd => loop { match get_char!(self) { '>' => go!(self: emit_comment; to Data), '\0' => go!(self: error; append_comment "--\u{fffd}"; to Comment), '!' => go!(self: error; to CommentEndBang), '-' => go!(self: error; push_comment '-'), c => go!(self: error; append_comment "--"; push_comment c; to Comment), }}, //§ comment-end-bang-state states::CommentEndBang => loop { match get_char!(self) { '-' => go!(self: append_comment "--!"; to CommentEndDash), '>' => go!(self: emit_comment; to Data), '\0' => go!(self: error; append_comment "--!\u{fffd}"; to Comment), c => go!(self: append_comment "--!"; push_comment c; to Comment), }}, //§ doctype-state states::Doctype => loop { match get_char!(self) { '\t' | '\n' | '\x0C' | ' ' => go!(self: to BeforeDoctypeName), _ => go!(self: error; reconsume BeforeDoctypeName), }}, //§ before-doctype-name-state states::BeforeDoctypeName => loop { match get_char!(self) { '\t' | '\n' | '\x0C' | ' ' => (), '\0' => go!(self: error; create_doctype; push_doctype_name '\u{fffd}'; to DoctypeName), '>' => go!(self: error; create_doctype; force_quirks; emit_doctype; to Data), c => go!(self: create_doctype; push_doctype_name (c.to_ascii_lowercase()); to DoctypeName), }}, //§ doctype-name-state states::DoctypeName => loop { match get_char!(self) { '\t' | '\n' | '\x0C' | ' ' => go!(self: to AfterDoctypeName), '>' => go!(self: emit_doctype; to Data), '\0' => go!(self: error; push_doctype_name '\u{fffd}'), c => go!(self: push_doctype_name (c.to_ascii_lowercase())), }}, //§ after-doctype-name-state states::AfterDoctypeName => loop { if eat!(self, "public") { go!(self: to AfterDoctypeKeyword Public); } else if eat!(self, "system") { go!(self: to AfterDoctypeKeyword System); } else { match get_char!(self) { '\t' | '\n' | '\x0C' | ' ' => (), '>' => go!(self: emit_doctype; to Data), _ => go!(self: error; force_quirks; to BogusDoctype), } } }, //§ after-doctype-public-keyword-state after-doctype-system-keyword-state states::AfterDoctypeKeyword(kind) => loop { match get_char!(self) { '\t' | '\n' | '\x0C' | ' ' => go!(self: to BeforeDoctypeIdentifier kind), '"' => go!(self: error; clear_doctype_id kind; to DoctypeIdentifierDoubleQuoted kind), '\'' => go!(self: error; clear_doctype_id kind; to DoctypeIdentifierSingleQuoted kind), '>' => go!(self: error; force_quirks; emit_doctype; to Data), _ => go!(self: error; force_quirks; to BogusDoctype), }}, //§ before-doctype-public-identifier-state before-doctype-system-identifier-state states::BeforeDoctypeIdentifier(kind) => loop { match get_char!(self) { '\t' | '\n' | '\x0C' | ' ' => (), '"' => go!(self: clear_doctype_id kind; to DoctypeIdentifierDoubleQuoted kind), '\'' => go!(self: clear_doctype_id kind; to DoctypeIdentifierSingleQuoted kind), '>' => go!(self: error; force_quirks; emit_doctype; to Data), _ => go!(self: error; force_quirks; to BogusDoctype), }}, //§ doctype-public-identifier-(double-quoted)-state doctype-system-identifier-(double-quoted)-state states::DoctypeIdentifierDoubleQuoted(kind) => loop { match get_char!(self) { '"' => go!(self: to AfterDoctypeIdentifier kind), '\0' => go!(self: error; push_doctype_id kind '\u{fffd}'), '>' => go!(self: error; force_quirks; emit_doctype; to Data), c => go!(self: push_doctype_id kind c), }}, //§ doctype-public-identifier-(single-quoted)-state doctype-system-identifier-(single-quoted)-state states::DoctypeIdentifierSingleQuoted(kind) => loop { match get_char!(self) { '\'' => go!(self: to AfterDoctypeIdentifier kind), '\0' => go!(self: error; push_doctype_id kind '\u{fffd}'), '>' => go!(self: error; force_quirks; emit_doctype; to Data), c => go!(self: push_doctype_id kind c), }}, //§ after-doctype-public-identifier-state states::AfterDoctypeIdentifier(Public) => loop { match get_char!(self) { '\t' | '\n' | '\x0C' | ' ' => go!(self: to BetweenDoctypePublicAndSystemIdentifiers), '>' => go!(self: emit_doctype; to Data), '"' => go!(self: error; clear_doctype_id System; to DoctypeIdentifierDoubleQuoted System), '\'' => go!(self: error; clear_doctype_id System; to DoctypeIdentifierSingleQuoted System), _ => go!(self: error; force_quirks; to BogusDoctype), }}, //§ after-doctype-system-identifier-state states::AfterDoctypeIdentifier(System) => loop { match get_char!(self) { '\t' | '\n' | '\x0C' | ' ' => (), '>' => go!(self: emit_doctype; to Data), _ => go!(self: error; to BogusDoctype), }}, //§ between-doctype-public-and-system-identifiers-state states::BetweenDoctypePublicAndSystemIdentifiers => loop { match get_char!(self) { '\t' | '\n' | '\x0C' | ' ' => (), '>' => go!(self: emit_doctype; to Data), '"' => go!(self: clear_doctype_id System; to DoctypeIdentifierDoubleQuoted System), '\'' => go!(self: clear_doctype_id System; to DoctypeIdentifierSingleQuoted System), _ => go!(self: error; force_quirks; to BogusDoctype), }}, //§ bogus-doctype-state states::BogusDoctype => loop { match get_char!(self) { '>' => go!(self: emit_doctype; to Data), _ => (), }}, //§ bogus-comment-state states::BogusComment => loop { match get_char!(self) { '>' => go!(self: emit_comment; to Data), '\0' => go!(self: push_comment '\u{fffd}'), c => go!(self: push_comment c), }}, //§ markup-declaration-open-state states::MarkupDeclarationOpen => loop { if eat_exact!(self, "--") { go!(self: clear_comment; to CommentStart); } else if eat!(self, "doctype") { go!(self: to Doctype); } else { if self.sink.adjusted_current_node_present_but_not_in_html_namespace() { if eat_exact!(self, "[CDATA[") { go!(self: clear_temp; to CdataSection); } } go!(self: error; to BogusComment); } }, //§ cdata-section-state states::CdataSection => loop { if eat_exact!(self, "]]>") { go!(self: emit_temp; to Data); } else { match get_char!(self) { '\0' => go!(self: emit_temp; emit '\0'), c => go!(self: push_temp c) } } } //§ END } } fn step_char_ref_tokenizer(&mut self) -> bool { // FIXME HACK: Take and replace the tokenizer so we don't // double-mut-borrow self. This is why it's boxed. let mut tok = self.char_ref_tokenizer.take().unwrap(); let outcome = tok.step(self); let progress = match outcome { char_ref::Done => { self.process_char_ref(tok.get_result()); return true; } char_ref::Stuck => false, char_ref::Progress => true, }; self.char_ref_tokenizer = Some(tok); progress } fn process_char_ref(&mut self, char_ref: CharRef) { let CharRef { mut chars, mut num_chars } = char_ref; if num_chars == 0 { chars[0] = '&'; num_chars = 1; } for i in 0 .. num_chars { let c = chars[i as usize]; match self.state { states::Data | states::RawData(states::Rcdata) => go!(self: emit c), states::AttributeValue(_) => go!(self: push_value c), _ => panic!("state {:?} should not be reachable in process_char_ref", self.state), } } } /// Indicate that we have reached the end of the input. pub fn end(&mut self) { // Handle EOF in the char ref sub-tokenizer, if there is one. // Do this first because it might un-consume stuff. match self.char_ref_tokenizer.take() { None => (), Some(mut tok) => { tok.end_of_file(self); self.process_char_ref(tok.get_result()); } } // Process all remaining buffered input. // If we're waiting for lookahead, we're not gonna get it. self.at_eof = true; self.run(); while self.eof_step() { // loop } if self.opts.profile { self.dump_profile(); } } fn dump_profile(&self) { let mut results: Vec<(states::State, u64)> = self.state_profile.iter().map(|(s, t)| (*s, *t)).collect(); results.sort_by(|&(_, x), &(_, y)| y.cmp(&x)); let total: u64 = results.iter().map(|&(_, t)| t).fold(0, ::std::ops::Add::add); println!("\nTokenizer profile, in nanoseconds"); println!("\n{:12} total in token sink", self.time_in_sink); println!("\n{:12} total in tokenizer", total); for (k, v) in results.into_iter() { let pct = 100.0 * (v as f64) / (total as f64); println!("{:12} {:4.1}% {:?}", v, pct, k); } } fn eof_step(&mut self) -> bool { debug!("processing EOF in state {:?}", self.state); match self.state { states::Data | states::RawData(Rcdata) | states::RawData(Rawtext) | states::RawData(ScriptData) | states::Plaintext | states::Quiescent => go!(self: eof), states::TagName | states::RawData(ScriptDataEscaped(_)) | states::BeforeAttributeName | states::AttributeName | states::AfterAttributeName | states::BeforeAttributeValue | states::AttributeValue(_) | states::AfterAttributeValueQuoted | states::SelfClosingStartTag | states::ScriptDataEscapedDash(_) | states::ScriptDataEscapedDashDash(_) => go!(self: error_eof; to Data), states::TagOpen => go!(self: error_eof; emit '<'; to Data), states::EndTagOpen => go!(self: error_eof; emit '<'; emit '/'; to Data), states::RawLessThanSign(ScriptDataEscaped(DoubleEscaped)) => go!(self: to RawData ScriptDataEscaped DoubleEscaped), states::RawLessThanSign(kind) => go!(self: emit '<'; to RawData kind), states::RawEndTagOpen(kind) => go!(self: emit '<'; emit '/'; to RawData kind), states::RawEndTagName(kind) => go!(self: emit '<'; emit '/'; emit_temp; to RawData kind), states::ScriptDataEscapeStart(kind) => go!(self: to RawData ScriptDataEscaped kind), states::ScriptDataEscapeStartDash => go!(self: to RawData ScriptData), states::ScriptDataDoubleEscapeEnd => go!(self: to RawData ScriptDataEscaped DoubleEscaped), states::CommentStart | states::CommentStartDash | states::Comment | states::CommentEndDash | states::CommentEnd | states::CommentEndBang => go!(self: error_eof; emit_comment; to Data), states::Doctype | states::BeforeDoctypeName => go!(self: error_eof; create_doctype; force_quirks; emit_doctype; to Data), states::DoctypeName | states::AfterDoctypeName | states::AfterDoctypeKeyword(_) | states::BeforeDoctypeIdentifier(_) | states::DoctypeIdentifierDoubleQuoted(_) | states::DoctypeIdentifierSingleQuoted(_) | states::AfterDoctypeIdentifier(_) | states::BetweenDoctypePublicAndSystemIdentifiers => go!(self: error_eof; force_quirks; emit_doctype; to Data), states::BogusDoctype => go!(self: emit_doctype; to Data), states::BogusComment => go!(self: emit_comment; to Data), states::MarkupDeclarationOpen => go!(self: error; to BogusComment), states::CdataSection => go!(self: emit_temp; to Data), } } } #[cfg(test)] #[allow(non_snake_case)] mod test { use super::option_push; // private items use tendril::{StrTendril, SliceExt}; #[test] fn push_to_None_gives_singleton() { let mut s: Option<StrTendril> = None; option_push(&mut s, 'x'); assert_eq!(s, Some("x".to_tendril())); } #[test] fn push_to_empty_appends() { let mut s: Option<StrTendril> = Some(StrTendril::new()); option_push(&mut s, 'x'); assert_eq!(s, Some("x".to_tendril())); } #[test] fn push_to_nonempty_appends() { let mut s: Option<StrTendril> = Some(StrTendril::from_slice("y")); option_push(&mut s, 'x'); assert_eq!(s, Some("yx".to_tendril())); } }<|fim▁end|>
_ => match lower_ascii_letter(c) { Some(cl) => go!(self: push_temp cl; emit c), None => go!(self: reconsume RawData ScriptDataEscaped DoubleEscaped),
<|file_name|>bitcoin_tr.ts<|end_file_name|><|fim▁begin|><?xml version="1.0" ?><!DOCTYPE TS><TS language="tr" version="2.0"> <defaultcodec>UTF-8</defaultcodec> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About Hellascoin</source> <translation>Hellascoin hakkında</translation> </message> <message> <location line="+39"/> <source>&lt;b&gt;Hellascoin&lt;/b&gt; version</source> <translation>&lt;b&gt;Hellascoin&lt;/b&gt; sürüm</translation> </message> <message> <location line="+57"/> <source> This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source> <translation> Bu yazılım deneme safhasındadır. MIT/X11 yazılım lisansı kapsamında yayınlanmıştır, COPYING dosyasına ya da http://www.opensource.org/licenses/mit-license.php sayfasına bakınız. Bu ürün OpenSSL projesi tarafından OpenSSL araç takımı (http://www.openssl.org/) için geliştirilen yazılımlar, Eric Young (eay@cryptsoft.com) tarafından hazırlanmış şifreleme yazılımları ve Thomas Bernard tarafından programlanmış UPnP yazılımı içerir.</translation> </message> <message> <location filename="../aboutdialog.cpp" line="+14"/> <source>Copyright</source> <translation>Telif hakkı</translation> </message> <message> <location line="+0"/> <source>The Hellascoin developers</source> <translation>Hellascoin geliştiricileri</translation> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation>Adres defteri</translation> </message> <message> <location line="+19"/> <source>Double-click to edit address or label</source> <translation>Adresi ya da etiketi düzenlemek için çift tıklayınız</translation> </message> <message> <location line="+27"/> <source>Create a new address</source> <translation>Yeni bir adres oluştur</translation> </message> <message> <location line="+14"/> <source>Copy the currently selected address to the system clipboard</source> <translation>Şu anda seçili olan adresi panoya kopyala</translation> </message> <message> <location line="-11"/> <source>&amp;New Address</source> <translation>&amp;Yeni adres</translation> </message> <message> <location filename="../addressbookpage.cpp" line="+63"/> <source>These are your Hellascoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source> <translation>Bunlar, ödeme almak için Hellascoin adresleridir. Kimin ödeme yaptığını izleyebilmek için her ödeme yollaması gereken kişiye değişik bir adres verebilirsiniz.</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>&amp;Copy Address</source> <translation>Adresi &amp;kopyala</translation> </message> <message> <location line="+11"/> <source>Show &amp;QR Code</source> <translation>&amp;QR kodunu göster</translation> </message> <message> <location line="+11"/> <source>Sign a message to prove you own a Hellascoin address</source> <translation>Bir Hellascoin adresinin sizin olduğunu ispatlamak için mesaj imzalayın</translation> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation>&amp;Mesaj imzala</translation> </message> <message> <location line="+25"/> <source>Delete the currently selected address from the list</source> <translation>Seçili adresi listeden sil</translation> </message> <message> <location line="+27"/> <source>Export the data in the current tab to a file</source> <translation>Güncel sekmedeki verileri bir dosyaya aktar</translation> </message> <message> <location line="+3"/> <source>&amp;Export</source> <translation>&amp;Dışa aktar</translation> </message> <message> <location line="-44"/> <source>Verify a message to ensure it was signed with a specified Hellascoin address</source> <translation>Belirtilen Hellascoin adresi ile imzalandığını doğrulamak için bir mesajı kontrol et</translation> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation>Mesaj &amp;kontrol et</translation> </message> <message> <location line="+14"/> <source>&amp;Delete</source> <translation>&amp;Sil</translation> </message> <message> <location filename="../addressbookpage.cpp" line="-5"/> <source>These are your Hellascoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source> <translation>Bunlar ödeme yapmak için kullanacağınız Hellascoin adreslerinizdir. Hellascoin yollamadan önce meblağı ve alıcı adresini daima kontrol ediniz.</translation> </message> <message> <location line="+13"/> <source>Copy &amp;Label</source> <translation>&amp;Etiketi kopyala</translation> </message> <message> <location line="+1"/> <source>&amp;Edit</source> <translation>&amp;Düzenle</translation> </message> <message> <location line="+1"/> <source>Send &amp;Coins</source> <translation>Bit&amp;coin Gönder</translation> </message> <message> <location line="+260"/> <source>Export Address Book Data</source> <translation>Adres defteri verilerini dışa aktar</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Virgülle ayrılmış değerler dosyası (*.csv)</translation> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation>Dışa aktarımda hata oluştu</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>%1 dosyasına yazılamadı.</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+144"/> <source>Label</source> <translation>Etiket</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Adres</translation> </message> <message> <location line="+36"/> <source>(no label)</source> <translation>(boş etiket)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation>Parola diyaloğu</translation> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation>Parolayı giriniz</translation> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation>Yeni parola</translation> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation>Yeni parolayı tekrarlayınız</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+33"/> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;10 or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation>Cüzdanınız için yeni parolayı giriniz.&lt;br/&gt;Lütfen &lt;b&gt;10 ya da daha fazla rastgele karakter&lt;/b&gt; veya &lt;b&gt;sekiz ya da daha fazla kelime&lt;/b&gt; içeren bir parola seçiniz.</translation> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation>Cüzdanı şifrele</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>Bu işlem cüzdan kilidini açmak için cüzdan parolanızı gerektirir.</translation> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation>Cüzdan kilidini aç</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>Bu işlem, cüzdan şifresini açmak için cüzdan parolasını gerektirir.</translation> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation>Cüzdan şifresini aç</translation> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation>Parolayı değiştir</translation> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>Cüzdan için eski ve yeni parolaları giriniz.</translation> </message> <message> <location line="+46"/> <source>Confirm wallet encryption</source> <translation>Cüzdan şifrelenmesini teyit eder</translation> </message> <message> <location line="+1"/> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR LITECOINS&lt;/b&gt;!</source> <translation>Uyarı: Eğer cüzdanınızı şifrelerseniz ve parolanızı kaybederseniz, &lt;b&gt;TÜM BİTCOİNLERİNİZİ KAYBEDERSİNİZ&lt;/b&gt;!</translation> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation>Cüzdanınızı şifrelemek istediğinizden emin misiniz?</translation> </message> <message> <location line="+15"/> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation>ÖNEMLİ: Önceden yapmış olduğunuz cüzdan dosyası yedeklemelerinin yeni oluşturulan şifrelenmiş cüzdan dosyası ile değiştirilmeleri gerekir. Güvenlik nedenleriyle yeni, şifrelenmiş cüzdanı kullanmaya başladığınızda eski şifrelenmemiş cüzdan dosyaları işe yaramaz hale gelecektir.</translation> </message> <message> <location line="+100"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation>Uyarı: Caps Lock tuşu faal durumda!</translation> </message> <message> <location line="-130"/> <location line="+58"/> <source>Wallet encrypted</source> <translation>Cüzdan şifrelendi</translation> </message> <message> <location line="-56"/> <source>Hellascoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your hellascoins from being stolen by malware infecting your computer.</source> <translation>Şifreleme işlemini tamamlamak için Hellascoin şimdi kapanacaktır. Cüzdanınızı şifrelemenin, Hellascoinlerinizin bilgisayara bulaşan kötücül bir yazılım tarafından çalınmaya karşı tamamen koruyamayacağını unutmayınız.</translation> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+42"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation>Cüzdan şifrelemesi başarısız oldu</translation> </message> <message> <location line="-54"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>Dahili bir hata sebebiyle cüzdan şifrelemesi başarısız oldu. Cüzdanınız şifrelenmedi.</translation> </message> <message> <location line="+7"/> <location line="+48"/> <source>The supplied passphrases do not match.</source> <translation>Girilen parolalar birbirleriyle uyumlu değil.</translation> </message> <message> <location line="-37"/> <source>Wallet unlock failed</source> <translation>Cüzdan kilidinin açılması başarısız oldu</translation> </message> <message> <location line="+1"/> <location line="+11"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>Cüzdan şifresinin açılması için girilen parola yanlıştı.</translation> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation>Cüzdan şifresinin açılması başarısız oldu</translation> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation>Cüzdan parolası başarılı bir şekilde değiştirildi.</translation> </message> </context> <context> <name>BitcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+233"/> <source>Sign &amp;message...</source> <translation>&amp;Mesaj imzala...</translation> </message> <message> <location line="+280"/> <source>Synchronizing with network...</source> <translation>Şebeke ile senkronizasyon...</translation> </message> <message> <location line="-349"/> <source>&amp;Overview</source> <translation>&amp;Genel bakış</translation> </message> <message> <location line="+1"/> <source>Show general overview of wallet</source> <translation>Cüzdana genel bakışı göster</translation> </message> <message> <location line="+20"/> <source>&amp;Transactions</source> <translation>&amp;Muameleler</translation> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation>Muamele tarihçesini tara</translation> </message> <message> <location line="+7"/> <source>Edit the list of stored addresses and labels</source> <translation>Saklanan adres ve etiket listesini düzenle</translation> </message> <message> <location line="-14"/> <source>Show the list of addresses for receiving payments</source> <translation>Ödeme alma adreslerinin listesini göster</translation> </message> <message> <location line="+31"/> <source>E&amp;xit</source> <translation>&amp;Çık</translation> </message> <message> <location line="+1"/> <source>Quit application</source> <translation>Uygulamadan çık</translation> </message> <message> <location line="+4"/> <source>Show information about Hellascoin</source> <translation>Hellascoin hakkında bilgi göster</translation> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation>&amp;Qt hakkında</translation> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation>Qt hakkında bilgi görüntü</translation> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation>&amp;Seçenekler...</translation> </message> <message> <location line="+6"/> <source>&amp;Encrypt Wallet...</source> <translation>Cüzdanı &amp;şifrele...</translation> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation>Cüzdanı &amp;yedekle...</translation> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation>Parolayı &amp;değiştir...</translation> </message> <message> <location line="+285"/> <source>Importing blocks from disk...</source> <translation>Bloklar diskten içe aktarılıyor...</translation> </message> <message> <location line="+3"/> <source>Reindexing blocks on disk...</source> <translation>Diskteki bloklar yeniden endeksleniyor...</translation> </message> <message> <location line="-347"/> <source>Send coins to a Hellascoin address</source> <translation>Bir Hellascoin adresine Hellascoin yolla</translation> </message> <message> <location line="+49"/> <source>Modify configuration options for Hellascoin</source> <translation>Hellascoin seçeneklerinin yapılandırmasını değiştir</translation> </message> <message> <location line="+9"/> <source>Backup wallet to another location</source> <translation>Cüzdanı diğer bir konumda yedekle</translation> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation>Cüzdan şifrelemesi için kullanılan parolayı değiştir</translation> </message> <message> <location line="+6"/> <source>&amp;Debug window</source> <translation>&amp;Hata ayıklama penceresi</translation> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation>Hata ayıklama ve teşhis penceresini aç</translation> </message> <message> <location line="-4"/> <source>&amp;Verify message...</source> <translation>Mesaj &amp;kontrol et...</translation> </message> <message> <location line="-165"/> <location line="+530"/> <source>Hellascoin</source> <translation>Hellascoin</translation> </message> <message> <location line="-530"/> <source>Wallet</source> <translation>Cüzdan</translation> </message> <message> <location line="+101"/> <source>&amp;Send</source> <translation>&amp;Gönder</translation> </message> <message> <location line="+7"/> <source>&amp;Receive</source> <translation>&amp;Al</translation> </message> <message> <location line="+14"/> <source>&amp;Addresses</source> <translation>&amp;Adresler</translation> </message> <message> <location line="+22"/> <source>&amp;About Hellascoin</source> <translation>Hellascoin &amp;Hakkında</translation> </message> <message> <location line="+9"/> <source>&amp;Show / Hide</source> <translation>&amp;Göster / Sakla</translation> </message> <message> <location line="+1"/> <source>Show or hide the main Window</source> <translation>Ana pencereyi görüntüle ya da sakla</translation> </message> <message> <location line="+3"/> <source>Encrypt the private keys that belong to your wallet</source> <translation>Cüzdanınızın özel anahtarlarını şifrele</translation> </message> <message> <location line="+7"/> <source>Sign messages with your Hellascoin addresses to prove you own them</source> <translation>Mesajları adreslerin size ait olduğunu ispatlamak için Hellascoin adresleri ile imzala</translation> </message> <message> <location line="+2"/> <source>Verify messages to ensure they were signed with specified Hellascoin addresses</source> <translation>Belirtilen Hellascoin adresleri ile imzalandıklarından emin olmak için mesajları kontrol et</translation> </message> <message> <location line="+28"/> <source>&amp;File</source> <translation>&amp;Dosya</translation> </message> <message> <location line="+7"/> <source>&amp;Settings</source> <translation>&amp;Ayarlar</translation> </message> <message> <location line="+6"/> <source>&amp;Help</source> <translation>&amp;Yardım</translation> </message> <message> <location line="+9"/> <source>Tabs toolbar</source> <translation>Sekme araç çubuğu</translation> </message> <message> <location line="+17"/> <location line="+10"/> <source>[testnet]</source> <translation>[testnet]</translation> </message> <message> <location line="+47"/> <source>Hellascoin client</source> <translation>Hellascoin istemcisi</translation> </message> <message numerus="yes"> <location line="+141"/> <source>%n active connection(s) to Hellascoin network</source> <translation><numerusform>Hellascoin şebekesine %n faal bağlantı</numerusform><numerusform>Hellascoin şebekesine %n faal bağlantı</numerusform></translation> </message> <message> <location line="+22"/> <source>No block source available...</source> <translation>Hiçbir blok kaynağı mevcut değil...</translation> </message> <message> <location line="+12"/> <source>Processed %1 of %2 (estimated) blocks of transaction history.</source> <translation>Muamele tarihçesinin toplam (tahmini) %2 blokundan %1 blok işlendi.</translation> </message> <message> <location line="+4"/> <source>Processed %1 blocks of transaction history.</source> <translation>Muamele tarihçesinde %1 blok işlendi.</translation> </message> <message numerus="yes"> <location line="+20"/> <source>%n hour(s)</source> <translation><numerusform>%n saat</numerusform><numerusform>%n saat</numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s)</source> <translation><numerusform>%n gün</numerusform><numerusform>%n gün</numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n week(s)</source> <translation><numerusform>%n hafta</numerusform><numerusform>%n hafta</numerusform></translation> </message> <message> <location line="+4"/> <source>%1 behind</source> <translation>%1 geride</translation> </message> <message> <location line="+14"/> <source>Last received block was generated %1 ago.</source> <translation>Son alınan blok %1 evvel oluşturulmuştu.</translation> </message> <message> <location line="+2"/> <source>Transactions after this will not yet be visible.</source> <translation>Bundan sonraki muameleler henüz görüntülenemez.</translation> </message> <message> <location line="+22"/> <source>Error</source> <translation>Hata</translation> </message> <message> <location line="+3"/> <source>Warning</source> <translation>Uyarı</translation> </message> <message> <location line="+3"/> <source>Information</source> <translation>Bilgi</translation> </message> <message> <location line="+70"/> <source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source> <translation>Bu muamele boyut sınırlarını aşmıştır. Gene de %1 ücret ödeyerek gönderebilirsiniz, ki bu ücret muamelenizi işleyen ve şebekeye yardım eden düğümlere ödenecektir. Ücreti ödemek istiyor musunuz?</translation> </message> <message> <location line="-140"/> <source>Up to date</source> <translation>Güncel</translation> </message> <message> <location line="+31"/> <source>Catching up...</source> <translation>Aralık kapatılıyor...</translation> </message> <message> <location line="+113"/> <source>Confirm transaction fee</source> <translation>Muamele ücretini teyit et</translation> </message> <message> <location line="+8"/> <source>Sent transaction</source> <translation>Muamele yollandı</translation> </message> <message> <location line="+0"/> <source>Incoming transaction</source> <translation>Gelen muamele</translation> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation>Tarih: %1 Miktar: %2 Tür: %3 Adres: %4 </translation> </message> <message> <location line="+33"/> <location line="+23"/> <source>URI handling</source> <translation>URI yönetimi</translation> </message> <message> <location line="-23"/> <location line="+23"/> <source>URI can not be parsed! This can be caused by an invalid Hellascoin address or malformed URI parameters.</source> <translation>URI okunamadı! Sebebi geçersiz bir Hellascoin adresi veya hatalı URI parametreleri olabilir.</translation> </message> <message> <location line="+17"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>Cüzdan &lt;b&gt;şifrelenmiştir&lt;/b&gt; ve şu anda &lt;b&gt;kilidi açıktır&lt;/b&gt;</translation> </message> <message> <location line="+8"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>Cüzdan &lt;b&gt;şifrelenmiştir&lt;/b&gt; ve şu anda &lt;b&gt;kilitlidir&lt;/b&gt;</translation> </message> <message> <location filename="../bitcoin.cpp" line="+111"/> <source>A fatal error occurred. Hellascoin can no longer continue safely and will quit.</source> <translation>Ciddi bir hata oluştu. Hellascoin artık güvenli bir şekilde işlemeye devam edemez ve kapanacaktır.</translation> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+104"/> <source>Network Alert</source> <translation>Şebeke hakkında uyarı</translation> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation>Adresi düzenle</translation> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation>&amp;Etiket</translation> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation>Bu adres defteri unsuru ile ilişkili etiket</translation> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation>&amp;Adres</translation> </message> <message> <location line="+10"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation>Bu adres defteri unsuru ile ilişkili adres. Bu, sadece gönderi adresi için değiştirilebilir.</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="+21"/> <source>New receiving address</source> <translation>Yeni alım adresi</translation> </message> <message> <location line="+4"/> <source>New sending address</source> <translation>Yeni gönderi adresi</translation> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation>Alım adresini düzenle</translation> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation>Gönderi adresini düzenle</translation> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>Girilen &quot;%1&quot; adresi hâlihazırda adres defterinde mevcuttur.</translation> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid Hellascoin address.</source> <translation>Girilen &quot;%1&quot; adresi geçerli bir Hellascoin adresi değildir.</translation> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation>Cüzdan kilidi açılamadı.</translation> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation>Yeni anahtar oluşturulması başarısız oldu.</translation> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+424"/> <location line="+12"/> <source>Hellascoin-Qt</source> <translation>Hellascoin-Qt</translation> </message> <message> <location line="-12"/> <source>version</source> <translation>sürüm</translation> </message> <message> <location line="+2"/> <source>Usage:</source> <translation>Kullanım:</translation> </message> <message> <location line="+1"/> <source>command-line options</source> <translation>komut satırı seçenekleri</translation> </message> <message> <location line="+4"/> <source>UI options</source> <translation>Kullanıcı arayüzü seçenekleri</translation> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation>Lisan belirt, mesela &quot;de_De&quot; (varsayılan: sistem dili)</translation> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation>Küçültülmüş olarak başlat</translation> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation>Başlatıldığında başlangıç ekranını göster (varsayılan: 1)</translation> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation>Seçenekler</translation> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation>&amp;Esas ayarlar</translation> </message> <message> <location line="+6"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source> <translation>Muamelelerin hızlı işlenmesini garantilemeye yardım eden, seçime dayalı kB başı muamele ücreti. Muamelelerin çoğunluğunun boyutu 1 kB&apos;dir.</translation> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation>Muamele ücreti &amp;öde</translation> </message> <message> <location line="+31"/> <source>Automatically start Hellascoin after logging in to the system.</source> <translation>Sistemde oturum açıldığında Hellascoin&apos;i otomatik olarak başlat.</translation> </message> <message> <location line="+3"/> <source>&amp;Start Hellascoin on system login</source> <translation>Hellascoin&apos;i sistem oturumuyla &amp;başlat</translation> </message> <message> <location line="+35"/> <source>Reset all client options to default.</source> <translation>İstemcinin tüm seçeneklerini varsayılan değerlere geri al.</translation> </message> <message> <location line="+3"/> <source>&amp;Reset Options</source> <translation>Seçenekleri &amp;sıfırla</translation> </message> <message> <location line="+13"/> <source>&amp;Network</source> <translation>&amp;Şebeke</translation> </message> <message> <location line="+6"/> <source>Automatically open the Hellascoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation>Yönlendiricide Hellascoin istemci portlarını otomatik olarak açar. Bu, sadece yönlendiricinizin UPnP desteği bulunuyorsa ve etkinse çalışabilir.</translation> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation>Portları &amp;UPnP kullanarak haritala</translation> </message> <message> <location line="+7"/> <source>Connect to the Hellascoin network through a SOCKS proxy (e.g. when connecting through Tor).</source> <translation>Hellascoin şebekesine SOCKS vekil sunucusu vasıtasıyla bağlan (mesela Tor ile bağlanıldığında).</translation> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy:</source> <translation>SOCKS vekil sunucusu vasıtasıyla ba&amp;ğlan:</translation> </message> <message> <location line="+9"/> <source>Proxy &amp;IP:</source> <translation>Vekil &amp;İP:</translation> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation>Vekil sunucunun İP adresi (mesela 127.0.0.1)</translation> </message> <message> <location line="+7"/> <source>&amp;Port:</source> <translation>&amp;Port:</translation> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation>Vekil sunucunun portu (mesela 9050)</translation> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation>SOCKS &amp;sürümü:</translation> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation>Vekil sunucunun SOCKS sürümü (mesela 5)</translation> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation>&amp;Pencere</translation> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation>Küçültüldükten sonra sadece çekmece ikonu göster.</translation> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation>İşlem çubuğu yerine sistem çekmecesine &amp;küçült</translation> </message> <message> <location line="+7"/> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation>Pencere kapatıldığında uygulamadan çıkmak yerine uygulamayı küçültür. Bu seçenek etkinleştirildiğinde, uygulama sadece menüden çıkış seçildiğinde kapanacaktır.</translation> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation>Kapatma sırasında k&amp;üçült</translation> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation>&amp;Görünüm</translation> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation>Kullanıcı arayüzü &amp;lisanı:</translation> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting Hellascoin.</source> <translation>Kullanıcı arayüzünün dili burada belirtilebilir. Bu ayar Hellascoin tekrar başlatıldığında etkinleşecektir.</translation> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation>Miktarı göstermek için &amp;birim:</translation> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation>Hellascoin gönderildiğinde arayüzde gösterilecek varsayılan alt birimi seçiniz.</translation> </message> <message> <location line="+9"/> <source>Whether to show Hellascoin addresses in the transaction list or not.</source> <translation>Muamele listesinde Hellascoin adreslerinin gösterilip gösterilmeyeceklerini belirler.</translation> </message> <message> <location line="+3"/> <source>&amp;Display addresses in transaction list</source> <translation>Muamele listesinde adresleri &amp;göster</translation> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation>&amp;Tamam</translation> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation>&amp;İptal</translation> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation>&amp;Uygula</translation> </message> <message> <location filename="../optionsdialog.cpp" line="+53"/> <source>default</source> <translation>varsayılan</translation> </message> <message> <location line="+130"/> <source>Confirm options reset</source> <translation>Seçeneklerin sıfırlanmasını teyit et</translation> </message> <message> <location line="+1"/> <source>Some settings may require a client restart to take effect.</source> <translation>Bazı ayarların dikkate alınması istemcinin tekrar başlatılmasını gerektirebilir.</translation> </message> <message> <location line="+0"/> <source>Do you want to proceed?</source> <translation>Devam etmek istiyor musunuz?</translation> </message> <message> <location line="+42"/> <location line="+9"/> <source>Warning</source> <translation>Uyarı</translation> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting Hellascoin.</source> <translation>Bu ayarlar Hellascoin tekrar başlatıldığında etkinleşecektir.</translation> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation>Girilen vekil sunucu adresi geçersizdir.</translation> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation>Form</translation> </message> <message> <location line="+50"/> <location line="+166"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the Hellascoin network after a connection is established, but this process has not completed yet.</source> <translation>Görüntülenen veriler zaman aşımına uğramış olabilir. Bağlantı kurulduğunda cüzdanınız otomatik olarak şebeke ile eşleşir ancak bu işlem henüz tamamlanmamıştır.</translation> </message> <message> <location line="-124"/> <source>Balance:</source> <translation>Bakiye:</translation> </message> <message> <location line="+29"/> <source>Unconfirmed:</source> <translation>Doğrulanmamış:</translation> </message> <message> <location line="-78"/> <source>Wallet</source> <translation>Cüzdan</translation> </message> <message> <location line="+107"/> <source>Immature:</source> <translation>Olgunlaşmamış:</translation> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation>Oluşturulan bakiye henüz olgunlaşmamıştır</translation> </message> <message> <location line="+46"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;Son muameleler&lt;/b&gt;</translation> </message> <message> <location line="-101"/> <source>Your current balance</source> <translation>Güncel bakiyeniz</translation> </message> <message> <location line="+29"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation>Doğrulanması beklenen ve henüz güncel bakiyeye ilâve edilmemiş muamelelerin toplamı</translation> </message> <message> <location filename="../overviewpage.cpp" line="+116"/> <location line="+1"/> <source>out of sync</source> <translation>eşleşme dışı</translation> </message> </context> <context> <name>PaymentServer</name> <message> <location filename="../paymentserver.cpp" line="+107"/> <source>Cannot start hellascoin: click-to-pay handler</source> <translation>Hellascoin başlatılamadı: tıkla-ve-öde yöneticisi</translation> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="+14"/> <source>QR Code Dialog</source> <translation>QR kodu diyaloğu</translation> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation>Ödeme talebi</translation> </message> <message> <location line="+56"/> <source>Amount:</source> <translation>Miktar:</translation> </message> <message> <location line="-44"/> <source>Label:</source> <translation>Etiket:</translation> </message> <message> <location line="+19"/> <source>Message:</source> <translation>Mesaj:</translation> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation>&amp;Farklı kaydet...</translation> </message> <message> <location filename="../qrcodedialog.cpp" line="+62"/> <source>Error encoding URI into QR Code.</source> <translation>URI&apos;nin QR koduna kodlanmasında hata oluştu.</translation> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation>Girilen miktar geçersizdir, kontrol ediniz.</translation> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation>Sonuç URI çok uzun, etiket ya da mesaj metnini kısaltmayı deneyiniz.</translation> </message> <message> <location line="+25"/> <source>Save QR Code</source> <translation>QR kodu kaydet</translation> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation>PNG resimleri (*.png)</translation> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation>İstemci ismi</translation> </message> <message> <location line="+10"/> <location line="+23"/> <location line="+26"/> <location line="+23"/> <location line="+23"/> <location line="+36"/> <location line="+53"/> <location line="+23"/> <location line="+23"/> <location filename="../rpcconsole.cpp" line="+339"/> <source>N/A</source> <translation>Mevcut değil</translation> </message> <message> <location line="-217"/> <source>Client version</source> <translation>İstemci sürümü</translation> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation>&amp;Malumat</translation> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation>Kullanılan OpenSSL sürümü</translation> </message> <message> <location line="+49"/> <source>Startup time</source> <translation>Başlama zamanı</translation> </message> <message> <location line="+29"/> <source>Network</source> <translation>Şebeke</translation> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation>Bağlantı sayısı</translation> </message> <message> <location line="+23"/> <source>On testnet</source> <translation>Testnet üzerinde</translation> </message> <message> <location line="+23"/> <source>Block chain</source> <translation>Blok zinciri</translation> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation>Güncel blok sayısı</translation> </message> <message> <location line="+23"/> <source>Estimated total blocks</source> <translation>Tahmini toplam blok sayısı</translation> </message> <message> <location line="+23"/> <source>Last block time</source> <translation>Son blok zamanı</translation> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation>&amp;Aç</translation> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation>Komut satırı seçenekleri</translation> </message> <message> <location line="+7"/> <source>Show the Hellascoin-Qt help message to get a list with possible Hellascoin command-line options.</source> <translation>Mevcut Hellascoin komut satırı seçeneklerinin listesini içeren Hellascoin-Qt yardımını göster.</translation> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation>&amp;Göster</translation> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation>&amp;Konsol</translation> </message> <message> <location line="-260"/> <source>Build date</source> <translation>Derleme tarihi</translation> </message> <message> <location line="-104"/> <source>Hellascoin - Debug window</source> <translation>Hellascoin - Hata ayıklama penceresi</translation> </message> <message> <location line="+25"/> <source>Hellascoin Core</source> <translation>Hellascoin Çekirdeği</translation> </message> <message> <location line="+279"/> <source>Debug log file</source> <translation>Hata ayıklama kütük dosyası</translation> </message> <message> <location line="+7"/> <source>Open the Hellascoin debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation>Güncel veri klasöründen Hellascoin hata ayıklama kütük dosyasını açar. Büyük kütük dosyaları için bu birkaç saniye alabilir.</translation> </message> <message> <location line="+102"/> <source>Clear console</source> <translation>Konsolu temizle</translation> </message> <message> <location filename="../rpcconsole.cpp" line="-30"/> <source>Welcome to the Hellascoin RPC console.</source> <translation>Hellascoin RPC konsoluna hoş geldiniz.</translation> </message> <message> <location line="+1"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation>Tarihçede gezinmek için imleç tuşlarını kullanınız, &lt;b&gt;Ctrl-L&lt;/b&gt; ile de ekranı temizleyebilirsiniz.</translation> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation>Mevcut komutların listesi için &lt;b&gt;help&lt;/b&gt; yazınız.</translation> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+124"/> <location line="+5"/> <location line="+5"/> <location line="+5"/> <location line="+6"/> <location line="+5"/> <location line="+5"/> <source>Send Coins</source> <translation>Hellascoin yolla</translation> </message> <message> <location line="+50"/> <source>Send to multiple recipients at once</source> <translation>Birçok alıcıya aynı anda gönder</translation> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation>&amp;Alıcı ekle</translation> </message> <message> <location line="+20"/> <source>Remove all transaction fields</source> <translation>Bütün muamele alanlarını kaldır</translation> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation>Tümünü &amp;temizle</translation> </message> <message> <location line="+22"/> <source>Balance:</source> <translation>Bakiye:</translation> </message> <message> <location line="+10"/> <source>123.456 BTC</source> <translation>123.456 BTC</translation> </message> <message> <location line="+31"/> <source>Confirm the send action</source> <translation>Yollama etkinliğini teyit ediniz</translation> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation>G&amp;önder</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-59"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation>&lt;b&gt;%1&lt;/b&gt; şu adrese: %2 (%3)</translation> </message> <message> <location line="+5"/> <source>Confirm send coins</source> <translation>Gönderiyi teyit ediniz</translation> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation>%1 göndermek istediğinizden emin misiniz?</translation> </message> <message> <location line="+0"/> <source> and </source> <translation> ve </translation> </message> <message> <location line="+23"/> <source>The recipient address is not valid, please recheck.</source> <translation>Alıcı adresi geçerli değildir, lütfen denetleyiniz.</translation> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation>Ödeyeceğiniz tutarın sıfırdan yüksek olması gerekir.</translation> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation>Tutar bakiyenizden yüksektir.</translation> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation>Toplam, %1 muamele ücreti ilâve edildiğinde bakiyenizi geçmektedir.</translation> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation>Çift adres bulundu, belli bir gönderi sırasında her adrese sadece tek bir gönderide bulunulabilir.</translation> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed!</source> <translation>Hata: Muamele oluşturması başarısız oldu!</translation> </message> <message> <location line="+5"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation>Hata: Muamele reddedildi. Cüzdanınızdaki madenî paraların bazıları zaten harcanmış olduğunda bu meydana gelebilir. Örneğin wallet.dat dosyasının bir kopyasını kullandıysanız ve kopyada para harcandığında ancak burada harcandığı işaretlenmediğinde.</translation> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation>Form</translation> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation>M&amp;iktar:</translation> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation>&amp;Şu kişiye öde:</translation> </message> <message> <location line="+34"/> <source>The address to send the payment to (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Ödemenin gönderileceği adres (mesela Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="+60"/> <location filename="../sendcoinsentry.cpp" line="+26"/> <source>Enter a label for this address to add it to your address book</source> <translation>Adres defterinize eklemek için bu adrese ilişik bir etiket giriniz</translation> </message> <message> <location line="-78"/> <source>&amp;Label:</source> <translation>&amp;Etiket:</translation> </message> <message> <location line="+28"/> <source>Choose address from address book</source> <translation>Adres defterinden adres seç</translation> </message> <message> <location line="+10"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="+7"/> <source>Paste address from clipboard</source> <translation>Panodan adres yapıştır</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+7"/> <source>Remove this recipient</source> <translation>Bu alıcıyı kaldır</translation> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a Hellascoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Hellascoin adresi giriniz (mesela Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation>İmzalar - Mesaj İmzala / Kontrol et</translation> </message> <message> <location line="+13"/> <source>&amp;Sign Message</source> <translation>Mesaj &amp;imzala</translation> </message> <message> <location line="+6"/> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation>Bir adresin sizin olduğunu ispatlamak için adresinizle mesaj imzalayabilirsiniz. Oltalama saldırılarının kimliğinizi imzanızla elde etmeyi deneyebilecekleri için belirsiz hiçbir şey imzalamamaya dikkat ediniz. Sadece ayrıntılı açıklaması olan ve tümüne katıldığınız ifadeleri imzalayınız.</translation> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Mesajın imzalanmasında kullanılacak adres (mesela Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="+10"/> <location line="+213"/> <source>Choose an address from the address book</source> <translation>Adres defterinden bir adres seç</translation> </message> <message> <location line="-203"/> <location line="+213"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="-203"/> <source>Paste address from clipboard</source> <translation>Panodan adres yapıştır</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+12"/> <source>Enter the message you want to sign here</source> <translation>İmzalamak istediğiniz mesajı burada giriniz</translation> </message> <message> <location line="+7"/> <source>Signature</source> <translation>İmza</translation> </message> <message> <location line="+27"/> <source>Copy the current signature to the system clipboard</source> <translation>Güncel imzayı sistem panosuna kopyala</translation> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this Hellascoin address</source> <translation>Bu Hellascoin adresinin sizin olduğunu ispatlamak için mesajı imzalayın</translation> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation>&amp;Mesajı imzala</translation> </message> <message> <location line="+14"/> <source>Reset all sign message fields</source> <translation>Tüm mesaj alanlarını sıfırla</translation> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation>Tümünü &amp;temizle</translation> </message> <message> <location line="-87"/> <source>&amp;Verify Message</source> <translation>Mesaj &amp;kontrol et</translation> </message> <message> <location line="+6"/> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation>İmza için kullanılan adresi, mesajı (satır sonları, boşluklar, sekmeler vs. karakterleri tam olarak kopyaladığınızdan emin olunuz) ve imzayı aşağıda giriniz. Bir ortadaki adam saldırısı tarafından kandırılmaya mâni olmak için imzadan, imzalı mesajın içeriğini aşan bir anlam çıkarmamaya dikkat ediniz.</translation> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Mesajı imzalamak için kullanılmış olan adres (mesela Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified Hellascoin address</source> <translation>Belirtilen Hellascoin adresi ile imzalandığını doğrulamak için mesajı kontrol et</translation> </message> <message> <location line="+3"/> <source>Verify &amp;Message</source> <translation>&amp;Mesaj kontrol et</translation> </message> <message> <location line="+14"/> <source>Reset all verify message fields</source> <translation>Tüm mesaj kontrolü alanlarını sıfırla</translation> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a Hellascoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Hellascoin adresi giriniz (mesela Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation>İmzayı oluşturmak için &quot;Mesaj İmzala&quot; unsurunu tıklayın</translation> </message> <message> <location line="+3"/> <source>Enter Hellascoin signature</source> <translation>Hellascoin imzası gir</translation> </message> <message> <location line="+82"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation>Girilen adres geçersizdir.</translation> </message> <message> <location line="-81"/> <location line="+8"/> <location line="+73"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation>Adresi kontrol edip tekrar deneyiniz.</translation> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation>Girilen adres herhangi bir anahtara işaret etmemektedir.</translation> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation>Cüzdan kilidinin açılması iptal edildi.</translation> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation>Girilen adres için özel anahtar mevcut değildir.</translation> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation>Mesajın imzalanması başarısız oldu.</translation> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation>Mesaj imzalandı.</translation> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation>İmzanın kodu çözülemedi.</translation> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation>İmzayı kontrol edip tekrar deneyiniz.</translation> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation>İmza mesajın hash değeri ile eşleşmedi.</translation> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation>Mesaj doğrulaması başarısız oldu.</translation> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation>Mesaj doğrulandı.</translation> </message> </context> <context> <name>SplashScreen</name> <message> <location filename="../splashscreen.cpp" line="+22"/> <source>The Hellascoin developers</source> <translation>Hellascoin geliştiricileri</translation> </message> <message> <location line="+1"/> <source>[testnet]</source> <translation>[testnet]</translation> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+20"/> <source>Open until %1</source> <translation>%1 değerine dek açık</translation> </message> <message> <location line="+6"/> <source>%1/offline</source> <translation>%1/çevrim dışı</translation> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation>%1/doğrulanmadı</translation> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation>%1 teyit</translation> </message> <message> <location line="+18"/> <source>Status</source> <translation>Durum</translation> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation><numerusform>, %n düğüm vasıtasıyla yayınlandı</numerusform><numerusform>, %n düğüm vasıtasıyla yayınlandı</numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation>Tarih</translation> </message> <message> <location line="+7"/> <source>Source</source> <translation>Kaynak</translation> </message> <message> <location line="+0"/> <source>Generated</source> <translation>Oluşturuldu</translation> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation>Gönderen</translation> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation>Alıcı</translation> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation>kendi adresiniz</translation> </message> <message> <location line="-2"/> <source>label</source> <translation>etiket</translation> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation>Gider</translation> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation><numerusform>%n ek blok sonrasında olgunlaşacak</numerusform><numerusform>%n ek blok sonrasında olgunlaşacak</numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation>kabul edilmedi</translation> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation>Gelir</translation> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation>Muamele ücreti</translation> </message> <message> <location line="+16"/> <source>Net amount</source> <translation>Net miktar</translation> </message> <message> <location line="+6"/> <source>Message</source> <translation>Mesaj</translation> </message> <message> <location line="+2"/> <source>Comment</source> <translation>Yorum</translation> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation>Muamele tanımlayıcı</translation> </message> <message> <location line="+3"/> <source>Generated coins must mature 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to &quot;not accepted&quot; and it won&apos;t be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation>Oluşturulan Hellascoin&apos;lerin harcanabilmelerinden önce 120 blok beklemeleri gerekmektedir. Bu blok, oluşturduğunuzda blok zincirine eklenmesi için ağda yayınlandı. Zincire eklenmesi başarısız olursa, durumu &quot;kabul edilmedi&quot; olarak değiştirilecek ve harcanamayacaktır. Bu, bazen başka bir düğüm sizden birkaç saniye önce ya da sonra blok oluşturursa meydana gelebilir.</translation> </message> <message> <location line="+7"/> <source>Debug information</source> <translation>Hata ayıklama verileri</translation> </message> <message> <location line="+8"/> <source>Transaction</source> <translation>Muamele</translation> </message> <message> <location line="+3"/> <source>Inputs</source> <translation>Girdiler</translation> </message> <message> <location line="+23"/> <source>Amount</source> <translation>Miktar</translation> </message> <message> <location line="+1"/> <source>true</source> <translation>doğru</translation> </message> <message> <location line="+0"/> <source>false</source> <translation>yanlış</translation> </message> <message> <location line="-209"/> <source>, has not been successfully broadcast yet</source> <translation>, henüz başarılı bir şekilde yayınlanmadı</translation> </message> <message numerus="yes"> <location line="-35"/> <source>Open for %n more block(s)</source> <translation><numerusform>%n ilâve blok için açık</numerusform><numerusform>%n ilâve blok için açık</numerusform></translation> </message> <message> <location line="+70"/> <source>unknown</source> <translation>bilinmiyor</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation>Muamele detayları</translation> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation>Bu pano muamelenin ayrıntılı açıklamasını gösterir</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+225"/> <source>Date</source> <translation>Tarih</translation> </message> <message> <location line="+0"/> <source>Type</source> <translation>Tür</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Adres</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation>Miktar</translation> </message> <message numerus="yes"> <location line="+57"/> <source>Open for %n more block(s)</source> <translation><numerusform>%n ilâve blok için açık</numerusform><numerusform>%n ilâve blok için açık</numerusform></translation> </message> <message> <location line="+3"/> <source>Open until %1</source> <translation>%1 değerine dek açık</translation> </message> <message> <location line="+3"/> <source>Offline (%1 confirmations)</source> <translation>Çevrimdışı (%1 teyit)</translation> </message> <message> <location line="+3"/> <source>Unconfirmed (%1 of %2 confirmations)</source> <translation>Doğrulanmadı (%1 (toplam %2 üzerinden) teyit)</translation> </message> <message> <location line="+3"/> <source>Confirmed (%1 confirmations)</source> <translation>Doğrulandı (%1 teyit)</translation> </message> <message numerus="yes"> <location line="+8"/> <source>Mined balance will be available when it matures in %n more block(s)</source> <translation><numerusform>Madenden çıkarılan bakiye %n ek blok sonrasında olgunlaştığında kullanılabilecektir</numerusform><numerusform>Madenden çıkarılan bakiye %n ek blok sonrasında olgunlaştığında kullanılabilecektir</numerusform></translation> </message> <message> <location line="+5"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>Bu blok başka hiçbir düğüm tarafından alınmamıştır ve muhtemelen kabul edilmeyecektir!</translation> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation>Oluşturuldu ama kabul edilmedi</translation> </message> <message> <location line="+43"/> <source>Received with</source> <translation>Şununla alındı</translation> </message> <message> <location line="+2"/> <source>Received from</source> <translation>Alındığı kişi</translation> </message> <message> <location line="+3"/> <source>Sent to</source> <translation>Gönderildiği adres</translation> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation>Kendinize ödeme</translation> </message> <message> <location line="+2"/> <source>Mined</source> <translation>Madenden çıkarılan</translation> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation>(mevcut değil)</translation> </message> <message> <location line="+199"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>Muamele durumu. Doğrulama sayısını görüntülemek için imleci bu alanda tutunuz.</translation> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation>Muamelenin alındığı tarih ve zaman.</translation> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation>Muamele türü.</translation> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation>Muamelenin alıcı adresi.</translation> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation>Bakiyeden alınan ya da bakiyeye eklenen miktar.</translation> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+52"/> <location line="+16"/> <source>All</source> <translation>Hepsi</translation> </message> <message> <location line="-15"/> <source>Today</source> <translation>Bugün</translation> </message> <message> <location line="+1"/> <source>This week</source> <translation>Bu hafta</translation> </message> <message> <location line="+1"/> <source>This month</source> <translation>Bu ay</translation> </message> <message> <location line="+1"/> <source>Last month</source> <translation>Geçen ay</translation> </message> <message> <location line="+1"/> <source>This year</source> <translation>Bu sene</translation> </message> <message> <location line="+1"/> <source>Range...</source> <translation>Aralık...</translation> </message> <message> <location line="+11"/> <source>Received with</source> <translation>Şununla alınan</translation> </message> <message> <location line="+2"/> <source>Sent to</source> <translation>Gönderildiği adres</translation> </message> <message> <location line="+2"/> <source>To yourself</source> <translation>Kendinize</translation> </message> <message> <location line="+1"/> <source>Mined</source> <translation>Oluşturulan</translation> </message> <message> <location line="+1"/> <source>Other</source> <translation>Diğer</translation> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation>Aranacak adres ya da etiket giriniz</translation> </message> <message> <location line="+7"/> <source>Min amount</source> <translation>Asgari miktar</translation> </message> <message> <location line="+34"/> <source>Copy address</source> <translation>Adresi kopyala</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>Etiketi kopyala</translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>Miktarı kopyala</translation> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation>Muamele kimliğini kopyala</translation> </message> <message> <location line="+1"/> <source>Edit label</source> <translation>Etiketi düzenle</translation> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation>Muamele detaylarını göster</translation> </message> <message> <location line="+139"/> <source>Export Transaction Data</source> <translation>Muamele verilerini dışa aktar</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Virgülle ayrılmış değerler dosyası (*.csv)</translation> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation>Doğrulandı</translation> </message> <message> <location line="+1"/> <source>Date</source> <translation>Tarih</translation> </message> <message> <location line="+1"/> <source>Type</source> <translation>Tür</translation> </message> <message> <location line="+1"/> <source>Label</source> <translation>Etiket</translation> </message> <message> <location line="+1"/> <source>Address</source> <translation>Adres</translation> </message> <message> <location line="+1"/> <source>Amount</source> <translation>Miktar</translation> </message> <message> <location line="+1"/> <source>ID</source> <translation>Tanımlayıcı</translation> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation>Dışa aktarımda hata oluştu</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>%1 dosyasına yazılamadı.</translation> </message> <message> <location line="+100"/> <source>Range:</source> <translation>Aralık:</translation> </message> <message> <location line="+8"/> <source>to</source> <translation>ilâ</translation> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+193"/> <source>Send Coins</source> <translation>Hellascoin yolla</translation> </message> </context> <context> <name>WalletView</name> <message> <location filename="../walletview.cpp" line="+42"/> <source>&amp;Export</source> <translation>&amp;Dışa aktar</translation> </message> <message> <location line="+1"/> <source>Export the data in the current tab to a file</source> <translation>Güncel sekmedeki verileri bir dosyaya aktar</translation> </message> <message> <location line="+193"/> <source>Backup Wallet</source> <translation>Cüzdanı yedekle</translation> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation>Cüzdan verileri (*.dat)</translation> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation>Yedekleme başarısız oldu</translation> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation>Cüzdanı değişik bir konuma kaydetmek denenirken bir hata meydana geldi.</translation> </message> <message> <location line="+4"/> <source>Backup Successful</source> <translation>Yedekleme başarılı</translation> </message> <message> <location line="+0"/> <source>The wallet data was successfully saved to the new location.</source> <translation>Cüzdan verileri başarılı bir şekilde yeni konuma kaydedildi.</translation> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+94"/> <source>Hellascoin version</source> <translation>Hellascoin sürümü</translation> </message> <message> <location line="+102"/> <source>Usage:</source> <translation>Kullanım:</translation> </message> <message> <location line="-29"/> <source>Send command to -server or hellascoind</source> <translation>-server ya da hellascoind&apos;ye komut gönder</translation> </message> <message> <location line="-23"/> <source>List commands</source> <translation>Komutları listele</translation> </message> <message> <location line="-12"/> <source>Get help for a command</source> <translation>Bir komut için yardım al</translation> </message> <message> <location line="+24"/> <source>Options:</source> <translation>Seçenekler:</translation> </message> <message> <location line="+24"/> <source>Specify configuration file (default: hellascoin.conf)</source> <translation>Yapılandırma dosyası belirt (varsayılan: hellascoin.conf)</translation> </message> <message> <location line="+3"/> <source>Specify pid file (default: hellascoind.pid)</source> <translation>Pid dosyası belirt (varsayılan: hellascoind.pid)</translation> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation>Veri dizinini belirt</translation> </message> <message> <location line="-9"/> <source>Set database cache size in megabytes (default: 25)</source> <translation>Veritabanı önbellek boyutunu megabayt olarak belirt (varsayılan: 25)</translation> </message> <message> <location line="-28"/> <source>Listen for connections on &lt;port&gt; (default: 9333 or testnet: 19333)</source> <translation>Bağlantılar için dinlenecek &lt;port&gt; (varsayılan: 9333 ya da testnet: 19333)</translation> </message> <message> <location line="+5"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation>Eşler ile en çok &lt;n&gt; adet bağlantı kur (varsayılan: 125)</translation> </message> <message> <location line="-48"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation>Eş adresleri elde etmek için bir düğüme bağlan ve ardından bağlantıyı kes</translation> </message> <message> <location line="+82"/> <source>Specify your own public address</source> <translation>Kendi genel adresinizi tanımlayın</translation> </message> <message> <location line="+3"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation>Aksaklık gösteren eşlerle bağlantıyı kesme sınırı (varsayılan: 100)</translation> </message> <message> <location line="-134"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation>Aksaklık gösteren eşlerle yeni bağlantıları engelleme süresi, saniye olarak (varsayılan: 86400)</translation> </message> <message> <location line="-29"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation>IPv4 üzerinde dinlemek için %u numaralı RPC portunun kurulumu sırasında hata meydana geldi: %s</translation> </message> <message> <location line="+27"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 9332 or testnet: 19332)</source> <translation>JSON-RPC bağlantılarını &lt;port&gt; üzerinde dinle (varsayılan: 9332 veya tesnet: 19332)</translation> </message> <message> <location line="+37"/> <source>Accept command line and JSON-RPC commands</source> <translation>Konut satırı ve JSON-RPC komutlarını kabul et</translation> </message> <message> <location line="+76"/> <source>Run in the background as a daemon and accept commands</source> <translation>Arka planda daemon (servis) olarak çalış ve komutları kabul et</translation> </message> <message> <location line="+37"/> <source>Use the test network</source> <translation>Deneme şebekesini kullan</translation> </message> <message> <location line="-112"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation>Dışarıdan gelen bağlantıları kabul et (varsayılan: -proxy veya -connect yoksa 1)</translation> </message> <message> <location line="-80"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=hellascoinrpc rpcpassword=%s (you do not need to remember this password) The username and password MUST NOT be the same. If the file does not exist, create it with owner-readable-only file permissions. It is also recommended to set alertnotify so you are notified of problems; for example: alertnotify=echo %%s | mail -s &quot;Hellascoin Alert&quot; admin@foo.com </source> <translation>%s, şu yapılandırma dosyasında rpc parolası belirtmeniz gerekir: %s Aşağıdaki rastgele oluşturulan parolayı kullanmanız tavsiye edilir: rpcuser=hellascoinrpc rpcpassword=%s (bu parolayı hatırlamanız gerekli değildir) Kullanıcı ismi ile parolanın FARKLI olmaları gerekir. Dosya mevcut değilse, sadece sahibi için okumayla sınırlı izin ile oluşturunuz. Sorunlar hakkında bildiri almak için alertnotify unsurunu ayarlamanız tavsiye edilir; mesela: alertnotify=echo %%s | mail -s &quot;Hellascoin Alert&quot; admin@foo.com </translation> </message> <message> <location line="+17"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation>IPv6 üzerinde dinlemek için %u numaralı RPC portu kurulurken bir hata meydana geldi, IPv4&apos;e dönülüyor: %s</translation> </message> <message> <location line="+3"/> <source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source> <translation>Belirtilen adrese bağlan ve daima ondan dinle. IPv6 için [makine]:port yazımını kullanınız</translation> </message> <message> <location line="+3"/> <source>Cannot obtain a lock on data directory %s. Hellascoin is probably already running.</source> <translation>%s veri dizininde kilit elde edilemedi. Hellascoin muhtemelen hâlihazırda çalışmaktadır.</translation> </message> <message> <location line="+3"/> <source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation>Hata: Muamele reddedildi! Cüzdanınızdaki madenî paraların bazıları zaten harcanmış olduğunda bu meydana gelebilir. Örneğin wallet.dat dosyasının bir kopyasını kullandıysanız ve kopyada para harcandığında ancak burada harcandığı işaretlenmediğinde.</translation> </message> <message> <location line="+4"/> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source> <translation>Hata: Muamelenin miktarı, karmaşıklığı ya da yakın geçmişte alınan fonların kullanılması nedeniyle bu muamele en az %s tutarında ücret gerektirmektedir!</translation> </message> <message> <location line="+3"/> <source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source> <translation>İlgili bir uyarı alındığında komut çalıştır (komuttaki %s mesaj ile değiştirilecektir)</translation> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation>Bir cüzdan muamelesi değiştiğinde komutu çalıştır (komuttaki %s TxID ile değiştirilecektir)</translation> </message> <message> <location line="+11"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation>Yüksek öncelikli/düşük ücretli muamelelerin boyutunu bayt olarak tanımla (varsayılan: 27000)</translation> </message> <message> <location line="+6"/> <source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source> <translation>Bu yayın öncesi bir deneme sürümüdür - tüm riski siz üstlenmiş olursunuz - hellascoin oluşturmak ya da ticari uygulamalar için kullanmayınız</translation> </message> <message> <location line="+5"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation>Uyarı: -paytxfee çok yüksek bir değere ayarlanmış! Bu, muamele gönderirseniz ödeyeceğiniz muamele ücretidir.</translation> </message> <message> <location line="+3"/> <source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source> <translation>Uyarı: Görüntülenen muameleler doğru olmayabilir! Sizin ya da diğer düğümlerin güncelleme yapması gerekebilir.</translation> </message> <message> <location line="+3"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong Hellascoin will not work properly.</source> <translation>Uyarı: Lütfen bilgisayarınızın tarih ve saatinin doğru olup olmadığını kontrol ediniz! Saatiniz doğru değilse Hellascoin gerektiği gibi çalışamaz.</translation> </message> <message> <location line="+3"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation>Uyarı: wallet.dat dosyasının okunması sırasında bir hata meydana geldi! Tüm anahtarlar doğru bir şekilde okundu, ancak muamele verileri ya da adres defteri unsurları hatalı veya eksik olabilir.</translation> </message> <message> <location line="+3"/> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation>Uyarı: wallet.dat bozuk, veriler geri kazanıldı! Özgün wallet.dat, wallet.{zamandamgası}.bak olarak %s klasörüne kaydedildi; bakiyeniz ya da muameleleriniz yanlışsa bir yedeklemeden tekrar yüklemeniz gerekir.</translation> </message> <message> <location line="+14"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation>Bozuk bir wallet.dat dosyasından özel anahtarları geri kazanmayı dene</translation> </message> <message> <location line="+2"/> <source>Block creation options:</source> <translation>Blok oluşturma seçenekleri:</translation> </message> <message> <location line="+5"/> <source>Connect only to the specified node(s)</source> <translation>Sadece belirtilen düğüme veya düğümlere bağlan</translation> </message> <message> <location line="+3"/> <source>Corrupted block database detected</source> <translation>Bozuk blok veritabanı tespit edildi</translation> </message> <message> <location line="+1"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation>Kendi IP adresini keşfet (varsayılan: dinlenildiğinde ve -externalip yoksa 1)</translation> </message> <message> <location line="+1"/> <source>Do you want to rebuild the block database now?</source> <translation>Blok veritabanını şimdi yeniden inşa etmek istiyor musunuz?</translation> </message> <message> <location line="+2"/> <source>Error initializing block database</source> <translation>Blok veritabanını başlatılırken bir hata meydana geldi</translation> </message> <message> <location line="+1"/> <source>Error initializing wallet database environment %s!</source> <translation>%s cüzdan veritabanı ortamının başlatılmasında hata meydana geldi!</translation> </message> <message> <location line="+1"/> <source>Error loading block database</source> <translation>Blok veritabanının yüklenmesinde hata</translation> </message> <message> <location line="+4"/> <source>Error opening block database</source> <translation>Blok veritabanının açılışı sırasında hata</translation> </message> <message> <location line="+2"/> <source>Error: Disk space is low!</source> <translation>Hata: Disk alanı düşük!</translation> </message> <message> <location line="+1"/> <source>Error: Wallet locked, unable to create transaction!</source> <translation>Hata: Cüzdan kilitli, muamele oluşturulamadı!</translation> </message> <message> <location line="+1"/> <source>Error: system error: </source> <translation>Hata: sistem hatası:</translation> </message> <message> <location line="+1"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation>Herhangi bir portun dinlenmesi başarısız oldu. Bunu istiyorsanız -listen=0 seçeneğini kullanınız.</translation> </message> <message> <location line="+1"/> <source>Failed to read block info</source> <translation>Blok verileri okunamadı</translation> </message> <message> <location line="+1"/> <source>Failed to read block</source> <translation>Blok okunamadı</translation> </message> <message> <location line="+1"/> <source>Failed to sync block index</source> <translation>Blok indeksi eşleştirilemedi</translation> </message> <message> <location line="+1"/> <source>Failed to write block index</source> <translation>Blok indeksi yazılamadı</translation> </message> <message> <location line="+1"/> <source>Failed to write block info</source> <translation>Blok verileri yazılamadı</translation> </message> <message> <location line="+1"/> <source>Failed to write block</source><|fim▁hole|> <translation>Blok yazılamadı</translation> </message> <message> <location line="+1"/> <source>Failed to write file info</source> <translation>Dosya verileri yazılamadı</translation> </message> <message> <location line="+1"/> <source>Failed to write to coin database</source> <translation>Madenî para veritabanına yazılamadı</translation> </message> <message> <location line="+1"/> <source>Failed to write transaction index</source> <translation>Muamele indeksi yazılamadı</translation> </message> <message> <location line="+1"/> <source>Failed to write undo data</source> <translation>Geri alma verilerinin yazılamadı</translation> </message> <message> <location line="+2"/> <source>Find peers using DNS lookup (default: 1 unless -connect)</source> <translation>Eşleri DNS araması vasıtasıyla bul (varsayılan: 1, eğer -connect kullanılmadıysa)</translation> </message> <message> <location line="+1"/> <source>Generate coins (default: 0)</source> <translation>Hellascoin oluştur (varsayılan: 0)</translation> </message> <message> <location line="+2"/> <source>How many blocks to check at startup (default: 288, 0 = all)</source> <translation>Başlangıçta kontrol edilecek blok sayısı (varsayılan: 288, 0 = hepsi)</translation> </message> <message> <location line="+1"/> <source>How thorough the block verification is (0-4, default: 3)</source> <translation>Blok kontrolünün ne kadar derin olacağı (0 ilâ 4, varsayılan: 3)</translation> </message> <message> <location line="+19"/> <source>Not enough file descriptors available.</source> <translation>Kafi derecede dosya tanımlayıcıları mevcut değil.</translation> </message> <message> <location line="+8"/> <source>Rebuild block chain index from current blk000??.dat files</source> <translation>Blok zinciri indeksini güncel blk000??.dat dosyalarından tekrar inşa et</translation> </message> <message> <location line="+16"/> <source>Set the number of threads to service RPC calls (default: 4)</source> <translation>RPC aramaları için iş parçacığı sayısını belirle (varsayılan: 4)</translation> </message> <message> <location line="+26"/> <source>Verifying blocks...</source> <translation>Bloklar kontrol ediliyor...</translation> </message> <message> <location line="+1"/> <source>Verifying wallet...</source> <translation>Cüzdan kontrol ediliyor...</translation> </message> <message> <location line="-69"/> <source>Imports blocks from external blk000??.dat file</source> <translation>Harici blk000??.dat dosyasından blokları içe aktarır</translation> </message> <message> <location line="-76"/> <source>Set the number of script verification threads (up to 16, 0 = auto, &lt;0 = leave that many cores free, default: 0)</source> <translation>Betik kontrolü iş parçacığı sayısını belirt (azami 16, 0 = otomatik, &lt;0 = bu sayıda çekirdeği boş bırak, varsayılan: 0)</translation> </message> <message> <location line="+77"/> <source>Information</source> <translation>Bilgi</translation> </message> <message> <location line="+3"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation>Geçersiz -tor adresi: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount for -minrelaytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>-minrelaytxfee=&lt;amount&gt; için geçersiz meblağ: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount for -mintxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>-mintxfee=&lt;amount&gt; için geçersiz meblağ: &apos;%s&apos;</translation> </message> <message> <location line="+8"/> <source>Maintain a full transaction index (default: 0)</source> <translation>Muamelelerin tamamının indeksini tut (varsayılan: 0)</translation> </message> <message> <location line="+2"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation>Bağlantı başına azami alım tamponu, &lt;n&gt;*1000 bayt (varsayılan: 5000)</translation> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation>Bağlantı başına azami yollama tamponu, &lt;n&gt;*1000 bayt (varsayılan: 1000)</translation> </message> <message> <location line="+2"/> <source>Only accept block chain matching built-in checkpoints (default: 1)</source> <translation>Sadece yerleşik kontrol noktalarıyla eşleşen blok zincirini kabul et (varsayılan: 1)</translation> </message> <message> <location line="+1"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation>Sadece &lt;net&gt; şebekesindeki düğümlere bağlan (IPv4, IPv6 ya da Tor)</translation> </message> <message> <location line="+2"/> <source>Output extra debugging information. Implies all other -debug* options</source> <translation>İlâve hata ayıklama verileri çıkart. Diğer tüm -debug* seçeneklerini ima eder</translation> </message> <message> <location line="+1"/> <source>Output extra network debugging information</source> <translation>İlâve şebeke hata ayıklama verileri çıkart</translation> </message> <message> <location line="+2"/> <source>Prepend debug output with timestamp</source> <translation>Hata ayıklama çıktısına tarih ön ekleri ilâve et</translation> </message> <message> <location line="+5"/> <source>SSL options: (see the Hellascoin Wiki for SSL setup instructions)</source> <translation> SSL seçenekleri: (SSL kurulum bilgisi için Hellascoin vikisine bakınız)</translation> </message> <message> <location line="+1"/> <source>Select the version of socks proxy to use (4-5, default: 5)</source> <translation>Kullanılacak socks vekil sunucu sürümünü seç (4-5, varsayılan: 5)</translation> </message> <message> <location line="+3"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation>Trace/hata ayıklama verilerini debug.log dosyası yerine konsola gönder</translation> </message> <message> <location line="+1"/> <source>Send trace/debug info to debugger</source> <translation>Hata ayıklayıcıya -debugger- trace/hata ayıklama verileri gönder</translation> </message> <message> <location line="+5"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation>Bayt olarak azami blok boyutunu tanımla (varsayılan: 250000)</translation> </message> <message> <location line="+1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation>Bayt olarak asgari blok boyutunu tanımla (varsayılan: 0)</translation> </message> <message> <location line="+2"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation>İstemci başlatıldığında debug.log dosyasını küçült (varsayılan: -debug bulunmadığında 1)</translation> </message> <message> <location line="+1"/> <source>Signing transaction failed</source> <translation>Muamelenin imzalanması başarısız oldu</translation> </message> <message> <location line="+2"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation>Bağlantı zaman aşım süresini milisaniye olarak belirt (varsayılan: 5000)</translation> </message> <message> <location line="+4"/> <source>System error: </source> <translation>Sistem hatası:</translation> </message> <message> <location line="+4"/> <source>Transaction amount too small</source> <translation>Muamele meblağı çok düşük</translation> </message> <message> <location line="+1"/> <source>Transaction amounts must be positive</source> <translation>Muamele tutarının pozitif olması lazımdır</translation> </message> <message> <location line="+1"/> <source>Transaction too large</source> <translation>Muamele çok büyük</translation> </message> <message> <location line="+7"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation>Dinlenecek portu haritalamak için UPnP kullan (varsayılan: 0)</translation> </message> <message> <location line="+1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation>Dinlenecek portu haritalamak için UPnP kullan (varsayılan: dinlenildiğinde 1)</translation> </message> <message> <location line="+1"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation>Gizli tor servislerine erişmek için vekil sunucu kullan (varsayılan: -proxy ile aynısı)</translation> </message> <message> <location line="+2"/> <source>Username for JSON-RPC connections</source> <translation>JSON-RPC bağlantıları için kullanıcı ismi</translation> </message> <message> <location line="+4"/> <source>Warning</source> <translation>Uyarı</translation> </message> <message> <location line="+1"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation>Uyarı: Bu sürüm çok eskidir, güncellemeniz gerekir!</translation> </message> <message> <location line="+1"/> <source>You need to rebuild the databases using -reindex to change -txindex</source> <translation>-txindex&apos;i değiştirmek için veritabanlarını -reindex kullanarak yeniden inşa etmeniz gerekir.</translation> </message> <message> <location line="+1"/> <source>wallet.dat corrupt, salvage failed</source> <translation>wallet.dat bozuk, geri kazanım başarısız oldu</translation> </message> <message> <location line="-50"/> <source>Password for JSON-RPC connections</source> <translation>JSON-RPC bağlantıları için parola</translation> </message> <message> <location line="-67"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation>Belirtilen İP adresinden JSON-RPC bağlantılarını kabul et</translation> </message> <message> <location line="+76"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation>Şu &lt;ip&gt; adresinde (varsayılan: 127.0.0.1) çalışan düğüme komut yolla</translation> </message> <message> <location line="-120"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation>En iyi blok değiştiğinde komutu çalıştır (komut için %s parametresi blok hash değeri ile değiştirilecektir)</translation> </message> <message> <location line="+147"/> <source>Upgrade wallet to latest format</source> <translation>Cüzdanı en yeni biçime güncelle</translation> </message> <message> <location line="-21"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation>Anahtar alan boyutunu &lt;n&gt; değerine ayarla (varsayılan: 100)</translation> </message> <message> <location line="-12"/> <source>Rescan the block chain for missing wallet transactions</source> <translation>Blok zincirini eksik cüzdan muameleleri için tekrar tara</translation> </message> <message> <location line="+35"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation>JSON-RPC bağlantıları için OpenSSL (https) kullan</translation> </message> <message> <location line="-26"/> <source>Server certificate file (default: server.cert)</source> <translation>Sunucu sertifika dosyası (varsayılan: server.cert)</translation> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation>Sunucu özel anahtarı (varsayılan: server.pem)</translation> </message> <message> <location line="-151"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation>Kabul edilebilir şifreler (varsayılan: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation> </message> <message> <location line="+165"/> <source>This help message</source> <translation>Bu yardım mesajı</translation> </message> <message> <location line="+6"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation>Bu bilgisayarda %s unsuruna bağlanılamadı. (bind şu hatayı iletti: %d, %s)</translation> </message> <message> <location line="-91"/> <source>Connect through socks proxy</source> <translation>Socks vekil sunucusu vasıtasıyla bağlan</translation> </message> <message> <location line="-10"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation>-addnode, -seednode ve -connect için DNS aramalarına izin ver</translation> </message> <message> <location line="+55"/> <source>Loading addresses...</source> <translation>Adresler yükleniyor...</translation> </message> <message> <location line="-35"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation>wallet.dat dosyasının yüklenmesinde hata oluştu: bozuk cüzdan</translation> </message> <message> <location line="+1"/> <source>Error loading wallet.dat: Wallet requires newer version of Hellascoin</source> <translation>wallet.dat dosyasının yüklenmesinde hata oluştu: cüzdanın daha yeni bir Hellascoin sürümüne ihtiyacı var</translation> </message> <message> <location line="+93"/> <source>Wallet needed to be rewritten: restart Hellascoin to complete</source> <translation>Cüzdanın tekrar yazılması gerekiyordu: işlemi tamamlamak için Hellascoin&apos;i yeniden başlatınız</translation> </message> <message> <location line="-95"/> <source>Error loading wallet.dat</source> <translation>wallet.dat dosyasının yüklenmesinde hata oluştu</translation> </message> <message> <location line="+28"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation>Geçersiz -proxy adresi: &apos;%s&apos;</translation> </message> <message> <location line="+56"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation>-onlynet için bilinmeyen bir şebeke belirtildi: &apos;%s&apos;</translation> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation>Bilinmeyen bir -socks vekil sürümü talep edildi: %i</translation> </message> <message> <location line="-96"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation>-bind adresi çözümlenemedi: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation>-externalip adresi çözümlenemedi: &apos;%s&apos;</translation> </message> <message> <location line="+44"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>-paytxfee=&lt;miktar&gt; için geçersiz miktar: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount</source> <translation>Geçersiz miktar</translation> </message> <message> <location line="-6"/> <source>Insufficient funds</source> <translation>Yetersiz bakiye</translation> </message> <message> <location line="+10"/> <source>Loading block index...</source> <translation>Blok indeksi yükleniyor...</translation> </message> <message> <location line="-57"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation>Bağlanılacak düğüm ekle ve bağlantıyı zinde tutmaya çalış</translation> </message> <message> <location line="-25"/> <source>Unable to bind to %s on this computer. Hellascoin is probably already running.</source> <translation>Bu bilgisayarda %s unsuruna bağlanılamadı. Hellascoin muhtemelen hâlihazırda çalışmaktadır.</translation> </message> <message> <location line="+64"/> <source>Fee per KB to add to transactions you send</source> <translation>Yolladığınız muameleler için eklenecek KB başı ücret</translation> </message> <message> <location line="+19"/> <source>Loading wallet...</source> <translation>Cüzdan yükleniyor...</translation> </message> <message> <location line="-52"/> <source>Cannot downgrade wallet</source> <translation>Cüzdan eski biçime geri alınamaz</translation> </message> <message> <location line="+3"/> <source>Cannot write default address</source> <translation>Varsayılan adres yazılamadı</translation> </message> <message> <location line="+64"/> <source>Rescanning...</source> <translation>Yeniden tarama...</translation> </message> <message> <location line="-57"/> <source>Done loading</source> <translation>Yükleme tamamlandı</translation> </message> <message> <location line="+82"/> <source>To use the %s option</source> <translation>%s seçeneğini kullanmak için</translation> </message> <message> <location line="-74"/> <source>Error</source> <translation>Hata</translation> </message> <message> <location line="-31"/> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation>rpcpassword=&lt;parola&gt; şu yapılandırma dosyasında belirtilmelidir: %s Dosya mevcut değilse, sadece sahibi için okumayla sınırlı izin ile oluşturunuz.</translation> </message> </context> </TS><|fim▁end|>
<|file_name|>topic_index.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- #--- #--- Python import sys import StringIO import argparse #--- #--- 3rd party from redmine import Redmine from redmine import exceptions as redmine_exceptions #--- class ProjectTree(object) : def __init__(self, allProjects ) : self._projects = list(allProjects) self._projectsByName = {} # name -> project for project in self._projects : self._projectsByName[project.name.encode('utf-8')] = project self._projects.sort(key = lambda p : self.getBreadcrumbTrail(p)) def iter_dfs(self) : for project in self._projects : yield project def getParent(self, project) : """ @return: None or project.parent """ try : parentProjectName = project.parent.name.encode('utf-8') except AttributeError : parentProjectName = '' if not parentProjectName : parentProject = None else : parentProject = self._projectsByName.get(parentProjectName, None) if 0 : print "DEBUG: parentName = %r" % (parentProjectName,) print "DEBUG: parentObject %r" % (parentProject,) return parentProject def getBreadcrumbTrail(self, project, encoding = 'utf-8') : """ @return: (..., parentName, projectName) """ return list(p.name.encode(encoding) for p in self.getAncestorsAndProject(project)) def getAncestorProjects(self, project) : def _iterAncestors(project) : parent = self.getParent(project) if parent is None : return yield parent for a in _iterAncestors(parent) : yield a return list(reversed(list(_iterAncestors(project)))) def getAncestorsAndProject(self, project) : return self.getAncestorProjects(project) + [project] #--- class PageTree(object) : def __init__(self, project, allPages) : self._project = project self._pages = list(allPages) self._pagesByTitle = {} # title -> page<|fim▁hole|> for page in self._pages : self._pagesByTitle[page.title.encode('utf-8')] = page self._pagesWithParent = {} # title -> {page -> [childPages, ...]} for page in self._pages : if 0 : print "DEBUG: %r %r" % (project, page,) self._insert(page) self._pages.sort(key = lambda p : self.getBreadcrumbTrail(p)) def getParent(self, page) : """ @return: None or page.parent """ try : parentPageTitle = page.parent.title.encode('utf-8') except AttributeError : parentPageTitle = '' if not parentPageTitle : parentPage = None else : parentPage = self._pagesByTitle.get(parentPageTitle, None) if 0 : print "DEBUG: parentPageTitle = %r" % (parentPageTitle,) print "DEBUG: parentPage %r" % (parentPage,) return parentPage def getBreadcrumbTrail(self, page, encoding = 'utf-8') : """ @return: (..., parentPage, page) """ return list(p.title.encode(encoding).replace('_', ' ') for p in self.getAncestorsAndPage(page)) def getAncestorPages(self, page) : def _iterAncestors(page) : parent = self.getParent(page) if parent is None : return yield parent for a in _iterAncestors(parent) : yield a return list(reversed(list(_iterAncestors(page)))) def getAncestorsAndPage(self, page) : return self.getAncestorPages(page) + [page] def _insert(self, page) : #self._pages.append(page) #if parentPage is None : # self.pagesWithParent[page] = [] return def iter_dfs(self) : for page in self._pages : yield page #--- def printGlobalTopicIndex(redmineHandle, topicParentPage) : lineCount = 0 for line in iterGlobaleTopicIndexLines(redmineHandle, topicParentPage) : lineCount += 1 print line return lineCount def iterGlobaleTopicIndexLines(redmineHandle, topicParentPage, **keywords) : """ Iterates over the lines of the target document line by line. @keyword printProgress: If True progress information will be printed to stdout @type printProgress: bool """ yield "{{>toc}}" yield "" yield "h1. %s" % (topicParentPage,) yield "" yield "Diese Seite wurde automatisch generiert. Manuelle Änderungen an dieser Seite werden beim nächsten Lauf überschrieben werdern!" yield "" yield "h2. In diesem Projekt" yield "" yield "{{child_pages}}" yield "" yield "h2. In diesem Projekt und Unterprojekten" yield "" letterHeading = None for entry in sorted(iterTopicEntries(redmineHandle, topicParentPage, **keywords)) : prettyPageTitle = entry[0] projectIdent = entry[1] projectBreadcrumbTrail = entry[2] pageAuthor = entry[3] pageUpdatedOn = entry[4] pageCreatedOn = entry[5] updatedOnDate = pageUpdatedOn.strftime("%d.%m.%Y") firstLetter = prettyPageTitle[0] if firstLetter != letterHeading : yield "" yield "" yield "h3. %s" % (firstLetter,) yield "" letterHeading = firstLetter indent = "*" yield "%(indent)s [[%(projectIdent)s:%(prettyPageTitle)s]] (%(projectBreadcrumbTrail)s) (zuletzt geändert am %(updatedOnDate)s von %(pageAuthor)s) " % locals() def iterTopicEntries(redmineHandle, topicParentPage, **keywords) : printProgress = keywords.get('printProgress', False) baseURL = redmineHandle.url r = redmineHandle allProjects = r.project.all() projectCount = len(allProjects) if projectCount == 0 : return projectTree = ProjectTree(allProjects) FIRST_TIME = True for (projNum, project) in enumerate(projectTree.iter_dfs()) : projectBreadcrumbTrail = " » ".join(projectTree.getBreadcrumbTrail(project)) pid = project.id # numeric projectIdent = project.identifier.encode('utf-8', 'ignore') # symbolic pname = project.name # singlePage = r.wiki_page.get('Mitarbeiter', project_id = PID) # yield singlePage.text allPagesQuery = r.wiki_page.filter(project_id = pid) try : allPages = list(allPagesQuery) except redmine_exceptions.ForbiddenError : #print "Cannot access pages of project '%(pident)s'!" % locals() allPages = [] if len(allPages) > 0 : if printProgress : print "%i/%i:" %(projNum+1, projectCount), if FIRST_TIME : FIRST_TIME = False pageTree = PageTree(project, allPages) for (pageNum,page) in enumerate(pageTree.iter_dfs()) : if printProgress : print ".", pageTitle = page.title.encode('utf-8', 'ignore') prettyPageTitle = pageTitle.replace('_', ' ') pageAuthor = page.author.name.encode('utf-8', 'ignore') pageCreatedOn = page.created_on pageUpdatedOn = page.updated_on pageBreadcrumbTrail = pageTree.getBreadcrumbTrail(page)[:-1] if topicParentPage in pageBreadcrumbTrail : indent = "*" yield (prettyPageTitle, projectIdent, projectBreadcrumbTrail, pageAuthor, pageUpdatedOn, pageCreatedOn) # yield "%(indent)s %(pageTitle)s (von %(pageAuthor)s) -> %(ancestors)r" % locals() if printProgress : print "" #--- class CLI(object) : """ Encapsulates the Command Line Interface. """ def __init__(self) : self._parser = parser = self._createParser() self._args = args = parser.parse_args() if args.apikey is None : print "You must provide a Redmine API-Key as first argument." sys.exit(1) return def _createParser(self) : parser = argparse.ArgumentParser() parser.add_argument("--apikey", help = "Valid API-key to use the Python REST-API") parser.add_argument("-t", "--targetpage", help = "Fully qualified Name of a Wiki page the result should be stored on", default = "") parser.add_argument("-p", "--projectid", help = "Id of the project the target wiki page belongs to", default = "") parser.add_argument("--topicparentpage", help = "Name of the parent page whose child pages should be collected.", default = "") return parser def getBaseURL(self) : """ Base URL of the Redmine instance. """ baseURL = 'https://redmine.itz.uni-halle.de' return baseURL def getApiKey(self) : """ Valid API-key to use the REST-API of Redmine. """ return self._args.apikey def getTargetPage(self) : """ @rtype: None or str """ return "Begriffe" # self._args.targetpage def getProjectId(self) : """Target Project ID""" return self._args.projectid def getTopicParentPage(self) : """Pages with this parent page will be listet on the target page.""" return self._args.topicparentpage.replace('_', ' ') #--- def main() : cli = CLI() baseURL = cli.getBaseURL() apiKey = cli.getApiKey() redmineHandle = Redmine(baseURL, key = apiKey) topicParentPage = cli.getTopicParentPage() allProjects = redmineHandle.project.all() projectCount = len(allProjects) if projectCount == 0 : print "You must provide a VALID Redmine API-Key!" return targetPage = cli.getTargetPage() targetProjectId = cli.getProjectId() print targetProjectId, targetPage if not targetPage or not targetProjectId: lineCount = printGlobalTopicIndex(redmineHandle, topicParentPage) else : pageLines = list(iterGlobaleTopicIndexLines(redmineHandle, topicParentPage, printProgress = True)) newText = "\n".join(pageLines) oldPage = redmineHandle.wiki_page.get(targetPage, project_id = targetProjectId) oldText = oldPage.text.encode('utf-8') if oldText != newText : redmineHandle.wiki_page.update(targetPage, project_id = targetProjectId, title = 'Global index', text = newText, parent_title ='', comments = 'automatisch aktualisiert') return if __name__ == '__main__' : #sys_stderr = sys.stderr #errbuf = StringIO.StringIO() #sys.stderr = errbuf try : main() except KeyboardInterrupt : sys.exit(0) #sys.stderr = sys_stderr<|fim▁end|>
<|file_name|>transaction.py<|end_file_name|><|fim▁begin|>""":mod:`flask.ext.volatile.transaction` --- Key-level transactions ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2011 by Hong Minhee, StyleShare :license: MIT License, see :file:`LICENSE` for more details. """ import time from werkzeug.contrib.cache import BaseCache __all__ = 'Transaction', 'Reference' class Transaction(object): """The key-level transaction block. It implements two interfaces: :class:`~collections.Iterable` If it is used in :keyword:`for` loop, the operations inside :keyword:`for` block become committed atomically:: for ref in Transaction(cache, 'cache_key'): value = ref() value = value + ['append element'] ref(value) The yielding object is :class:`Reference`. :class:`~collections.Callable` If a function is passed into the transaction object, the operations inside the function are committed atomically:: def block(value): return value + ['append element'] t = Transaction(cache, 'cache_key') t(block) The block function takes a cached value and a return value will be committed. Of course it can be used as decorator also:: @Transaction(cache, 'cache_key') def block(value): return value + ['append element'] :param cache: the cache client to use :type cache: :class:`werkzeug.contrib.cache.BaseCache` :param key: the key to operate atomically :param version_key: the key for versioning. by default ``__ver`` suffix appended to ``key`` :type timeout: the cache timeout for the key (if not specified, it uses the default timeout) """ def __init__(self, cache, key, version_key=None, timeout=None): if not isinstance(cache, BaseCache): raise TypeError('cache must be a werkzeug.contrib.cache.BaseCache ' 'object, but %r passed' % cache) self.cache = cache self.key = key if version_key is None: version_key = key + '__ver' self.version_key = version_key self.timeout = timeout def __iter__(self): i = 0 while True: ref = Reference(self, i) yield ref if ref.commit(): break i += 1 def __call__(self, block): for ref in self: ref.set(block(ref.value)) class Reference(object): """The reference to key. It provides atomic :meth:`get`/:meth:`set` operations for the key. There redundant ways to :meth:`get`/:meth:`set` the value: By property You can get or set the :attr:`value` property. By methods You can use :meth:`get()` and :meth:`set` methods. By call It is callable. You can get the value by calling the reference without any arguments and set the value by calling the reference with an argument of the value to set. :param transaction: the transaction block :type transaction: :class:`Transaction` :param tried_number: the retried number in a transaction. default is 0 .. note:: <|fim▁hole|> This object is automatically made by :class:`Transaction`. You don't have to instantiate it directly. """ def __init__(self, transaction, tried_number=0): if not isinstance(transaction, Transaction): raise TypeError('expected a flask.ext.volatile.transaction.' 'Transaction, but %r passed' % transaction) self.transaction = transaction self.cache = transaction.cache self.key = transaction.key self.version_key = transaction.version_key self.timeout = transaction.timeout self.version = None self.tried_number = tried_number @property def value(self): """The read/write property for the value inside the key.""" self.version = time.time() self.cache.set(self.version_key, self.version, self.timeout) val = self.cache.get(self.key) if val: return val[1] @value.setter def value(self, value): self._val = value def get(self): """Gets the value inside the key. :returns: the value inside the key """ return self.value def set(self, value): """Sets the value into the key. :param value: the new value to set into the key """ self.value = value def commit(self): """Tries committing the operations and its result. :returns: ``False`` if it conflicted :rtype: :class:`bool` """ try: val = self._val except AttributeError: return True self.cache.set(self.key, (self.version, val), self.timeout) check = self.cache.get(self.key) return check and check[0] == self.version def __call__(self, *args): if len(args) > 1: raise TypeError('too many arguments') elif args: self.set(args[0]) return self.value<|fim▁end|>
<|file_name|>version.hpp<|end_file_name|><|fim▁begin|>#include "farversion.hpp" <|fim▁hole|>#define PLUGIN_BUILD 37 #define PLUGIN_DESC L"File names case conversion for Far Manager" #define PLUGIN_NAME L"FileCase" #define PLUGIN_FILENAME L"FileCase.dll" #define PLUGIN_AUTHOR FARCOMPANYNAME #define PLUGIN_VERSION MAKEFARVERSION(FARMANAGERVERSION_MAJOR,FARMANAGERVERSION_MINOR,FARMANAGERVERSION_REVISION,PLUGIN_BUILD,VS_RELEASE)<|fim▁end|>
<|file_name|>AutoRestAzureSpecialParametersTestClientImpl.java<|end_file_name|><|fim▁begin|>/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ package fixtures.azurespecials.implementation; import com.microsoft.azure.AzureClient; import com.microsoft.azure.AzureServiceClient; import com.microsoft.azure.RestClient; import com.microsoft.rest.credentials.ServiceClientCredentials; import fixtures.azurespecials.ApiVersionDefaults; import fixtures.azurespecials.ApiVersionLocals; import fixtures.azurespecials.AutoRestAzureSpecialParametersTestClient; import fixtures.azurespecials.Headers; import fixtures.azurespecials.Odatas; import fixtures.azurespecials.SkipUrlEncodings; import fixtures.azurespecials.SubscriptionInCredentials; import fixtures.azurespecials.SubscriptionInMethods; import fixtures.azurespecials.XMsClientRequestIds; /** * Initializes a new instance of the AutoRestAzureSpecialParametersTestClientImpl class. */ public final class AutoRestAzureSpecialParametersTestClientImpl extends AzureServiceClient implements AutoRestAzureSpecialParametersTestClient { /** the {@link AzureClient} used for long running operations. */ private AzureClient azureClient; /** * Gets the {@link AzureClient} used for long running operations.<|fim▁hole|> return this.azureClient; } /** The subscription id, which appears in the path, always modeled in credentials. The value is always '1234-5678-9012-3456'. */ private String subscriptionId; /** * Gets The subscription id, which appears in the path, always modeled in credentials. The value is always '1234-5678-9012-3456'. * * @return the subscriptionId value. */ public String subscriptionId() { return this.subscriptionId; } /** * Sets The subscription id, which appears in the path, always modeled in credentials. The value is always '1234-5678-9012-3456'. * * @param subscriptionId the subscriptionId value. * @return the service client itself */ public AutoRestAzureSpecialParametersTestClientImpl withSubscriptionId(String subscriptionId) { this.subscriptionId = subscriptionId; return this; } /** The api version, which appears in the query, the value is always '2015-07-01-preview'. */ private String apiVersion; /** * Gets The api version, which appears in the query, the value is always '2015-07-01-preview'. * * @return the apiVersion value. */ public String apiVersion() { return this.apiVersion; } /** Gets or sets the preferred language for the response. */ private String acceptLanguage; /** * Gets Gets or sets the preferred language for the response. * * @return the acceptLanguage value. */ public String acceptLanguage() { return this.acceptLanguage; } /** * Sets Gets or sets the preferred language for the response. * * @param acceptLanguage the acceptLanguage value. * @return the service client itself */ public AutoRestAzureSpecialParametersTestClientImpl withAcceptLanguage(String acceptLanguage) { this.acceptLanguage = acceptLanguage; return this; } /** Gets or sets the retry timeout in seconds for Long Running Operations. Default value is 30. */ private int longRunningOperationRetryTimeout; /** * Gets Gets or sets the retry timeout in seconds for Long Running Operations. Default value is 30. * * @return the longRunningOperationRetryTimeout value. */ public int longRunningOperationRetryTimeout() { return this.longRunningOperationRetryTimeout; } /** * Sets Gets or sets the retry timeout in seconds for Long Running Operations. Default value is 30. * * @param longRunningOperationRetryTimeout the longRunningOperationRetryTimeout value. * @return the service client itself */ public AutoRestAzureSpecialParametersTestClientImpl withLongRunningOperationRetryTimeout(int longRunningOperationRetryTimeout) { this.longRunningOperationRetryTimeout = longRunningOperationRetryTimeout; return this; } /** When set to true a unique x-ms-client-request-id value is generated and included in each request. Default is true. */ private boolean generateClientRequestId; /** * Gets When set to true a unique x-ms-client-request-id value is generated and included in each request. Default is true. * * @return the generateClientRequestId value. */ public boolean generateClientRequestId() { return this.generateClientRequestId; } /** * Sets When set to true a unique x-ms-client-request-id value is generated and included in each request. Default is true. * * @param generateClientRequestId the generateClientRequestId value. * @return the service client itself */ public AutoRestAzureSpecialParametersTestClientImpl withGenerateClientRequestId(boolean generateClientRequestId) { this.generateClientRequestId = generateClientRequestId; return this; } /** * The XMsClientRequestIds object to access its operations. */ private XMsClientRequestIds xMsClientRequestIds; /** * Gets the XMsClientRequestIds object to access its operations. * @return the XMsClientRequestIds object. */ public XMsClientRequestIds xMsClientRequestIds() { return this.xMsClientRequestIds; } /** * The SubscriptionInCredentials object to access its operations. */ private SubscriptionInCredentials subscriptionInCredentials; /** * Gets the SubscriptionInCredentials object to access its operations. * @return the SubscriptionInCredentials object. */ public SubscriptionInCredentials subscriptionInCredentials() { return this.subscriptionInCredentials; } /** * The SubscriptionInMethods object to access its operations. */ private SubscriptionInMethods subscriptionInMethods; /** * Gets the SubscriptionInMethods object to access its operations. * @return the SubscriptionInMethods object. */ public SubscriptionInMethods subscriptionInMethods() { return this.subscriptionInMethods; } /** * The ApiVersionDefaults object to access its operations. */ private ApiVersionDefaults apiVersionDefaults; /** * Gets the ApiVersionDefaults object to access its operations. * @return the ApiVersionDefaults object. */ public ApiVersionDefaults apiVersionDefaults() { return this.apiVersionDefaults; } /** * The ApiVersionLocals object to access its operations. */ private ApiVersionLocals apiVersionLocals; /** * Gets the ApiVersionLocals object to access its operations. * @return the ApiVersionLocals object. */ public ApiVersionLocals apiVersionLocals() { return this.apiVersionLocals; } /** * The SkipUrlEncodings object to access its operations. */ private SkipUrlEncodings skipUrlEncodings; /** * Gets the SkipUrlEncodings object to access its operations. * @return the SkipUrlEncodings object. */ public SkipUrlEncodings skipUrlEncodings() { return this.skipUrlEncodings; } /** * The Odatas object to access its operations. */ private Odatas odatas; /** * Gets the Odatas object to access its operations. * @return the Odatas object. */ public Odatas odatas() { return this.odatas; } /** * The Headers object to access its operations. */ private Headers headers; /** * Gets the Headers object to access its operations. * @return the Headers object. */ public Headers headers() { return this.headers; } /** * Initializes an instance of AutoRestAzureSpecialParametersTestClient client. * * @param credentials the management credentials for Azure */ public AutoRestAzureSpecialParametersTestClientImpl(ServiceClientCredentials credentials) { this("http://localhost", credentials); } /** * Initializes an instance of AutoRestAzureSpecialParametersTestClient client. * * @param baseUrl the base URL of the host * @param credentials the management credentials for Azure */ public AutoRestAzureSpecialParametersTestClientImpl(String baseUrl, ServiceClientCredentials credentials) { this(new RestClient.Builder() .withBaseUrl(baseUrl) .withCredentials(credentials) .build()); } /** * Initializes an instance of AutoRestAzureSpecialParametersTestClient client. * * @param restClient the REST client to connect to Azure. */ public AutoRestAzureSpecialParametersTestClientImpl(RestClient restClient) { super(restClient); initialize(); } protected void initialize() { this.apiVersion = "2015-07-01-preview"; this.acceptLanguage = "en-US"; this.longRunningOperationRetryTimeout = 30; this.generateClientRequestId = true; this.xMsClientRequestIds = new XMsClientRequestIdsImpl(restClient().retrofit(), this); this.subscriptionInCredentials = new SubscriptionInCredentialsImpl(restClient().retrofit(), this); this.subscriptionInMethods = new SubscriptionInMethodsImpl(restClient().retrofit(), this); this.apiVersionDefaults = new ApiVersionDefaultsImpl(restClient().retrofit(), this); this.apiVersionLocals = new ApiVersionLocalsImpl(restClient().retrofit(), this); this.skipUrlEncodings = new SkipUrlEncodingsImpl(restClient().retrofit(), this); this.odatas = new OdatasImpl(restClient().retrofit(), this); this.headers = new HeadersImpl(restClient().retrofit(), this); this.azureClient = new AzureClient(this); } /** * Gets the User-Agent header for the client. * * @return the user agent string. */ @Override public String userAgent() { return String.format("Azure-SDK-For-Java/%s (%s)", getClass().getPackage().getImplementationVersion(), "AutoRestAzureSpecialParametersTestClient, 2015-07-01-preview"); } }<|fim▁end|>
* @return the azure client; */ public AzureClient getAzureClient() {
<|file_name|>remote_viewer_it.ts<|end_file_name|><|fim▁begin|><?xml version="1.0" encoding="utf-8"?> <!DOCTYPE TS> <TS version="2.0" language="it_IT"> <context> <name>BookmarksWidget</name> <message> <source>Filter:</source> <translation>Filtro:</translation> </message> </context> <context> <name>FontDialog</name> <message> <source>Select Terminal Font</source> <translation>Seleziona carattere terminale</translation> </message> <message> <source>Font:</source> <translation>Carattere:</translation> </message> <message> <source>Size:</source> <translation>Dimensione:</translation> </message> <message> <source>Preview</source> <translation>Anteprima</translation> </message> </context> <context> <name>GetURLDialog</name> <message> <source>Get URL</source> <translation>Ottieni URL</translation> </message> <message> <source>Connect</source> <translation>Соnnetti</translation> </message> <message> <source>Info</source> <translation>Informazioni</translation> </message> <message> <source>URL schema</source> <translation>Schema URL</translation> </message> <message> <source>If you have SSH access to remote host and an internal address for VM graphics then you can use Remote Viewer with such path: &lt;vnc|spice&gt;://HOST[:PORT]/?transport=ssh&amp;user=&lt;USER&gt;&amp;addr=&lt;IP&gt;&amp;port=&lt;NUMBER&gt; If you have graphic socket on local or remote host: &lt;vnc|spice&gt;://[HOST[:PORT]]/?[transport=ssh&amp;user=&lt;USER&gt;&amp;]socket=/path/to/socket</source> <translation>Se hai accesso SSH all&apos;host remoto e un indirizzo interno per la schermo della VM puoi utilizzare il visualizzatore remoto con questo percorso: &lt;vnc|spice&gt;://HOST[:PORTA]/?transport=ssh&amp;user=&lt;UTENTE&gt;&amp;addr=&lt;IP&gt;&amp;port=&lt;NUMERO&gt;</translation> </message> </context> <context> <name>LXC_Viewer</name> <message> <source>In &apos;&lt;b&gt;%1&lt;/b&gt;&apos;: Display destroyed.</source> <translation>In &apos;&lt;b&gt;%1&lt;/b&gt;&apos;: schermo terminato.</translation> </message> <message> <source>In &apos;&lt;b&gt;%1&lt;/b&gt;&apos;:&lt;br&gt; Connection or Domain is NULL or inactive</source> <translation>In &apos;&lt;b&gt;%1&lt;/b&gt;&apos;:&lt;br&gt; La connessione o il dominio è NULL o inattiva</translation> </message> <message> <source>In &apos;&lt;b&gt;%1&lt;/b&gt;&apos;: Open PTY Error...</source> <translation>In &apos;&lt;b&gt;%1&lt;/b&gt;&apos;: errore di apertura PTY...</translation> </message> <message> <source>In &apos;&lt;b&gt;%1&lt;/b&gt;&apos;: Stream Registration success. PTY opened. Terminal is active.</source> <translation>In &apos;&lt;b&gt;%1&lt;/b&gt;&apos;: registrazione del flusso avvenuta. PTY aperto. Il terminale è attivo.</translation> </message> </context> <context> <name>LXC_ViewerThread</name> <message> <source>In &apos;&lt;b&gt;%1&lt;/b&gt;&apos;: Console opened in ZERO-mode...</source> <translation>In &apos;&lt;b&gt;%1&lt;/b&gt;&apos;: console aperta in modalità ZERO...</translation> </message> <message> <source>In &apos;&lt;b&gt;%1&lt;/b&gt;&apos;: Open console failed...</source> <translation>In &apos;&lt;b&gt;%1&lt;/b&gt;&apos;: apertura della console non riuscita...</translation> </message> <message> <source>In &apos;&lt;b&gt;%1&lt;/b&gt;&apos;: EOF.</source> <translation>In &apos;&lt;b&gt;%1&lt;/b&gt;&apos;: EOF.</translation> </message> </context> <context> <name>PropertiesDialog</name> <message> <source>Terminal settings</source> <translation>Impostazioni del terminale</translation> </message> <message> <source>Appearance</source> <translation>Aspetto</translation> </message> <message> <source>Behavior</source> <translation>Comportamento</translation> </message> <message> <source>Shortcuts</source> <translation>Scorciatoie</translation> </message> <message> <source>Dropdown</source> <translation>Menu a tendina</translation> </message> <message> <source>Bookmarks</source> <translation>Segnalibri</translation> </message> <message> <source>Color scheme</source> <translation>Schema di colori</translation> </message> <message> <source>Widget style</source> <translation>Stile degli oggetti</translation> </message> <message> <source>Scrollbar position</source> <translation>Posizione della barra di scorrimento</translation> </message> <message> <source>Tabs position</source> <translation>Posizione delle schede</translation> </message> <message> <source>Show the menu bar</source> <translation>Mostra la barra di stato</translation> </message> <message> <source>Always show the tab bar</source> <translation>Mostra sempre la barra delle schede</translation> </message> <message> <source>Show a border around the current terminal</source> <translation>Mostra un bordo intorno al terminale attuale</translation> </message> <message> <source>Application transparency</source> <translation>Trasparenza dell&apos;applicazione</translation> </message> <message> <source> %</source> <translation> %</translation> </message> <message> <source>Terminal transparency</source> <translation>Trasparenza del terminale</translation> </message> <message> <source>Start with preset:</source> <translation>Avvia con preimpostazione:</translation> </message> <message> <source>None (single terminal)</source> <translation>Nessuna (terminale singolo)</translation> </message> <message> <source>2 terminals horizontally</source> <translation>2 terminali orizzontalmente</translation> </message> <message> <source>2 terminals vertically</source> <translation>2 terminali verticalmente</translation> </message> <message> <source>4 terminals</source> <translation>4 terminali</translation> </message> <message> <source>Font</source> <translation>Carattere</translation> </message> <message> <source>&amp;Set Font...</source> <translation>Impo&amp;sta carattere...</translation> </message> <message> <source>Emulation</source> <translation>Emulazione</translation> </message> <message> <source>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;Which behavior to emulate. Note that this does not have to match your operating system.&lt;/p&gt;&lt;p&gt;The &lt;span style=&quot; font-weight:600;&quot;&gt;default&lt;/span&gt; emulation is a fallback with a minimal featureset.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</source> <translation>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;Quale comportamento emulare. Nota che questo non deve corrispondere al tuo sistema operativo.&lt;/p&gt;&lt;p&gt;L&apos;emulazione &lt;span style=&quot; font-weight:600;&quot;&gt;predefinita&lt;/span&gt; è un ripiego con un insieme ridotto di funzionalità.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</translation> </message> <message> <source>Action after paste</source> <translation>Azione dopo incolla</translation> </message> <message> <source>Open new terminals in current working directory</source> <translation>Apri nuovi terminali nella cartella di lavoro attuale</translation> </message> <message> <source>Ask for confirmation when closing</source> <translation>Chiedi conferma alla chiusura</translation> </message> <message> <source>Unlimited history</source> <translation>Cronologia illimitata</translation> </message> <message> <source>History size (in lines)</source> <translation>Dimensione della cronologia (in righe)</translation> </message> <message> <source>Shortcut</source> <translation>Scorciatoia</translation> </message> <message> <source>Key</source> <translation>Tasto</translation> </message> <message> <source>Show on start</source> <translation>Mostra all&apos;avvio</translation> </message> <message> <source>Size</source> <translation>Dimensione</translation> </message> <message> <source>Height</source> <translation>Altezza</translation> </message> <message> <source>%</source> <translation>%</translation> </message> <message> <source>Width</source> <translation>Larghezza</translation> </message> <message> <source>Shortcut:</source> <translation>Scorciatoia:</translation> </message> <message> <source>Edit bookmark file contents</source> <translation>Modifica il contenuto del file dei segnalibri</translation> </message> <message> <source>Enable bookmarks</source> <translation>Abilita i segnalibri</translation> </message> <message> <source>Bookmark file</source> <translation>File dei segnalibri</translation> </message> <message> <source>Find...</source> <translation>Trova...</translation> </message> <message> <source>You can specify your own bookmarks file location. It allows easy bookmark sharing with tools like OwnCloud or Dropbox.</source> <translation>Puoi specificare la posizione del tuo file dei segnalibri. Consente una rapida condivisione dei segnalibri con strumenti come OwnCloud o Dropbox.</translation> </message> <message> <source>No scrollbar</source> <translation>Nessuna barra di scorrimento</translation> </message> <message> <source>Left</source> <translation>Sinistra</translation> </message> <message> <source>Right</source> <translation>Destra</translation> </message> <message> <source>Top</source> <translation>Alto</translation> </message> <message> <source>Bottom</source> <translation>Basso</translation> </message> <message> <source>No move</source> <translation>Nessuno spostamento</translation> </message> <message> <source>Move start</source> <translation>Sposta all&apos;inizio</translation> </message> <message> <source>Move end</source> <translation>Sposta alla fine</translation> </message> <message> <source>System Default</source> <translation>Valori predefiniti di sistema</translation> </message> <message> <source>Open or create bookmarks file</source> <translation>Apri o crea il file dei segnalibri</translation> </message> </context> <context> <name>QObject</name> <message> <source>Local Bookmarks</source> <translation>Segnalibri locali</translation> </message> <message> <source>Synchronized Bookmarks</source> <translation>Segnalibri sincronizzati</translation> </message> </context> <context> <name>QSpiceMainChannel</name> <message> <source>main_channel</source> <translation>canale principale</translation> </message> <message> <source>file transfer</source> <translation>traferimento file</translation> </message> </context> <context> <name>QSpiceSmartcardWidget</name> <message> <source>Smartcards</source> <translation>Smartcard</translation> </message> </context> <context> <name>QSpiceUsbDeviceManager</name> <message> <source>connect to guest.</source> <translation>connettiti al guest.</translation> </message> <message> <source>connected to guest already.</source> <translation>già connesso al guest.</translation> </message> <message> <source>disconnect from guest.</source> <translation>disconnettiti dal guest.</translation> </message> <message> <source>disconnected from guest already.</source> <translation>già disconnesso dal guest.</translation> </message> </context> <context> <name>QSpiceUsbDeviceWidget</name> <message> <source>USB Redirection</source> <translation>Redirezione USB</translation> </message> </context> <context> <name>QSpiceWidget</name> <message> <source>Download: %1 %</source> <translation>Scaricamento: %1 %</translation> </message> <message> <source>no event, or ignored event</source> <translation>nessun evento, o evento ignorato</translation> </message> <message> <source>connection is authentified and ready</source> <translation>la connessione è autenticata e pronta</translation> </message> <message> <source>disconnecting from the current host and connecting to the target host</source> <translation>disconnessione dall&apos;host attuale e connessione all&apos;host di destinazione</translation> </message> <message> <source>connection is closed normally (sent if channel was ready)</source> <translation>la connessione è chiusa normalmente (inviata se il canale era pronto)</translation> </message> <message> <source>connection error</source> <translation>errore di connessione</translation> </message> <message> <source>SSL error</source> <translation>Errore SSL</translation> </message> <message> <source>error during link process</source> <translation>errore durante il processo di collegamento</translation> </message> <message> <source>authentication error</source> <translation>errore di autenticazione</translation> </message> <message> <source>IO error</source> <translation>Errore di I/O</translation> </message> <message> <source>Save Image to</source> <translation>Salva immagine in</translation> </message> </context> <context> <name>Spice_Viewer</name> <message> <source>Copy files to Guest</source> <translation>Copia file al guest</translation> </message> </context> <context> <name>Spice_Viewer_Only</name> <message> <source>Copy files to Guest</source> <translation>Copia file al guest</translation> </message> <message> <source>Qt Remote Viewer -- %1</source> <translation>Visore remoto Qt -- %1</translation> </message> </context> <context> <name>TermMainWindow</name> <message> <source>Bookmarks</source> <translation>Segnalibri</translation> </message> <message> <source>Rename Session</source> <translation>Rinomina sessione</translation> </message> <message> <source>Clear Current Tab</source> <translation>Cancella scheda attuale</translation> </message> <message> <source>Copy Selection</source> <translation>Copia selezione</translation> </message> <message> <source>Paste Clipboard</source> <translation>Incolla appunti</translation> </message> <message> <source>Paste Selection</source> <translation>Incolla selezione</translation> </message> <message> <source>Zoom in</source> <translation>Ingrandisci</translation> </message> <message> <source>Zoom out</source> <translation>Rimpicciolisci</translation> </message> <message> <source>Zoom reset</source> <translation>Ripristina ingrandimento</translation> </message> <message> <source>Find...</source> <translation>Trova...</translation> </message> <message> <source>Toggle Menu</source> <translation>Commuta menu</translation> </message> <message> <source>Hide Window Borders</source> <translation>Nascondi bordi delle finestre</translation> </message> <message> <source>None</source> <translation>Nessuno</translation> </message> <message> <source>Right</source> <translation>Destra</translation> </message> <message> <source>Left</source> <translation>Sinistra</translation> </message> <message> <source>Scrollbar Layout</source> <translation>Disposizione barra di scorrimento</translation> </message> <message> <source>A lightweight multiplatform terminal emulator</source> <translation>Un emulatore di terminale leggero e multi-piattaforma</translation> </message> </context> <context> <name>TermWidgetHolder</name> <message> <source>Load Session</source> <translation>Carica sessione</translation> </message> <message> <source>List of saved sessions:</source> <translation>Elenco delle sessioni salvate:</translation> </message> </context> <context> <name>TransformationModeMenu</name> <message> <source>fast (no smoothing)</source> <translation>veloce (senza arrotondamento)</translation> </message> <message> <source>smooth (slower)</source> <translation>regolare (più lenta)</translation> </message> </context> <context> <name>URLMenu</name> <message> <source>delete URL from list</source> <translation>elimina URL dall&apos;elenco</translation> </message> <message> <source>clear URL list</source> <translation>cancella elenco degli URL</translation> </message> </context> <context> <name>VM_State_Widget</name> <message> <source>File download progress</source> <translation>Avanzamento dello scaricamento dei file</translation> </message> <message> <source>ON</source> <translation>ON</translation> </message> <message> <source>OFF</source> <translation>OFF</translation> </message> <message> <source> Click to choose devices</source> <translation> Fai clic per scegliere i dispositivi</translation> </message> <message> <source> Click to choose mode</source> <translation> Fai clic per scegliere la modalità</translation> </message> <message> <source>SmartCard channel</source> <translation>Canale smartcard</translation> </message> <message> <source>Cursor channel</source> <translation>Canale del cursore</translation> </message> <message> <source>Inputs channel</source> <translation>Canale degli ingressi</translation> </message> <message> <source>Display channel</source> <translation>Canale dello schermo</translation> </message> <message> <source>USB Redirect channel</source> <translation>Canale redirezione USB</translation> </message> <message> <source>WebDAV channel</source> <translation>Canale WebDAV</translation> </message> <message> <source>Playback channel</source> <translation>Canale di riproduzione</translation> </message> <message> <source>Record channel</source> <translation>Canale di registrazione</translation> </message> </context> <context> <name>VM_Viewer</name> <message> <source>&lt;%1&gt; Virtual Machine in [ %2 ] connection</source> <translation>&lt;%1&gt; Macchina virtuale nella connessione [ %2 ]</translation> </message> <message> <source>In &apos;&lt;b&gt;%1&lt;/b&gt;&apos;:&lt;br&gt; Getting the address data is failed.</source> <translation>In &apos;&lt;b&gt;%1&lt;/b&gt;&apos;:&lt;br&gt; Recupero dei dati dell&apos;indirizzo non riuscito.</translation> </message> <message> <source>In &apos;&lt;b&gt;%1&lt;/b&gt;&apos;:&lt;br&gt; Open the VM graphics is failed.</source> <translation>In &apos;&lt;b&gt;%1&lt;/b&gt;&apos;:&lt;br&gt; Apertura dello schermo delle VM non riuscita.</translation> </message> <message> <source>&apos;&lt;b&gt;%1&lt;/b&gt;&apos; VM viewer closed.</source> <translation>&apos;&lt;b&gt;%1&lt;/b&gt;&apos; Visore VM chiuso.</translation> </message> <message> <source>Connection &apos;%1&apos;</source> <translation>Connessione &apos;%1&apos;</translation> </message> <message> <source>&lt;b&gt;%1 %2:&lt;/b&gt;&lt;br&gt;&lt;font color=&apos;blue&apos;&gt;&lt;b&gt;EVENT&lt;/b&gt;&lt;/font&gt;: %3</source> <translation>&lt;b&gt;%1 %2:&lt;/b&gt;&lt;br&gt;&lt;font color=&apos;blue&apos;&gt;&lt;b&gt;EVENTO&lt;/b&gt;&lt;/font&gt;: %3</translation> </message> <message> <source>Save to</source> <translation>Salva in</translation> </message> <message> <source>Restore from</source> <translation>Ripristina da</translation> </message> <message> <source>SSH tunnel is destroyed.</source> <translation>Il canale SSH è terminato.</translation> </message><|fim▁hole|> <message> <source>Shift+F11</source> <comment>View|Full Screen</comment> <translation>Maiusc+F11</translation> </message> </context> <context> <name>VM_Viewer_Only</name> <message> <source>In &apos;&lt;b&gt;%1&lt;/b&gt;&apos;:&lt;br&gt; Getting the address data is failed.</source> <translation>In &apos;&lt;b&gt;%1&lt;/b&gt;&apos;:&lt;br&gt; Recupero dei dati dell&apos;indirizzo non riuscito.</translation> </message> <message> <source>In &apos;&lt;b&gt;%1&lt;/b&gt;&apos;:&lt;br&gt; Open the address is failed.</source> <translation>In &apos;&lt;b&gt;%1&lt;/b&gt;&apos;:&lt;br&gt; Apertura dell&apos;indirizzo non riuscita.</translation> </message> <message> <source>Can&apos;t connect to host: %1</source> <translation>Impossibile connettersi all&apos;host: %1</translation> </message> <message> <source>SSH tunnel is destroyed.</source> <translation>Il tunnel SSH è terminato.</translation> </message> <message> <source>Shift+F11</source> <comment>View|Full Screen</comment> <translation>Maiusc+F11</translation> </message> </context> <context> <name>VNC_Viewer</name> <message> <source>Save Image to</source> <translation>Salva immagine in</translation> </message> </context> <context> <name>VNC_Viewer_Only</name> <message> <source>Save Image to</source> <translation>Salva immagine in</translation> </message> <message> <source>Qt Remote Viewer -- %1</source> <translation>Visore remoto Qt -- %1</translation> </message> </context> <context> <name>ViewerToolBar</name> <message> <source>Pause</source> <translation>Sospendi</translation> </message> <message> <source>Reboot</source> <translation>Riavvia</translation> </message> <message> <source>Reset</source> <translation>Reset</translation> </message> <message> <source>Shutdown</source> <translation>Spegni</translation> </message> <message> <source>Save</source> <translation>Salva</translation> </message> <message> <source>Stop</source> <translation>Ferma</translation> </message> <message> <source>create Snapshot of Current Domain</source> <translation>crea istantanea del dominio attuale</translation> </message> <message> <source>more Snapshot actions for Domain</source> <translation>altre azioni di istantanea per dominio</translation> </message> <message> <source>Snapshot now!</source> <translation>Istantanea subito!</translation> </message> <message> <source>Reconnect</source> <translation>Riconnetti</translation> </message> <message> <source>Send key sequence</source> <translation>Invia sequenza di tasti</translation> </message> <message> <source>get Guest Screenshot</source> <translation>Ottieni schermata del guest</translation> </message> <message> <source>Copy Files to Guest</source> <translation>Copia file al guest</translation> </message> <message> <source>Copy from Guest to Clipboard</source> <translation>Copia dal guest agli appunti</translation> </message> <message> <source>Paste Clipboard to Guest</source> <translation>Incolla appunti al guest</translation> </message> <message> <source>FullScreen</source> <translation>Schermo intero</translation> </message> <message> <source>Scale to window</source> <translation>Scala alla finestra</translation> </message> </context> <context> <name>VncView</name> <message> <source>Password required</source> <translation>Password richiesta</translation> </message> <message> <source>Please enter the password for the remote desktop:</source> <translation>Digita la password per il desktop remoto:</translation> </message> </context> <context> <name>mainWindow</name> <message> <source>MainWindow</source> <translation>Finestra principale</translation> </message> <message> <source>File</source> <translation>File</translation> </message> <message> <source>Actions</source> <translation>Azioni</translation> </message> <message> <source>Help</source> <translation>Aiuto</translation> </message> <message> <source>View</source> <translation>Visualizza</translation> </message> <message> <source>Edit</source> <translation>Modifica</translation> </message> <message> <source>About...</source> <translation>Informazioni...</translation> </message> <message> <source>About Qt...</source> <translation>Informazioni su Qt...</translation> </message> <message> <source>&amp;Preferences...</source> <translation>&amp;Preferenze...</translation> </message> <message> <source>&amp;Quit</source> <translation>&amp;Esci</translation> </message> </context> </TS><|fim▁end|>
<|file_name|>course.service.spec.ts<|end_file_name|><|fim▁begin|>/* tslint:disable max-line-length */ import { TestBed, getTestBed } from '@angular/core/testing'; import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { HttpClient, HttpResponse } from '@angular/common/http'; import { of } from 'rxjs'; import { take, map } from 'rxjs/operators'; import * as moment from 'moment'; import { DATE_TIME_FORMAT } from 'app/shared/constants/input.constants'; import { CourseService } from 'app/entities/course/course.service'; import { ICourse, Course } from 'app/shared/model/course.model'; describe('Service Tests', () => { describe('Course Service', () => { let injector: TestBed; let service: CourseService; let httpMock: HttpTestingController; let elemDefault: ICourse; let currentDate: moment.Moment; beforeEach(() => { TestBed.configureTestingModule({ imports: [HttpClientTestingModule], }); injector = getTestBed(); service = injector.get(CourseService); httpMock = injector.get(HttpTestingController); currentDate = moment(); elemDefault = new Course(0, 'AAAAAAA', 'AAAAAAA', 'AAAAAAA', 'AAAAAAA', currentDate, currentDate, false); }); describe('Service methods', async () => { it('should find an element', async () => { const returnedFromService = Object.assign( { startDate: currentDate.format(DATE_TIME_FORMAT),<|fim▁hole|> elemDefault, ); service .find(123) .pipe(take(1)) .subscribe(resp => expect(resp).toMatchObject({ body: elemDefault })); const req = httpMock.expectOne({ method: 'GET' }); req.flush(JSON.stringify(returnedFromService)); }); it('should create a Course', async () => { const returnedFromService = Object.assign( { id: 0, startDate: currentDate.format(DATE_TIME_FORMAT), endDate: currentDate.format(DATE_TIME_FORMAT), }, elemDefault, ); const expected = Object.assign( { startDate: currentDate, endDate: currentDate, }, returnedFromService, ); service .create(new Course(null)) .pipe(take(1)) .subscribe(resp => expect(resp).toMatchObject({ body: expected })); const req = httpMock.expectOne({ method: 'POST' }); req.flush(JSON.stringify(returnedFromService)); }); it('should update a Course', async () => { const returnedFromService = Object.assign( { title: 'BBBBBB', studentGroupName: 'BBBBBB', teachingAssistantGroupName: 'BBBBBB', instructorGroupName: 'BBBBBB', startDate: currentDate.format(DATE_TIME_FORMAT), endDate: currentDate.format(DATE_TIME_FORMAT), onlineCourse: true, }, elemDefault, ); const expected = Object.assign( { startDate: currentDate, endDate: currentDate, }, returnedFromService, ); service .update(expected) .pipe(take(1)) .subscribe(resp => expect(resp).toMatchObject({ body: expected })); const req = httpMock.expectOne({ method: 'PUT' }); req.flush(JSON.stringify(returnedFromService)); }); it('should return a list of Course', async () => { const returnedFromService = Object.assign( { title: 'BBBBBB', studentGroupName: 'BBBBBB', teachingAssistantGroupName: 'BBBBBB', instructorGroupName: 'BBBBBB', startDate: currentDate.format(DATE_TIME_FORMAT), endDate: currentDate.format(DATE_TIME_FORMAT), onlineCourse: true, }, elemDefault, ); const expected = Object.assign( { startDate: currentDate, endDate: currentDate, }, returnedFromService, ); service .query(expected) .pipe( take(1), map(resp => resp.body), ) .subscribe(body => expect(body).toContainEqual(expected)); const req = httpMock.expectOne({ method: 'GET' }); req.flush(JSON.stringify([returnedFromService])); httpMock.verify(); }); it('should delete a Course', async () => { const rxPromise = service.delete(123).subscribe(resp => expect(resp.ok)); const req = httpMock.expectOne({ method: 'DELETE' }); req.flush({ status: 200 }); }); }); afterEach(() => { httpMock.verify(); }); }); });<|fim▁end|>
endDate: currentDate.format(DATE_TIME_FORMAT), },
<|file_name|>admin.module.ts<|end_file_name|><|fim▁begin|>import { NgModule } from '@angular/core' import { CommonModule } from '@angular/common' import { FormsModule } from '@angular/forms' import { AdminRoutes } from './admin.routes' //Compnsants pour le panneau d'administration import { HomePageAdmin } from './home_page_admin.component' import { DocsAdminPage } from './docs/docs_page.component' import { HomeAdminComponent } from './home/home_admin.component' import { AttrsDataAdminComponent } from './docs/attrs_data/attrs_data.component' import { SpeciesManagementComponent } from './docs/species/species_management.component' @NgModule({<|fim▁hole|> AdminRoutes ], declarations: [ HomePageAdmin, HomeAdminComponent, DocsAdminPage, AttrsDataAdminComponent, SpeciesManagementComponent ], providers: [ ] }) export class AdminModule {}<|fim▁end|>
imports: [ CommonModule, FormsModule,
<|file_name|>16.d.ts<|end_file_name|><|fim▁begin|>import { LogoTumblr16 } from "../../"; <|fim▁hole|><|fim▁end|>
export = LogoTumblr16;
<|file_name|>0004_auto_20150117_1017.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('profiles', '0003_auto_20150115_1939'), ] operations = [ migrations.AddField( model_name='calendalluser', name='location', field=models.CharField(blank=True, max_length=30, verbose_name='User location'), preserve_default=True, ), migrations.AddField( model_name='calendalluser', name='url', field=models.URLField(blank=True, verbose_name='User homepage'), preserve_default=True,<|fim▁hole|><|fim▁end|>
), ]
<|file_name|>auth.py<|end_file_name|><|fim▁begin|>"""Implement the auth feature from Hass.io for Add-ons.""" from ipaddress import ip_address import logging import os from aiohttp import web from aiohttp.web_exceptions import ( HTTPInternalServerError, HTTPNotFound, HTTPUnauthorized, ) import voluptuous as vol from homeassistant.auth.models import User from homeassistant.components.http import HomeAssistantView from homeassistant.components.http.const import KEY_HASS_USER, KEY_REAL_IP from homeassistant.components.http.data_validator import RequestDataValidator from homeassistant.core import callback from homeassistant.exceptions import HomeAssistantError import homeassistant.helpers.config_validation as cv from homeassistant.helpers.typing import HomeAssistantType from .const import ATTR_ADDON, ATTR_PASSWORD, ATTR_USERNAME _LOGGER = logging.getLogger(__name__) SCHEMA_API_AUTH = vol.Schema( { vol.Required(ATTR_USERNAME): cv.string, vol.Required(ATTR_PASSWORD): cv.string, vol.Required(ATTR_ADDON): cv.string, }, extra=vol.ALLOW_EXTRA, ) <|fim▁hole|>) @callback def async_setup_auth_view(hass: HomeAssistantType, user: User): """Auth setup.""" hassio_auth = HassIOAuth(hass, user) hassio_password_reset = HassIOPasswordReset(hass, user) hass.http.register_view(hassio_auth) hass.http.register_view(hassio_password_reset) class HassIOBaseAuth(HomeAssistantView): """Hass.io view to handle auth requests.""" def __init__(self, hass: HomeAssistantType, user: User): """Initialize WebView.""" self.hass = hass self.user = user def _check_access(self, request: web.Request): """Check if this call is from Supervisor.""" # Check caller IP hassio_ip = os.environ["HASSIO"].split(":")[0] if request[KEY_REAL_IP] != ip_address(hassio_ip): _LOGGER.error("Invalid auth request from %s", request[KEY_REAL_IP]) raise HTTPUnauthorized() # Check caller token if request[KEY_HASS_USER].id != self.user.id: _LOGGER.error("Invalid auth request from %s", request[KEY_HASS_USER].name) raise HTTPUnauthorized() def _get_provider(self): """Return Homeassistant auth provider.""" prv = self.hass.auth.get_auth_provider("homeassistant", None) if prv is not None: return prv _LOGGER.error("Can't find Home Assistant auth.") raise HTTPNotFound() class HassIOAuth(HassIOBaseAuth): """Hass.io view to handle auth requests.""" name = "api:hassio:auth" url = "/api/hassio_auth" @RequestDataValidator(SCHEMA_API_AUTH) async def post(self, request, data): """Handle auth requests.""" self._check_access(request) await self._check_login(data[ATTR_USERNAME], data[ATTR_PASSWORD]) return web.Response(status=200) async def _check_login(self, username, password): """Check User credentials.""" provider = self._get_provider() try: await provider.async_validate_login(username, password) except HomeAssistantError: raise HTTPUnauthorized() from None class HassIOPasswordReset(HassIOBaseAuth): """Hass.io view to handle password reset requests.""" name = "api:hassio:auth:password:reset" url = "/api/hassio_auth/password_reset" @RequestDataValidator(SCHEMA_API_PASSWORD_RESET) async def post(self, request, data): """Handle password reset requests.""" self._check_access(request) await self._change_password(data[ATTR_USERNAME], data[ATTR_PASSWORD]) return web.Response(status=200) async def _change_password(self, username, password): """Check User credentials.""" provider = self._get_provider() try: await self.hass.async_add_executor_job( provider.data.change_password, username, password ) await provider.data.async_save() except HomeAssistantError: raise HTTPInternalServerError()<|fim▁end|>
SCHEMA_API_PASSWORD_RESET = vol.Schema( {vol.Required(ATTR_USERNAME): cv.string, vol.Required(ATTR_PASSWORD): cv.string}, extra=vol.ALLOW_EXTRA,
<|file_name|>portal.rs<|end_file_name|><|fim▁begin|>use app; use components::*; use specs::Join; use specs; use levels; #[derive(Clone)]<|fim▁hole|>} impl specs::Component for Portal { type Storage = specs::VecStorage<Self>; } impl Portal { pub fn new(destination: levels::Level) -> Self { Portal { destination: destination, } } } pub struct PortalSystem; impl specs::System<app::UpdateContext> for PortalSystem { fn run(&mut self, arg: specs::RunArg, context: app::UpdateContext) { let (grid_squares, players, states, portals, entities) = arg.fetch(|world| { ( world.read::<GridSquare>(), world.read::<PlayerControl>(), world.read::<PhysicState>(), world.read::<Portal>(), world.entities() ) }); let mut player_pos = None; for (_, state) in (&players, &states).iter() { player_pos = Some(state.position); break; } if let Some(player_pos) = player_pos { for (portal,entity) in (&portals, &entities).iter() { let pos = grid_squares.get(entity).expect("portal expect grid square component").position; if (player_pos[0] - pos[0]).powi(2) + (player_pos[1] - pos[1]).powi(2) < 0.01 { context.control_tx.send(app::Control::GotoLevel(portal.destination.clone())).unwrap(); } } } } }<|fim▁end|>
pub struct Portal { destination: levels::Level,
<|file_name|>fr-MG.ts<|end_file_name|><|fim▁begin|>/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js export default [ 'fr-MG', [ ['AM', 'PM'], , ], , [ ['D', 'L', 'M', 'M', 'J', 'V', 'S'], ['dim.', 'lun.', 'mar.', 'mer.', 'jeu.', 'ven.', 'sam.'], ['dimanche', 'lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi', 'samedi'], ['di', 'lu', 'ma', 'me', 'je', 've', 'sa'] ], , [ ['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'], [ 'janv.', 'févr.', 'mars', 'avr.', 'mai', 'juin', 'juil.', 'août', 'sept.', 'oct.', 'nov.', 'déc.' ], [ 'janvier', 'février', 'mars', 'avril', 'mai', 'juin', 'juillet', 'août', 'septembre', 'octobre', 'novembre', 'décembre' ] ], , [['av. J.-C.', 'ap. J.-C.'], , ['avant Jésus-Christ', 'après Jésus-Christ']], 1, [6, 0], ['dd/MM/y', 'd MMM y', 'd MMMM y', 'EEEE d MMMM y'], ['HH:mm', 'HH:mm:ss', 'HH:mm:ss z', 'HH:mm:ss zzzz'], [ '{1} {0}', '{1} \'à\' {0}', , ], [',', ' ', ';', '%', '+', '-', 'E', '×', '‰', '∞', 'NaN', ':'], ['#,##0.###', '#,##0 %', '#,##0.00 ¤', '#E0'], 'Ar', 'ariary malgache', function(n: number): number {<|fim▁hole|> if (i === 0 || i === 1) return 1; return 5; } ];<|fim▁end|>
let i = Math.floor(Math.abs(n));
<|file_name|>rm.go<|end_file_name|><|fim▁begin|>package dockercommand import docker "github.com/fsouza/go-dockerclient" type RmOptions struct { Container []string Force bool } func (dock *Docker) Rm(options *RmOptions) error { for _, containerID := range options.Container {<|fim▁hole|> } } return nil }<|fim▁end|>
err := dock.client.RemoveContainer(docker.RemoveContainerOptions{ID: containerID, Force: options.Force}) if err != nil { return err
<|file_name|>search.js<|end_file_name|><|fim▁begin|><|fim▁hole|> switch(action.type) { case types.SEARCH_INPUT_SUCCESS: return action.data; case types.SEARCH_INPUT_FAILED: return action.error.message; default: return state; } }; export default search;<|fim▁end|>
import * as types from '../actions/types'; const search = (state = [], action) => {
<|file_name|>bug_972.py<|end_file_name|><|fim▁begin|>import unittest from PySide.QtCore import QSizeF from PySide.QtGui import QGraphicsProxyWidget, QSizePolicy, QPushButton, QGraphicsScene, QGraphicsView from helper import TimedQApplication def createItem(minimum, preferred, maximum, name): w = QGraphicsProxyWidget() w.setWidget(QPushButton(name))<|fim▁hole|> w.setPreferredSize(preferred) w.setMaximumSize(maximum) w.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) return w class TestBug972 (TimedQApplication): # Test if the function QGraphicsProxyWidget.setWidget have the correct behavior def testIt(self): scene = QGraphicsScene() minSize = QSizeF(30, 100) prefSize = QSizeF(210, 100) maxSize = QSizeF(300, 100) a = createItem(minSize, prefSize, maxSize, "A") b = createItem(minSize, prefSize, maxSize, "B") c = createItem(minSize, prefSize, maxSize, "C") d = createItem(minSize, prefSize, maxSize, "D") view = QGraphicsView(scene) view.show() self.app.exec_() if __name__ == "__main__": unittest.main()<|fim▁end|>
w.setMinimumSize(minimum)
<|file_name|>gst010.py<|end_file_name|><|fim▁begin|># -*- Mode: Python -*- # vi:si:et:sw=4:sts=4:ts=4 # Flumotion - a streaming media server # Copyright (C) 2004,2005,2006,2007,2008,2009 Fluendo, S.L. # Copyright (C) 2010,2011 Flumotion Services, S.A. # All rights reserved. # # This file may be distributed and/or modified under the terms of # the GNU Lesser General Public License version 2.1 as published by # the Free Software Foundation. # This file is distributed without any warranty; without even the implied # warranty of merchantability or fitness for a particular purpose. # See "LICENSE.LGPL" in the source distribution for more information. # # Headers in this file shall remain intact. import gobject import gst import gst.interfaces from twisted.internet.threads import deferToThread from twisted.internet import defer from flumotion.common import gstreamer, errors, log, messages from flumotion.common.i18n import N_, gettexter from flumotion.twisted import defer as fdefer from flumotion.worker.checks import check __version__ = "$Rev$" T_ = gettexter() class BusResolution(fdefer.Resolution): pipeline = None signal_id = None def cleanup(self): if self.pipeline: if self.signal_id: self.pipeline.get_bus().remove_signal_watch() self.pipeline.get_bus().disconnect(self.signal_id) self.signal_id = None self.pipeline.set_state(gst.STATE_NULL) self.pipeline = None def do_element_check(pipeline_str, element_name, check_proc, state=None, set_state_deferred=False): """ Parse the given pipeline and set it to the given state. When the bin reaches that state, perform the given check function on the element with the given name. @param pipeline_str: description of the pipeline used to test @param element_name: name of the element being checked @param check_proc: a function to call with the GstElement as argument. @param state: an unused keyword parameter that will be removed when support for GStreamer 0.8 is dropped. @param set_state_deferred: a flag to say whether the set_state is run in a deferToThread @type set_state_deferred: bool @returns: a deferred that will fire with the result of check_proc, or fail. @rtype: L{twisted.internet.defer.Deferred} """ def run_check(pipeline, resolution): element = pipeline.get_by_name(element_name) try: retval = check_proc(element) resolution.callback(retval) except check.CheckProcError, e: log.debug('check', 'CheckProcError when running %r: %r', check_proc, e.data) resolution.errback(errors.RemoteRunError(e.data)) except Exception, e: log.debug('check', 'Unhandled exception while running %r: %r', check_proc, e) resolution.errback(errors.RemoteRunError( log.getExceptionMessage(e))) # set pipeline state to NULL so worker does not consume # unnecessary resources pipeline.set_state(gst.STATE_NULL) def message_rcvd(bus, message, pipeline, resolution): t = message.type if t == gst.MESSAGE_STATE_CHANGED: if message.src == pipeline: old, new, pending = message.parse_state_changed() if new == gst.STATE_PLAYING: run_check(pipeline, resolution) elif t == gst.MESSAGE_ERROR: gerror, debug = message.parse_error() # set pipeline state to NULL so worker does not consume # unnecessary resources pipeline.set_state(gst.STATE_NULL) resolution.errback(errors.GStreamerGstError( message.src, gerror, debug)) elif t == gst.MESSAGE_EOS: resolution.errback(errors.GStreamerError( "Unexpected end of stream")) else: log.debug('check', 'message: %s: %s:' % ( message.src.get_path_string(), message.type.value_nicks[1])) if message.structure: log.debug('check', 'message: %s' % message.structure.to_string()) else: log.debug('check', 'message: (no structure)') return True resolution = BusResolution() log.debug('check', 'parsing pipeline %s' % pipeline_str) try: pipeline = gst.parse_launch(pipeline_str) log.debug('check', 'parsed pipeline %s' % pipeline_str) except gobject.GError, e: resolution.errback(errors.GStreamerError(e.message)) return resolution.d bus = pipeline.get_bus() bus.add_signal_watch() signal_id = bus.connect('message', message_rcvd, pipeline, resolution) resolution.signal_id = signal_id resolution.pipeline = pipeline log.debug('check', 'setting state to playing') if set_state_deferred: d = deferToThread(pipeline.set_state, gst.STATE_PLAYING) def stateChanged(res): return resolution.d d.addCallback(stateChanged) return d else: pipeline.set_state(gst.STATE_PLAYING) return resolution.d def check1394(mid, guid): """ Probe the firewire device. Return a deferred firing a result. The result is either: - succesful, with a None value: no device found - succesful, with a dictionary of width, height, and par as a num/den pair - failed @param mid: the id to set on the message. @param guid: the id of the selected device. @rtype: L{twisted.internet.defer.Deferred} of L{flumotion.common.messages.Result} """ result = messages.Result() def do_check(demux): pad = demux.get_pad('video') if not pad or pad.get_negotiated_caps() == None: raise errors.GStreamerError('Pipeline failed to negotiate?') caps = pad.get_negotiated_caps() s = caps.get_structure(0) w = s['width'] h = s['height'] par = s['pixel-aspect-ratio'] # FIXME: not a good idea to reuse the result name which # also exists in the parent context. # pychecker should warn; however it looks like # the parent result doesn't get stored as name, # but instead with STORE_DEREF result = dict(width=w, height=h, par=(par.num, par.denom)) log.debug('check', 'returning dict %r' % result) return result pipeline = \ 'dv1394src guid=%s ! dvdemux name=demux .video ! fakesink' % guid d = do_element_check(pipeline, 'demux', do_check) def errbackResult(failure): log.debug('check', 'returning failed Result, %r' % failure) m = None if failure.check(errors.GStreamerGstError): source, gerror, debug = failure.value.args<|fim▁hole|> log.debug('check', 'GStreamer GError: %s (debug: %s)' % ( gerror.message, debug)) if gerror.domain == "gst-resource-error-quark": if gerror.code == int(gst.RESOURCE_ERROR_NOT_FOUND): # dv1394src was fixed after gst-plugins-good 0.10.2 # to distinguish NOT_FOUND and OPEN_READ version = gstreamer.get_plugin_version('1394') if version >= (0, 10, 0, 0) and version <= (0, 10, 2, 0): m = messages.Error(T_( N_("Could not find or open the Firewire device. " "Check the device node and its permissions."))) else: m = messages.Error(T_( N_("No Firewire device found."))) elif gerror.code == int(gst.RESOURCE_ERROR_OPEN_READ): m = messages.Error(T_( N_("Could not open Firewire device for reading. " "Check permissions on the device."))) if not m: m = check.handleGStreamerDeviceError(failure, 'Firewire', mid=mid) if not m: m = messages.Error(T_(N_("Could not probe Firewire device.")), debug=check.debugFailure(failure)) m.id = mid result.add(m) return result d.addCallback(check.callbackResult, result) d.addErrback(errbackResult) return d<|fim▁end|>
<|file_name|>object.js<|end_file_name|><|fim▁begin|>import Ember from 'ember'; import ObjectProxyMixin from '../mixins/object'; export default Ember.ObjectProxy.extend(ObjectProxyMixin, {<|fim▁hole|><|fim▁end|>
_storageType: 'session' });
<|file_name|>jquery.easing.js<|end_file_name|><|fim▁begin|>/* * jQuery Easing v1.3 - http://gsgd.co.uk/sandbox/jquery/easing/ * * Uses the built in easing capabilities added In jQuery 1.1 * to offer multiple easing options * * TERMS OF USE - jQuery Easing * * Open source under the BSD License. * * Copyright © 2008 George McGinley Smith * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * Neither the name of the author nor the names of contributors may be used to endorse * or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * */ // t: current time, b: begInnIng value, c: change In value, d: duration jQuery.easing['jswing'] = jQuery.easing['swing']; jQuery.extend( jQuery.easing, { def: 'easeOutQuad', swing: function (x, t, b, c, d) { //alert(jQuery.easing.default); return jQuery.easing[jQuery.easing.def](x, t, b, c, d); }, easeInQuad: function (x, t, b, c, d) { return c*(t/=d)*t + b; }, easeOutQuad: function (x, t, b, c, d) { return -c *(t/=d)*(t-2) + b; }, easeInOutQuad: function (x, t, b, c, d) { if ((t/=d/2) < 1) return c/2*t*t + b; return -c/2 * ((--t)*(t-2) - 1) + b; }, easeInCubic: function (x, t, b, c, d) { return c*(t/=d)*t*t + b; }, easeOutCubic: function (x, t, b, c, d) { return c*((t=t/d-1)*t*t + 1) + b; }, easeInOutCubic: function (x, t, b, c, d) { if ((t/=d/2) < 1) return c/2*t*t*t + b; return c/2*((t-=2)*t*t + 2) + b; }, easeInQuart: function (x, t, b, c, d) { return c*(t/=d)*t*t*t + b; }, easeOutQuart: function (x, t, b, c, d) { return -c * ((t=t/d-1)*t*t*t - 1) + b; }, easeInOutQuart: function (x, t, b, c, d) { if ((t/=d/2) < 1) return c/2*t*t*t*t + b; return -c/2 * ((t-=2)*t*t*t - 2) + b; }, easeInQuint: function (x, t, b, c, d) { return c*(t/=d)*t*t*t*t + b; }, easeOutQuint: function (x, t, b, c, d) { return c*((t=t/d-1)*t*t*t*t + 1) + b; }, easeInOutQuint: function (x, t, b, c, d) { if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b; return c/2*((t-=2)*t*t*t*t + 2) + b; }, easeInSine: function (x, t, b, c, d) { return -c * Math.cos(t/d * (Math.PI/2)) + c + b; }, easeOutSine: function (x, t, b, c, d) { return c * Math.sin(t/d * (Math.PI/2)) + b; }, easeInOutSine: function (x, t, b, c, d) { return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b; }, easeInExpo: function (x, t, b, c, d) { return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b; }, easeOutExpo: function (x, t, b, c, d) { return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b; }, easeInOutExpo: function (x, t, b, c, d) { if (t==0) return b; if (t==d) return b+c; if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b; return c/2 * (-Math.pow(2, -10 * --t) + 2) + b; }, easeInCirc: function (x, t, b, c, d) { return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b; }, easeOutCirc: function (x, t, b, c, d) { return c * Math.sqrt(1 - (t=t/d-1)*t) + b; }, easeInOutCirc: function (x, t, b, c, d) { if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b; return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b; }, easeInElastic: function (x, t, b, c, d) { var s=1.70158;var p=0;var a=c; if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3; if (a < Math.abs(c)) { a=c; var s=p/4; } else var s = p/(2*Math.PI) * Math.asin (c/a); return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b; }, easeOutElastic: function (x, t, b, c, d) { var s=1.70158;var p=0;var a=c; if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3; if (a < Math.abs(c)) { a=c; var s=p/4; } else var s = p/(2*Math.PI) * Math.asin (c/a); return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b; }, easeInOutElastic: function (x, t, b, c, d) { var s=1.70158;var p=0;var a=c; if (t==0) return b; if ((t/=d/2)==2) return b+c; if (!p) p=d*(.3*1.5); if (a < Math.abs(c)) { a=c; var s=p/4; } else var s = p/(2*Math.PI) * Math.asin (c/a); if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b; return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b; }, easeInBack: function (x, t, b, c, d, s) { if (s == undefined) s = 1.70158; return c*(t/=d)*t*((s+1)*t - s) + b; }, easeOutBack: function (x, t, b, c, d, s) { if (s == undefined) s = 1.70158; return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b; }, <|fim▁hole|> return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b; }, easeInBounce: function (x, t, b, c, d) { return c - jQuery.easing.easeOutBounce (x, d-t, 0, c, d) + b; }, easeOutBounce: function (x, t, b, c, d) { if ((t/=d) < (1/2.75)) { return c*(7.5625*t*t) + b; } else if (t < (2/2.75)) { return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b; } else if (t < (2.5/2.75)) { return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b; } else { return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b; } }, easeInOutBounce: function (x, t, b, c, d) { if (t < d/2) return jQuery.easing.easeInBounce (x, t*2, 0, c, d) * .5 + b; return jQuery.easing.easeOutBounce (x, t*2-d, 0, c, d) * .5 + c*.5 + b; } });<|fim▁end|>
easeInOutBack: function (x, t, b, c, d, s) { if (s == undefined) s = 1.70158; if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
<|file_name|>plano.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from django import forms from django.utils.translation import ugettext_lazy as _ from django.forms import inlineformset_factory from djangosige.apps.financeiro.models import PlanoContasGrupo, PlanoContasSubgrupo class PlanoContasGrupoForm(forms.ModelForm):<|fim▁hole|> class Meta: model = PlanoContasGrupo fields = ('tipo_grupo', 'descricao',) widgets = { 'descricao': forms.TextInput(attrs={'class': 'form-control'}), 'tipo_grupo': forms.Select(attrs={'class': 'form-control'}), } labels = { 'descricao': _('Descrição'), 'tipo_grupo': _('Tipo de lançamento'), } class PlanoContasSubgrupoForm(forms.ModelForm): class Meta: model = PlanoContasSubgrupo fields = ('descricao',) widgets = { 'descricao': forms.TextInput(attrs={'class': 'form-control'}), } labels = { 'descricao': _('Descrição'), } PlanoContasSubgrupoFormSet = inlineformset_factory( PlanoContasGrupo, PlanoContasSubgrupo, form=PlanoContasSubgrupoForm, fk_name='grupo', extra=1, can_delete=True)<|fim▁end|>
<|file_name|>verification_completed.go<|end_file_name|><|fim▁begin|>// Copyright 2021 The LUCI Authors. // // 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,<|fim▁hole|>package handler import ( "context" "go.chromium.org/luci/common/errors" "go.chromium.org/luci/common/logging" "go.chromium.org/luci/common/retry/transient" "go.chromium.org/luci/gae/service/datastore" migrationpb "go.chromium.org/luci/cv/api/migration" "go.chromium.org/luci/cv/internal/changelist" "go.chromium.org/luci/cv/internal/configs/prjcfg" "go.chromium.org/luci/cv/internal/gerrit" "go.chromium.org/luci/cv/internal/migration" "go.chromium.org/luci/cv/internal/run" "go.chromium.org/luci/cv/internal/run/impl/state" "go.chromium.org/luci/cv/internal/usertext" ) const ( logEntryCQDVerifiedLabel = "CQD Verified" logEntryCQDVerificationFailed = "CQD Verification Failed" ) // OnCQDVerificationCompleted implements Handler interface. func (impl *Impl) OnCQDVerificationCompleted(ctx context.Context, rs *state.RunState) (*Result, error) { switch status := rs.Status; { case run.IsEnded(status): logging.Debugf(ctx, "Ignoring CQDVerificationCompleted event because Run is %s", status) return &Result{State: rs}, nil case status == run.Status_WAITING_FOR_SUBMISSION || status == run.Status_SUBMITTING: // Run probably entered submission phase due to previously received // CQDVerificationCompleted event. Delay processing this event // until submission completes. return &Result{State: rs, PreserveEvents: true}, nil case status != run.Status_RUNNING: return nil, errors.Reason("expected RUNNING status, got %s", status).Err() } vr := migration.VerifiedCQDRun{ID: rs.ID} switch err := datastore.Get(ctx, &vr); { case err == datastore.ErrNoSuchEntity: return nil, errors.New("received CQDVerificationCompleted event but VerifiedRun entity doesn't exist") case err != nil: return nil, errors.Annotate(err, "failed to load VerifiedRun").Tag(transient.Tag).Err() } rs = rs.ShallowCopy() switch vr.Payload.Action { case migrationpb.ReportVerifiedRunRequest_ACTION_SUBMIT: rs.Status = run.Status_WAITING_FOR_SUBMISSION rs.LogInfo(ctx, logEntryCQDVerifiedLabel, usertext.OnFullRunSucceeded(rs.Mode)) return impl.OnReadyForSubmission(ctx, rs) case migrationpb.ReportVerifiedRunRequest_ACTION_DRY_RUN_OK: msg, reason := usertext.OnRunSucceeded(rs.Mode) meta := reviewInputMeta{ notify: gerrit.Whoms{gerrit.Owner, gerrit.CQVoters}, message: msg, addToAttention: gerrit.Whoms{gerrit.CQVoters}, reason: reason, } if err := impl.cancelTriggers(ctx, rs, meta); err != nil { return nil, err } rs.LogInfo(ctx, logEntryCQDVerifiedLabel, meta.message) se := impl.endRun(ctx, rs, run.Status_SUCCEEDED) return &Result{State: rs, SideEffectFn: se}, nil case migrationpb.ReportVerifiedRunRequest_ACTION_FAIL: _, reason := usertext.OnRunFailed(rs.Mode) meta := reviewInputMeta{ notify: gerrit.Whoms{gerrit.Owner, gerrit.CQVoters}, message: vr.Payload.FinalMessage, // Add the same set of group/people to the attention set. addToAttention: gerrit.Whoms{gerrit.Owner, gerrit.CQVoters}, reason: reason, } if err := impl.cancelTriggers(ctx, rs, meta); err != nil { return nil, err } rs.LogInfo(ctx, logEntryCQDVerificationFailed, meta.message) se := impl.endRun(ctx, rs, run.Status_FAILED) return &Result{State: rs, SideEffectFn: se}, nil default: return nil, errors.Reason("unknown action %s", vr.Payload.Action).Err() } } func (impl *Impl) cancelTriggers(ctx context.Context, rs *state.RunState, meta reviewInputMeta) error { runCLs, err := run.LoadRunCLs(ctx, rs.ID, rs.CLs) if err != nil { return err } runCLExternalIDs := make([]changelist.ExternalID, len(runCLs)) for i, cl := range runCLs { runCLExternalIDs[i] = cl.ExternalID } cg, err := prjcfg.GetConfigGroup(ctx, rs.ID.LUCIProject(), rs.ConfigGroupID) if err != nil { return err } return impl.cancelCLTriggers(ctx, rs.ID, runCLs, runCLExternalIDs, cg, meta) }<|fim▁end|>
// 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.
<|file_name|>interfaces.go<|end_file_name|><|fim▁begin|>/* Copyright 2014 Google Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package apiserver import ( "github.com/GoogleCloudPlatform/kubernetes/pkg/api" "github.com/GoogleCloudPlatform/kubernetes/pkg/labels" "github.com/GoogleCloudPlatform/kubernetes/pkg/runtime" "github.com/GoogleCloudPlatform/kubernetes/pkg/watch" ) // RESTStorage is a generic interface for RESTful storage services. // Resources which are exported to the RESTful API of apiserver need to implement this interface. It is expected // that objects may implement any of the REST* interfaces. // TODO: implement dynamic introspection (so GenericREST objects can indicate what they implement) type RESTStorage interface { // New returns an empty object that can be used with Create and Update after request data has been put into it. // This object must be a pointer type for use with Codec.DecodeInto([]byte, runtime.Object) New() runtime.Object } type RESTLister interface { // NewList returns an empty object that can be used with the List call. // This object must be a pointer type for use with Codec.DecodeInto([]byte, runtime.Object) NewList() runtime.Object // List selects resources in the storage which match to the selector. List(ctx api.Context, label, field labels.Selector) (runtime.Object, error) } type RESTGetter interface { // Get finds a resource in the storage by id and returns it. // Although it can return an arbitrary error value, IsNotFound(err) is true for the // returned error value err when the specified resource is not found. Get(ctx api.Context, id string) (runtime.Object, error) } type RESTDeleter interface { // Delete finds a resource in the storage and deletes it. // Although it can return an arbitrary error value, IsNotFound(err) is true for the // returned error value err when the specified resource is not found. // Delete *may* return the object that was deleted, or a status object indicating additional // information about deletion. Delete(ctx api.Context, id string) (runtime.Object, error) } type RESTCreater interface { // New returns an empty object that can be used with Create after request data has been put into it. // This object must be a pointer type for use with Codec.DecodeInto([]byte, runtime.Object) New() runtime.Object // Create creates a new version of a resource. Create(ctx api.Context, obj runtime.Object) (runtime.Object, error) } type RESTUpdater interface { // New returns an empty object that can be used with Update after request data has been put into it. // This object must be a pointer type for use with Codec.DecodeInto([]byte, runtime.Object) New() runtime.Object // Update finds a resource in the storage and updates it. Some implementations // may allow updates creates the object - they should set the created boolean // to true.<|fim▁hole|> // RESTResult indicates the result of a REST transformation. type RESTResult struct { // The result of this operation. May be nil if the operation has no meaningful // result (like Delete) runtime.Object // May be set true to indicate that the Update operation resulted in the object // being created. Created bool } // ResourceWatcher should be implemented by all RESTStorage objects that // want to offer the ability to watch for changes through the watch api. type ResourceWatcher interface { // 'label' selects on labels; 'field' selects on the object's fields. Not all fields // are supported; an error should be returned if 'field' tries to select on a field that // isn't supported. 'resourceVersion' allows for continuing/starting a watch at a // particular version. Watch(ctx api.Context, label, field labels.Selector, resourceVersion string) (watch.Interface, error) } // Redirector know how to return a remote resource's location. type Redirector interface { // ResourceLocation should return the remote location of the given resource, or an error. ResourceLocation(ctx api.Context, id string) (remoteLocation string, err error) }<|fim▁end|>
Update(ctx api.Context, obj runtime.Object) (runtime.Object, bool, error) }
<|file_name|>widget-document.js<|end_file_name|><|fim▁begin|>/** * @author Anakeen * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License */ // Utility function to add an event listener function addEvent(o,e,f){ if (o.addEventListener){ o.addEventListener(e,f,true); return true; } else if (o.attachEvent){ return o.attachEvent("on"+e,f); } else { return false; } } // Utility function to send an event // o the object // en the event name : mouseup, mouseodwn function sendEvent(o,en) { if (o) { if( document.createEvent ) { // var ne=document.createEvent("HTMLEvents"); var ne; if ((en.indexOf('mouse') > -1)||(en.indexOf('click') > -1)) ne=document.createEvent("MouseEvents"); else ne=document.createEvent("HTMLEvents"); ne.initEvent(en,true,true); o.dispatchEvent(ne); } else { try { o.fireEvent( "on"+en ); } catch (ex) { ; } } } } Ext.fdl.Document = Ext.extend(Ext.Panel, { document: null, context: null, mode: 'view', forceExt: false, forceClassic: false, displayToolbar: true, displaynotes: true, notes: [], layout: 'fit', toString: function(){ return 'Ext.fdl.Document'; }, initComponent: function(){ if(!this.document){ console.log('Ext.fdl.Document is not provided a document.'); } this.context = this.document.context; if(this.displayToolbar){ this.tbar = new Ext.Toolbar({ enableOverflow: true, hidden: true, height: 28 }); } Ext.fdl.Document.superclass.initComponent.call(this); this.on({ afterrender: { fn: function(){ this.switchMode(this.mode); var o = this; (function(){ o.viewNotes(); }).defer(1000); fdldoc = this.document; (function(){ fdldoc.addUserTag({ tag: 'VIEWED' }); }).defer(1000); }, scope: this } }); }, setDocument: function(document){ this.document = document ; }, reload: function(){ this.switchMode(this.mode); }, switchMode: function(mode){ var me = this ; if (this.showMask) { this.showMask(); } this.removeAll(); switch (mode) { case 'view': if ((this.document.getProperty('generateVersion') == 3 && !this.forceClassic)|| this.forceExt) { var dcv = this.document.getDefaultConsultationView(); var subPanel = new Ext.fdl.SubDocument({ document: this.document, config: this.config }); subPanel.on('close',function(){ this.fireEvent('close',this); },this); subPanel.switchMode = function(mode){ me.switchMode(mode); }; if (dcv) { if (!eval('window.' + dcv.extwidget)) { // Dynamically add Javascript file this.includeJS(dcv.extsrc); } // Override document with extended behaviours Ext.apply(subPanel, eval('window.' + dcv.extwidget)); } else { Ext.apply(subPanel, Ext.fdl.DocumentDefaultView); } this.add(subPanel); subPanel.on('afterrender',function(){ subPanel.display(); }); } else { this.renderViewClassic(); } break; case 'edit': case 'create': //var dev = this.document.getDefaultEditionView(); if ((this.document.getProperty('generateVersion') == 3 && !this.forceClassic) || this.forceExt) { var dev = this.document.getDefaultEditionView(); var subPanel = new Ext.fdl.SubDocument({ document: this.document, mode: mode, config: this.config }); subPanel.on('close',function(){ this.fireEvent('close',this); },this); subPanel.switchMode = function(mode){ me.switchMode(mode); }; if (dev) { if (!eval('window.' + dev.extwidget)) { // Dynamically add Javascript file this.includeJS(dev.extsrc); } // Override document with extended behaviours Ext.apply(subPanel, eval('window.' + dev.extwidget)); } else { Ext.apply(subPanel, Ext.fdl.DocumentDefaultEdit); } this.add(subPanel); subPanel.on('afterrender',function(){ subPanel.display(); }); } else { this.renderEditClassic(); } break; default: break; }; this.mode = mode; // Do layout will not work on render. It must not be called first time. if (this.firstLayout) { this.doLayout(); } this.firstLayout = true; if (this.hideMask) { this.hideMask(); } }, generateMenu: function(panel,menu,mediaObject){ var me = this ; //console.log('GENERATE MENU',panel,menu,mediaObject.dom); //panel.getTopToolbar().removeAll(); menu.removeAll(); var documentMenu = mediaObject.dom.contentWindow.documentMenu; //console.log('DOCUMENT MENU',documentMenu); var documentId = (mediaObject.dom.contentWindow.document.getElementsByName('document-id').length > 0) ? mediaObject.dom.contentWindow.document.getElementsByName('document-id')[0].content : '' ; //console.log('DOCUMENT ID', documentId); var document = this.context.getDocument({ id: documentId, useCache:true, latest: false }); if(document && document.id){ this.setDocument(document); //console.log('DOCUMENT',documentId,me.document.getTitle()); //me.publish('modifydocument',me.document); } for(var name in documentMenu){ var menuObject = documentMenu[name]; var menuItem = Ext.fdl.MenuManager.getMenuItem(menuObject,{ widgetDocument:me, documentId:documentId, panel: panel, mediaObject: mediaObject, context: this.context, menu: menu }); console.log('MENU ITEM',menuItem); menu.add(menuItem); } menu.add(new Ext.Toolbar.Fill()); var toolbarStatus = me.documentToolbarStatus(); for (var i = 0; i < toolbarStatus.length; i++) { if (toolbarStatus[i]) { menu.add(toolbarStatus[i]); } } menu.doLayout(); menu.show(); mediaObject.dom.contentWindow.displaySaveForce = function(){ if (mediaObject.dom.contentWindow.documentMenu.saveforce) { mediaObject.dom.contentWindow.documentMenu.saveforce.visibility = 1 ; me.generateMenu(panel,menu,mediaObject); } }; }, // If this function returns a string, confirm when closing this document displaying this string. // This method is used in Ext.fdl.Window to check if document can be closed with ou without confirm. closeConfirm: function(){ if(this.mediaObject){ try { if(this.mediaObject.dom.contentWindow.beforeUnload){ var beforeUnload = this.mediaObject.dom.contentWindow.beforeUnload(); return beforeUnload ; } } catch(exception) { } } return false; }, renderViewClassic: function(){ //console.log('RENDER VIEW CLASSIC DOCUMENT ID',this.document.id); var me = this ; if(!this.config){ this.config = {}; } if(!this.config.targetRelation){ //this.config.targetRelation = 'Ext.fdl.Document.prototype.publish("opendocument",null,%V%,"view")'; } console.log('CONFIG',this.config); delete this.config.opener ; var sconf=''; if (this.config && this.document.context) sconf=JSON.stringify(this.config); //console.log(this.config); //console.log(JSON.stringify(this.config)); if(this.config.url){ var url = this.config.url ; url = url.replace(new RegExp("(action=FDL_CARD)","i"),"action=VIEWEXTDOC"); //url = this.document.context.url + url ; console.log('Calculated URL',url); } else { url = this.document.context.url + '?app=FDL&action=VIEWEXTDOC&id=' + this.document.getProperty('id') + '&extconfig='+encodeURI(sconf); } var mediaPanel = new Ext.ux.MediaPanel({ style: 'height:100%;', bodyStyle: 'height:100%;', border: false, autoScroll: false, mediaCfg: { mediaType: 'HTM', url: url }, listeners : { mediaload : function(panel,mediaObject){ me.mediaObject = mediaObject; var menu = me.getTopToolbar(); console.log('MEDIA OBJECT',mediaObject); me.generateMenu(panel,menu,mediaObject); addEvent(mediaObject.dom,'load',function(){ var menu = me.getTopToolbar(); console.log('MEDIA OBJECT',mediaObject); me.generateMenu(panel,menu,mediaObject); }); } } }); this.add(mediaPanel); this.doLayout(); }, renderEditClassic: function(){ var me = this ; if(!this.config){ this.config = {}; } if(this.config.url){ var url = this.config.url ; url = url.replace(new RegExp("(app=GENERIC)","i"),"app=FDL"); url = url.replace(new RegExp("(action=GENERIC_EDIT)","i"),"action=EDITEXTDOC"); //url = this.document.context.url + url ; console.log('Calculated URL',url); } else { var url = this.document.context.url + '?app=FDL&action=EDITEXTDOC&classid=' + this.document.getProperty('fromid') + '&id=' + this.document.getProperty('id'); } var mediaPanel = new Ext.ux.MediaPanel({ style: 'height:100%;', bodyStyle: 'height:100%;', border: false, autoScroll: false, mediaCfg: { mediaType: 'HTM', url: url }, listeners : { mediaload : function(panel,mediaObject){ me.mediaObject = mediaObject; var menu = me.getTopToolbar(); console.log('MEDIA OBJECT(1)',mediaObject); me.generateMenu(panel,menu,mediaObject); addEvent(mediaObject.dom,'load',function(){ var menu = me.getTopToolbar(); console.log('MEDIA OBJECT(2)',mediaObject); me.generateMenu(panel,menu,mediaObject); }); } } }); this.add(mediaPanel); this.doLayout(); }, displayUrl: function(url,target,config){ this.publish('openurl',url,target,config); }, addNote: function(){ var note = this.document.context.createDocument({ familyId: 'SIMPLENOTE', mode: 'view' }); if (note) { note.setValue('note_pasteid', this.document.getProperty('initid')); note.setValue('note_width', 200); note.setValue('note_height', 200); note.setValue('note_top', 50); note.setValue('note_left', 50); note.save(); this.document.reload(); var nid=note.getProperty('initid'); this.viewNotes(); var wnid = this.notes[nid]; if (wnid) { var p = wnid.items.itemAt(0); //console.log("note",p); setTimeout(function(){ p.items.itemAt(0).items.itemAt(0).setVisible(false); p.items.itemAt(0).items.itemAt(1).setVisible(true); p.items.itemAt(0).items.itemAt(2).setVisible(true); p.items.itemAt(0).items.itemAt(3).setVisible(true); p.items.itemAt(0).items.itemAt(1).focus(); }, 1000); } } }, viewNotes: function(config){ var noteids = this.document.getProperty('postitid'); if (noteids.length > 0) { for (var i = 0; i < noteids.length; i++) { if (noteids[i] > 0) { var note; if (!this.notes[noteids[i]]) { note = this.document.context.getDocument({ id: noteids[i] }); var wd = new Ext.fdl.Document({ style: 'padding:0px;margin:0px;', bodyStyle: 'padding:0px;margin:0px;', document: note, anchor: '100% 100%', displayToolbar: false, listeners: {close: function (panel) { panel.ownerCt.close(); }} }); this.notes[noteids[i]] = wd; } else { note = this.notes[noteids[i]].document; } if (note.isAlive()) { var color = 'yellow'; var nocolor = note.getValue('note_color'); if (nocolor) color = nocolor; var x = parseInt(note.getValue('note_left')); var y = parseInt(note.getValue('note_top')); if ((!this.notes[noteids[i]].window) || (this.notes[noteids[i]].window.getWidth() == 0)) { var notewin = new Ext.Window({ layout: 'fit', cls: 'x-fdl-note', style: 'padding:0px;margin:0px;background-color:' + color, title: note.getTitle(), closeAction: 'hide', width: parseInt(note.getValue('note_width')), height: parseInt(note.getValue('note_height')), resizable: true, note: note, tools: [{ id: 'close', qtip: 'Cacher la note', // hidden:true, handler: function(event, toolEl, panel){ panel.setVisible(false); } }], plain: true, renderTo: this.body, constrain: true, items: [this.notes[note.id]], x: x, y: y, listeners: { move: function(o){ if (this.note && (this.note.getProperty('owner') == this.note.context.getUser().id)) { var xy = o.getPosition(true); if ((o.getWidth() > 0) && (xy[0] > 0)) { this.note.setValue('note_width', o.getWidth()); this.note.setValue('note_height', o.getHeight()); this.note.setValue('note_left', xy[0]); this.note.setValue('note_top', xy[1]); this.note.save(); } } }, close: function(o){ } } }); this.notes[noteids[i]].window = notewin; notewin.show(); } else { if (config && config.undisplay) this.notes[noteids[i]].window.setVisible(false); else this.notes[noteids[i]].window.setVisible(true); } } } } } }, includeJS: function(url){ console.log('Include JS', url); if (window.XMLHttpRequest) { var XHR = new XMLHttpRequest(); } else { var XHR = new ActiveXObject("Microsoft.XMLHTTP"); } if (XHR) { XHR.open("GET", (this.document.context.url + url), false); XHR.send(null); eval(XHR.responseText); } else { return false; } }, detailSearch: function(){ return new Ext.fdl.DSearch({ document: this.document, hidden: true, border: false }); }, documentToolbarStatus: function(){ // If document is in creation mode, no toolbar status to display if(!this.document.id){ return false ; } var u = this.document.context.getUser(); var info = u.getInfo(); var statestatus = null; var statestatustext = ''; if(this.document.getProperty('version')){ console.log('VERSION',this.document.getProperty('version')); statestatustext = 'version ' + this.document.getProperty('version')+' '; } if (this.document.hasWorkflow()){ if(this.document.isFixed()) { statestatustext += '<i>' + '<span style="padding-left:10px;margin-right:3px;background-color:' + this.document.getColorState() + '">&nbsp;</span>' + this.document.getLocalisedState() + '</i>'; } else { if (this.document.getActivityState()) { statestatustext += '<i>' + this.document.getActivityState() + '</i>'; } else { statestatustext += '<i>' + this.document.getLocalisedState() + '</i>'; } } } if(statestatustext){ statestatus = new Ext.Toolbar.TextItem(statestatustext); } var lockstatus = null; if (this.document.getProperty('locked') > 0) { if (this.document.getProperty('locked') == info['id']) { lockstatus = new Ext.Toolbar.TextItem('<img ext:qtip="Verrouillé par ' + this.document.getProperty('locker') + '" src="' + this.document.context.url + 'FDL/Images/greenlock.png" style="height:16px" />'); } else { lockstatus = new Ext.Toolbar.TextItem('<img ext:qtip="Vérrouillé par ' + this.document.getProperty('locker') + '" src="' + this.document.context.url + 'FDL/Images/redlock.png" style="height:16px" />'); } } var readstatus = null; if (this.document.getProperty('locked') == -1) { readstatus = new Ext.Toolbar.TextItem('<img ext:qtip="Figé" src="' + this.document.context.url + 'FDL/Images/readfixed.png" style="height:16px" />'); } else if (!this.document.canEdit()) { readstatus = new Ext.Toolbar.TextItem('<img ext:qtip="Lecture seule" src="' + this.document.context.url + 'FDL/Images/readonly.png" style="height:16px" />'); } var postitstatus = null; if (this.document.getProperty('postitid').length > 0) { //console.log(this.document.getProperty('postitid')); postitstatus = new Ext.Button({ tooltip: 'Afficher/Cacher les notes', text: 'Notes', icon: this.document.context.url + 'Images/simplenote16.png', scope: this, handler: function(b, e){ this.displaynotes = (!this.displaynotes); this.viewNotes({ undisplay: (!this.displaynotes) }); } }); } // TODO Correct the icon path var allocatedstatus = null; if (this.document.getProperty('allocated')) { var an = this.document.getProperty('allocatedname'); var aimg = this.document.context.url + "Images/allocatedred16.png"; if (this.document.getProperty('allocated') == this.document.context.getUser().id) { aimg = this.document.context.url + "Images/allocatedgreen16.png"; } allocatedstatus = new Ext.Toolbar.TextItem('<img ext:qtip="Affecté à ' + an + '" src="' + aimg + '" style="height:16px" />'); } return [statestatus,lockstatus, readstatus, postitstatus, allocatedstatus]; } }); Ext.reg('fdl-document', Ext.fdl.Document); Ext.fdl.SubDocument = Ext.extend(Ext.form.FormPanel, { document: null, context: null, mode: 'view', // Force Ext default rendering, ignoring generateVersion property forceExt: false, displayToolbar: true, border: false, bodyStyle: 'overflow-y:auto; padding: 0px;', //frame: true, autoHeight: false, layout: 'form', method: 'POST', enctype: 'multipart/form-data', fileUpload: true, initComponent: function(){ if(!this.document){ console.log('Ext.fdl.Document is not provided a document.'); } this.context = this.document.context; Ext.fdl.SubDocument.superclass.initComponent.call(this); }, close: function(){ console.log('DOCUMENT CLOSE'); this.fireEvent('close',this); }, getHtmlValue: function(attrid, tag){ var as = this.document.getAttributes(); var ht = ''; for (var aid in as) { oa = as[aid]; if (oa.parentId == attrid && oa.getValue) { if (oa.getValue() != '') ht += '<' + tag + '>' + oa.getLabel() + ' : ' + oa.getValue() + '</' + tag + '>'; } } return ht; }, applyLink: function(attrid){ var me = this; if (attrid) { var text = me.document.getValue(attrid) || ''; var reg = new RegExp("", "ig"); reg.compile("\\[ADOC ([0-9]*)\\]", "ig"); var getLink = function(str, id){ var value = me.document.getValue(id); var display = me.document.getDisplayValue(id); return "<a class='docid' oncontextmenu='window.Fdl.ApplicationManager.displayDocument(" + value + ");return false;' href='javascript:window.Fdl.ApplicationManager.displayDocument(" + value + ");'> " + // me.context.getDocument({ // id: id // }).getTitle() + display + "</a>"; }; text = text.replace(reg, getLink); } return text; }, orderAttribute: function(){ if (!this.ordered) { function sortAttribute(attr1, attr2){ return attr1.rank - attr2.rank; }; function giveRank(type){ for (var i = 0; i < ordered.length; i++) { if (ordered[i].type == type) { for (var j = 0; j < ordered.length; j++) { if ((ordered[i].id == ordered[j].parentId) && (ordered[i].rank > ordered[j].rank || ordered[i].rank == 0)) { ordered[i].rank = ordered[j].rank; } } } } }; var ordered = new Array(); var as = this.document.getAttributes(); for (var aid in as) { ordered.push(as[aid]); } //ordered = ordered.slice(); // Makes an independant copy of attribute array // Each structuring attribute is given its children lowest rank giveRank('array'); giveRank('frame'); giveRank('tab'); ordered.sort(sortAttribute); this.ordered = ordered; } return this.ordered; }, documentToolbarButton: function(){ var button = new Ext.Button({ text: 'Document', menu: [{ xtype: 'menuitem', text: this.context._("eui::ToEdit"), scope: this, handler: function(){ this.switchMode('edit'); }, disabled: !this.document.canEdit() }, { xtype: 'menuitem', text: 'Verrouiller', scope: this, handler: function(){ this.document.lock(); Ext.Info.msg(this.document.getTitle(), "Verrouillage"); this.switchMode(this.mode); }, disabled: !this.document.canEdit(), hidden: (this.document.getProperty('locked') > 0 || this.document.getProperty('locked') == -1) }, { xtype: 'menuitem', text: 'Déverrouiller', scope: this, handler: function(){ this.document.unlock(); Ext.Info.msg(this.document.getTitle(), "Déverrouillage"); this.switchMode(this.mode); }, disabled: !this.document.canEdit(), hidden: (this.document.getProperty('locked') == 0 || this.document.getProperty('locked') == -1) }, { xtype: 'menuitem', text: 'Actualiser', scope: this, handler: function(){ this.document.reload(); this.switchMode(this.mode); } }, { xtype: 'menuitem', text: 'Supprimer', scope: this, handler: function(){ this.document.remove(); updateDesktop(); this.ownerCt.destroy(); } }, { xtype: 'menuitem', text: 'Historique', scope: this, handler: function(){ var histowin = Ext.fdl.viewDocumentHistory(this.document); histowin.show(); } }, { xtype: 'menuitem', text: 'Ajouter une note', scope: this, handler: function(){ var nid = this.addNote(); this.viewNotes(); var wnid = this.notes[nid]; if (wnid) { var p = wnid.items.itemAt(0); setTimeout(function(){ p.items.itemAt(0).setVisible(false); p.items.itemAt(1).setVisible(true); p.items.itemAt(2).setVisible(true); p.items.itemAt(3).setVisible(true); p.items.itemAt(1).focus(); }, 1000); } }, hidden: (this.document.getProperty('locked') == -1) }, { xtype: 'menuitem', text: 'Affecter un utilisateur', scope: this, handler: function(){ var o = this; //console.log(o); var oa = new Fdl.RelationAttribute({ relationFamilyId: 'IUSER' }); console.log('THISDOCUMENT', this.document, oa); oa._family = this.document; //console.log(oa); var wu = new Ext.fdl.DocId({ attribute: oa }); var toolbar = new Ext.Toolbar({ scope: this, items: [{ xtype: 'button', text: 'Affecter', scope: this, handler: function(){ var uid = wu.getValue(); if (uid) { if (this.document.allocate({ userId: uid })) { this.switchMode(this.mode); } else { Ext.Msg.alert(Fdl.getLastErrorMessage()); } w.close(); } } }, { xtype: 'button', scope: this, text: 'Enlever l\'affectation', handler: function(){ if (this.document.unallocate()) { this.switchMode(this.mode); } else { Ext.Msg.alert(Fdl.getLastErrorMessage()); } w.close(); } }, { xtype: 'button', text: 'Annuler', handler: function(){ w.close(); } }] }); var w = new Ext.Window({ constrain: true, renderTo: o.ownerCt.body, title: 'Affecter un utilisateur', bbar: toolbar, items: [wu] }); // var f = new Ext.FormPanel({ // items: [wu, toolbar] // }); // w.add(f); w.show(); (function(){ wu.focus(); }).defer(1000); }, disabled: !this.document.canEdit() }, { xtype: 'menuitem', text: 'Enregistrer une version', scope: this, handler: function(){ Ext.Msg.prompt('Version', 'Entrer le nom de la version', function(btn, text){ if (btn == 'ok') { // Fdl.ApplicationManager.closeDocument(this.document.id); var previousId = this.document.id; // Add Revision change document id ... this.document.addRevision({ version: text, volatileVersion: true }); // ... so we need to notify a document //Fdl.ApplicationManager.notifyDocument(this.document, previousId); // this.switchMode(this.mode); // this.doLayout(); } }, this); }, disabled: !this.document.canEdit(), hidden:(this.document.getProperty('doctype')!='F') }] }); return button; }, cycleToolbarButton: function(){ if (this.document.hasWorkflow()) { var menu = Array(); var fs = this.document.getFollowingStates(); for (var i = 0; i < fs.length; i++) { menu.push({ xtype: 'menuitem', text: fs[i].transition ? Ext.util.Format.capitalize(fs[i].transitionLabel) : "Passer à l'état : " + fs[i].label, style: 'background-color:' + fs[i].color + ';', scope: this, to_state: fs[i].state, handler: function(b, e){ var previousId = this.document.id; if (this.document.changeState({ state: b.to_state })) { Fdl.ApplicationManager.notifyDocument(this.document, previousId); Ext.Info.msg(this.document.getTitle(), "Changement d'état"); } else { // Error during state change } // this.switchMode(this.mode); // this.doLayout(); } }); } menu.push({ xtype: 'menuitem', text: 'Voir le graphe', scope: this, handler: function(){ var wid = this.document.getProperty('wid'); new Ext.Window({ title: 'Cycle pour ' + this.document.getTitle(), resizable: true, width: 800, height: 400, border: false, items: [new Ext.ux.MediaPanel({ mediaCfg: { mediaType: 'HTM', url: '/?app=FDL&action=WORKFLOW_GRAPH&id=' + wid, width: '100%', height: '100%' } })] }).show(); } }); var button = new Ext.Button({ text: 'Cycle', menu: menu }); return button; } return null; }, documentToolbarStatus: function(){ var u = this.document.context.getUser(); var info = u.getInfo(); var lockstatus = null; if (this.document.getProperty('locked') > 0) { if (this.document.getProperty('locked') == info['id']) { lockstatus = new Ext.Toolbar.TextItem('<img ext:qtip="Verrouillé par ' + this.document.getProperty('locker') + '" src="FDL/Images/greenlock.png" style="height:16px" />'); } else { lockstatus = new Ext.Toolbar.TextItem('<img ext:qtip="Vérrouillé par ' + this.document.getProperty('locker') + '" src="FDL/Images/redlock.png" style="height:16px" />'); } } var readstatus = null; if (this.document.getProperty('locked') == -1) { readstatus = new Ext.Toolbar.TextItem('<img ext:qtip="Figé" src="FDL/Images/readfixed.png" style="height:16px" />'); } else if (!this.document.canEdit()) { readstatus = new Ext.Toolbar.TextItem('<img ext:qtip="Lecture seule" src="FDL/Images/readonly.png" style="height:16px" />'); } var postitstatus = null; if (this.document.getProperty('postitid').length > 0) { //console.log(this.document.getProperty('postitid')); postitstatus = new Ext.Button({ tooltip: 'Afficher/Cacher les notes', text: 'Notes', icon: 'Images/simplenote16.png', scope: this, handler: function(b, e){ this.displaynotes = (!this.displaynotes); this.viewNotes({ undisplay: (!this.displaynotes) }); } }); } // TODO Correct the icon path var allocatedstatus = null; if (this.document.getProperty('allocated')) { var an = this.document.getProperty('allocatedname'); var aimg = "Images/allocatedred16.png"; if (this.document.getProperty('allocated') == this.document.context.getUser().id) { aimg = "Images/allocatedgreen16.png"; } allocatedstatus = new Ext.Toolbar.TextItem('<img ext:qtip="Affecté à ' + an + '" src="' + aimg + '" style="height:16px" />'); } return [lockstatus, readstatus, postitstatus, allocatedstatus]; }, adminToolbarButton: function(){ var button = new Ext.Button({ text: 'Administration', menu: [{ xtype: 'menuitem', text: 'Famille', scope: this, handler: function(b, e){ Fdl.ApplicationManager.displayFamily(this.document.getProperty('fromid')); } }, { xtype: 'menuitem', text: 'Modifier le Cycle', scope: this, handler: function(b, e){ Fdl.ApplicationManager.displayCycleEditor(this.document.getProperty('wid')); } }, { xtype: 'menuitem', text: 'Administrer le Cycle', scope: this, handler: function(b, e){ Fdl.ApplicationManager.displayDocument(this.document.getProperty('wid'), 'edit'); } }, { xtype: 'menuitem', text: 'Propriétés', handler: function(b, e){ Ext.Msg.alert('Propriétés', 'Pas encore disponible.'); } }] }); return button; }, renderToolbar: function(){ if (!this.displayToolbar) { return false; } var toolbar = new Ext.Toolbar({ style: 'margin-bottom:10px;' }); toolbar.add(this.documentToolbarButton()); // Add cycle toolbar button if applicable var cycleToolbarButton = this.cycleToolbarButton(); if (cycleToolbarButton) { toolbar.add(cycleToolbarButton); } // toolbar.add(this.adminToolbarButton()); toolbar.add(new Ext.Toolbar.Fill()); var toolbarStatus = this.documentToolbarStatus(); for (var i = 0; i < toolbarStatus.length; i++) { if (toolbarStatus[i]) { toolbar.add(toolbarStatus[i]); } } return toolbar; }, /** * * @param {Object} attrid * @param {Object} config (display : if true returns widget even if value is empty) */ getExtValue: function(attrid, config){ if ((config && config.display) || this.alwaysDisplay) { var display = true; } if ((config && config.hideHeader)) { var hideHeader = true; } var attr = this.document.getAttribute(attrid); if (!attr) { return null; } var ordered = this.orderAttribute(); // Handle Visibility switch (attr.getVisibility()) { case 'W': case 'R': case 'S': break; case 'O': case 'H': case 'I': return null; break; case 'U': //For array, prevents add and delete of rows break; } switch (attr.type) { case 'menu': case 'action': return new Ext.Button({ text: attr.getLabel(), handler: this.handleAction }); break; case 'text': case 'longtext': case 'date': case 'integer': case 'int': case 'double': case 'money': if (this.document.getValue(attr.id) || display) { return new Ext.fdl.DisplayField({ fieldLabel: Ext.util.Format.capitalize(attr.getLabel()), value: this.document.getValue(attr.id) }); } else { return null; } break; case 'htmltext': if (this.document.getValue(attr.id) || display) { return new Ext.fdl.DisplayField({ fieldLabel: Ext.util.Format.capitalize(attr.getLabel()), value: this.applyLink(attr.id) }); } else { return null; } break; case 'time': if (this.document.getValue(attr.id) || display) { return new Ext.form.TimeField({ fieldLabel: Ext.util.Format.capitalize(attr.getLabel()), value: this.document.getValue(attr.id), disabled: true }); } else { return null; } break; case 'timestamp': if (this.document.getValue(attr.id) || display) { return new Ext.ux.form.DateTime({ fieldLabel: Ext.util.Format.capitalize(attr.getLabel()), value: this.document.getValue(attr.id), disabled: true }); } else { return null; } break; case 'password': if (this.document.getValue(attr.id) || display) { return new Ext.form.TextField({ fieldLabel: Ext.util.Format.capitalize(attr.getLabel()), inputType: 'password', value: this.document.getValue(attr.id), disabled: true }); } else { return null; } break; case 'image': // return new Ext.form.FileUploadField({ // fieldLabel: attr.getLabel(), // buttonCfg: { // text: '', // iconCls: 'upload-icon' // }, // disabled: true // }); return null; break; case 'color': // return new Ext.form.ColorField({ // fieldLabel: attr.getLabel() // }) ////console.log('Attribute not represented : ' + attr.type); return null; break; case 'frame': var frame = new Ext.form.FieldSet({ title: Ext.util.Format.capitalize(attr.getLabel()), autoHeight: true, collapsible: true, width: 'auto', labelWidth: 150, style: 'margin:10px;', bodyStyle: 'padding-left:40px;width:auto;' }); var empty = true; for (var i = 0; i < ordered.length; i++) { var curAttr = ordered[i]; if (curAttr.parentId == attr.id) { var extValue = this.getExtValue(curAttr.id); if (extValue != null) { frame.add(extValue); empty = false; } } } if (!empty || display) { return frame; } else { return null; } break; case 'tab': var tab = new Ext.Panel({ title: Ext.util.Format.capitalize(attr.getLabel()), autoHeight: true, autoWidth: true, width: 'auto', layout: 'form', border: false, defaults: { //width: 'auto', // as we use deferredRender:false we mustn't // render tabs into display:none containers hideMode: 'offsets' } }); var empty = true; for (var i = 0; i < ordered.length; i++) { var curAttr = ordered[i]; if (curAttr.parentId == attr.id) { var extValue = this.getExtValue(curAttr.id); if (extValue != null) { tab.add(extValue); empty = false; } } } if (!empty || display) { return tab; } else { return null; } break; case 'array': var elements = attr.getElements(); var fields = new Array(); for (var i = 0; i < elements.length; i++) { fields.push(elements[i].id); } //console.log('VALUES',this.document.getValues(attr.id)); //var values = attr.getArrayValues() var values = this.document.getValue(attr.id) || []; if (values.length == 0 && !display) { return null; } for (var i = 0; i < elements.length; i++) { // Transform docid into links if (elements[i].type == 'docid') { for (var j = 0; j < values.length; j++) { if (values[j][elements[i].id]) { values[j][elements[i].id] = "<a class='docid' " + 'href="javascript:window.Fdl.ApplicationManager.displayDocument(' + values[j][elements[i].id] + ');"' + 'oncontextmenu="window.Fdl.ApplicationManager.displayDocument(' + values[j][elements[i].id] + ');return false;">' + elements[i].getTitle()[j] + "</a>"; } else { values[j][elements[i].id] = ''; } } } // Transform enum with correct label if (elements[i].type == 'enum') { for (var j = 0; j < values.length; j++) { values[j][elements[i].id] = elements[i].getEnumLabel({ key: values[j][elements[i].id] }); } } } var store = new Ext.data.JsonStore({ fields: fields, data: values }); var columns = []; for (var i = 0; i < ordered.length; i++) { var curAttr = ordered[i]; if (curAttr.parentId == attr.id) { // Handle Visibility switch (curAttr.getVisibility()) { case 'W': case 'R': case 'S': columns.push({ header: Ext.util.Format.capitalize(curAttr.getLabel()), dataIndex: curAttr.id }); break; case 'O': case 'H': case 'I': break; case 'U': //For array, prevents add and delete of rows break; } } } var array = new Ext.grid.GridPanel({ title: Ext.util.Format.capitalize(attr.getLabel()), autoHeight: true, collapsible: true, titleCollapse: true, viewConfig: { forceFit: true, autoFill: true }, animCollapse: false, disableSelection: true, store: store, columns: columns, style: 'margin-bottom:10px;', header: !hideHeader, border: false }); return array; break; case 'enum': //console.log('Attribute not represented : ' + attr.type); return null; break; case 'docid': if (this.document.getValue(attr.id) || display) { if (attr.getOption('multiple') != 'yes') { return new Ext.fdl.DisplayField({ fieldLabel: Ext.util.Format.capitalize(attr.getLabel()), value: "<a class='docid' " + 'href="javascript:window.Fdl.ApplicationManager.displayDocument(' + this.document.getValue(attr.id) + ');"' + 'oncontextmenu="window.Fdl.ApplicationManager.displayDocument(' + this.document.getValue(attr.id) + ');return false;">' + (this.document.getDisplayValue(attr.id) || '') + "</a>" }); } else { var values = this.document.getValue(attr.id); var displays = this.document.getDisplayValue(attr.id); console.log('Attribute', values, displays); var fieldValue = ''; for (var i = 0; i < values.length; i++) { fieldValue += "<a class='docid' " + 'href="javascript:window.Fdl.ApplicationManager.displayDocument(' + values[i] + ');"' + 'oncontextmenu="window.Fdl.ApplicationManager.displayDocument(' + values[i] + ');return false;">' + displays[i] + "</a><br/>"; } return new Ext.fdl.DisplayField({ fieldLabel: Ext.util.Format.capitalize(attr.getLabel()), value: fieldValue }); } } else { return null; } break; case 'file': if (this.document.getValue(attr.id) || display) { return new Ext.fdl.DisplayField({ fieldLabel: Ext.util.Format.capitalize(attr.getLabel()), value: '<a class="docid" ' + 'href="' + this.document.getDisplayValue(attr.id, { url: true, inline: false }) + '" >' + this.document.getDisplayValue(attr.id) + "</a>" }); } else { return null; } break; default: //console.log('Attribute not represented : ' + attr.type); return null; break; } }, getHeader: function(){ return new Ext.Panel({ html: "" /* html: '<img src=' + this.document.getIcon({ width: 48 }) + ' style="float:left;padding:0px 5px 5px 0px;" />' + "<p style='font-size:12;'>" + this.document.getProperty('fromtitle') + '</p>' + '<h1 style="display:inline;font-size:14;text-transform: uppercase;">' + (this.document.getProperty('id') ? this.document.getTitle() : ('Création ' + this.document.getProperty('fromtitle'))) + '</h1>' + '<span style="padding-left:10px">' + (this.document.getProperty('version') ? (' Version ' + this.document.getProperty('version')) : '') + '</span>' + (this.document.hasWorkflow() ? "<p><i style='border-style:none none solid none;border-width:2px;border-color:" + this.document.getColorState() + "'>" + (this.document.isFixed() ? ('(' + this.document.getLocalisedState() + ') ') : '') )+ "<b>" + (this.document.getActivityState() ? Ext.util.Format.capitalize(this.document.getActivityState()) : '') + "</b>" + '</i></p>'*/ }); }, /** * Get Ext default input component for a given id. * @param {Object} attrid * @param {Object} inArray * @param {Object} rank * @param {Object} defaultValue * @param {Object} empty */ getExtInput: function(attrid, inArray, rank, defaultValue, empty){ var attr = this.document.getAttribute(attrid); if (!attr) { return null; } //var name = inArray ? attr.id + '[]' : attr.id; var name = attr.id; var ordered = this.orderAttribute(); // Handle Visibility switch (attr.getVisibility()) { case 'W': case 'O': break; case 'R': case 'H': case 'I': return null; break; case 'S': //Viewable in edit mode but not editable var disabled = true; break; case 'U': //For array, prevents add and delete of rows break; } switch (attr.type) { case 'menu': // return new Ext.Button({ // text: Ext.util.Format.capitalize(attr.getLabel()), // handler: this.handleAction // }); break; case 'text': return new Ext.fdl.Text({ fieldLabel: Ext.util.Format.capitalize(attr.getLabel()), value: !empty ? (rank != undefined ? this.document.getValue(attr.id)[rank] : this.document.getValue(attr.id)) : null, name: name, allowBlank: !attr.needed, disabled: disabled }); break; case 'longtext': return new Ext.fdl.LongText({ fieldLabel: Ext.util.Format.capitalize(attr.getLabel()), value: !empty ? (rank != undefined ? this.document.getValue(attr.id)[rank] : this.document.getValue(attr.id)) : null,<|fim▁hole|> break; case 'htmltext': return new Ext.fdl.HtmlText({ fieldLabel: Ext.util.Format.capitalize(attr.getLabel()), value: this.document.getValue(attr.id), name: name, disabled: disabled }); break; case 'int': case 'integer': return new Ext.fdl.Integer({ fieldLabel: Ext.util.Format.capitalize(attr.getLabel()), value: this.document.getValue(attr.id), name: name, allowBlank: !attr.needed, disabled: disabled }); break; case 'double': return new Ext.fdl.Double({ fieldLabel: Ext.util.Format.capitalize(attr.getLabel()), value: this.document.getValue(attr.id), name: name, allowBlank: !attr.needed, disabled: disabled }); break; case 'money': return new Ext.fdl.Money({ fieldLabel: Ext.util.Format.capitalize(attr.getLabel()), value: this.document.getValue(attr.id), name: name, allowBlank: !attr.needed, disabled: disabled }); break; case 'date': return new Ext.fdl.Date({ fieldLabel: Ext.util.Format.capitalize(attr.getLabel()), altFormats: 'd-j-Y|d-m-Y', format: 'd/m/Y', value: !empty ? (rank != undefined ? this.document.getValue(attr.id)[rank] : this.document.getValue(attr.id)) : null, name: name, disabled: disabled }); break; case 'time': return new Ext.form.TimeField({ fieldLabel: Ext.util.Format.capitalize(attr.getLabel()), value: this.document.getValue(attr.id), name: name, disabled: disabled }); break; case 'timestamp': return new Ext.ux.form.DateTime({ fieldLabel: Ext.util.Format.capitalize(attr.getLabel()), name: name, disabled: disabled }); break; case 'password': return new Ext.form.TextField({ fieldLabel: Ext.util.Format.capitalize(attr.getLabel()), inputType: 'password', value: this.document.getValue(attr.id), name: name, disabled: disabled }); break; case 'image': return new Ext.fdl.Image({ fieldLabel: Ext.util.Format.capitalize(attr.getLabel()), name: name, value: attr.getFileName() }); break; case 'file': return new Ext.fdl.File({ fieldLabel: Ext.util.Format.capitalize(attr.getLabel()), name: name, value: attr.getFileName() }); break; case 'color': return new Ext.fdl.Color({ fieldLabel: Ext.util.Format.capitalize(attr.getLabel()), name: name }); break; case 'frame': var frame = new Ext.form.FieldSet({ title: Ext.util.Format.capitalize(attr.getLabel()), autoHeight: true, autoWidth: true, collapsible: true, labelWidth: 150, //width: 'auto', style: 'margin:10px;', //bodyStyle: 'padding-left:40px;width:auto;' bodyStyle: 'padding-left:20px;', anchor: '100%' }); for (var i = 0; i < ordered.length; i++) { var curAttr = ordered[i]; if (curAttr.parentId == attr.id) { var ext_input = this.getExtInput(curAttr.id); if (ext_input != null) { frame.add(ext_input); } } } return frame; break; case 'tab': var tab = new Ext.Panel({ title: Ext.util.Format.capitalize(attr.getLabel()), autoHeight: true, autoWidth: true, //frame: true, layout: 'form', border: false, defaults: { // as we use deferredRender:false we mustn't // render tabs into display:none containers //hideMode: 'offsets' } }); var empty = true; for (var i = 0; i < ordered.length; i++) { var curAttr = ordered[i]; if (curAttr.parentId == attr.id) { tab.add(this.getExtInput(curAttr.id)); empty = false; } } if (!empty) { return tab; } else { return null; } break; // Improvement for using RowEditor with array /* case 'array': var elements = attr.getElements(); var values = attr.getArrayValues(); var docWidget = this; var columns = [new Ext.grid.RowNumberer()]; var fields = []; for (var i = 0; i < elements.length; i++) { var attr = this.document.getAttribute(elements[i].id); var col = Ext.apply({},{ editor: this.getExtInput(elements[i].id, true, null, null, true), header: attr.getLabel(), dataIndex: elements[i].id, hideable: false, viewCfg: { autoFill: true, forceFit: true } }); //should be a method switch(attr.type){ case 'docid': var renderer = attr.getTitle.createDelegate(attr); //this is not the good renderer //the good one would only be fdl.getTitle //that does not exists currently break; default: var renderer = null; break; } if(renderer){ Ext.apply(col, { renderer: renderer }); } //EO method var field = Ext.apply({},{ name: elements[i].id }) columns.push(col); fields.push(field); } var store = new Ext.data.Store({ reader: new Ext.data.JsonReader({ fields: fields }), data: values }) // not forget to include ext/examples/ux/RowEditor.js //maybe work on roweditor about last row... var editor = new Ext.ux.RowEditor({ saveText: 'Update' }); //var arrayPanel = new Ext.grid.EditorGridPanel({ //only gridpanel if using roweditor! var arrayPanel = new Ext.grid.GridPanel({ title: Ext.util.Format.capitalize(attr.getLabel()), frame: true, plugins:[editor], collapsible: true, titleCollapse: true, animCollapse: false, style: 'margin-bottom:10px;', columns: columns, store: store, autoHeight: true, autoScroll: true, bbar: [{ ref: '../addBtn', iconCls: 'icon-row-add', text: 'Add row', handler: function(){ var e = new store.recordType(); editor.stopEditing(); store.insert(0, e); arrayPanel.getView().refresh(); arrayPanel.getSelectionModel().selectRow(0); editor.startEditing(0); } },{ ref: '../removeBtn', iconCls: 'icon-row-delete', text: 'Remove row', disabled: true, handler: function(){ editor.stopEditing(); var s = arrayPanel.getSelectionModel().getSelections(); for(var i = 0, r; r = s[i]; i++){ store.remove(r); } } }] }); arrayPanel.getSelectionModel().on('selectionchange', function(sm){ arrayPanel.removeBtn.setDisabled(sm.getCount() < 1); }); return arrayPanel; break; */ case 'array': var elements = attr.getElements(); var fields = new Array(); for (var i = 0; i < elements.length; i++) { fields.push(elements[i].id); } //var values = attr.getArrayValues(); var values = this.document.getValue(attr.id) || []; var docWidget = this; var columns = 0; for (var i = 0; i < elements.length; i++) { // Handle Visibility switch (elements[i].getVisibility()) { case 'W': case 'O': columns++; break; } } var arrayPanel = new Ext.Panel({ title: Ext.util.Format.capitalize(attr.getLabel()), frame: true, collapsible: true, titleCollapse: true, animCollapse: false, style: 'margin-bottom:10px;', layout: 'table', layoutConfig: { columns: columns }, bbar: [{ text: 'Ajouter', tooltip: 'Ajouter', scope: docWidget, handler: function(){ // For each columnPanel child // Add one row of editor widget var elements = attr.getElements(); for (var i = 0; i < elements.length; i++) { switch (elements[i].getVisibility()) { case 'W': case 'O': var editorWidget = this.getExtInput(elements[i].id, true, null, null, true); arrayPanel.add(editorWidget); break; } } arrayPanel.doLayout(); } }] }); for (var i = 0; i < elements.length; i++) { // Handle Visibility switch (elements[i].getVisibility()) { case 'W': case 'O': switch (elements[i].type) { case 'enum': if (attr.getOption('eformat') == 'bool') { var width = 60; } else { var width = 120; } break; case 'docid': var width = 200; break; case 'date': var width = 110; break; default: var width = 100; break; } var columnPanel = new Ext.Panel({ title: Ext.util.Format.capitalize(elements[i].getLabel()), width: width, style: 'overflow:auto;', bodyStyle: 'text-align:center;margin-top:3px;', frame: false, layout: 'form', hideLabels: true }); arrayPanel.add(columnPanel); break; } } for (var j = 0; j < values.length; j++) { for (var i = 0; i < elements.length; i++) { switch (elements[i].getVisibility()) { case 'W': case 'O': var editorWidget = this.getExtInput(elements[i].id, true, j, values[j][elements[i].id]); arrayPanel.add(editorWidget); } } } return arrayPanel; break; case 'enum': // var label = attr.getEnumLabel({ // key: this.document.getValue(attr.id)[rank] // }); // // if (attr.getOption('eformat') == 'bool') { // // return new Ext.ux.form.XCheckbox({ // fieldLabel: inArray ? ' ' : Ext.util.Format.capitalize(attr.getLabel()), // //boxLabel: inArray ? '' : Ext.util.Format.capitalize(attr.getLabel()) , // checked: this.document.getValue(attr.id)[rank] == 'yes' ? true : false, // submitOnValue: 'yes', // submitOffValue: 'no', // name: name, // style: inArray ? 'margin:auto;' : '' // }); // // } // else { // // var items = attr.getEnumItems(); // // return new Ext.form.ComboBox({ // // fieldLabel: inArray ? ' ' : Ext.util.Format.capitalize(attr.getLabel()), // // valueField: 'key', // displayField: 'label', // // width: 150, // // // Required to give simple select behaviour // //emptyText: '--Famille--', // editable: false, // forceSelection: true, // disableKeyFilter: true, // triggerAction: 'all', // mode: 'local', // // value: items[0].key, // // store: new Ext.data.JsonStore({ // data: items, // fields: ['key', 'label'] // }) // // }); // // } break; case 'docid': if (attr.getOption('multiple') == 'yes') { return new Ext.fdl.MultiDocId({ attribute: attr, fieldLabel: Ext.util.Format.capitalize(attr.getLabel()), docIdList: this.document.getValue(attr.id), docTitleList: this.document.getValue(attr.id + '_title') }); } else { return new Ext.fdl.DocId({ attribute: attr, fieldLabel: Ext.util.Format.capitalize(attr.getLabel()), //value: this.document.getValue(attr.id), value: !empty ? (rank != null ? this.document.getDisplayValue(attr.id)[rank] : this.document.getDisplayValue(attr.id)) : null, //name: attr.id, hiddenName: name, hiddenValue: !empty ? (defaultValue != null ? defaultValue : this.document.getValue(attr.id)) : null, allowBlank: !attr.needed, disabled: disabled }); } break; default: console.log('Attribute not represented : ' + attr.type); return null; break; } } });<|fim▁end|>
name: name, allowBlank: !attr.needed, disabled: disabled });
<|file_name|>markup.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2013-2014, Martín Gaitán # Copyright (c) 2012-2013, Alexander Jung-Loddenkemper # This file is part of Waliki (http://waliki.nqnwebs.com/) # License: BSD (https://github.com/mgaitan/waliki/blob/master/LICENSE) #=============================================================================== # DOCS #=============================================================================== """All supported markups """ #=============================================================================== # IMPORTS #=============================================================================== import re import docutils.core import docutils.io import markdown import textwrap from rst2html5 import HTML5Writer import wiki #=============================================================================== # MARKUP BASE #=============================================================================== class Markup(object): """ Base markup class.""" NAME = 'Text' META_LINE = '%s: %s\n' EXTENSION = '.txt' HOWTO = """ """ def __init__(self, raw_content): self.raw_content = raw_content @classmethod def render_meta(cls, key, value): return cls.META_LINE % (key, value) def process(self): """ return (html, body, meta) where HTML is the rendered output body is the the editable content (text), and meta is a dictionary with at least ['title', 'tags'] keys """ raise NotImplementedError("override in a subclass") @classmethod def howto(cls): return cls(textwrap.dedent(cls.HOWTO)).process()[0] #=============================================================================== # MARKDOWN #=============================================================================== class Markdown(Markup): NAME = 'markdown' META_LINE = '%s: %s\n' EXTENSION = '.md' HOWTO = """ This editor is [markdown][] featured. * I am * a * list Turns into: * I am * a * list `**bold** and *italics*` turn into **bold** and *italics*. Very easy! Create links with `[Wiki](http://github.com/alexex/wiki)`. They turn into [Wiki][http://github.com/alexex/wiki]. Headers are as follows: # Level 1 ## Level 2 ### Level 3 [markdown]: http://daringfireball.net/projects/markdown/ """ def process(self): # Processes Markdown text to HTML, returns original markdown text, # and adds meta md = markdown.Markdown(['codehilite', 'fenced_code', 'meta']) html = md.convert(self.raw_content) meta_lines, body = self.raw_content.split('\n\n', 1) meta = md.Meta return html, body, meta #=============================================================================== # RESTRUCTURED TEXT #=============================================================================== class RestructuredText(Markup): NAME = 'restructuredtext' META_LINE = '.. %s: %s\n' IMAGE_LINE = '.. image:: %(url)s' LINK_LINE = '`%(filename)s <%(url)s>`_' EXTENSION = '.rst' HOWTO = """ This editor is `reStructuredText`_ featured:: * I am * a * list Turns into: * I am * a * list<|fim▁hole|> Create links with ```Wiki <http://github.com/alexex/wiki>`_``. They turn into `Wiki <https://github.com/alexex/wiki>`_. Headers are just any underline (and, optionally, overline). For example:: Level 1 ******* Level 2 ------- Level 3 +++++++ .. _reStructuredText: http://docutils.sourceforge.net/rst.html """ def process(self): settings = {'initial_header_level': 2, 'record_dependencies': True, 'stylesheet_path': None, 'link_stylesheet': True, 'syntax_highlight': 'short', } html = self._rst2html(self.raw_content, settings_overrides=settings) # Convert unknow links to internal wiki links. # Examples: # Something_ will link to '/something' # `something great`_ to '/something_great' # `another thing <thing>`_ '/thing' refs = re.findall(r'Unknown target name: "(.*)"', html) if refs: content = self.raw_content + self.get_autolinks(refs) html = self._rst2html(content, settings_overrides=settings) meta_lines, body = self.raw_content.split('\n\n', 1) meta = self._parse_meta(meta_lines.split('\n')) return html, body, meta def get_autolinks(self, refs): autolinks = '\n'.join(['.. _%s: /%s' % (ref, wiki.urlify(ref, False)) for ref in refs]) return '\n\n' + autolinks def _rst2html(self, source, source_path=None, source_class=docutils.io.StringInput, destination_path=None, reader=None, reader_name='standalone', parser=None, parser_name='restructuredtext', writer=None, writer_name=None, settings=None, settings_spec=None, settings_overrides=None, config_section=None, enable_exit_status=None): if not writer: writer = HTML5Writer() # Taken from Nikola # http://bit.ly/14CmQyh output, pub = docutils.core.publish_programmatically( source=source, source_path=source_path, source_class=source_class, destination_class=docutils.io.StringOutput, destination=None, destination_path=destination_path, reader=reader, reader_name=reader_name, parser=parser, parser_name=parser_name, writer=writer, writer_name=writer_name, settings=settings, settings_spec=settings_spec, settings_overrides=settings_overrides, config_section=config_section, enable_exit_status=enable_exit_status) return pub.writer.parts['body'] def _parse_meta(self, lines): """ Parse Meta-Data. Taken from Python-Markdown""" META_RE = re.compile(r'^\.\.\s(?P<key>.*?): (?P<value>.*)') meta = {} key = None for line in lines: if line.strip() == '': continue m1 = META_RE.match(line) if m1: key = m1.group('key').lower().strip() value = m1.group('value').strip() try: meta[key].append(value) except KeyError: meta[key] = [value] return meta #=============================================================================== # MAIN #=============================================================================== if __name__ == "__main__": print(__doc__)<|fim▁end|>
``**bold** and *italics*`` turn into **bold** and *italics*. Very easy!
<|file_name|>test_mockdata.py<|end_file_name|><|fim▁begin|>import unittest from src.data_structures.mockdata import MockData class TestMockData (unittest.TestCase): def setUp(self): self.data = MockData() def test_random_data(self): data = MockData() a_set = data.get_random_elements(10)<|fim▁hole|> unittest.main()<|fim▁end|>
self.assertTrue(len(a_set) == 10, "the data should have 10 elements!") if __name__ == '__main__':
<|file_name|>setup.py<|end_file_name|><|fim▁begin|>from setuptools import find_packages, setup from auspost_pac import __version__ as version setup( name='python-auspost-pac', version=version, license='BSD', author='Sam Kingston', author_email='sam@sjkwi.com.au', description='Python API for Australia Post\'s Postage Assessment Calculator (pac).', url='https://github.com/sjkingo/python-auspost-pac',<|fim▁hole|> install_requires=[ 'cached_property', 'frozendict', 'requests', ], packages=find_packages(), classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python', ], )<|fim▁end|>
<|file_name|>block-must-not-have-result-res.rs<|end_file_name|><|fim▁begin|>struct R; impl Drop for R { fn drop(&mut self) {<|fim▁hole|>fn main() { }<|fim▁end|>
true //~ ERROR mismatched types } }
<|file_name|>lint-non-camel-case-with-trailing-underscores.rs<|end_file_name|><|fim▁begin|>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. //<|fim▁hole|>// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // This is ok because we often use the trailing underscore to mean 'prime' #[forbid(non_camel_case_types)] type Foo_ = int; pub fn main() { }<|fim▁end|>
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
<|file_name|>google.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python #coding:utf-8 # Author: Beining --<cnbeining#gmail.com> # Purpose: A Chrome DCP handler. # Created: 07/15/2015 #Original copyright info: #Author: Xiaoxia #Contact: xiaoxia@xiaoxia.org #Website: xiaoxia.org import sys import argparse from threading import Thread, Lock from struct import unpack from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer from httplib import HTTPResponse, HTTPSConnection from SocketServer import ThreadingMixIn import socket, os, select import time, sys, random import threading import select import socket import ssl import socket import urllib2 # Minimize Memory Usage threading.stack_size(128*1024) BufferSize = 8192 RemoteTimeout = 15 from hashlib import md5 global PROXY_MODE PROXY_MODE = 'HTTPS' #---------------------------------------------------------------------- def get_long_int(): """None->int get a looooooong integer.""" return str(random.randint(100000000, 999999999)) #---------------------------------------------------------------------- def get_google_header(): """None->str As in https://github.com/cnbeining/datacompressionproxy/blob/master/background.js#L10-L18 . P.S: This repo is a fork of the original one on google code. """ authValue = 'ac4500dd3b7579186c1b0620614fdb1f7d61f944' timestamp = str(int(time.time())) return 'ps=' + timestamp + '-' + get_long_int() + '-' + get_long_int() + '-' + get_long_int() + ', sid=' + md5((timestamp + authValue + timestamp).encode('utf-8')).hexdigest() + ', b=2403, p=61, c=win' #---------------------------------------------------------------------- def check_if_ssl(): """None->str Check whether DCP should use HTTPS. As in https://support.google.com/chrome/answer/3517349?hl=en""" response = urllib2.urlopen('http://check.googlezip.net/connect') if response.getcode() is 200 and 'OK' in response.read(): print('INFO: Running in HTTPS mode.') return 'HTTPS' else: print('WARNING: Running in HTTP mode, your network admin can see your traffic!') return 'HTTP' class Handler(BaseHTTPRequestHandler): remote = None # Ignore Connection Failure def handle(self): try: BaseHTTPRequestHandler.handle(self) except socket.error: pass def finish(self): try: BaseHTTPRequestHandler.finish(self) except socket.error: pass def sogouProxy(self): if self.headers["Host"].startswith('chrome_dcp_proxy_pac.cnbeining'): #Give a PAC file self.wfile.write("HTTP/1.1 200 OK".encode('ascii') + b'\r\n') hstr = '''Host: 127.0.0.1 function FindProxyForURL(url, host) { if (url.substring(0,5) == 'http:' && !isPlainHostName(host) && !shExpMatch(host, '*.local') && !isInNet(dnsResolve(host), '10.0.0.0', '255.0.0.0') && !isInNet(dnsResolve(host), '172.16.0.0', '255.240.0.0') && !isInNet(dnsResolve(host), '192.168.0.0', '255.255.0.0') && !isInNet(dnsResolve(host), '127.0.0.0', '255.255.255.0') ) return 'PROXY ''' + server_ip + ':' + str(server_port) + '''; DIRECT';<|fim▁hole|>}''' self.wfile.write(hstr + b'\r\n') return if self.remote is None or self.lastHost != self.headers["Host"]: if PROXY_MODE == 'HTTPS': context = ssl.SSLContext(ssl.PROTOCOL_TLSv1) context.verify_mode = ssl.CERT_REQUIRED context.check_hostname = True context.load_default_certs() s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(RemoteTimeout) self.remote = context.wrap_socket(s, server_hostname='proxy.googlezip.net') self.remote.connect(('proxy.googlezip.net', 443)) else: #HTTP self.remote = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.remote.settimeout(RemoteTimeout) self.remote.connect(("compress.googlezip.net", 80)) self.remote.sendall(self.requestline.encode('ascii') + b"\r\n") # Add Verification Tags self.headers["Chrome-Proxy"] = get_google_header() headerstr = str(self.headers).replace("\r\n", "\n").replace("\n", "\r\n") self.remote.sendall(headerstr.encode('ascii') + b"\r\n") # Send Post data if self.command == 'POST': self.remote.sendall(self.rfile.read(int(self.headers['Content-Length']))) response = HTTPResponse(self.remote, method=self.command) response.begin() # Reply to the browser status = "HTTP/1.1 " + str(response.status) + " " + response.reason self.wfile.write(status.encode('ascii') + b'\r\n') hlist = [] for line in response.msg.headers: # Fixed multiple values of a same name if 'TRANSFER-ENCODING' not in line.upper(): hlist.append(line) self.wfile.write("".join(hlist) + b'\r\n') if self.command == "CONNECT": # NO HTTPS, as Chrome DCP does not allow HTTPS traffic return else: while True: response_data = response.read(BufferSize) if not response_data: break self.wfile.write(response_data) do_POST = do_GET = do_CONNECT = sogouProxy class ThreadingHTTPServer(ThreadingMixIn, HTTPServer): address_family = socket.AF_INET6 if __name__=='__main__': global server_ip, server_port parser = argparse.ArgumentParser() parser.add_argument('-p', '--port', default=8080) parser.add_argument('-m', '--mode', default= 'HTTPS') parser.add_argument('-i', '--ip', default= '') args = vars(parser.parse_args()) PROXY_MODE = args['mode'].upper() if str(args['mode']).upper() == 'HTTP' or str(args['mode']).upper() == 'HTTPS' else check_if_ssl() server_ip, server_port = str(args['ip']), int(args['port']) server_address = (server_ip, server_port) server = ThreadingHTTPServer(server_address, Handler) if not server_ip: server_ip = '127.0.0.1' proxy_host = "proxy.googlezip.net:443" if PROXY_MODE == 'HTTPS' else "compress.googlezip.net:80" print('Proxy over %s.\nPlease set your browser\'s proxy to %s.' % (proxy_host, server_address)) print('Or use PAC file: http://chrome_dcp_proxy_pac.cnbeining.com/1.pac') try: server.serve_forever() except: os._exit(1)<|fim▁end|>
return 'DIRECT';
<|file_name|>employee_birthday.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors<|fim▁hole|> import frappe from frappe import _ def execute(filters=None): if not filters: filters = {} columns = get_columns() data = get_employees(filters) return columns, data def get_columns(): return [ _("Employee") + ":Link/Employee:120", _("Name") + ":Data:200", _("Date of Birth")+ ":Date:100", _("Branch") + ":Link/Branch:120", _("Department") + ":Link/Department:120", _("Designation") + ":Link/Designation:120", _("Gender") + "::60", _("Company") + ":Link/Company:120" ] def get_employees(filters): conditions = get_conditions(filters) return frappe.db.sql("""select name, employee_name, date_of_birth, branch, department, designation, gender, company from tabEmployee where status = 'Active' %s""" % conditions, as_list=1) def get_conditions(filters): conditions = "" if filters.get("month"): month = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"].index(filters["month"]) + 1 conditions += " and month(date_of_birth) = '%s'" % month if filters.get("company"): conditions += " and company = '%s'" % \ filters["company"].replace("'", "\\'") return conditions<|fim▁end|>
# License: GNU General Public License v3. See license.txt
<|file_name|>FormatLangPair_impl_ari_1_5_0.java<|end_file_name|><|fim▁begin|>package ch.loway.oss.ari4java.generated.ari_1_5_0.models; // ---------------------------------------------------- // THIS CLASS WAS GENERATED AUTOMATICALLY // PLEASE DO NOT EDIT // Generated on: Sat Sep 19 08:50:54 CEST 2015 // ---------------------------------------------------- import ch.loway.oss.ari4java.generated.*; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import java.util.Date; import java.util.List; import java.util.Map; /********************************************************** * Identifies the format and language of a sound file * * Defined in file: sounds.json * Generated by: Model *********************************************************/ public class FormatLangPair_impl_ari_1_5_0 implements FormatLangPair, java.io.Serializable { private static final long serialVersionUID = 1L; /** */ private String format; public String getFormat() { return format; } @JsonDeserialize( as=String.class ) public void setFormat(String val ) {<|fim▁hole|> /** */ private String language; public String getLanguage() { return language; } @JsonDeserialize( as=String.class ) public void setLanguage(String val ) { language = val; } /** No missing signatures from interface */ }<|fim▁end|>
format = val; }
<|file_name|>image_annotator_client_example_test.go<|end_file_name|><|fim▁begin|>// Copyright 2019 Google LLC // // 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 // // https://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. // Code generated by gapic-generator. DO NOT EDIT. package vision_test import ( "context" vision "cloud.google.com/go/vision/apiv1" visionpb "google.golang.org/genproto/googleapis/cloud/vision/v1" ) func ExampleNewImageAnnotatorClient() { ctx := context.Background() c, err := vision.NewImageAnnotatorClient(ctx) if err != nil { // TODO: Handle error. } // TODO: Use client. _ = c } func ExampleImageAnnotatorClient_BatchAnnotateImages() { ctx := context.Background() c, err := vision.NewImageAnnotatorClient(ctx) if err != nil { // TODO: Handle error. } req := &visionpb.BatchAnnotateImagesRequest{ // TODO: Fill request struct fields. } resp, err := c.BatchAnnotateImages(ctx, req) if err != nil { // TODO: Handle error. } // TODO: Use resp. _ = resp } func ExampleImageAnnotatorClient_BatchAnnotateFiles() { ctx := context.Background() c, err := vision.NewImageAnnotatorClient(ctx) if err != nil { // TODO: Handle error. } req := &visionpb.BatchAnnotateFilesRequest{ // TODO: Fill request struct fields. } resp, err := c.BatchAnnotateFiles(ctx, req) if err != nil { // TODO: Handle error. } // TODO: Use resp. _ = resp } func ExampleImageAnnotatorClient_AsyncBatchAnnotateImages() { ctx := context.Background() c, err := vision.NewImageAnnotatorClient(ctx) if err != nil { // TODO: Handle error. } req := &visionpb.AsyncBatchAnnotateImagesRequest{ // TODO: Fill request struct fields. } op, err := c.AsyncBatchAnnotateImages(ctx, req) if err != nil { // TODO: Handle error. } resp, err := op.Wait(ctx) if err != nil { // TODO: Handle error. } // TODO: Use resp. _ = resp } func ExampleImageAnnotatorClient_AsyncBatchAnnotateFiles() { ctx := context.Background() c, err := vision.NewImageAnnotatorClient(ctx) if err != nil { // TODO: Handle error. } req := &visionpb.AsyncBatchAnnotateFilesRequest{ // TODO: Fill request struct fields. } op, err := c.AsyncBatchAnnotateFiles(ctx, req) if err != nil { // TODO: Handle error. }<|fim▁hole|> if err != nil { // TODO: Handle error. } // TODO: Use resp. _ = resp }<|fim▁end|>
resp, err := op.Wait(ctx)
<|file_name|>fragment_program.py<|end_file_name|><|fim▁begin|>'''OpenGL extension ARB.fragment_program This module customises the behaviour of the OpenGL.raw.GL.ARB.fragment_program to provide a more Python-friendly API Overview (from the spec) Unextended OpenGL mandates a certain set of configurable per- fragment computations defining texture application, texture environment, color sum, and fog operations. Several extensions have added further per-fragment computations to OpenGL. For example, extensions have defined new texture environment capabilities (ARB_texture_env_add, ARB_texture_env_combine, ARB_texture_env_dot3, ARB_texture_env_crossbar), per-fragment depth comparisons (ARB_depth_texture, ARB_shadow, ARB_shadow_ambient, EXT_shadow_funcs), per-fragment lighting (EXT_fragment_lighting, EXT_light_texture), and environment mapped bump mapping (ATI_envmap_bumpmap). Each such extension adds a small set of relatively inflexible per- fragment computations. This inflexibility is in contrast to the typical flexibility provided by the underlying programmable floating point engines (whether micro-coded fragment engines, DSPs, or CPUs) that are traditionally used to implement OpenGL's texturing computations. The purpose of this extension is to expose to the OpenGL application writer a significant degree of per-fragment programmability for computing fragment parameters. For the purposes of discussing this extension, a fragment program is a sequence of floating-point 4-component vector operations that determines how a set of program parameters (not specific to an individual fragment) and an input set of per-fragment parameters are transformed to a set of per-fragment result parameters. The per-fragment computations for standard OpenGL given a particular set of texture and fog application modes (along with any state for extensions defining per-fragment computations) is, in essence, a fragment program. However, the sequence of operations is defined implicitly by the current OpenGL state settings rather than defined explicitly as a sequence of instructions. <|fim▁hole|> This extension provides an explicit mechanism for defining fragment program instruction sequences for application-defined fragment programs. In order to define such fragment programs, this extension defines a fragment programming model including a floating-point 4-component vector instruction set and a relatively large set of floating-point 4-component registers. The extension's fragment programming model is designed for efficient hardware implementation and to support a wide variety of fragment programs. By design, the entire set of existing fragment programs defined by existing OpenGL per-fragment computation extensions can be implemented using the extension's fragment programming model. The official definition of this extension is available here: http://www.opengl.org/registry/specs/ARB/fragment_program.txt ''' from OpenGL import platform, constants, constant, arrays from OpenGL import extensions, wrapper from OpenGL.GL import glget import ctypes from OpenGL.raw.GL.ARB.fragment_program import * ### END AUTOGENERATED SECTION from OpenGL.GL import glget glget.addGLGetConstant( GL_FRAGMENT_PROGRAM_ARB, (1,) )<|fim▁end|>
<|file_name|>signup.module.ts<|end_file_name|><|fim▁begin|>import { NgModule } from '@angular/core'; import { IonicPageModule } from 'ionic-angular'; import { SignupPage } from './signup'; @NgModule({ declarations: [ SignupPage, ], imports: [ IonicPageModule.forChild(SignupPage),<|fim▁hole|>}) export class SignupPageModule {}<|fim▁end|>
], exports: [ SignupPage ]
<|file_name|>util.hpp<|end_file_name|><|fim▁begin|>// Endless Online Bot v0.0.1 #ifndef UTIL_HPP_INCLUDED #define UTIL_HPP_INCLUDED #include <math.h> #include <vector> #include <string> int path_length(int x1, int y1, int x2, int y2); <|fim▁hole|>#endif // UTIL_HPP_INCLUDED<|fim▁end|>
std::vector<std::string> Args(std::string str); std::string Lowercase(std::string str);
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>// (c) 2016-2017 Productize SPRL <joost@productize.be> //! Kicad file format parser and generator library #![warn(missing_docs)] #[macro_use] extern crate log; extern crate shellexpand; extern crate symbolic_expressions; // extern crate strum; // #[macro_use] // extern crate strum_macros; use std::fmt; use std::path::{Path, PathBuf}; use std::result; pub use symbolic_expressions::{Sexp,SexpError}; pub use error::*; /// read file utility wrapper function pub use util::read_file; /// write file utility wrapper function pub use util::write_file; fn parse_split_quote_aware_int(n_opt: Option<usize>, s: &str) -> Result<Vec<String>, KicadError> { let mut i = 0; let mut v: Vec<String> = vec![]; // if we are inside our outside a quoted string let mut inside_quotation = false; let mut quotation_seen = false; let mut s2: String = "".into(); for c in s.chars() { if let Some(n) = n_opt { if i == n { // if we're in the nth. just keep collecting in current string s2.push(c); continue; } } // detection of starting " if !inside_quotation && c == '\"' { inside_quotation = true; continue; } // detection of final " if inside_quotation && c == '\"' { inside_quotation = false; quotation_seen = true; continue; } // detection of space before or in between parts if !inside_quotation && c == ' ' { if !s2.is_empty() || quotation_seen { i += 1; v.push(s2.clone()); s2.clear(); } quotation_seen = false; continue; } s2.push(c); } if !s2.is_empty() || quotation_seen { v.push(s2.clone()) } if let Some(n) = n_opt { if v.len() < n { return str_error(format!("expecting {} elements in {}", n, s)); } } Ok(v) } fn parse_split_quote_aware_n(n: usize, s: &str) -> Result<Vec<String>, KicadError> { parse_split_quote_aware_int(Some(n), s) } fn parse_split_quote_aware(s: &str) -> Result<Vec<String>, KicadError> { parse_split_quote_aware_int(None, s) } /// types of Kicad files that can be found #[derive(Debug)] pub enum KicadFile { /// unknown file, probably no kicad file Unknown(PathBuf), /// a Kicad module, also know as a footprint Module(footprint::Module), /// a Kicad schematic file Schematic(schematic::Schematic), /// a Kicad layout file Layout(layout::Layout), /// a Kicad symbol library file SymbolLib(symbol_lib::SymbolLib), /// a Kicad project file Project(project::Project), /// a Kicad fp-lib-table file FpLibTable(fp_lib_table::FpLibTable), } /// types of Kicad files that we expect to read #[derive(PartialEq)] pub enum Expected { /// a Kicad module, also know as a footprint Module, /// a Kicad schematic file Schematic, /// a Kicad layout file Layout, /// a Kicad symbol library file SymbolLib, /// a Kicad project file Project, /// an fp-lib-table file FpLibTable, /// any Kicad file Any, } impl fmt::Display for KicadFile { fn fmt(&self, f: &mut fmt::Formatter) -> std::result::Result<(), fmt::Error> { match *self { KicadFile::Unknown(ref x) => write!(f, "unknown: {}", x.to_str().unwrap()), KicadFile::Module(_) => write!(f, "module"), KicadFile::Schematic(_) => write!(f, "schematic"), KicadFile::Layout(_) => write!(f, "layout"), KicadFile::SymbolLib(_) => write!(f, "symbollib"), KicadFile::Project(_) => write!(f, "project"), KicadFile::FpLibTable(_) => write!(f, "fp-lib-table"), } } } /// try to read a file, trying to parse it as the different formats /// and matching it against the Expected type #[cfg_attr(feature = "cargo-clippy", allow(needless_pass_by_value))] pub fn read_kicad_file(name: &Path, expected: Expected) -> Result<KicadFile, KicadError> { let data = read_file(name)?; match footprint::parse(&data) { Ok(module) => return Ok(KicadFile::Module(module)), Err(x) => if expected == Expected::Module { return Err(x); }, } match schematic::parse(Some(PathBuf::from(name)), &data) { Ok(sch) => return Ok(KicadFile::Schematic(sch)), Err(x) => if expected == Expected::Schematic { return Err(x); }, } match layout::parse(&data) { Ok(layout) => return Ok(KicadFile::Layout(layout)), Err(x) => if expected == Expected::Layout { return Err(x); }, } match symbol_lib::parse_str(&data) { Ok(sl) => return Ok(KicadFile::SymbolLib(sl)), Err(x) => if expected == Expected::SymbolLib { return Err(x); }, } match project::parse_str(&data) { Ok(p) => return Ok(KicadFile::Project(p)), Err(x) => if expected == Expected::Project { return Err(x); }, } match fp_lib_table::parse(&data) { Ok(p) => return Ok(KicadFile::FpLibTable(p)), Err(x) => if expected == Expected::FpLibTable { return Err(x.into()); }, } Ok(KicadFile::Unknown(PathBuf::from(name))) } /// read a file, expecting it to be a Kicad module file pub fn read_module(name: &Path) -> Result<footprint::Module, KicadError> { match read_kicad_file(name, Expected::Module)? { KicadFile::Module(mo) => Ok(mo), x => str_error(format!("unexpected {} in {}", x, name.display())), } } /// read a file, expecting it to be a Kicad schematic pub fn read_schematic(name: &Path) -> Result<schematic::Schematic, KicadError> { match read_kicad_file(name, Expected::Schematic)? { KicadFile::Schematic(mo) => Ok(mo), x => str_error(format!("unexpected {} in {}", x, name.display())), } } /// read a file, expecting it to be a Kicad layout file pub fn read_layout(name: &Path) -> Result<layout::Layout, KicadError> { match read_kicad_file(name, Expected::Layout)? { KicadFile::Layout(mo) => Ok(mo), x => str_error(format!("unexpected {} in {}", x, name.display())), } } /// write out a kicad Layout to a file pub fn write_layout(layout: &layout::Layout, name: &Path) -> Result<(), KicadError> { let s = layout::layout_to_string(layout, 0)?; write_file(name, &s) } /// write out a kicad `Module` to a file pub fn write_module(module: &footprint::Module, name: &Path) -> Result<(), KicadError> { let s = footprint::module_to_string(module, 0)?; write_file(&name, &s) } /// read a file, expecting it to be a Kicad symbol library file pub fn read_symbol_lib(name: &Path) -> Result<symbol_lib::SymbolLib, KicadError> { match read_kicad_file(name, Expected::SymbolLib)? { KicadFile::SymbolLib(mo) => Ok(mo), x => str_error(format!("unexpected {} in {}", x, name.display())), } } /// read a file, expecting it to be a Kicad project file pub fn read_project(name: &Path) -> Result<project::Project, KicadError> { match read_kicad_file(name, Expected::Project)? { KicadFile::Project(mo) => Ok(mo), x => str_error(format!("unexpected {} in {}", x, name.display())), } } /// read a file, expecting it to be an fp-lib-table pub fn read_fp_lib_table(name: &Path) -> Result<fp_lib_table::FpLibTable, KicadError> { match read_kicad_file(name, Expected::FpLibTable)? { KicadFile::FpLibTable(mo) => Ok(mo), x => str_error(format!("unexpected {} in {}", x, name.display())), } } fn wrap<X, Y, F, G>(s: &Sexp, make: F, wrapper: G) -> result::Result<Y,SexpError> where F: Fn(&Sexp) -> result::Result<X,SexpError>, G: Fn(X) -> Y, { Ok(wrapper(make(s)?)) } #[derive(Debug)] /// A bounding box pub struct Bound { /// smaller x pub x1: f64, /// smaller y pub y1: f64, /// bigger x pub x2: f64, /// bigger y pub y2: f64, /// item is bounded pub is_bounded: bool, } impl Default for Bound { fn default() -> Bound { Bound { x1: 0.0, y1: 0.0, x2: 0.0, y2: 0.0, is_bounded: false, } } } impl Bound { /// create a new bound pub fn new(x1: f64, y1: f64, x2: f64, y2: f64) -> Bound { Bound { x1: x1, y1: y1, x2: x2, y2: y2, is_bounded: true, } } /// create a new bound pub fn new_from_i64(x1: i64, y1: i64, x2: i64, y2: i64) -> Bound { Bound { x1: x1 as f64, y1: y1 as f64, x2: x2 as f64, y2: y2 as f64, is_bounded: true, } } /// update the bound with another one pub fn update(&mut self, other: &Bound) { if other.is_bounded { if !self.is_bounded { self.is_bounded = true; self.x1 = other.x1; self.y1 = other.y1; self.x2 = other.x2; self.y2 = other.y2; } else { self.x1 = self.x1.min(other.x1); self.y1 = self.y1.min(other.y1); self.x2 = self.x2.max(other.x2); self.y2 = self.y2.max(other.y2); } } } /// call this when you constructed a default bound and potentionally had zero updates pub fn swap_if_needed(&mut self) { if self.x1 > self.x2 { std::mem::swap(&mut self.x1, &mut self.x2); } if self.y1 > self.y2 { std::mem::swap(&mut self.y1, &mut self.y2); } } /// calculate the width of the `Bound` pub fn width(&self) -> f64 { (self.x1 - self.x2).abs() }<|fim▁hole|> /// calculate the height of the `Bound` pub fn height(&self) -> f64 { (self.y1 - self.y2).abs() } } /// calculate the bounding box of a layout item pub trait BoundingBox { /// calculate the bounding box of a layout item fn bounding_box(&self) -> Bound; } /// item location can be adjusted pub trait Adjust { /// adjust the location of the item fn adjust(&mut self, x: f64, y: f64); } /// ordering used for ordering by component reference /// to e.g. avoid U1 U101 U2 and get U1 U2 U101 pub fn reference_ord(r: &str) -> (char, i64) { let c = r.chars().nth(0).unwrap(); let mut s = String::new(); for c in r.chars() { if c >= '0' && c <= '9' { s.push(c) } // if the &str contains a list of references, // only take 1st element if c == ',' { break; } } let num = match s.parse::<i64>() { Ok(n) => n, Err(_) => 0, }; (c, num) } /// Kicad error handling code and types pub mod error; /// Kicad footprint format handling pub mod footprint; /// Kicad schematic format handling pub mod schematic; /// Kicad layout format handling pub mod layout; /// Kicad symbol library format handling pub mod symbol_lib; /// Kicad project format handling pub mod project; /// Kicad fp-lib-table format handling pub mod fp_lib_table; /// checking and fixing related to the Kicad Library Convention pub mod checkfix; mod util; mod formatter;<|fim▁end|>
<|file_name|>exceptions.py<|end_file_name|><|fim▁begin|><|fim▁hole|># Copyright (C) 2015 by Per Unneberg class NotInstalledError(Exception): """Error thrown if program/command/application cannot be found in path Args: msg (str): String described by exception code (int, optional): Error code, defaults to 2. """ def __init__(self, msg, code=2): self.msg = msg self.code = code class SamplesException(Exception): """Error thrown if samples missing or wrong number. Args: msg (str): String described by exception code (int, optional): Error code, defaults to 2. """ def __init__(self, msg, code=2): self.msg = msg self.code = code class OutputFilesException(Exception): """Error thrown if outputfiles missing or wrong number. Args: msg (str): String described by exception code (int, optional): Error code, defaults to 2. """ def __init__(self, msg, code=2): self.msg = msg self.code = code<|fim▁end|>
<|file_name|>ServicePort.cpp<|end_file_name|><|fim▁begin|>// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "modules/navigatorconnect/ServicePort.h" #include "bindings/core/v8/ScriptValue.h" #include "bindings/core/v8/SerializedScriptValueFactory.h" #include "core/dom/MessagePort.h" #include "modules/navigatorconnect/ServicePortCollection.h" #include "public/platform/Platform.h"<|fim▁hole|> ServicePort* ServicePort::create(ServicePortCollection* collection, const WebServicePort& port) { return new ServicePort(collection, port); } ServicePort::~ServicePort() { } String ServicePort::targetURL() const { return m_port.targetUrl.string(); } String ServicePort::name() const { return m_port.name; } ScriptValue ServicePort::data(ScriptState* scriptState) const { if (!m_serializedData) return ScriptValue::createNull(scriptState); return ScriptValue(scriptState, m_serializedData->deserialize(scriptState->isolate())); } void ServicePort::postMessage(ExecutionContext* executionContext, PassRefPtr<SerializedScriptValue> message, const MessagePortArray* ports, ExceptionState& exceptionState) { OwnPtr<MessagePortChannelArray> channels; if (ports) { channels = MessagePort::disentanglePorts(executionContext, ports, exceptionState); if (exceptionState.hadException()) return; } WebString messageString = message->toWireString(); OwnPtr<WebMessagePortChannelArray> webChannels = MessagePort::toWebMessagePortChannelArray(channels.release()); if (m_collection) { WebServicePortProvider* provider = m_collection->provider(); provider->postMessage(m_port.id, messageString, webChannels.leakPtr()); } } void ServicePort::close() { // TODO(mek): Figure out if this should throw instead of just quietly fail. if (!m_isOpen) return; m_collection->closePort(this); m_collection = nullptr; m_isOpen = false; } DEFINE_TRACE(ServicePort) { visitor->trace(m_collection); } ServicePort::ServicePort(ServicePortCollection* collection, const WebServicePort& port) : m_isOpen(true), m_port(port), m_collection(collection) { if (!m_port.data.isEmpty()) { m_serializedData = SerializedScriptValueFactory::instance().createFromWire(m_port.data); } } } // namespace blink<|fim▁end|>
#include "public/platform/modules/navigator_services/WebServicePortProvider.h" namespace blink {
<|file_name|>index.d.ts<|end_file_name|><|fim▁begin|>import * as _ from "lodash"; declare const sampleSize: typeof _.sampleSize;<|fim▁hole|><|fim▁end|>
export default sampleSize;
<|file_name|>qdesigner_formwindow.cpp<|end_file_name|><|fim▁begin|>/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) **<|fim▁hole|>** This file is part of the Qt Designer of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qdesigner_formwindow.h" #include "qdesigner_workbench.h" #include "formwindowbase_p.h" // sdk #include <QtDesigner/QDesignerFormWindowInterface> #include <QtDesigner/QDesignerFormEditorInterface> #include <QtDesigner/QDesignerPropertySheetExtension> #include <QtDesigner/QDesignerPropertyEditorInterface> #include <QtDesigner/QDesignerFormWindowManagerInterface> #include <QtDesigner/QDesignerTaskMenuExtension> #include <QtDesigner/QExtensionManager> #include <QtCore/QEvent> #include <QtCore/QFile> #include <QtGui/QAction> #include <QtGui/QCloseEvent> #include <QtGui/QFileDialog> #include <QtGui/QMessageBox> #include <QtGui/QPushButton> #include <QtGui/QVBoxLayout> #include <QtGui/QUndoCommand> #include <QtGui/QWindowStateChangeEvent> QT_BEGIN_NAMESPACE QDesignerFormWindow::QDesignerFormWindow(QDesignerFormWindowInterface *editor, QDesignerWorkbench *workbench, QWidget *parent, Qt::WindowFlags flags) : QWidget(parent, flags), m_editor(editor), m_workbench(workbench), m_action(new QAction(this)), m_initialized(false), m_windowTitleInitialized(false) { Q_ASSERT(workbench); setMaximumSize(0xFFF, 0xFFF); QDesignerFormEditorInterface *core = workbench->core(); if (m_editor) { m_editor->setParent(this); } else { m_editor = core->formWindowManager()->createFormWindow(this); } QVBoxLayout *l = new QVBoxLayout(this); l->setMargin(0); l->addWidget(m_editor); m_action->setCheckable(true); connect(m_editor->commandHistory(), SIGNAL(indexChanged(int)), this, SLOT(updateChanged())); connect(m_editor, SIGNAL(geometryChanged()), this, SLOT(geometryChanged())); qdesigner_internal::FormWindowBase::setupDefaultAction(m_editor); } QDesignerFormWindow::~QDesignerFormWindow() { if (workbench()) workbench()->removeFormWindow(this); } QAction *QDesignerFormWindow::action() const { return m_action; } void QDesignerFormWindow::changeEvent(QEvent *e) { switch (e->type()) { case QEvent::WindowTitleChange: m_action->setText(windowTitle().remove(QLatin1String("[*]"))); break; case QEvent::WindowIconChange: m_action->setIcon(windowIcon()); break; case QEvent::WindowStateChange: { const QWindowStateChangeEvent *wsce = static_cast<const QWindowStateChangeEvent *>(e); const bool wasMinimized = Qt::WindowMinimized & wsce->oldState(); const bool isMinimizedNow = isMinimized(); if (wasMinimized != isMinimizedNow ) emit minimizationStateChanged(m_editor, isMinimizedNow); } break; default: break; } QWidget::changeEvent(e); } QRect QDesignerFormWindow::geometryHint() const { const QPoint point(0, 0); // If we have a container, we want to be just as big. // QMdiSubWindow attempts to resize its children to sizeHint() when switching user interface modes. if (QWidget *mainContainer = m_editor->mainContainer()) return QRect(point, mainContainer->size()); return QRect(point, sizeHint()); } QDesignerFormWindowInterface *QDesignerFormWindow::editor() const { return m_editor; } QDesignerWorkbench *QDesignerFormWindow::workbench() const { return m_workbench; } void QDesignerFormWindow::firstShow() { // Set up handling of file name changes and set initial title. if (!m_windowTitleInitialized) { m_windowTitleInitialized = true; if (m_editor) { connect(m_editor, SIGNAL(fileNameChanged(QString)), this, SLOT(updateWindowTitle(QString))); updateWindowTitle(m_editor->fileName()); } } show(); } int QDesignerFormWindow::getNumberOfUntitledWindows() const { const int totalWindows = m_workbench->formWindowCount(); if (!totalWindows) return 0; int maxUntitled = 0; // Find the number of untitled windows excluding ourselves. // Do not fall for 'untitled.ui', match with modified place holder. // This will cause some problems with i18n, but for now I need the string to be "static" QRegExp rx(QLatin1String("untitled( (\\d+))?\\[\\*\\]")); for (int i = 0; i < totalWindows; ++i) { QDesignerFormWindow *fw = m_workbench->formWindow(i); if (fw != this) { const QString title = m_workbench->formWindow(i)->windowTitle(); if (rx.indexIn(title) != -1) { if (maxUntitled == 0) ++maxUntitled; if (rx.captureCount() > 1) { const QString numberCapture = rx.cap(2); if (!numberCapture.isEmpty()) maxUntitled = qMax(numberCapture.toInt(), maxUntitled); } } } } return maxUntitled; } void QDesignerFormWindow::updateWindowTitle(const QString &fileName) { if (!m_windowTitleInitialized) { m_windowTitleInitialized = true; if (m_editor) connect(m_editor, SIGNAL(fileNameChanged(QString)), this, SLOT(updateWindowTitle(QString))); } QString fileNameTitle; if (fileName.isEmpty()) { fileNameTitle = QLatin1String("untitled"); if (const int maxUntitled = getNumberOfUntitledWindows()) { fileNameTitle += QLatin1Char(' '); fileNameTitle += QString::number(maxUntitled + 1); } } else { fileNameTitle = QFileInfo(fileName).fileName(); } if (const QWidget *mc = m_editor->mainContainer()) { setWindowIcon(mc->windowIcon()); setWindowTitle(tr("%1 - %2[*]").arg(mc->windowTitle()).arg(fileNameTitle)); } else { setWindowTitle(fileNameTitle); } } void QDesignerFormWindow::closeEvent(QCloseEvent *ev) { if (m_editor->isDirty()) { raise(); QMessageBox box(QMessageBox::Information, tr("Save Form?"), tr("Do you want to save the changes to this document before closing?"), QMessageBox::Discard | QMessageBox::Cancel | QMessageBox::Save, m_editor); box.setInformativeText(tr("If you don't save, your changes will be lost.")); box.setWindowModality(Qt::WindowModal); static_cast<QPushButton *>(box.button(QMessageBox::Save))->setDefault(true); switch (box.exec()) { case QMessageBox::Save: { bool ok = workbench()->saveForm(m_editor); ev->setAccepted(ok); m_editor->setDirty(!ok); break; } case QMessageBox::Discard: m_editor->setDirty(false); // Not really necessary, but stops problems if we get close again. ev->accept(); break; case QMessageBox::Cancel: ev->ignore(); break; } } } void QDesignerFormWindow::updateChanged() { // Sometimes called after form window destruction. if (m_editor) { setWindowModified(m_editor->isDirty()); updateWindowTitle(m_editor->fileName()); } } void QDesignerFormWindow::resizeEvent(QResizeEvent *rev) { if(m_initialized) { m_editor->setDirty(true); setWindowModified(true); } m_initialized = true; QWidget::resizeEvent(rev); } void QDesignerFormWindow::geometryChanged() { // If the form window changes, re-update the geometry of the current widget in the property editor. // Note that in the case of layouts, non-maincontainer widgets must also be updated, // so, do not do it for the main container only const QDesignerFormEditorInterface *core = m_editor->core(); QObject *object = core->propertyEditor()->object(); if (object == 0 || !object->isWidgetType()) return; static const QString geometryProperty = QLatin1String("geometry"); const QDesignerPropertySheetExtension *sheet = qt_extension<QDesignerPropertySheetExtension*>(core->extensionManager(), object); const int geometryIndex = sheet->indexOf(geometryProperty); if (geometryIndex == -1) return; core->propertyEditor()->setPropertyValue(geometryProperty, sheet->property(geometryIndex)); } QT_END_NAMESPACE<|fim▁end|>
<|file_name|>test_pymongo.py<|end_file_name|><|fim▁begin|># Copyright 2009-2014 MongoDB, 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.<|fim▁hole|>"""Test the pymongo module itself.""" import unittest import os import sys sys.path[0:0] = [""] import pymongo from test import host, port class TestPyMongo(unittest.TestCase): def test_mongo_client_alias(self): # Testing that pymongo module imports mongo_client.MongoClient c = pymongo.MongoClient(host, port) self.assertEqual(c.host, host) self.assertEqual(c.port, port) if __name__ == "__main__": unittest.main()<|fim▁end|>
<|file_name|>jquery.cycle.all.js<|end_file_name|><|fim▁begin|>/*! * jQuery Cycle Plugin (with Transition Definitions) * Examples and documentation at: http://jquery.malsup.com/cycle/ * Copyright (c) 2007-2013 M. Alsup * Version: 3.0.3 (11-JUL-2013) * Dual licensed under the MIT and GPL licenses. * http://jquery.malsup.com/license.html * Requires: jQuery v1.7.1 or later */ ;(function($, undefined) { "use strict"; var ver = '3.0.3'; function debug(s) { if ($.fn.cycle.debug) log(s); } function log() { /*global console */ if (window.console && console.log) console.log('[cycle] ' + Array.prototype.join.call(arguments,' ')); } $.expr[':'].paused = function(el) { return el.cyclePause; }; // the options arg can be... // a number - indicates an immediate transition should occur to the given slide index // a string - 'pause', 'resume', 'toggle', 'next', 'prev', 'stop', 'destroy' or the name of a transition effect (ie, 'fade', 'zoom', etc) // an object - properties to control the slideshow // // the arg2 arg can be... // the name of an fx (only used in conjunction with a numeric value for 'options') // the value true (only used in first arg == 'resume') and indicates // that the resume should occur immediately (not wait for next timeout) $.fn.cycle = function(options, arg2) { var o = { s: this.selector, c: this.context }; // in 1.3+ we can fix mistakes with the ready state if (this.length === 0 && options != 'stop') { if (!$.isReady && o.s) { log('DOM not ready, queuing slideshow'); $(function() { $(o.s,o.c).cycle(options,arg2); }); return this; } // is your DOM ready? http://docs.jquery.com/Tutorials:Introducing_$(document).ready() log('terminating; zero elements found by selector' + ($.isReady ? '' : ' (DOM not ready)')); return this; } // iterate the matched nodeset return this.each(function() { var opts = handleArguments(this, options, arg2); if (opts === false) return; opts.updateActivePagerLink = opts.updateActivePagerLink || $.fn.cycle.updateActivePagerLink; // stop existing slideshow for this container (if there is one) if (this.cycleTimeout) clearTimeout(this.cycleTimeout); this.cycleTimeout = this.cyclePause = 0; this.cycleStop = 0; // issue #108 var $cont = $(this); var $slides = opts.slideExpr ? $(opts.slideExpr, this) : $cont.children(); var els = $slides.get(); if (els.length < 2) { log('terminating; too few slides: ' + els.length); return; } var opts2 = buildOptions($cont, $slides, els, opts, o); if (opts2 === false) return; var startTime = opts2.continuous ? 10 : getTimeout(els[opts2.currSlide], els[opts2.nextSlide], opts2, !opts2.backwards); // if it's an auto slideshow, kick it off if (startTime) { startTime += (opts2.delay || 0); if (startTime < 10) startTime = 10; debug('first timeout: ' + startTime); this.cycleTimeout = setTimeout(function(){go(els,opts2,0,!opts.backwards);}, startTime); } }); }; function triggerPause(cont, byHover, onPager) { var opts = $(cont).data('cycle.opts'); if (!opts) return; var paused = !!cont.cyclePause; if (paused && opts.paused) opts.paused(cont, opts, byHover, onPager); else if (!paused && opts.resumed) opts.resumed(cont, opts, byHover, onPager); } // process the args that were passed to the plugin fn function handleArguments(cont, options, arg2) { if (cont.cycleStop === undefined) cont.cycleStop = 0; if (options === undefined || options === null) options = {}; if (options.constructor == String) { switch(options) { case 'destroy': case 'stop': var opts = $(cont).data('cycle.opts'); if (!opts) return false; cont.cycleStop++; // callbacks look for change if (cont.cycleTimeout) clearTimeout(cont.cycleTimeout); cont.cycleTimeout = 0; if (opts.elements) $(opts.elements).stop(); $(cont).removeData('cycle.opts'); if (options == 'destroy') destroy(cont, opts); return false; case 'toggle': cont.cyclePause = (cont.cyclePause === 1) ? 0 : 1; checkInstantResume(cont.cyclePause, arg2, cont); triggerPause(cont); return false; case 'pause': cont.cyclePause = 1; triggerPause(cont); return false; case 'resume': cont.cyclePause = 0; checkInstantResume(false, arg2, cont); triggerPause(cont); return false; case 'prev': case 'next': opts = $(cont).data('cycle.opts'); if (!opts) { log('options not found, "prev/next" ignored'); return false; } if (typeof arg2 == 'string') opts.oneTimeFx = arg2; $.fn.cycle[options](opts); return false; default: options = { fx: options }; } return options; } else if (options.constructor == Number) { // go to the requested slide var num = options; options = $(cont).data('cycle.opts'); if (!options) { log('options not found, can not advance slide'); return false; } if (num < 0 || num >= options.elements.length) { log('invalid slide index: ' + num); return false; } options.nextSlide = num; if (cont.cycleTimeout) { clearTimeout(cont.cycleTimeout); cont.cycleTimeout = 0; } if (typeof arg2 == 'string') options.oneTimeFx = arg2; go(options.elements, options, 1, num >= options.currSlide); return false; } return options; function checkInstantResume(isPaused, arg2, cont) { if (!isPaused && arg2 === true) { // resume now! var options = $(cont).data('cycle.opts'); if (!options) { log('options not found, can not resume'); return false; } if (cont.cycleTimeout) { clearTimeout(cont.cycleTimeout); cont.cycleTimeout = 0; } go(options.elements, options, 1, !options.backwards); } } } function removeFilter(el, opts) { if (!$.support.opacity && opts.cleartype && el.style.filter) { try { el.style.removeAttribute('filter'); } catch(smother) {} // handle old opera versions } } // unbind event handlers function destroy(cont, opts) { if (opts.next) $(opts.next).unbind(opts.prevNextEvent); if (opts.prev) $(opts.prev).unbind(opts.prevNextEvent); if (opts.pager || opts.pagerAnchorBuilder) $.each(opts.pagerAnchors || [], function() { this.unbind().remove(); }); opts.pagerAnchors = null; $(cont).unbind('mouseenter.cycle mouseleave.cycle'); if (opts.destroy) // callback opts.destroy(opts); } // one-time initialization function buildOptions($cont, $slides, els, options, o) { var startingSlideSpecified; // support metadata plugin (v1.0 and v2.0) var opts = $.extend({}, $.fn.cycle.defaults, options || {}, $.metadata ? $cont.metadata() : $.meta ? $cont.data() : {}); var meta = $.isFunction($cont.data) ? $cont.data(opts.metaAttr) : null; if (meta) opts = $.extend(opts, meta); if (opts.autostop) opts.countdown = opts.autostopCount || els.length; var cont = $cont[0]; $cont.data('cycle.opts', opts); opts.$cont = $cont; opts.stopCount = cont.cycleStop; opts.elements = els; opts.before = opts.before ? [opts.before] : []; opts.after = opts.after ? [opts.after] : []; // push some after callbacks if (!$.support.opacity && opts.cleartype) opts.after.push(function() { removeFilter(this, opts); }); if (opts.continuous) opts.after.push(function() { go(els,opts,0,!opts.backwards); }); saveOriginalOpts(opts); // clearType corrections if (!$.support.opacity && opts.cleartype && !opts.cleartypeNoBg) clearTypeFix($slides); // container requires non-static position so that slides can be position within if ($cont.css('position') == 'static') $cont.css('position', 'relative'); if (opts.width) $cont.width(opts.width); if (opts.height && opts.height != 'auto') $cont.height(opts.height); if (opts.startingSlide !== undefined) { opts.startingSlide = parseInt(opts.startingSlide,10); if (opts.startingSlide >= els.length || opts.startSlide < 0) opts.startingSlide = 0; // catch bogus input else startingSlideSpecified = true; } else if (opts.backwards) opts.startingSlide = els.length - 1; else opts.startingSlide = 0; // if random, mix up the slide array if (opts.random) { opts.randomMap = []; for (var i = 0; i < els.length; i++) opts.randomMap.push(i); opts.randomMap.sort(function(a,b) {return Math.random() - 0.5;}); if (startingSlideSpecified) { // try to find the specified starting slide and if found set start slide index in the map accordingly for ( var cnt = 0; cnt < els.length; cnt++ ) { if ( opts.startingSlide == opts.randomMap[cnt] ) { opts.randomIndex = cnt; } } } else { opts.randomIndex = 1; opts.startingSlide = opts.randomMap[1]; } } else if (opts.startingSlide >= els.length) opts.startingSlide = 0; // catch bogus input opts.currSlide = opts.startingSlide || 0; var first = opts.startingSlide; // set position and zIndex on all the slides $slides.css({position: 'absolute', top:0, left:0}).hide().each(function(i) { var z; if (opts.backwards) z = first ? i <= first ? els.length + (i-first) : first-i : els.length-i; else z = first ? i >= first ? els.length - (i-first) : first-i : els.length-i; $(this).css('z-index', z); }); // make sure first slide is visible $(els[first]).css('opacity',1).show(); // opacity bit needed to handle restart use case removeFilter(els[first], opts); // stretch slides if (opts.fit) { if (!opts.aspect) { if (opts.width) $slides.width(opts.width); if (opts.height && opts.height != 'auto') $slides.height(opts.height); } else { $slides.each(function(){ var $slide = $(this); var ratio = (opts.aspect === true) ? $slide.width()/$slide.height() : opts.aspect; if( opts.width && $slide.width() != opts.width ) { $slide.width( opts.width ); $slide.height( opts.width / ratio ); } if( opts.height && $slide.height() < opts.height ) { $slide.height( opts.height ); $slide.width( opts.height * ratio ); } }); } } if (opts.center && ((!opts.fit) || opts.aspect)) { $slides.each(function(){ var $slide = $(this); $slide.css({ "margin-left": opts.width ? ((opts.width - $slide.width()) / 2) + "px" : 0, "margin-top": opts.height ? ((opts.height - $slide.height()) / 2) + "px" : 0 }); }); } if (opts.center && !opts.fit && !opts.slideResize) { $slides.each(function(){ var $slide = $(this); $slide.css({ "margin-left": opts.width ? ((opts.width - $slide.width()) / 2) + "px" : 0, "margin-top": opts.height ? ((opts.height - $slide.height()) / 2) + "px" : 0 }); }); } // stretch container var reshape = (opts.containerResize || opts.containerResizeHeight) && $cont.innerHeight() < 1; if (reshape) { // do this only if container has no size http://tinyurl.com/da2oa9 var maxw = 0, maxh = 0; for(var j=0; j < els.length; j++) { var $e = $(els[j]), e = $e[0], w = $e.outerWidth(), h = $e.outerHeight(); if (!w) w = e.offsetWidth || e.width || $e.attr('width'); if (!h) h = e.offsetHeight || e.height || $e.attr('height'); maxw = w > maxw ? w : maxw; maxh = h > maxh ? h : maxh; } if (opts.containerResize && maxw > 0 && maxh > 0) $cont.css({width:maxw+'px',height:maxh+'px'}); if (opts.containerResizeHeight && maxh > 0) $cont.css({height:maxh+'px'}); } var pauseFlag = false; // https://github.com/malsup/cycle/issues/44 if (opts.pause) $cont.bind('mouseenter.cycle', function(){ pauseFlag = true; this.cyclePause++; triggerPause(cont, true); }).bind('mouseleave.cycle', function(){ if (pauseFlag) this.cyclePause--; triggerPause(cont, true); }); if (supportMultiTransitions(opts) === false) return false; // apparently a lot of people use image slideshows without height/width attributes on the images. // Cycle 2.50+ requires the sizing info for every slide; this block tries to deal with that. var requeue = false; options.requeueAttempts = options.requeueAttempts || 0; $slides.each(function() { // try to get height/width of each slide var $el = $(this); this.cycleH = (opts.fit && opts.height) ? opts.height : ($el.height() || this.offsetHeight || this.height || $el.attr('height') || 0); this.cycleW = (opts.fit && opts.width) ? opts.width : ($el.width() || this.offsetWidth || this.width || $el.attr('width') || 0); if ( $el.is('img') ) { var loading = (this.cycleH === 0 && this.cycleW === 0 && !this.complete); // don't requeue for images that are still loading but have a valid size if (loading) { if (o.s && opts.requeueOnImageNotLoaded && ++options.requeueAttempts < 100) { // track retry count so we don't loop forever log(options.requeueAttempts,' - img slide not loaded, requeuing slideshow: ', this.src, this.cycleW, this.cycleH); setTimeout(function() {$(o.s,o.c).cycle(options);}, opts.requeueTimeout); requeue = true; return false; // break each loop } else { log('could not determine size of image: '+this.src, this.cycleW, this.cycleH); } } } return true; }); if (requeue) return false; opts.cssBefore = opts.cssBefore || {}; opts.cssAfter = opts.cssAfter || {};<|fim▁hole|> $slides.not(':eq('+first+')').css(opts.cssBefore); $($slides[first]).css(opts.cssFirst); if (opts.timeout) { opts.timeout = parseInt(opts.timeout,10); // ensure that timeout and speed settings are sane if (opts.speed.constructor == String) opts.speed = $.fx.speeds[opts.speed] || parseInt(opts.speed,10); if (!opts.sync) opts.speed = opts.speed / 2; var buffer = opts.fx == 'none' ? 0 : opts.fx == 'shuffle' ? 500 : 250; while((opts.timeout - opts.speed) < buffer) // sanitize timeout opts.timeout += opts.speed; } if (opts.easing) opts.easeIn = opts.easeOut = opts.easing; if (!opts.speedIn) opts.speedIn = opts.speed; if (!opts.speedOut) opts.speedOut = opts.speed; opts.slideCount = els.length; opts.currSlide = opts.lastSlide = first; if (opts.random) { if (++opts.randomIndex == els.length) opts.randomIndex = 0; opts.nextSlide = opts.randomMap[opts.randomIndex]; } else if (opts.backwards) opts.nextSlide = opts.startingSlide === 0 ? (els.length-1) : opts.startingSlide-1; else opts.nextSlide = opts.startingSlide >= (els.length-1) ? 0 : opts.startingSlide+1; // run transition init fn if (!opts.multiFx) { var init = $.fn.cycle.transitions[opts.fx]; if ($.isFunction(init)) init($cont, $slides, opts); else if (opts.fx != 'custom' && !opts.multiFx) { log('unknown transition: ' + opts.fx,'; slideshow terminating'); return false; } } // fire artificial events var e0 = $slides[first]; if (!opts.skipInitializationCallbacks) { if (opts.before.length) opts.before[0].apply(e0, [e0, e0, opts, true]); if (opts.after.length) opts.after[0].apply(e0, [e0, e0, opts, true]); } if (opts.next) $(opts.next).bind(opts.prevNextEvent,function(){return advance(opts,1);}); if (opts.prev) $(opts.prev).bind(opts.prevNextEvent,function(){return advance(opts,0);}); if (opts.pager || opts.pagerAnchorBuilder) buildPager(els,opts); exposeAddSlide(opts, els); return opts; } // save off original opts so we can restore after clearing state function saveOriginalOpts(opts) { opts.original = { before: [], after: [] }; opts.original.cssBefore = $.extend({}, opts.cssBefore); opts.original.cssAfter = $.extend({}, opts.cssAfter); opts.original.animIn = $.extend({}, opts.animIn); opts.original.animOut = $.extend({}, opts.animOut); $.each(opts.before, function() { opts.original.before.push(this); }); $.each(opts.after, function() { opts.original.after.push(this); }); } function supportMultiTransitions(opts) { var i, tx, txs = $.fn.cycle.transitions; // look for multiple effects if (opts.fx.indexOf(',') > 0) { opts.multiFx = true; opts.fxs = opts.fx.replace(/\s*/g,'').split(','); // discard any bogus effect names for (i=0; i < opts.fxs.length; i++) { var fx = opts.fxs[i]; tx = txs[fx]; if (!tx || !txs.hasOwnProperty(fx) || !$.isFunction(tx)) { log('discarding unknown transition: ',fx); opts.fxs.splice(i,1); i--; } } // if we have an empty list then we threw everything away! if (!opts.fxs.length) { log('No valid transitions named; slideshow terminating.'); return false; } } else if (opts.fx == 'all') { // auto-gen the list of transitions opts.multiFx = true; opts.fxs = []; for (var p in txs) { if (txs.hasOwnProperty(p)) { tx = txs[p]; if (txs.hasOwnProperty(p) && $.isFunction(tx)) opts.fxs.push(p); } } } if (opts.multiFx && opts.randomizeEffects) { // munge the fxs array to make effect selection random var r1 = Math.floor(Math.random() * 20) + 30; for (i = 0; i < r1; i++) { var r2 = Math.floor(Math.random() * opts.fxs.length); opts.fxs.push(opts.fxs.splice(r2,1)[0]); } debug('randomized fx sequence: ',opts.fxs); } return true; } // provide a mechanism for adding slides after the slideshow has started function exposeAddSlide(opts, els) { opts.addSlide = function(newSlide, prepend) { var $s = $(newSlide), s = $s[0]; if (!opts.autostopCount) opts.countdown++; els[prepend?'unshift':'push'](s); if (opts.els) opts.els[prepend?'unshift':'push'](s); // shuffle needs this opts.slideCount = els.length; // add the slide to the random map and resort if (opts.random) { opts.randomMap.push(opts.slideCount-1); opts.randomMap.sort(function(a,b) {return Math.random() - 0.5;}); } $s.css('position','absolute'); $s[prepend?'prependTo':'appendTo'](opts.$cont); if (prepend) { opts.currSlide++; opts.nextSlide++; } if (!$.support.opacity && opts.cleartype && !opts.cleartypeNoBg) clearTypeFix($s); if (opts.fit && opts.width) $s.width(opts.width); if (opts.fit && opts.height && opts.height != 'auto') $s.height(opts.height); s.cycleH = (opts.fit && opts.height) ? opts.height : $s.height(); s.cycleW = (opts.fit && opts.width) ? opts.width : $s.width(); $s.css(opts.cssBefore); if (opts.pager || opts.pagerAnchorBuilder) $.fn.cycle.createPagerAnchor(els.length-1, s, $(opts.pager), els, opts); if ($.isFunction(opts.onAddSlide)) opts.onAddSlide($s); else $s.hide(); // default behavior }; } // reset internal state; we do this on every pass in order to support multiple effects $.fn.cycle.resetState = function(opts, fx) { fx = fx || opts.fx; opts.before = []; opts.after = []; opts.cssBefore = $.extend({}, opts.original.cssBefore); opts.cssAfter = $.extend({}, opts.original.cssAfter); opts.animIn = $.extend({}, opts.original.animIn); opts.animOut = $.extend({}, opts.original.animOut); opts.fxFn = null; $.each(opts.original.before, function() { opts.before.push(this); }); $.each(opts.original.after, function() { opts.after.push(this); }); // re-init var init = $.fn.cycle.transitions[fx]; if ($.isFunction(init)) init(opts.$cont, $(opts.elements), opts); }; // this is the main engine fn, it handles the timeouts, callbacks and slide index mgmt function go(els, opts, manual, fwd) { var p = opts.$cont[0], curr = els[opts.currSlide], next = els[opts.nextSlide]; // opts.busy is true if we're in the middle of an animation if (manual && opts.busy && opts.manualTrump) { // let manual transitions requests trump active ones debug('manualTrump in go(), stopping active transition'); $(els).stop(true,true); opts.busy = 0; clearTimeout(p.cycleTimeout); } // don't begin another timeout-based transition if there is one active if (opts.busy) { debug('transition active, ignoring new tx request'); return; } // stop cycling if we have an outstanding stop request if (p.cycleStop != opts.stopCount || p.cycleTimeout === 0 && !manual) return; // check to see if we should stop cycling based on autostop options if (!manual && !p.cyclePause && !opts.bounce && ((opts.autostop && (--opts.countdown <= 0)) || (opts.nowrap && !opts.random && opts.nextSlide < opts.currSlide))) { if (opts.end) opts.end(opts); return; } // if slideshow is paused, only transition on a manual trigger var changed = false; if ((manual || !p.cyclePause) && (opts.nextSlide != opts.currSlide)) { changed = true; var fx = opts.fx; // keep trying to get the slide size if we don't have it yet curr.cycleH = curr.cycleH || $(curr).height(); curr.cycleW = curr.cycleW || $(curr).width(); next.cycleH = next.cycleH || $(next).height(); next.cycleW = next.cycleW || $(next).width(); // support multiple transition types if (opts.multiFx) { if (fwd && (opts.lastFx === undefined || ++opts.lastFx >= opts.fxs.length)) opts.lastFx = 0; else if (!fwd && (opts.lastFx === undefined || --opts.lastFx < 0)) opts.lastFx = opts.fxs.length - 1; fx = opts.fxs[opts.lastFx]; } // one-time fx overrides apply to: $('div').cycle(3,'zoom'); if (opts.oneTimeFx) { fx = opts.oneTimeFx; opts.oneTimeFx = null; } $.fn.cycle.resetState(opts, fx); // run the before callbacks if (opts.before.length) $.each(opts.before, function(i,o) { if (p.cycleStop != opts.stopCount) return; o.apply(next, [curr, next, opts, fwd]); }); // stage the after callacks var after = function() { opts.busy = 0; $.each(opts.after, function(i,o) { if (p.cycleStop != opts.stopCount) return; o.apply(next, [curr, next, opts, fwd]); }); if (!p.cycleStop) { // queue next transition queueNext(); } }; debug('tx firing('+fx+'); currSlide: ' + opts.currSlide + '; nextSlide: ' + opts.nextSlide); // get ready to perform the transition opts.busy = 1; if (opts.fxFn) // fx function provided? opts.fxFn(curr, next, opts, after, fwd, manual && opts.fastOnEvent); else if ($.isFunction($.fn.cycle[opts.fx])) // fx plugin ? $.fn.cycle[opts.fx](curr, next, opts, after, fwd, manual && opts.fastOnEvent); else $.fn.cycle.custom(curr, next, opts, after, fwd, manual && opts.fastOnEvent); } else { queueNext(); } if (changed || opts.nextSlide == opts.currSlide) { // calculate the next slide var roll; opts.lastSlide = opts.currSlide; if (opts.random) { opts.currSlide = opts.nextSlide; if (++opts.randomIndex == els.length) { opts.randomIndex = 0; opts.randomMap.sort(function(a,b) {return Math.random() - 0.5;}); } opts.nextSlide = opts.randomMap[opts.randomIndex]; if (opts.nextSlide == opts.currSlide) opts.nextSlide = (opts.currSlide == opts.slideCount - 1) ? 0 : opts.currSlide + 1; } else if (opts.backwards) { roll = (opts.nextSlide - 1) < 0; if (roll && opts.bounce) { opts.backwards = !opts.backwards; opts.nextSlide = 1; opts.currSlide = 0; } else { opts.nextSlide = roll ? (els.length-1) : opts.nextSlide-1; opts.currSlide = roll ? 0 : opts.nextSlide+1; } } else { // sequence roll = (opts.nextSlide + 1) == els.length; if (roll && opts.bounce) { opts.backwards = !opts.backwards; opts.nextSlide = els.length-2; opts.currSlide = els.length-1; } else { opts.nextSlide = roll ? 0 : opts.nextSlide+1; opts.currSlide = roll ? els.length-1 : opts.nextSlide-1; } } } if (changed && opts.pager) opts.updateActivePagerLink(opts.pager, opts.currSlide, opts.activePagerClass); function queueNext() { // stage the next transition var ms = 0, timeout = opts.timeout; if (opts.timeout && !opts.continuous) { ms = getTimeout(els[opts.currSlide], els[opts.nextSlide], opts, fwd); if (opts.fx == 'shuffle') ms -= opts.speedOut; } else if (opts.continuous && p.cyclePause) // continuous shows work off an after callback, not this timer logic ms = 10; if (ms > 0) p.cycleTimeout = setTimeout(function(){ go(els, opts, 0, !opts.backwards); }, ms); } } // invoked after transition $.fn.cycle.updateActivePagerLink = function(pager, currSlide, clsName) { $(pager).each(function() { $(this).children().removeClass(clsName).eq(currSlide).addClass(clsName); }); }; // calculate timeout value for current transition function getTimeout(curr, next, opts, fwd) { if (opts.timeoutFn) { // call user provided calc fn var t = opts.timeoutFn.call(curr,curr,next,opts,fwd); while (opts.fx != 'none' && (t - opts.speed) < 250) // sanitize timeout t += opts.speed; debug('calculated timeout: ' + t + '; speed: ' + opts.speed); if (t !== false) return t; } return opts.timeout; } // expose next/prev function, caller must pass in state $.fn.cycle.next = function(opts) { advance(opts,1); }; $.fn.cycle.prev = function(opts) { advance(opts,0);}; // advance slide forward or back function advance(opts, moveForward) { var val = moveForward ? 1 : -1; var els = opts.elements; var p = opts.$cont[0], timeout = p.cycleTimeout; if (timeout) { clearTimeout(timeout); p.cycleTimeout = 0; } if (opts.random && val < 0) { // move back to the previously display slide opts.randomIndex--; if (--opts.randomIndex == -2) opts.randomIndex = els.length-2; else if (opts.randomIndex == -1) opts.randomIndex = els.length-1; opts.nextSlide = opts.randomMap[opts.randomIndex]; } else if (opts.random) { opts.nextSlide = opts.randomMap[opts.randomIndex]; } else { opts.nextSlide = opts.currSlide + val; if (opts.nextSlide < 0) { if (opts.nowrap) return false; opts.nextSlide = els.length - 1; } else if (opts.nextSlide >= els.length) { if (opts.nowrap) return false; opts.nextSlide = 0; } } var cb = opts.onPrevNextEvent || opts.prevNextClick; // prevNextClick is deprecated if ($.isFunction(cb)) cb(val > 0, opts.nextSlide, els[opts.nextSlide]); go(els, opts, 1, moveForward); return false; } function buildPager(els, opts) { var $p = $(opts.pager); $.each(els, function(i,o) { $.fn.cycle.createPagerAnchor(i,o,$p,els,opts); }); opts.updateActivePagerLink(opts.pager, opts.startingSlide, opts.activePagerClass); } $.fn.cycle.createPagerAnchor = function(i, el, $p, els, opts) { var a; if ($.isFunction(opts.pagerAnchorBuilder)) { a = opts.pagerAnchorBuilder(i,el); debug('pagerAnchorBuilder('+i+', el) returned: ' + a); } else a = '<a href="#">'+(i+1)+'</a>'; if (!a) return; var $a = $(a); // don't reparent if anchor is in the dom if ($a.parents('body').length === 0) { var arr = []; if ($p.length > 1) { $p.each(function() { var $clone = $a.clone(true); $(this).append($clone); arr.push($clone[0]); }); $a = $(arr); } else { $a.appendTo($p); } } opts.pagerAnchors = opts.pagerAnchors || []; opts.pagerAnchors.push($a); var pagerFn = function(e) { e.preventDefault(); opts.nextSlide = i; var p = opts.$cont[0], timeout = p.cycleTimeout; if (timeout) { clearTimeout(timeout); p.cycleTimeout = 0; } var cb = opts.onPagerEvent || opts.pagerClick; // pagerClick is deprecated if ($.isFunction(cb)) cb(opts.nextSlide, els[opts.nextSlide]); go(els,opts,1,opts.currSlide < i); // trigger the trans // return false; // <== allow bubble }; if ( /mouseenter|mouseover/i.test(opts.pagerEvent) ) { $a.hover(pagerFn, function(){/* no-op */} ); } else { $a.bind(opts.pagerEvent, pagerFn); } if ( ! /^click/.test(opts.pagerEvent) && !opts.allowPagerClickBubble) $a.bind('click.cycle', function(){return false;}); // suppress click var cont = opts.$cont[0]; var pauseFlag = false; // https://github.com/malsup/cycle/issues/44 if (opts.pauseOnPagerHover) { $a.hover( function() { pauseFlag = true; cont.cyclePause++; triggerPause(cont,true,true); }, function() { if (pauseFlag) cont.cyclePause--; triggerPause(cont,true,true); } ); } }; // helper fn to calculate the number of slides between the current and the next $.fn.cycle.hopsFromLast = function(opts, fwd) { var hops, l = opts.lastSlide, c = opts.currSlide; if (fwd) hops = c > l ? c - l : opts.slideCount - l; else hops = c < l ? l - c : l + opts.slideCount - c; return hops; }; // fix clearType problems in ie6 by setting an explicit bg color // (otherwise text slides look horrible during a fade transition) function clearTypeFix($slides) { debug('applying clearType background-color hack'); function hex(s) { s = parseInt(s,10).toString(16); return s.length < 2 ? '0'+s : s; } function getBg(e) { for ( ; e && e.nodeName.toLowerCase() != 'html'; e = e.parentNode) { var v = $.css(e,'background-color'); if (v && v.indexOf('rgb') >= 0 ) { var rgb = v.match(/\d+/g); return '#'+ hex(rgb[0]) + hex(rgb[1]) + hex(rgb[2]); } if (v && v != 'transparent') return v; } return '#ffffff'; } $slides.each(function() { $(this).css('background-color', getBg(this)); }); } // reset common props before the next transition $.fn.cycle.commonReset = function(curr,next,opts,w,h,rev) { $(opts.elements).not(curr).hide(); if (typeof opts.cssBefore.opacity == 'undefined') opts.cssBefore.opacity = 1; opts.cssBefore.display = 'block'; if (opts.slideResize && w !== false && next.cycleW > 0) opts.cssBefore.width = next.cycleW; if (opts.slideResize && h !== false && next.cycleH > 0) opts.cssBefore.height = next.cycleH; opts.cssAfter = opts.cssAfter || {}; opts.cssAfter.display = 'none'; $(curr).css('zIndex',opts.slideCount + (rev === true ? 1 : 0)); $(next).css('zIndex',opts.slideCount + (rev === true ? 0 : 1)); }; // the actual fn for effecting a transition $.fn.cycle.custom = function(curr, next, opts, cb, fwd, speedOverride) { var $l = $(curr), $n = $(next); var speedIn = opts.speedIn, speedOut = opts.speedOut, easeIn = opts.easeIn, easeOut = opts.easeOut, animInDelay = opts.animInDelay, animOutDelay = opts.animOutDelay; $n.css(opts.cssBefore); if (speedOverride) { if (typeof speedOverride == 'number') speedIn = speedOut = speedOverride; else speedIn = speedOut = 1; easeIn = easeOut = null; } var fn = function() { $n.delay(animInDelay).animate(opts.animIn, speedIn, easeIn, function() { cb(); }); }; $l.delay(animOutDelay).animate(opts.animOut, speedOut, easeOut, function() { $l.css(opts.cssAfter); if (!opts.sync) fn(); }); if (opts.sync) fn(); }; // transition definitions - only fade is defined here, transition pack defines the rest $.fn.cycle.transitions = { fade: function($cont, $slides, opts) { $slides.not(':eq('+opts.currSlide+')').css('opacity',0); opts.before.push(function(curr,next,opts) { $.fn.cycle.commonReset(curr,next,opts); opts.cssBefore.opacity = 0; }); opts.animIn = { opacity: 1 }; opts.animOut = { opacity: 0 }; opts.cssBefore = { top: 0, left: 0 }; } }; $.fn.cycle.ver = function() { return ver; }; // override these globally if you like (they are all optional) $.fn.cycle.defaults = { activePagerClass: 'activeSlide', // class name used for the active pager link after: null, // transition callback (scope set to element that was shown): function(currSlideElement, nextSlideElement, options, forwardFlag) allowPagerClickBubble: false, // allows or prevents click event on pager anchors from bubbling animIn: null, // properties that define how the slide animates in animInDelay: 0, // allows delay before next slide transitions in animOut: null, // properties that define how the slide animates out animOutDelay: 0, // allows delay before current slide transitions out aspect: false, // preserve aspect ratio during fit resizing, cropping if necessary (must be used with fit option) autostop: 0, // true to end slideshow after X transitions (where X == slide count) autostopCount: 0, // number of transitions (optionally used with autostop to define X) backwards: false, // true to start slideshow at last slide and move backwards through the stack before: null, // transition callback (scope set to element to be shown): function(currSlideElement, nextSlideElement, options, forwardFlag) center: null, // set to true to have cycle add top/left margin to each slide (use with width and height options) cleartype: !$.support.opacity, // true if clearType corrections should be applied (for IE) cleartypeNoBg: false, // set to true to disable extra cleartype fixing (leave false to force background color setting on slides) containerResize: 1, // resize container to fit largest slide containerResizeHeight: 0, // resize containers height to fit the largest slide but leave the width dynamic continuous: 0, // true to start next transition immediately after current one completes cssAfter: null, // properties that defined the state of the slide after transitioning out cssBefore: null, // properties that define the initial state of the slide before transitioning in delay: 0, // additional delay (in ms) for first transition (hint: can be negative) easeIn: null, // easing for "in" transition easeOut: null, // easing for "out" transition easing: null, // easing method for both in and out transitions end: null, // callback invoked when the slideshow terminates (use with autostop or nowrap options): function(options) fastOnEvent: 0, // force fast transitions when triggered manually (via pager or prev/next); value == time in ms fit: 0, // force slides to fit container fx: 'fade', // name of transition effect (or comma separated names, ex: 'fade,scrollUp,shuffle') fxFn: null, // function used to control the transition: function(currSlideElement, nextSlideElement, options, afterCalback, forwardFlag) height: 'auto', // container height (if the 'fit' option is true, the slides will be set to this height as well) manualTrump: true, // causes manual transition to stop an active transition instead of being ignored metaAttr: 'cycle', // data- attribute that holds the option data for the slideshow next: null, // element, jQuery object, or jQuery selector string for the element to use as event trigger for next slide nowrap: 0, // true to prevent slideshow from wrapping onPagerEvent: null, // callback fn for pager events: function(zeroBasedSlideIndex, slideElement) onPrevNextEvent: null, // callback fn for prev/next events: function(isNext, zeroBasedSlideIndex, slideElement) pager: null, // element, jQuery object, or jQuery selector string for the element to use as pager container pagerAnchorBuilder: null, // callback fn for building anchor links: function(index, DOMelement) pagerEvent: 'click.cycle', // name of event which drives the pager navigation pause: 0, // true to enable "pause on hover" pauseOnPagerHover: 0, // true to pause when hovering over pager link prev: null, // element, jQuery object, or jQuery selector string for the element to use as event trigger for previous slide prevNextEvent: 'click.cycle',// event which drives the manual transition to the previous or next slide random: 0, // true for random, false for sequence (not applicable to shuffle fx) randomizeEffects: 1, // valid when multiple effects are used; true to make the effect sequence random requeueOnImageNotLoaded: true, // requeue the slideshow if any image slides are not yet loaded requeueTimeout: 250, // ms delay for requeue rev: 0, // causes animations to transition in reverse (for effects that support it such as scrollHorz/scrollVert/shuffle) shuffle: null, // coords for shuffle animation, ex: { top:15, left: 200 } skipInitializationCallbacks: false, // set to true to disable the first before/after callback that occurs prior to any transition slideExpr: null, // expression for selecting slides (if something other than all children is required) slideResize: 1, // force slide width/height to fixed size before every transition speed: 1000, // speed of the transition (any valid fx speed value) speedIn: null, // speed of the 'in' transition speedOut: null, // speed of the 'out' transition startingSlide: undefined,// zero-based index of the first slide to be displayed sync: 1, // true if in/out transitions should occur simultaneously timeout: 4000, // milliseconds between slide transitions (0 to disable auto advance) timeoutFn: null, // callback for determining per-slide timeout value: function(currSlideElement, nextSlideElement, options, forwardFlag) updateActivePagerLink: null,// callback fn invoked to update the active pager link (adds/removes activePagerClass style) width: null // container width (if the 'fit' option is true, the slides will be set to this width as well) }; })(jQuery); /*! * jQuery Cycle Plugin Transition Definitions * This script is a plugin for the jQuery Cycle Plugin * Examples and documentation at: http://malsup.com/jquery/cycle/ * Copyright (c) 2007-2010 M. Alsup * Version: 2.73 * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html */ (function($) { "use strict"; // // These functions define slide initialization and properties for the named // transitions. To save file size feel free to remove any of these that you // don't need. // $.fn.cycle.transitions.none = function($cont, $slides, opts) { opts.fxFn = function(curr,next,opts,after){ $(next).show(); $(curr).hide(); after(); }; }; // not a cross-fade, fadeout only fades out the top slide $.fn.cycle.transitions.fadeout = function($cont, $slides, opts) { $slides.not(':eq('+opts.currSlide+')').css({ display: 'block', 'opacity': 1 }); opts.before.push(function(curr,next,opts,w,h,rev) { $(curr).css('zIndex',opts.slideCount + (rev !== true ? 1 : 0)); $(next).css('zIndex',opts.slideCount + (rev !== true ? 0 : 1)); }); opts.animIn.opacity = 1; opts.animOut.opacity = 0; opts.cssBefore.opacity = 1; opts.cssBefore.display = 'block'; opts.cssAfter.zIndex = 0; }; // scrollUp/Down/Left/Right $.fn.cycle.transitions.scrollUp = function($cont, $slides, opts) { $cont.css('overflow','hidden'); opts.before.push($.fn.cycle.commonReset); var h = $cont.height(); opts.cssBefore.top = h; opts.cssBefore.left = 0; opts.cssFirst.top = 0; opts.animIn.top = 0; opts.animOut.top = -h; }; $.fn.cycle.transitions.scrollDown = function($cont, $slides, opts) { $cont.css('overflow','hidden'); opts.before.push($.fn.cycle.commonReset); var h = $cont.height(); opts.cssFirst.top = 0; opts.cssBefore.top = -h; opts.cssBefore.left = 0; opts.animIn.top = 0; opts.animOut.top = h; }; $.fn.cycle.transitions.scrollLeft = function($cont, $slides, opts) { $cont.css('overflow','hidden'); opts.before.push($.fn.cycle.commonReset); var w = $cont.width(); opts.cssFirst.left = 0; opts.cssBefore.left = w; opts.cssBefore.top = 0; opts.animIn.left = 0; opts.animOut.left = 0-w; }; $.fn.cycle.transitions.scrollRight = function($cont, $slides, opts) { $cont.css('overflow','hidden'); opts.before.push($.fn.cycle.commonReset); var w = $cont.width(); opts.cssFirst.left = 0; opts.cssBefore.left = -w; opts.cssBefore.top = 0; opts.animIn.left = 0; opts.animOut.left = w; }; $.fn.cycle.transitions.scrollHorz = function($cont, $slides, opts) { $cont.css('overflow','hidden').width(); opts.before.push(function(curr, next, opts, fwd) { if (opts.rev) fwd = !fwd; $.fn.cycle.commonReset(curr,next,opts); opts.cssBefore.left = fwd ? (next.cycleW-1) : (1-next.cycleW); opts.animOut.left = fwd ? -curr.cycleW : curr.cycleW; }); opts.cssFirst.left = 0; opts.cssBefore.top = 0; opts.animIn.left = 0; opts.animOut.top = 0; }; $.fn.cycle.transitions.scrollVert = function($cont, $slides, opts) { $cont.css('overflow','hidden'); opts.before.push(function(curr, next, opts, fwd) { if (opts.rev) fwd = !fwd; $.fn.cycle.commonReset(curr,next,opts); opts.cssBefore.top = fwd ? (1-next.cycleH) : (next.cycleH-1); opts.animOut.top = fwd ? curr.cycleH : -curr.cycleH; }); opts.cssFirst.top = 0; opts.cssBefore.left = 0; opts.animIn.top = 0; opts.animOut.left = 0; }; // slideX/slideY $.fn.cycle.transitions.slideX = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $(opts.elements).not(curr).hide(); $.fn.cycle.commonReset(curr,next,opts,false,true); opts.animIn.width = next.cycleW; }); opts.cssBefore.left = 0; opts.cssBefore.top = 0; opts.cssBefore.width = 0; opts.animIn.width = 'show'; opts.animOut.width = 0; }; $.fn.cycle.transitions.slideY = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $(opts.elements).not(curr).hide(); $.fn.cycle.commonReset(curr,next,opts,true,false); opts.animIn.height = next.cycleH; }); opts.cssBefore.left = 0; opts.cssBefore.top = 0; opts.cssBefore.height = 0; opts.animIn.height = 'show'; opts.animOut.height = 0; }; // shuffle $.fn.cycle.transitions.shuffle = function($cont, $slides, opts) { var i, w = $cont.css('overflow', 'visible').width(); $slides.css({left: 0, top: 0}); opts.before.push(function(curr,next,opts) { $.fn.cycle.commonReset(curr,next,opts,true,true,true); }); // only adjust speed once! if (!opts.speedAdjusted) { opts.speed = opts.speed / 2; // shuffle has 2 transitions opts.speedAdjusted = true; } opts.random = 0; opts.shuffle = opts.shuffle || {left:-w, top:15}; opts.els = []; for (i=0; i < $slides.length; i++) opts.els.push($slides[i]); for (i=0; i < opts.currSlide; i++) opts.els.push(opts.els.shift()); // custom transition fn (hat tip to Benjamin Sterling for this bit of sweetness!) opts.fxFn = function(curr, next, opts, cb, fwd) { if (opts.rev) fwd = !fwd; var $el = fwd ? $(curr) : $(next); $(next).css(opts.cssBefore); var count = opts.slideCount; $el.animate(opts.shuffle, opts.speedIn, opts.easeIn, function() { var hops = $.fn.cycle.hopsFromLast(opts, fwd); for (var k=0; k < hops; k++) { if (fwd) opts.els.push(opts.els.shift()); else opts.els.unshift(opts.els.pop()); } if (fwd) { for (var i=0, len=opts.els.length; i < len; i++) $(opts.els[i]).css('z-index', len-i+count); } else { var z = $(curr).css('z-index'); $el.css('z-index', parseInt(z,10)+1+count); } $el.animate({left:0, top:0}, opts.speedOut, opts.easeOut, function() { $(fwd ? this : curr).hide(); if (cb) cb(); }); }); }; $.extend(opts.cssBefore, { display: 'block', opacity: 1, top: 0, left: 0 }); }; // turnUp/Down/Left/Right $.fn.cycle.transitions.turnUp = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,true,false); opts.cssBefore.top = next.cycleH; opts.animIn.height = next.cycleH; opts.animOut.width = next.cycleW; }); opts.cssFirst.top = 0; opts.cssBefore.left = 0; opts.cssBefore.height = 0; opts.animIn.top = 0; opts.animOut.height = 0; }; $.fn.cycle.transitions.turnDown = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,true,false); opts.animIn.height = next.cycleH; opts.animOut.top = curr.cycleH; }); opts.cssFirst.top = 0; opts.cssBefore.left = 0; opts.cssBefore.top = 0; opts.cssBefore.height = 0; opts.animOut.height = 0; }; $.fn.cycle.transitions.turnLeft = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,false,true); opts.cssBefore.left = next.cycleW; opts.animIn.width = next.cycleW; }); opts.cssBefore.top = 0; opts.cssBefore.width = 0; opts.animIn.left = 0; opts.animOut.width = 0; }; $.fn.cycle.transitions.turnRight = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,false,true); opts.animIn.width = next.cycleW; opts.animOut.left = curr.cycleW; }); $.extend(opts.cssBefore, { top: 0, left: 0, width: 0 }); opts.animIn.left = 0; opts.animOut.width = 0; }; // zoom $.fn.cycle.transitions.zoom = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,false,false,true); opts.cssBefore.top = next.cycleH/2; opts.cssBefore.left = next.cycleW/2; $.extend(opts.animIn, { top: 0, left: 0, width: next.cycleW, height: next.cycleH }); $.extend(opts.animOut, { width: 0, height: 0, top: curr.cycleH/2, left: curr.cycleW/2 }); }); opts.cssFirst.top = 0; opts.cssFirst.left = 0; opts.cssBefore.width = 0; opts.cssBefore.height = 0; }; // fadeZoom $.fn.cycle.transitions.fadeZoom = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,false,false); opts.cssBefore.left = next.cycleW/2; opts.cssBefore.top = next.cycleH/2; $.extend(opts.animIn, { top: 0, left: 0, width: next.cycleW, height: next.cycleH }); }); opts.cssBefore.width = 0; opts.cssBefore.height = 0; opts.animOut.opacity = 0; }; // blindX $.fn.cycle.transitions.blindX = function($cont, $slides, opts) { var w = $cont.css('overflow','hidden').width(); opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts); opts.animIn.width = next.cycleW; opts.animOut.left = curr.cycleW; }); opts.cssBefore.left = w; opts.cssBefore.top = 0; opts.animIn.left = 0; opts.animOut.left = w; }; // blindY $.fn.cycle.transitions.blindY = function($cont, $slides, opts) { var h = $cont.css('overflow','hidden').height(); opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts); opts.animIn.height = next.cycleH; opts.animOut.top = curr.cycleH; }); opts.cssBefore.top = h; opts.cssBefore.left = 0; opts.animIn.top = 0; opts.animOut.top = h; }; // blindZ $.fn.cycle.transitions.blindZ = function($cont, $slides, opts) { var h = $cont.css('overflow','hidden').height(); var w = $cont.width(); opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts); opts.animIn.height = next.cycleH; opts.animOut.top = curr.cycleH; }); opts.cssBefore.top = h; opts.cssBefore.left = w; opts.animIn.top = 0; opts.animIn.left = 0; opts.animOut.top = h; opts.animOut.left = w; }; // growX - grow horizontally from centered 0 width $.fn.cycle.transitions.growX = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,false,true); opts.cssBefore.left = this.cycleW/2; opts.animIn.left = 0; opts.animIn.width = this.cycleW; opts.animOut.left = 0; }); opts.cssBefore.top = 0; opts.cssBefore.width = 0; }; // growY - grow vertically from centered 0 height $.fn.cycle.transitions.growY = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,true,false); opts.cssBefore.top = this.cycleH/2; opts.animIn.top = 0; opts.animIn.height = this.cycleH; opts.animOut.top = 0; }); opts.cssBefore.height = 0; opts.cssBefore.left = 0; }; // curtainX - squeeze in both edges horizontally $.fn.cycle.transitions.curtainX = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,false,true,true); opts.cssBefore.left = next.cycleW/2; opts.animIn.left = 0; opts.animIn.width = this.cycleW; opts.animOut.left = curr.cycleW/2; opts.animOut.width = 0; }); opts.cssBefore.top = 0; opts.cssBefore.width = 0; }; // curtainY - squeeze in both edges vertically $.fn.cycle.transitions.curtainY = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,true,false,true); opts.cssBefore.top = next.cycleH/2; opts.animIn.top = 0; opts.animIn.height = next.cycleH; opts.animOut.top = curr.cycleH/2; opts.animOut.height = 0; }); opts.cssBefore.height = 0; opts.cssBefore.left = 0; }; // cover - curr slide covered by next slide $.fn.cycle.transitions.cover = function($cont, $slides, opts) { var d = opts.direction || 'left'; var w = $cont.css('overflow','hidden').width(); var h = $cont.height(); opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts); opts.cssAfter.display = ''; if (d == 'right') opts.cssBefore.left = -w; else if (d == 'up') opts.cssBefore.top = h; else if (d == 'down') opts.cssBefore.top = -h; else opts.cssBefore.left = w; }); opts.animIn.left = 0; opts.animIn.top = 0; opts.cssBefore.top = 0; opts.cssBefore.left = 0; }; // uncover - curr slide moves off next slide $.fn.cycle.transitions.uncover = function($cont, $slides, opts) { var d = opts.direction || 'left'; var w = $cont.css('overflow','hidden').width(); var h = $cont.height(); opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,true,true,true); if (d == 'right') opts.animOut.left = w; else if (d == 'up') opts.animOut.top = -h; else if (d == 'down') opts.animOut.top = h; else opts.animOut.left = -w; }); opts.animIn.left = 0; opts.animIn.top = 0; opts.cssBefore.top = 0; opts.cssBefore.left = 0; }; // toss - move top slide and fade away $.fn.cycle.transitions.toss = function($cont, $slides, opts) { var w = $cont.css('overflow','visible').width(); var h = $cont.height(); opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,true,true,true); // provide default toss settings if animOut not provided if (!opts.animOut.left && !opts.animOut.top) $.extend(opts.animOut, { left: w*2, top: -h/2, opacity: 0 }); else opts.animOut.opacity = 0; }); opts.cssBefore.left = 0; opts.cssBefore.top = 0; opts.animIn.left = 0; }; // wipe - clip animation $.fn.cycle.transitions.wipe = function($cont, $slides, opts) { var w = $cont.css('overflow','hidden').width(); var h = $cont.height(); opts.cssBefore = opts.cssBefore || {}; var clip; if (opts.clip) { if (/l2r/.test(opts.clip)) clip = 'rect(0px 0px '+h+'px 0px)'; else if (/r2l/.test(opts.clip)) clip = 'rect(0px '+w+'px '+h+'px '+w+'px)'; else if (/t2b/.test(opts.clip)) clip = 'rect(0px '+w+'px 0px 0px)'; else if (/b2t/.test(opts.clip)) clip = 'rect('+h+'px '+w+'px '+h+'px 0px)'; else if (/zoom/.test(opts.clip)) { var top = parseInt(h/2,10); var left = parseInt(w/2,10); clip = 'rect('+top+'px '+left+'px '+top+'px '+left+'px)'; } } opts.cssBefore.clip = opts.cssBefore.clip || clip || 'rect(0px 0px 0px 0px)'; var d = opts.cssBefore.clip.match(/(\d+)/g); var t = parseInt(d[0],10), r = parseInt(d[1],10), b = parseInt(d[2],10), l = parseInt(d[3],10); opts.before.push(function(curr, next, opts) { if (curr == next) return; var $curr = $(curr), $next = $(next); $.fn.cycle.commonReset(curr,next,opts,true,true,false); opts.cssAfter.display = 'block'; var step = 1, count = parseInt((opts.speedIn / 13),10) - 1; (function f() { var tt = t ? t - parseInt(step * (t/count),10) : 0; var ll = l ? l - parseInt(step * (l/count),10) : 0; var bb = b < h ? b + parseInt(step * ((h-b)/count || 1),10) : h; var rr = r < w ? r + parseInt(step * ((w-r)/count || 1),10) : w; $next.css({ clip: 'rect('+tt+'px '+rr+'px '+bb+'px '+ll+'px)' }); (step++ <= count) ? setTimeout(f, 13) : $curr.css('display', 'none'); })(); }); $.extend(opts.cssBefore, { display: 'block', opacity: 1, top: 0, left: 0 }); opts.animIn = { left: 0 }; opts.animOut = { left: 0 }; }; })(jQuery);<|fim▁end|>
opts.cssFirst = opts.cssFirst || {}; opts.animIn = opts.animIn || {}; opts.animOut = opts.animOut || {};
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># coding=utf-8 from __future__ import unicode_literals from collections import OrderedDict from .. import BaseProvider localized = True class Provider(BaseProvider): all_colors = OrderedDict(( ("AliceBlue", "#F0F8FF"), ("AntiqueWhite", "#FAEBD7"), ("Aqua", "#00FFFF"), ("Aquamarine", "#7FFFD4"), ("Azure", "#F0FFFF"), ("Beige", "#F5F5DC"), ("Bisque", "#FFE4C4"), ("Black", "#000000"), ("BlanchedAlmond", "#FFEBCD"), ("Blue", "#0000FF"), ("BlueViolet", "#8A2BE2"), ("Brown", "#A52A2A"), ("BurlyWood", "#DEB887"), ("CadetBlue", "#5F9EA0"), ("Chartreuse", "#7FFF00"), ("Chocolate", "#D2691E"), ("Coral", "#FF7F50"), ("CornflowerBlue", "#6495ED"), ("Cornsilk", "#FFF8DC"), ("Crimson", "#DC143C"), ("Cyan", "#00FFFF"), ("DarkBlue", "#00008B"), ("DarkCyan", "#008B8B"), ("DarkGoldenRod", "#B8860B"), ("DarkGray", "#A9A9A9"), ("DarkGreen", "#006400"), ("DarkKhaki", "#BDB76B"), ("DarkMagenta", "#8B008B"), ("DarkOliveGreen", "#556B2F"), ("DarkOrange", "#FF8C00"), ("DarkOrchid", "#9932CC"), ("DarkRed", "#8B0000"), ("DarkSalmon", "#E9967A"), ("DarkSeaGreen", "#8FBC8F"), ("DarkSlateBlue", "#483D8B"), ("DarkSlateGray", "#2F4F4F"), ("DarkTurquoise", "#00CED1"), ("DarkViolet", "#9400D3"), ("DeepPink", "#FF1493"), ("DeepSkyBlue", "#00BFFF"), ("DimGray", "#696969"), ("DodgerBlue", "#1E90FF"), ("FireBrick", "#B22222"), ("FloralWhite", "#FFFAF0"), ("ForestGreen", "#228B22"), ("Fuchsia", "#FF00FF"), ("Gainsboro", "#DCDCDC"), ("GhostWhite", "#F8F8FF"), ("Gold", "#FFD700"), ("GoldenRod", "#DAA520"), ("Gray", "#808080"), ("Green", "#008000"),<|fim▁hole|> ("HotPink", "#FF69B4"), ("IndianRed", "#CD5C5C"), ("Indigo", "#4B0082"), ("Ivory", "#FFFFF0"), ("Khaki", "#F0E68C"), ("Lavender", "#E6E6FA"), ("LavenderBlush", "#FFF0F5"), ("LawnGreen", "#7CFC00"), ("LemonChiffon", "#FFFACD"), ("LightBlue", "#ADD8E6"), ("LightCoral", "#F08080"), ("LightCyan", "#E0FFFF"), ("LightGoldenRodYellow", "#FAFAD2"), ("LightGray", "#D3D3D3"), ("LightGreen", "#90EE90"), ("LightPink", "#FFB6C1"), ("LightSalmon", "#FFA07A"), ("LightSeaGreen", "#20B2AA"), ("LightSkyBlue", "#87CEFA"), ("LightSlateGray", "#778899"), ("LightSteelBlue", "#B0C4DE"), ("LightYellow", "#FFFFE0"), ("Lime", "#00FF00"), ("LimeGreen", "#32CD32"), ("Linen", "#FAF0E6"), ("Magenta", "#FF00FF"), ("Maroon", "#800000"), ("MediumAquaMarine", "#66CDAA"), ("MediumBlue", "#0000CD"), ("MediumOrchid", "#BA55D3"), ("MediumPurple", "#9370DB"), ("MediumSeaGreen", "#3CB371"), ("MediumSlateBlue", "#7B68EE"), ("MediumSpringGreen", "#00FA9A"), ("MediumTurquoise", "#48D1CC"), ("MediumVioletRed", "#C71585"), ("MidnightBlue", "#191970"), ("MintCream", "#F5FFFA"), ("MistyRose", "#FFE4E1"), ("Moccasin", "#FFE4B5"), ("NavajoWhite", "#FFDEAD"), ("Navy", "#000080"), ("OldLace", "#FDF5E6"), ("Olive", "#808000"), ("OliveDrab", "#6B8E23"), ("Orange", "#FFA500"), ("OrangeRed", "#FF4500"), ("Orchid", "#DA70D6"), ("PaleGoldenRod", "#EEE8AA"), ("PaleGreen", "#98FB98"), ("PaleTurquoise", "#AFEEEE"), ("PaleVioletRed", "#DB7093"), ("PapayaWhip", "#FFEFD5"), ("PeachPuff", "#FFDAB9"), ("Peru", "#CD853F"), ("Pink", "#FFC0CB"), ("Plum", "#DDA0DD"), ("PowderBlue", "#B0E0E6"), ("Purple", "#800080"), ("Red", "#FF0000"), ("RosyBrown", "#BC8F8F"), ("RoyalBlue", "#4169E1"), ("SaddleBrown", "#8B4513"), ("Salmon", "#FA8072"), ("SandyBrown", "#F4A460"), ("SeaGreen", "#2E8B57"), ("SeaShell", "#FFF5EE"), ("Sienna", "#A0522D"), ("Silver", "#C0C0C0"), ("SkyBlue", "#87CEEB"), ("SlateBlue", "#6A5ACD"), ("SlateGray", "#708090"), ("Snow", "#FFFAFA"), ("SpringGreen", "#00FF7F"), ("SteelBlue", "#4682B4"), ("Tan", "#D2B48C"), ("Teal", "#008080"), ("Thistle", "#D8BFD8"), ("Tomato", "#FF6347"), ("Turquoise", "#40E0D0"), ("Violet", "#EE82EE"), ("Wheat", "#F5DEB3"), ("White", "#FFFFFF"), ("WhiteSmoke", "#F5F5F5"), ("Yellow", "#FFFF00"), ("YellowGreen", "#9ACD32"), )) safe_colors = ( 'black', 'maroon', 'green', 'navy', 'olive', 'purple', 'teal', 'lime', 'blue', 'silver', 'gray', 'yellow', 'fuchsia', 'aqua', 'white', ) def color_name(self): return self.random_element(self.all_colors.keys()) def safe_color_name(self): return self.random_element(self.safe_colors) def hex_color(self): return "#{0}".format( ("%x" % self.random_int( 1, 16777215)).ljust( 6, '0')) def safe_hex_color(self): color = ("%x" % self.random_int(0, 255)).ljust(3, '0') return "#{0}{0}{1}{1}{2}{2}".format(*color) def rgb_color(self): return ','.join(map(str, (self.random_int(0, 255) for _ in range(3)))) def rgb_css_color(self): return 'rgb(%s)' % ','.join( map(str, (self.random_int(0, 255) for _ in range(3))))<|fim▁end|>
("GreenYellow", "#ADFF2F"), ("HoneyDew", "#F0FFF0"),
<|file_name|>0012_auto_20150422_2019.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('managers', '0011_auto_20150422_2018'), ] operations = [ migrations.AlterField( model_name='managerprofile', name='picture', field=models.ImageField(default=b'/static/assets/admin/layout/img/avatar.jpg', upload_to=b'profiles'), preserve_default=True, ),<|fim▁hole|><|fim▁end|>
]
<|file_name|>SecurityOptionalConfig.java<|end_file_name|><|fim▁begin|>/* * Licensed to David Pilato (the "Author") under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. Author licenses this * file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an<|fim▁hole|> * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package fr.pilato.spring.elasticsearch.it.annotation; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.Properties; import static fr.pilato.spring.elasticsearch.ElasticsearchAbstractFactoryBean.XPACK_USER; import static fr.pilato.spring.elasticsearch.it.BaseTest.testCredentials; @Configuration public class SecurityOptionalConfig { @Bean("esProperties") public Properties properties() { Properties properties = new Properties(); properties.setProperty(XPACK_USER, testCredentials); return properties; } }<|fim▁end|>
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
<|file_name|>widgets.py<|end_file_name|><|fim▁begin|># -*- coding: utf8 -*- # # Created by 'myth' on 8/26/15 from tkinter import * from algorithms import ASTAR_OPTIONS, ASTAR_HEURISTIC, GAC_DEFAULT_K, GAC_DEFAULT_CONSTRAINT from common import * def generate_menus(window): """ Takes in the window main menu bar and registers the submenus and their commands :param window: The main application window """ # Define menu labels and their commands here menus = [ (u'File', [ (u'Exit', window.controller.exit) ]), (u'Boards', sorted([ (os.path.basename(board), lambda fp=board: window.controller.load_board(file_path=fp)) for board in fetch_files_from_dir(rootdir='module1/boards/') ])), (u'Graphs', sorted([ (os.path.basename(board), lambda fp=board: window.controller.load_graph(file_path=fp)) for board in fetch_files_from_dir(rootdir='module2/graphs/') ])), (u'Nonograms', sorted([ (os.path.basename(board), lambda fp=board: window.controller.load_nonogram(file_path=fp)) for board in fetch_files_from_dir(rootdir='module3/nonograms/') ])), (u'Run', [ (u'GO!', window.controller.solve), ]), ] # Iterate over the main menu components and their actions for name, actions in menus: menu = Menu(window.menu, tearoff=0) window.menu.add_cascade(label=name, menu=menu) # Register commands for label, cmd in actions: menu.add_command(label=label, command=cmd) def generate_options(frame, module=1): """ Generates options for :param frame: Stats and options frame reference """ # Clear all widgets for consistency for child_widget in frame.winfo_children(): child_widget.destroy() mode_label = Label(frame, text='Algorithm mode:') mode_label.grid(row=0, padx=5, pady=5, ipadx=5, ipady=5, sticky='W') mode_var = StringVar(master=frame, value=ASTAR_OPTIONS[0], name='algorithm_mode') frame.master.controller.references['algorithm_mode'] = mode_var options = OptionMenu(frame, mode_var, *ASTAR_OPTIONS) options.grid(row=0, column=1, sticky='E') heuristic_label = Label(frame, text='Heuristic:') heuristic_label.grid(row=1, padx=5, pady=5, ipadx=5, ipady=5, sticky='W') if module == 1: heuristic_var = StringVar(master=frame, value=ASTAR_HEURISTIC[0], name='heuristic') h_options = OptionMenu(frame, heuristic_var, *ASTAR_HEURISTIC) else: heuristic_var = StringVar(master=frame, value='minimum_domain_sum', name='heuristic') h_options = OptionMenu(frame, heuristic_var, 'minimum_domain_sum') frame.master.controller.references['heuristic'] = heuristic_var h_options.grid(row=1, column=1, sticky='E') if module == 1 or module == 3: update_interval_label = Label(frame, text='Update interval (ms):') update_interval_label.grid(row=2, padx=5, pady=5, ipadx=5, ipady=5, sticky='W') update_interval = Entry(frame) update_interval.insert(0, str(GUI_UPDATE_INTERVAL)) update_interval.grid(row=2, column=1, padx=5, pady=5, ipadx=5, ipady=5, sticky='E') frame.master.controller.references['update_interval'] = update_interval elif module == 2: k_value_label = Label(frame, text='K value:') k_value_label.grid(row=3, padx=5, pady=5, ipadx=5, ipady=5, sticky='W') k_value = Entry(frame) k_value.insert(0, str(GAC_DEFAULT_K)) k_value.grid(row=3, column=1, padx=5, pady=5, ipadx=5, ipady=5, sticky='E') frame.master.controller.references['k_value'] = k_value constraint_formula_label = Label(frame, text='Constraint formula:') constraint_formula_label.grid(row=4, padx=5, pady=5, ipadx=5, ipady=5, sticky='W')<|fim▁hole|> constraint_formula.insert(0, GAC_DEFAULT_CONSTRAINT) constraint_formula.grid(row=4, column=1, padx=5, pady=5, ipadx=5, ipady=5, sticky='E') frame.master.controller.references['constraint_formula'] = constraint_formula def generate_stats(frame, module=1): """ Generates and fills the Statistics LabelFrame """ # Clear all widgets for consistency for child_widget in frame.winfo_children(): child_widget.destroy() path_length = StringVar(frame) path_length.set('Path length: 0') path_length_label = Label(frame, textvariable=path_length) frame.master.controller.references['path_length'] = path_length path_length_label.grid(row=0, padx=5, pady=5, ipadx=5, ipady=5, sticky='W') open_set_size = StringVar(frame) open_set_size.set('OpenSet size: 0') open_set_size_label = Label(frame, textvariable=open_set_size) frame.master.controller.references['open_set_size'] = open_set_size open_set_size_label.grid(row=1, padx=5, pady=5, ipadx=5, ipady=5, sticky='W') closed_set_size = StringVar(frame) closed_set_size.set('ClosedSet size: 0') closed_set_size_label = Label(frame, textvariable=closed_set_size) frame.master.controller.references['closed_set_size'] = closed_set_size closed_set_size_label.grid(row=2, padx=5, pady=5, ipadx=5, ipady=5, sticky='W') total_set_size = StringVar(frame) total_set_size.set('Total set size: 0') total_set_size_label = Label(frame, textvariable=total_set_size) frame.master.controller.references['total_set_size'] = total_set_size total_set_size_label.grid(row=3, padx=5, pady=5, ipadx=5, ipady=5, sticky='W') if module == 2: total_unsatisfied_constraints = StringVar(frame) total_unsatisfied_constraints.set('Unsatisfied constraints: 0') total_unsatisfied_constraints_label = Label(frame, textvariable=total_unsatisfied_constraints) frame.master.controller.references['total_unsatisfied_constraints'] = total_unsatisfied_constraints total_unsatisfied_constraints_label.grid(row=4, padx=5, pady=5, ipadx=5, ipady=5, sticky='W') total_missing_assignment = StringVar(frame) total_missing_assignment.set('Vertices missing assignment: 0') total_missing_assignment_label = Label(frame, textvariable=total_missing_assignment) frame.master.controller.references['total_missing_assignment'] = total_missing_assignment total_missing_assignment_label.grid(row=5, padx=5, pady=5, ipadx=5, ipady=5, sticky='W')<|fim▁end|>
constraint_formula = Entry(frame)
<|file_name|>new_security_install.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python """ Do whatever is needed to get a security upload released @contact: Debian FTP Master <ftpmaster@debian.org> @copyright: 2010 Joerg Jaspert <joerg@debian.org> @license: GNU General Public License version 2 or later """ # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ################################################################################ ################################################################################ import os import sys import time import apt_pkg import commands import errno import fcntl from daklib import queue from daklib import daklog from daklib import utils from daklib.dbconn import * from daklib.regexes import re_taint_free from daklib.config import Config Options = None Logger = None Queue = None changes = [] def usage(): print """Usage: dak security-install [OPTIONS] changesfiles Do whatever there is to do for a security release -h, --help show this help and exit -n, --no-action don't commit changes -s, --sudo dont bother, used internally """ sys.exit() def spawn(command): if not re_taint_free.match(command): utils.fubar("Invalid character in \"%s\"." % (command)) if Options["No-Action"]: print "[%s]" % (command) else: (result, output) = commands.getstatusoutput(command) if (result != 0): utils.fubar("Invocation of '%s' failed:\n%s\n" % (command, output), result) ##################### ! ! ! N O T E ! ! ! ##################### # # These functions will be reinvoked by semi-priveleged users, be careful not # to invoke external programs that will escalate privileges, etc. # ##################### ! ! ! N O T E ! ! ! ##################### def sudo(arg, fn, exit): if Options["Sudo"]: os.spawnl(os.P_WAIT, "/usr/bin/sudo", "/usr/bin/sudo", "-u", "dak", "-H", "/usr/local/bin/dak", "new-security-install", "-"+arg) else: fn() if exit: quit() def do_Approve(): sudo("A", _do_Approve, True) def _do_Approve(): print "Locking unchecked" with os.fdopen(os.open('/srv/security-master.debian.org/lock/unchecked.lock', os.O_CREAT | os.O_RDWR ), 'r') as lock_fd: while True: try: fcntl.flock(lock_fd, fcntl.LOCK_EX | fcntl.LOCK_NB) break except IOError as e: if e.errno in (errno.EACCES, errno.EAGAIN): print "Another process keeping the unchecked lock, waiting." time.sleep(10) else: raise # 1. Install accepted packages print "Installing accepted packages into security archive" for queue in ("embargoed",): spawn("dak process-policy {0}".format(queue)) # 2. Run all the steps that are needed to publish the changed archive print "Doing loadsa stuff in the archive, will take time, please be patient" os.environ['configdir'] = '/srv/security-master.debian.org/dak/config/debian-security' spawn("/srv/security-master.debian.org/dak/config/debian-security/cronscript unchecked-dinstall") print "Triggering metadata export for packages.d.o and other consumers" spawn("/srv/security-master.debian.org/dak/config/debian-security/export.sh") ######################################################################## ######################################################################## def main(): global Options, Logger, Queue, changes cnf = Config() Arguments = [('h', "Help", "Security::Options::Help"), ('n', "No-Action", "Security::Options::No-Action"), ('c', 'Changesfile', "Security::Options::Changesfile"), ('s', "Sudo", "Security::Options::Sudo"), ('A', "Approve", "Security::Options::Approve") ] for i in ["Help", "No-Action", "Changesfile", "Sudo", "Approve"]: key = "Security::Options::%s" % i if key not in cnf: cnf[key] = "" changes_files = apt_pkg.parse_commandline(cnf.Cnf, Arguments, sys.argv) Options = cnf.subtree("Security::Options") if Options['Help']: usage() changesfiles={} for a in changes_files: if not a.endswith(".changes"): utils.fubar("not a .changes file: %s" % (a)) changesfiles[a]=1 changes = changesfiles.keys() username = utils.getusername() if username != "dak": print "Non-dak user: %s" % username Options["Sudo"] = "y" if Options["No-Action"]: Options["Sudo"] = "" if not Options["Sudo"] and not Options["No-Action"]: Logger = daklog.Logger("security-install") session = DBConn().session() # If we call ourselve to approve, we do just that and exit if Options["Approve"]: do_Approve() sys.exit() if len(changes) == 0: utils.fubar("Need changes files as arguments") # Yes, we could do this inside do_Approve too. But this way we see who exactly # called it (ownership of the file) acceptfiles={} for change in changes: dbchange=get_dbchange(os.path.basename(change), session) # strip epoch from version version=dbchange.version version=version[(version.find(':')+1):] # strip possible version from source (binNMUs) source = dbchange.source.split(None, 1)[0] acceptfilename="%s/COMMENTS/ACCEPT.%s_%s" % (os.path.dirname(os.path.abspath(changes[0])), source, version) acceptfiles[acceptfilename]=1 print "Would create %s now and then go on to accept this package, if you allow me to." % (acceptfiles.keys()) if Options["No-Action"]: sys.exit(0) else: raw_input("Press Enter to continue") for acceptfilename in acceptfiles.keys(): accept_file = file(acceptfilename, "w") accept_file.write("OK\n") accept_file.close()<|fim▁hole|> do_Approve() if __name__ == '__main__': main()<|fim▁end|>
<|file_name|>plotting_NR.py<|end_file_name|><|fim▁begin|>def plot_kinematics(signal, background, nbins=100, mass_range=(50., 110.), pt_range=(200., 500.), mass_pad=10, pt_pad=50, linewidth=1, title=None): import numpy as np from matplotlib import pyplot as plt import h5py pt_min, pt_max = pt_range mass_min, mass_max = mass_range plt.style.use('seaborn-white') signal_h5file_events = h5py.File(signal, 'r') signal_aux = signal_h5file_events['auxvars'] background_h5file_events = h5py.File(background, 'r') background_aux = background_h5file_events['auxvars'] signal_selection = ((signal_aux['mass_trimmed'] > mass_min) & (signal_aux['mass_trimmed'] < mass_max) & (signal_aux['pt_trimmed'] > pt_min) & (signal_aux['pt_trimmed'] < pt_max)) background_selection = ((background_aux['mass_trimmed'] > mass_min) & (background_aux['mass_trimmed'] < mass_max) & (background_aux['pt_trimmed'] > pt_min) & (background_aux['pt_trimmed'] < pt_max)) #signal_selection = slice(0, None) #background_selection = slice(0, None) if 'weights' in signal_aux.dtype.names: signal_weights = signal_aux['weights'] else: signal_weights = np.ones(len(signal_aux)) if 'weights' in background_aux.dtype.names: background_weights = background_aux['weights'] else: background_weights = np.ones(len(background_aux)) signal_weights = signal_weights[signal_selection] background_weights = background_weights[background_selection] fig, ax = plt.subplots(2, 2, figsize=(10, 10)) if title is not None: fig.suptitle(title, fontsize=16) vals1, _, _ = ax[0, 0].hist(signal_aux['pt_trimmed'][signal_selection],<|fim▁hole|> linewidth=linewidth, label=r'Signal', weights=signal_weights) vals2, _, _ = ax[0, 0].hist(background_aux['pt_trimmed'][background_selection], bins=np.linspace(pt_min - pt_pad, pt_max + pt_pad, nbins), histtype='stepfilled', facecolor='none', edgecolor='black', normed=1, linestyle='dotted', linewidth=linewidth, label='QCD Background', weights=background_weights) ax[0, 0].set_ylim((0, 1.3 * max(np.max(vals1), np.max(vals2)))) ax[0, 0].set_ylabel('Normalized to Unity') ax[0, 0].set_xlabel(r'Trimmed $p_{T}$ [GeV]', fontsize=12) p1, = ax[0, 0].plot([0, 0], label='Signal', color='blue') p2, = ax[0, 0].plot([0, 0], label='QCD Background', color='black', linestyle='dotted') ax[0, 0].legend([p1, p2], ['Signal', 'QCD Background'], frameon=False, handlelength=3) ax[0, 0].set_xlim((pt_min - pt_pad, pt_max + pt_pad)) ax[0, 0].ticklabel_format(style='sci', scilimits=(0,0), axis='y') vals1, _, _ = ax[0, 1].hist(signal_aux['mass_trimmed'][signal_selection], bins=np.linspace(mass_min - mass_pad, mass_max + mass_pad, nbins), histtype='stepfilled', facecolor='none', edgecolor='blue', normed=1, linewidth=linewidth, label=r'Signal', weights=signal_weights) vals2, _, _ = ax[0, 1].hist(background_aux['mass_trimmed'][background_selection], bins=np.linspace(mass_min - mass_pad, mass_max + mass_pad, nbins), histtype='stepfilled', facecolor='none', edgecolor='black', normed=1, linestyle='dotted', linewidth=linewidth, label='QCD Background', weights=background_weights) ax[0, 1].set_ylim((0, 1.3 * max(np.max(vals1), np.max(vals2)))) ax[0, 1].set_ylabel('Normalized to Unity') ax[0, 1].set_xlabel(r'Trimmed Mass [GeV]', fontsize=12) p1, = ax[0, 1].plot([0, 0], label='Signal', color='blue') p2, = ax[0, 1].plot([0, 0], label='QCD Background', color='black', linestyle='dotted') ax[0, 1].legend([p1, p2], ['Signal', 'QCD Background'], frameon=False, handlelength=3) ax[0, 1].set_xlim((mass_min - mass_pad, mass_max + mass_pad)) signal_tau32 = np.true_divide(signal_aux['tau_3'], signal_aux['tau_2'])[signal_selection] background_tau32 = np.true_divide(background_aux['tau_3'], background_aux['tau_2'])[background_selection] # remove NaN infinity and zero signal_tau32_nonan = ~np.isnan(signal_tau32) & ~np.isinf(signal_tau32) & (signal_tau32 != 0) background_tau32_nonan = ~np.isnan(background_tau32) & ~np.isinf(background_tau32) & (background_tau32 != 0) vals1, _, _ = ax[1, 0].hist(signal_tau32[signal_tau32_nonan], bins=np.linspace(0, 1, nbins), histtype='stepfilled', facecolor='none', edgecolor='blue', normed=1, linewidth=linewidth, label=r'W jets', weights=signal_weights[signal_tau32_nonan]) vals2, _, _ = ax[1, 0].hist(background_tau32[background_tau32_nonan], bins=np.linspace(0, 1, nbins), histtype='stepfilled', facecolor='none', edgecolor='black', normed=1, linestyle='dotted', linewidth=linewidth, label='QCD jets', weights=background_weights[background_tau32_nonan]) ax[1, 0].set_ylim((0, 1.3 * max(np.max(vals1), np.max(vals2)))) ax[1, 0].set_ylabel('Normalized to Unity') ax[1, 0].set_xlabel(r'$\tau_{32}$', fontsize=12) p1, = ax[1, 0].plot([0, 0], label='W jets', color='blue') p2, = ax[1, 0].plot([0, 0], label='QCD jets', color='black', linestyle='dotted') ax[1, 0].legend([p1, p2], ['W jets', 'QCD jets'], frameon=False, handlelength=3) ax[1, 0].set_xlim((0, 1)) vals1, _, _ = ax[1, 1].hist(signal_aux['subjet_dr'][signal_selection], bins=np.linspace(0, 1.2, nbins), histtype='stepfilled', facecolor='none', edgecolor='blue', normed=1, linewidth=linewidth, label=r'W jets', weights=signal_weights) vals2, _, _ = ax[1, 1].hist(background_aux['subjet_dr'][background_selection], bins=np.linspace(0, 1.2, nbins), histtype='stepfilled', facecolor='none', edgecolor='black', normed=1, linestyle='dotted', linewidth=linewidth, label='QCD jets', weights=background_weights) ax[1, 1].set_ylim((0, 1.3 * max(np.max(vals1), np.max(vals2)))) ax[1, 1].set_ylabel('Normalized to Unity') ax[1, 1].set_xlabel(r'Subjets $\Delta R$', fontsize=12) p1, = ax[1, 1].plot([0, 0], label='W jets', color='blue') p2, = ax[1, 1].plot([0, 0], label='QCD jets', color='black', linestyle='dotted') ax[1, 1].legend([p1, p2], ['W jets', 'QCD jets'], frameon=False, handlelength=3) ax[1, 1].set_xlim((0, 1.2)) fig.tight_layout() if title is not None: plt.subplots_adjust(top=0.93) return fig<|fim▁end|>
bins=np.linspace(pt_min - pt_pad, pt_max + pt_pad, nbins), histtype='stepfilled', facecolor='none', edgecolor='blue', normed=1,
<|file_name|>todo.js<|end_file_name|><|fim▁begin|>const ADD_TODO = 'ADD_TODO'; const TOGGLE_TODO = 'TOGGLE_TODO'; const SET_VISIBILITY_FILTER = 'SET_VISIBILITY_FILTER'; const SHOW_ALL = 'SHOW_ALL'; const todo = (state = {}, action) => { switch (action.type) { case ADD_TODO: return { id: action.id, text: action.text, completed: false }; case TOGGLE_TODO: if (state.id !== action.id) { return state; } return { ...state, completed: !state.completed }; default: return state; } }; const initialState = { todos: [], filter: SHOW_ALL }; export default function reducer(state = initialState, action) { let todos; switch (action.type) { case ADD_TODO: todos = [todo(undefined, action), ...state.todos]; return { ...state, filter: SHOW_ALL, todos }; case TOGGLE_TODO: todos = state.todos.map(td => todo(td, action) ); return { ...state,<|fim▁hole|> case SET_VISIBILITY_FILTER: return { ...state, filter: action.filter, todos: [...state.todos] }; default: return state; } } export function addTodo(id, text) { return { type: ADD_TODO, id, text }; } export function toggleTodo(id) { return { type: TOGGLE_TODO, id }; } export function setVisibilityFilter(filter) { return { type: SET_VISIBILITY_FILTER, filter }; }<|fim▁end|>
todos };
<|file_name|>quantization.py<|end_file_name|><|fim▁begin|># # Copyright 2016 The BigDL Authors. # # 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. # from neural_compressor.conf.config import Quantization_Conf<|fim▁hole|>from neural_compressor.experimental import Quantization, common from neural_compressor.experimental.common import Metric from .metric import METRICS class QuantizationINC(Quantization): def __init__(self, framework: str, conf='', approach='post_training_static_quant', tuning_strategy='bayesian', accuracy_criterion: dict = None, timeout=0, max_trials=1, inputs=None, outputs=None ): """ Create a Intel Neural Compressor Quantization object. To understand INC quantization, please refer to https://github.com/intel/neural-compressor/blob/master/docs/Quantization.md. :param framework: 'tensorflow', 'pytorch', 'pytorch_fx', 'pytorch_ipex', 'onnxrt_integer', 'onnxrt_qlinear' or 'mxnet'; allow new framework backend extension. Default: 'pytorch_fx'. Consistent with Intel Neural Compressor Quantization. :param conf: A path to conf yaml file for quantization. Default: None, using default config. :param approach: 'post_training_static_quant', 'post_training_dynamic_quant', 'quant_aware_training'. Default: 'post_training_static_quant'. :param tuning_strategy: 'bayesian', 'basic', 'mse', 'sigopt'. Default: 'bayesian'. :param accuracy_criterion: Tolerable accuracy drop. accuracy_criterion = {'relative': 0.1, 'higher_is_better':True} allows relative accuracy loss: 1%. accuracy_criterion = { 'absolute': 0.99, 'higher_is_better':False} means accuracy < 0.99 must be satisfied. :param timeout: Tuning timeout (seconds). Default: 0, which means early stop. combine with max_trials field to decide when to exit. :param max_trials: Max tune times. Default: 1. Combine with timeout field to decide when to exit. :param inputs: For tensorflow to specify names of inputs. e.g. inputs=['img',] :param outputs: For tensorflow to specify names of outputs. e.g. outputs=['logits',] """ qconf = Quantization_Conf(conf) cfg = qconf.usr_cfg # Override default config cfg.model.framework = framework cfg.quantization.approach = approach cfg.tuning.strategy.name = tuning_strategy if accuracy_criterion: cfg.tuning.accuracy_criterion = accuracy_criterion cfg.tuning.exit_policy.timeout = timeout cfg.tuning.exit_policy.max_trials = max_trials cfg.model.inputs = inputs cfg.model.outputs = outputs super().__init__(qconf) def post_training_quantize(self, model, calib_dataloader=None, val_dataloader=None, metric=None): self.check(calib_dataloader, val_dataloader, metric) self.model = common.Model(model) def func(data): # TODO: only x, y are supported here for onnx quantization import torch x, y = zip(*data) if isinstance(x[0], torch.Tensor): x = torch.stack(x, dim=0).numpy() if isinstance(y[0], torch.Tensor): y = torch.stack(y, dim=0).numpy() return x, y if calib_dataloader: if "pytorch" in self.cfg.model.framework or "tensorflow" in self.cfg.model.framework: self.calib_dataloader = calib_dataloader if "onnx" in self.cfg.model.framework: import torch assert isinstance(calib_dataloader, torch.utils.data.DataLoader), \ "Only torch dataloader is supported for onnx quantization." # add a collate_fn to transform torch dataloader to a numpy dataloader calib_dataloader.collate_fn = func self.calib_dataloader = calib_dataloader if val_dataloader: if "pytorch" in self.cfg.model.framework or "tensorflow" in self.cfg.model.framework: self.eval_dataloader = val_dataloader if "onnx" in self.cfg.model.framework: import torch assert isinstance(val_dataloader, torch.utils.data.DataLoader), \ "Only torch dataloader is supported for onnx quantization." # add a collate_fn to transform torch dataloader to a numpy dataloader val_dataloader.collate_fn = func self.eval_dataloader = val_dataloader if metric: framework = self.cfg.model.framework if 'pytorch' in framework: framework_metric = METRICS['pytorch'] elif 'onnx' in framework: framework_metric = METRICS['onnx'] else: framework_metric = METRICS[framework] class MyMetric(framework_metric): def __init__(self): """ This local class is to resolve dumping issue in tensorflow. In tensorflow, INC will try to dump the metric to yaml which somehow causes unexpected error. So we moved metric assignment to the new local class to avoid that. """ self.metric = metric self.metric = Metric( MyMetric, name=f"{framework}_{type(metric).__name__}_" f"{framework_metric.get_next_metric_id()}" ) quantized = self() # unset the collate_fn and set back to default_collate # TODO: use users' original collate function if "onnx" in self.cfg.model.framework: from torch.utils.data.dataloader import default_collate if calib_dataloader: calib_dataloader.collate_fn = default_collate if val_dataloader: val_dataloader.collate_fn = default_collate if quantized: return quantized else: raise RuntimeError("Found no quantized model satisfying accuracy criterion.") def check(self, calib_dataloader, val_dataloader, metric): """ Call before self.__call__() to check if the object is well-initialized for quantization. """ if self.cfg.quantization.approach == 'post_training_static_quant': assert calib_dataloader, \ "calib_calib_dataloader must not be None when approach is " \ "post-training static quantization." if self.cfg.quantization.approach == 'post_training_dynamic_quant': assert calib_dataloader is None, \ "calib_calib_dataloader must be None when approach is " \ "post-training dynamic quantization." if metric and not val_dataloader: raise RuntimeError("val_dataloader must be specified when metric is not None.")<|fim▁end|>
<|file_name|>main.go<|end_file_name|><|fim▁begin|>package main import ( "encoding/json" "errors" "fmt" "io/ioutil" "log" "math/rand" "net/http" "net/http/httputil" "strings" ) type App struct { Service string `json:"service"` Host string `json:"host"` IP string `json:"ip"` Port string `json:"port"` }<|fim▁hole|> panic(err.Error()) } var apps []App err = json.Unmarshal(body, &apps) if err != nil { panic(err.Error()) } return apps } func Route(apps []App, path string) ([]byte, error) { item := rand.Intn(len(apps)) url := "http://" + apps[item].IP + ":" + apps[item].Port if len(path) > 0 { url = url + "/" + path } body, err := MakeRequest("GET", url) if err != nil { return nil, err } return body, nil } func GetAppName(r *http.Request) (string, error) { url := strings.SplitN(strings.TrimLeft(r.URL.Path, "/"), "/", 2) if len(url) == 0 || len(url[0]) == 0 { return "", errors.New("no app name") } return url[0], nil } func handleApplications(w http.ResponseWriter, r *http.Request) { url := strings.SplitN(strings.TrimLeft(r.URL.Path, "/"), "/", 2) fmt.Printf("%#v\n", url) if len(url) == 0 || len(url[0]) == 0 { fmt.Fprintf(w, "%v\n", struct { Type string `json:"error"` Message string `json:"message"` }{ "error", "no app name", }) return } applicationName := url[0] var path string if len(url) == 1 { path = "" } else { path = url[1] } // Router logic starts here app := GetEndpoint(applicationName) fmt.Fprintf(w, "Application: %s\n", applicationName) resp, err := Route(app, path) if err != nil { fmt.Fprintf(w, "error: %s\n", err.Error()) } fmt.Fprintf(w, "%s", resp) } func main() { // http.HandleFunc("/app1", func(w http.ResponseWriter, r *http.Request) { // app1 := GetEndpoint("maxapp1") // fmt.Fprintf(w, "app1:\n") // resp, err := Route(app1, "") // if err != nil { // fmt.Fprintf(w, "error: %s\n", err.Error()) // } // fmt.Fprintf(w, "%s\n", resp) // }) // http.HandleFunc("/app2", func(w http.ResponseWriter, r *http.Request) { // app2 := GetEndpoint("maxapp2") // fmt.Fprintf(w, "app2:\n") // resp, err := Route(app2, "") // if err != nil { // fmt.Fprintf(w, "error: %s\n", err.Error()) // } // fmt.Fprintf(w, "%s\n", resp) // }) // http.HandleFunc("/from2", func(w http.ResponseWriter, r *http.Request) { // app1 := GetEndpoint("maxapp1") // fmt.Fprintf(w, "app1:\n") // resp, err := Route(app1, "/from2") // if err != nil { // fmt.Fprintf(w, "error: %s\n", err.Error()) // } // fmt.Fprintf(w, "%s\n", resp) // }) // http.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) { // app1 := GetEndpoint("maxapp1") // app2 := GetEndpoint("maxapp2") // fmt.Fprintf(w, "app1:\n") // fmt.Fprintf(w, "%v\n", app1) // fmt.Fprintf(w, "app2:\n") // fmt.Fprintf(w, "%v\n", app2) // }) println("ready") log.Fatal(http.ListenAndServe(":3000", &httputil.ReverseProxy{ Director: func(r *http.Request) { r.URL.Scheme = "http" appName, err := GetAppName(r) if err != nil { // SendError(err, w) } apps := GetEndpoint(appName) item := rand.Intn(len(apps)) r.URL.Host = apps[item].Host + ":" + apps[item].Port }, })) // log.Fatal(http.ListenAndServe(":3000", http.HandlerFunc(handleApplications))) } func MakeRequest(httpType, url string) ([]byte, error) { reader := strings.NewReader("") request, err := http.NewRequest(httpType, url, reader) if err != nil { return nil, err } client := &http.Client{} resp, err := client.Do(request) if err != nil { return nil, err } defer resp.Body.Close() return ioutil.ReadAll(resp.Body) } func SendError(err error, w http.ResponseWriter) { fmt.Fprintf(w, "%v\n", struct { Type string `json:"error"` Message string `json:"message"` }{ "error", err.Error(), }) return }<|fim▁end|>
func GetEndpoint(name string) []App { body, err := MakeRequest("GET", "http://52.34.228.148:8123/v1/services/_"+name+"._tcp.marathon.mesos") if err != nil {
<|file_name|>Loop.py<|end_file_name|><|fim▁begin|>from __future__ import print_function from __future__ import absolute_import from __future__ import unicode_literals from SimPEG import Mesh, Utils import numpy as np import matplotlib.pyplot as plt import matplotlib.patches as patches from scipy.sparse import spdiags,csr_matrix, eye,kron,hstack,vstack,eye,diags import copy from scipy.constants import mu_0 from SimPEG import SolverLU from scipy.sparse.linalg import spsolve,splu from SimPEG.EM import TDEM from SimPEG.EM.Analytics.TDEM import hzAnalyticDipoleT,hzAnalyticCentLoopT from scipy.interpolate import interp2d,LinearNDInterpolator from scipy.special import ellipk,ellipe def rectangular_plane_layout(mesh,corner, closed = False,I=1.): """ corner: sorted list of four corners (x,y,z) 2--3 | | 1--4 y | |--> x Output: Js """ Jx = np.zeros(mesh.nEx) Jy = np.zeros(mesh.nEy) Jz = np.zeros(mesh.nEz) indy1 = np.logical_and( \ np.logical_and( \ np.logical_and(mesh.gridEy[:,0]>=corner[0,0],mesh.gridEy[:,0]<=corner[1,0]), \ np.logical_and(mesh.gridEy[:,1] >=corner[0,1] , mesh.gridEy[:,1]<=corner[1,1] )), (mesh.gridEy[:,2] == corner[0,2] ) ) indx1 = np.logical_and( \ np.logical_and( \ np.logical_and(mesh.gridEx[:,0]>=corner[1,0],mesh.gridEx[:,0]<=corner[2,0]), \ np.logical_and(mesh.gridEx[:,1] >=corner[1,1] , mesh.gridEx[:,1]<=corner[2,1] )), (mesh.gridEx[:,2] == corner[1,2] ) ) indy2 = np.logical_and( \ np.logical_and( \ np.logical_and(mesh.gridEy[:,0]>=corner[2,0],mesh.gridEy[:,0]<=corner[3,0]), \ np.logical_and(mesh.gridEy[:,1] <=corner[2,1] , mesh.gridEy[:,1]>=corner[3,1] )), (mesh.gridEy[:,2] == corner[2,2] ) ) if closed: indx2 = np.logical_and( \ np.logical_and( \ np.logical_and(mesh.gridEx[:,0]>=corner[0,0],mesh.gridEx[:,0]<=corner[3,0]), \ np.logical_and(mesh.gridEx[:,1] >=corner[0,1] , mesh.gridEx[:,1]<=corner[3,1] )), (mesh.gridEx[:,2] == corner[0,2] ) ) else: indx2 = [] Jy[indy1] = -I Jx[indx1] = -I Jy[indy2] = I Jx[indx2] = I J = np.hstack((Jx,Jy,Jz)) J = J*mesh.edge return J def BiotSavart(locs,mesh,Js): """ Compute the magnetic field generated by current discretized on a mesh using Biot-Savart law Input: locs: observation locations mesh: mesh on which the current J is discretized Js: discretized source current in A-m (Finite Volume formulation) Output: B: magnetic field [Bx,By,Bz] """ c = mu_0/(4*np.pi) nwire = np.sum(Js!=0.) ind= np.where(Js!=0.) ind = ind[0] B = np.zeros([locs.shape[0],3]) gridE = np.vstack([mesh.gridEx,mesh.gridEy,mesh.gridEz]) for i in range(nwire): # x wire if ind[i]<mesh.nEx: r = locs-gridE[ind[i]] I = Js[ind[i]]*np.hstack([np.ones([locs.shape[0],1]),np.zeros([locs.shape[0],1]),np.zeros([locs.shape[0],1])]) cr = np.cross(I,r) rsq = np.linalg.norm(r,axis=1)**3. B = B + c*cr/rsq[:,None] # y wire elif ind[i]<mesh.nEx+mesh.nEy: r = locs-gridE[ind[i]] I = Js[ind[i]]*np.hstack([np.zeros([locs.shape[0],1]),np.ones([locs.shape[0],1]),np.zeros([locs.shape[0],1])]) cr = np.cross(I,r) rsq = np.linalg.norm(r,axis=1)**3. B = B + c*cr/rsq[:,None] # z wire elif ind[i]<mesh.nEx+mesh.nEy+mesh.nEz: r = locs-gridE[ind[i]] I = Js[ind[i]]*np.hstack([np.zeros([locs.shape[0],1]),np.zeros([locs.shape[0],1]),np.ones([locs.shape[0],1])]) cr = np.cross(I,r) rsq = np.linalg.norm(r,axis=1)**3. B = B + c*cr/rsq[:,None] else: print('error: index of J out of bounds (number of edges in the mesh)') return B def analytic_infinite_wire(obsloc,wireloc,orientation,I=1.): """ Compute the response of an infinite wire with orientation 'orientation' and current I at the obsvervation locations obsloc Output:<|fim▁hole|> """ n,d = obsloc.shape t,d = wireloc.shape d = np.sqrt(np.dot(obsloc**2.,np.ones([d,t]))+np.dot(np.ones([n,d]),(wireloc.T)**2.) - 2.*np.dot(obsloc,wireloc.T)) distr = np.amin(d, axis=1, keepdims = True) idxmind = d.argmin(axis=1) r = obsloc - wireloc[idxmind] orient = np.c_[[orientation for i in range(obsloc.shape[0])]] B = (mu_0*I)/(2*np.pi*(distr**2.))*np.cross(orientation,r) return B def mag_dipole(m,obsloc): """ Compute the response of an infinitesimal mag dipole at location (0,0,0) with orientation X and magnetic moment 'm' at the obsvervation locations obsloc Output: B: magnetic field [Bx,By,Bz] """ loc = np.r_[[[0.,0.,0.]]] n,d = obsloc.shape t,d = loc.shape d = np.sqrt(np.dot(obsloc**2.,np.ones([d,t]))+np.dot(np.ones([n,d]),(loc.T)**2.) - 2.*np.dot(obsloc,loc.T)) d = d.flatten() ind = np.where(d==0.) d[ind] = 1e6 x = obsloc[:,0] y = obsloc[:,1] z = obsloc[:,2] #orient = np.c_[[orientation for i in range(obsloc.shape[0])]] Bz = (mu_0*m)/(4*np.pi*(d**3.))*(3.*((z**2.)/(d**2.))-1.) By = (mu_0*m)/(4*np.pi*(d**3.))*(3.*(z*y)/(d**2.)) Bx = (mu_0*m)/(4*np.pi*(d**3.))*(3.*(x*z)/(d**2.)) B = np.vstack([Bx,By,Bz]).T return B def circularloop(a,obsloc,I=1.): """ From Simpson, Lane, Immer, Youngquist 2001 Compute the magnetic field B response of a current loop of radius 'a' with intensity 'I'. input: a: radius in m obsloc: obsvervation locations Output: B: magnetic field [Bx,By,Bz] """ x = np.atleast_2d(obsloc[:,0]).T y = np.atleast_2d(obsloc[:,1]).T z = np.atleast_2d(obsloc[:,2]).T r = np.linalg.norm(obsloc,axis=1) loc = np.r_[[[0.,0.,0.]]] n,d = obsloc.shape r2 = x**2.+y**2.+z**2. rho2 = x**2.+y**2. alpha2 = a**2.+r2-2*a*np.sqrt(rho2) beta2 = a**2.+r2+2*a*np.sqrt(rho2) k2 = 1-(alpha2/beta2) lbda = x**2.-y**2. C = mu_0*I/np.pi Bx = ((C*x*z)/(2*alpha2*np.sqrt(beta2)*rho2))*\ ((a**2.+r2)*ellipe(k2)-alpha2*ellipk(k2)) Bx[np.isnan(Bx)] = 0. By = ((C*y*z)/(2*alpha2*np.sqrt(beta2)*rho2))*\ ((a**2.+r2)*ellipe(k2)-alpha2*ellipk(k2)) By[np.isnan(By)] = 0. Bz = (C/(2.*alpha2*np.sqrt(beta2)))*\ ((a**2.-r2)*ellipe(k2)+alpha2*ellipk(k2)) Bz[np.isnan(Bz)] = 0. #print(Bx.shape) #print(By.shape) #print(Bz.shape) B = np.hstack([Bx,By,Bz]) return B<|fim▁end|>
B: magnetic field [Bx,By,Bz]
<|file_name|>conf.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # # flask_slack documentation build configuration file, created by # sphinx-quickstart on Sun Oct 19 16:31:35 2014. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys import os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.insert(0, os.path.abspath('..')) sys.path.append(os.path.abspath('_themes')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.doctest', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'flask_slack' copyright = u'2014, VeryCB' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '0.1.5' # The full version, including alpha/beta/rc tags. release = '0.1.5' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all # documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'flask' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. html_theme_options = { 'index_logo': None } # Add any paths that contain custom themes here, relative to this directory. html_theme_path = ['_themes'] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. #html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y'<|fim▁hole|>#html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'flask_slackdoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ ('index', 'flask_slack.tex', u'flask\\_slack Documentation', u'VeryCB', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'flask_slack', u'flask_slack Documentation', [u'VeryCB'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'flask_slack', u'flask_slack Documentation', u'VeryCB', 'flask_slack', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False<|fim▁end|>
# If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities.
<|file_name|>HttpSession.java<|end_file_name|><|fim▁begin|>package ru.stqa.pft.mantis.appmanager; import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients;<|fim▁hole|>import java.io.IOException; import java.util.ArrayList; import java.util.List; public class HttpSession { private CloseableHttpClient httpclient; private ApplicationManager app; public HttpSession(ApplicationManager app) { this.app = app; httpclient = HttpClients.custom().setRedirectStrategy(new LaxRedirectStrategy()).build(); } public boolean login(String username, String password) throws IOException { HttpPost post = new HttpPost(app.getProperty("web.baseUrl") + "/login.php"); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("username", username)); params.add(new BasicNameValuePair("password", password)); params.add(new BasicNameValuePair("secure_session", "on")); params.add(new BasicNameValuePair("return", "index.php")); post.setEntity(new UrlEncodedFormEntity(params)); CloseableHttpResponse response = httpclient.execute(post); String body = geTextFrom(response); return body.contains(String.format("<span id=\"logged-in-user\">%s</span>", username)); } private String geTextFrom(CloseableHttpResponse response) throws IOException { try { return EntityUtils.toString(response.getEntity()); } finally { response.close(); } } public boolean isLoggedInAs(String username) throws IOException { HttpGet get = new HttpGet(app.getProperty("web.baseUrl") + "/index.php"); CloseableHttpResponse response = httpclient.execute(get); String body = geTextFrom(response); // return body.contains(String.format("<span class=\"italic\">%s</span>", username)); return body.contains(String.format("<span id=\"logged-in-user\">%s</span>", username)); } }<|fim▁end|>
import org.apache.http.impl.client.LaxRedirectStrategy; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils;
<|file_name|>privatelinkresources.go<|end_file_name|><|fim▁begin|>package cognitiveservices // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. import ( "context" "github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest/azure" "github.com/Azure/go-autorest/autorest/validation" "github.com/Azure/go-autorest/tracing" "net/http" ) // PrivateLinkResourcesClient is the cognitive Services Management Client type PrivateLinkResourcesClient struct { BaseClient } // NewPrivateLinkResourcesClient creates an instance of the PrivateLinkResourcesClient client. func NewPrivateLinkResourcesClient(subscriptionID string) PrivateLinkResourcesClient { return NewPrivateLinkResourcesClientWithBaseURI(DefaultBaseURI, subscriptionID) } // NewPrivateLinkResourcesClientWithBaseURI creates an instance of the PrivateLinkResourcesClient client using a custom // endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure // stack). func NewPrivateLinkResourcesClientWithBaseURI(baseURI string, subscriptionID string) PrivateLinkResourcesClient { return PrivateLinkResourcesClient{NewWithBaseURI(baseURI, subscriptionID)} } // List gets the private link resources that need to be created for a Cognitive Services account. // Parameters: // resourceGroupName - the name of the resource group. The name is case insensitive. // accountName - the name of Cognitive Services account. func (client PrivateLinkResourcesClient) List(ctx context.Context, resourceGroupName string, accountName string) (result PrivateLinkResourceListResult, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/PrivateLinkResourcesClient.List") defer func() { sc := -1 if result.Response.Response != nil { sc = result.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }()<|fim▁hole|> } if err := validation.Validate([]validation.Validation{ {TargetValue: resourceGroupName, Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}, {TargetValue: accountName, Constraints: []validation.Constraint{{Target: "accountName", Name: validation.MaxLength, Rule: 64, Chain: nil}, {Target: "accountName", Name: validation.MinLength, Rule: 2, Chain: nil}, {Target: "accountName", Name: validation.Pattern, Rule: `^[a-zA-Z0-9][a-zA-Z0-9_.-]*$`, Chain: nil}}}, {TargetValue: client.SubscriptionID, Constraints: []validation.Constraint{{Target: "client.SubscriptionID", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil { return result, validation.NewError("cognitiveservices.PrivateLinkResourcesClient", "List", err.Error()) } req, err := client.ListPreparer(ctx, resourceGroupName, accountName) if err != nil { err = autorest.NewErrorWithError(err, "cognitiveservices.PrivateLinkResourcesClient", "List", nil, "Failure preparing request") return } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "cognitiveservices.PrivateLinkResourcesClient", "List", resp, "Failure sending request") return } result, err = client.ListResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "cognitiveservices.PrivateLinkResourcesClient", "List", resp, "Failure responding to request") return } return } // ListPreparer prepares the List request. func (client PrivateLinkResourcesClient) ListPreparer(ctx context.Context, resourceGroupName string, accountName string) (*http.Request, error) { pathParameters := map[string]interface{}{ "accountName": autorest.Encode("path", accountName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2021-04-30" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/privateLinkResources", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // ListSender sends the List request. The method will close the // http.Response Body if it receives an error. func (client PrivateLinkResourcesClient) ListSender(req *http.Request) (*http.Response, error) { return client.Send(req, azure.DoRetryWithRegistration(client.Client)) } // ListResponder handles the response to the List request. The method always // closes the http.Response Body. func (client PrivateLinkResourcesClient) ListResponder(resp *http.Response) (result PrivateLinkResourceListResult, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return }<|fim▁end|>
<|file_name|>forms.py<|end_file_name|><|fim▁begin|>from __future__ import absolute_import import json from django import forms from django.contrib.auth.models import AnonymousUser from django.core.exceptions import ObjectDoesNotExist try: from django.urls import reverse, resolve except: from django.core.urlresolvers import reverse, resolve from django.core.validators import EMPTY_VALUES from django.db import models from django.http.request import HttpRequest from django.utils.encoding import smart_str, force_text<|fim▁hole|>class ChainedChoicesMixin(object): """ Form Mixin to be used with ChainedChoicesForm and ChainedChoicesModelForm. It loads the options when there is already an instance or initial data. """ user = None prefix = None fields = [] chained_fields_names = [] chained_model_fields_names = [] def init_chained_choices(self, *args, **kwargs): self.chained_fields_names = self.get_fields_names_by_type(ChainedChoiceField) self.chained_model_fields_names = self.get_fields_names_by_type(ChainedModelChoiceField) + self.get_fields_names_by_type(ChainedModelMultipleChoiceField) self.user = kwargs.get('user', self.user) if kwargs.get('data', None) is not None: self.set_choices_via_ajax(kwargs['data']) elif len(args) > 0 and args[0] not in EMPTY_VALUES: self.set_choices_via_ajax(args[0]) elif kwargs.get('instance', None) is not None: oldest_parent_field_names = list(set(self.get_oldest_parent_field_names())) youngest_child_names = list(set(self.get_youngest_children_field_names())) for youngest_child_name in youngest_child_names: self.find_instance_attr(kwargs['instance'], youngest_child_name) for oldest_parent_field_name in oldest_parent_field_names: try: self.fields[oldest_parent_field_name].initial = getattr(self, '%s' % oldest_parent_field_name) except AttributeError: pass self.set_choices_via_ajax() elif 'initial' in kwargs and kwargs['initial'] not in EMPTY_VALUES: self.set_choices_via_ajax(kwargs['initial'], is_initial=True) else: for field_name in self.chained_fields_names + self.chained_model_fields_names: empty_label = self.fields[field_name].empty_label self.fields[field_name].choices = [('', empty_label)] def set_choices_via_ajax(self, kwargs=None, is_initial=False): for field_name in self.chained_fields_names + self.chained_model_fields_names: field = self.fields[field_name] try: if kwargs is not None: # initial data do not have any prefix if self.prefix in EMPTY_VALUES or is_initial: parent_value = kwargs.get(field.parent_field, None) field_value = kwargs.get(field_name, None) else: parent_value = kwargs.get('%s-%s' % (self.prefix, field.parent_field), None) field_value = kwargs.get('%s-%s' % (self.prefix, field_name), None) else: parent_value = self.initial.get(field.parent_field, None) field_value = self.initial.get(field_name, None) if parent_value is None: parent_value = getattr(self, '%s' % field.parent_field, None) if field_value is None: field_value = getattr(self, '%s' % field_name, None) field.choices = [('', field.empty_label)] # check that parent_value is valid if parent_value: parent_value = getattr(parent_value, 'pk', parent_value) url = force_text(field.ajax_url) params = { 'field_name': field_name, 'parent_value': parent_value, 'field_value': field_value } # This will get the callable from the url. # All we need to do is pass in a 'request' url_callable = resolve(url).func # Build the fake request fake_request = HttpRequest() fake_request.META["SERVER_NAME"] = "localhost" fake_request.META["SERVER_PORT"] = '80' # Add parameters and user if supplied fake_request.method = "GET" for key, value in params.items(): fake_request.GET[key] = value if hasattr(self, "user") and self.user: fake_request.user = self.user else: fake_request.user = AnonymousUser() # Get the response response = url_callable(fake_request) # Apply the data (if it's returned) if smart_str(response.content): try: field.choices += json.loads(smart_str(response.content)) except ValueError: raise ValueError('Data returned from request (url={url}, params={params}) could not be deserialized to Python object: {data}'.format( url=url, params=params, data=response.content )) field.initial = field_value except ObjectDoesNotExist: field.choices = () def get_fields_names_by_type(self, type_): result = [] for field_name in self.fields: field = self.fields[field_name] if isinstance(field, type_): result.append(field_name) return result def get_parent_fields_names(self): result = [] for field_name in self.fields: field = self.fields[field_name] if hasattr(field, 'parent_field'): result.append(field.parent_field) return result def get_children_field_names(self, parent_name): if parent_name in EMPTY_VALUES: return [] result = [] for field_name in self.fields: field = self.fields[field_name] if getattr(field, 'parent_field', None) == parent_name: result.append(field_name) return result def get_chained_fields_names(self): chained_fields_names = self.get_fields_names_by_type(ChainedChoiceField) chained_model_fields_names = self.get_fields_names_by_type(ChainedModelChoiceField) return chained_fields_names + chained_model_fields_names def get_oldest_parent_field_names(self): chained_fields_names = self.get_fields_names_by_type(ChainedChoiceField) chained_model_fields_names = self.get_fields_names_by_type(ChainedModelChoiceField) oldest_parent_field_names = [] for field_name in self.get_parent_fields_names(): if field_name not in chained_fields_names and field_name not in chained_model_fields_names: oldest_parent_field_names.append(field_name) return oldest_parent_field_names def get_youngest_children_field_names(self): result = [] chained_fields_names = self.get_fields_names_by_type(ChainedChoiceField) chained_model_fields_names = self.get_fields_names_by_type(ChainedModelChoiceField) for field_name in chained_fields_names + chained_model_fields_names: if field_name not in self.get_parent_fields_names(): result.append(field_name) return result def find_instance_attr(self, instance, attr_name): field = self.fields[attr_name] if hasattr(instance, attr_name): attribute = getattr(instance, attr_name) attr_value = getattr(attribute, 'pk', smart_str(attribute)) if attribute else None setattr(self, '%s' % attr_name, attr_value) if hasattr(field, 'parent_field'): parent_instance = attribute if isinstance(attribute, models.Model) else instance self.find_instance_attr(parent_instance, field.parent_field) class ChainedChoicesForm(forms.Form, ChainedChoicesMixin): """ Form class to be used with ChainedChoiceField and ChainedSelect widget If there is request POST data in *args (i.e. form validation was invalid) then the options will be loaded when the form is built. """ def __init__(self, language_code=None, *args, **kwargs): if kwargs.get('user'): self.user = kwargs.pop('user') # To get request.user. Do not use kwargs.pop('user', None) due to potential security hole super(ChainedChoicesForm, self).__init__(*args, **kwargs) self.language_code = language_code self.init_chained_choices(*args, **kwargs) def is_valid(self): if self.language_code: # response is not translated to requested language code :/ # so translation is triggered manually from django.utils.translation import activate activate(self.language_code) return super(ChainedChoicesForm, self).is_valid() class ChainedChoicesModelForm(forms.ModelForm, ChainedChoicesMixin): """ Form class to be used with ChainedChoiceField and ChainedSelect widget If there is already an instance (i.e. editing) then the options will be loaded when the form is built. """ def __init__(self, *args, **kwargs): if kwargs.get('user'): self.user = kwargs.pop('user') # To get request.user. Do not use kwargs.pop('user', None) due to potential security hole super(ChainedChoicesModelForm, self).__init__(*args, **kwargs) self.language_code = kwargs.get('language_code', None) self.init_chained_choices(*args, **kwargs) def is_valid(self): if self.language_code: # response is not translated to requested language code :/ # so translation is triggered manually from django.utils.translation import activate activate(self.language_code) return super(ChainedChoicesModelForm, self).is_valid()<|fim▁end|>
from .form_fields import ChainedChoiceField, ChainedModelChoiceField, ChainedModelMultipleChoiceField
<|file_name|>enigma-gui-resizable-window.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python3 from tkinter import * from tkinter.messagebox import * fenetre = Tk() fenetre.title("The Enigma Machine") fenetre.configure(background='white') fenetre.geometry("550x800") class AutoScrollbar(Scrollbar): #create a 'responsive' scrollbar def set(self, lo, hi): if float(lo) <= 0.0 and float(hi) >= 1.0: self.tk.call("grid", "remove", self) else: self.grid() Scrollbar.set(self, lo, hi) def pack(self, **kw): raise(TclError, "can't pack this widget") def place(self, **kw): raise(TclError, "can't grid this widget") vscrollbar = AutoScrollbar(fenetre) vscrollbar.grid(row=0, column=1, sticky=N+S) hscrollbar = AutoScrollbar(fenetre, orient=HORIZONTAL) hscrollbar.grid(row=1, column=0, sticky=E+W) canvas = Canvas(fenetre, yscrollcommand=vscrollbar.set, xscrollcommand=hscrollbar.set) canvas.grid(row=0, column=0, sticky=N+S+E+W) vscrollbar.config(command=canvas.yview) hscrollbar.config(command=canvas.xview) # make the canvas expandable fenetre.grid_rowconfigure(0, weight=1) fenetre.grid_columnconfigure(0, weight=1) # # create canvas contents frame = Frame(canvas, background="white", borderwidth=0) #enigma_image image = PhotoImage(file="enigma.gif") Label(frame, image=image, background="white", borderwidth=0).pack(padx=10, pady=10, side=TOP) #help_button def help(): showinfo("The Enigma Machine Quick Start", "Hello World!\nThis is a quick tutorial on how to use this app!\nFirst, you need to choose the order of the rotors.\nThen you need to set the rotors' position\nYou can finally write your message and encrypt it by pressing the Return key!\nThat's it, you've just encrypt your first enigma message!\n Have fun!") helpButton = Button(frame, text ="Help! Quick Start", command = help, background="white") helpButton.pack(padx=5, pady=5) #spinboxes_choose_rotors frameRotor = Frame(frame, background='white') var4 = StringVar() spinbox = Spinbox(frameRotor, values = ("rotor1=[J,G,D,Q,O,X,U,S,C,A,M,I,F,R,V,T,P,N,E,W,K,B,L,Z,Y,H]", "rotor2=[N,T,Z,P,S,F,B,O,K,M,W,R,C,J,D,I,V,L,A,E,Y,U,X,H,G,Q]", "rotor3=[J,V,I,U,B,H,T,C,D,Y,A,K,E,Q,Z,P,O,S,G,X,N,R,M,W,F,L]"), textvariable=var4, width=44) var4.set("rotor1=[J,G,D,Q,O,X,U,S,C,A,M,I,F,R,V,T,P,N,E,W,K,B,L,Z,Y,H]") spinbox.grid(row=0, column=1) var5 = StringVar() spinbox = Spinbox(frameRotor, values = ("rotor1=[J,G,D,Q,O,X,U,S,C,A,M,I,F,R,V,T,P,N,E,W,K,B,L,Z,Y,H]", "rotor2=[N,T,Z,P,S,F,B,O,K,M,W,R,C,J,D,I,V,L,A,E,Y,U,X,H,G,Q]", "rotor3=[J,V,I,U,B,H,T,C,D,Y,A,K,E,Q,Z,P,O,S,G,X,N,R,M,W,F,L]"), textvariable=var5, width=44) var5.set("rotor2=[N,T,Z,P,S,F,B,O,K,M,W,R,C,J,D,I,V,L,A,E,Y,U,X,H,G,Q]") spinbox.grid(row=1, column=1) var6 = StringVar() spinbox = Spinbox(frameRotor, values = ("rotor1=[J,G,D,Q,O,X,U,S,C,A,M,I,F,R,V,T,P,N,E,W,K,B,L,Z,Y,H]", "rotor2=[N,T,Z,P,S,F,B,O,K,M,W,R,C,J,D,I,V,L,A,E,Y,U,X,H,G,Q]", "rotor3=[J,V,I,U,B,H,T,C,D,Y,A,K,E,Q,Z,P,O,S,G,X,N,R,M,W,F,L]"), textvariable=var6, width=44) var6.set("rotor3=[J,V,I,U,B,H,T,C,D,Y,A,K,E,Q,Z,P,O,S,G,X,N,R,M,W,F,L]") spinbox.grid(row=2, column=1) var7 = StringVar() spinbox = Spinbox(frameRotor, values = ("reflec=[Y,R,U,H,Q,S,L,D,P,X,N,G,O,K,M,I,E,B,F,Z,C,W,V,J,A,T]"), textvariable=var7, width=44) var7.set("reflec=[Y,R,U,H,Q,S,L,D,P,X,N,G,O,K,M,I,E,B,F,Z,C,W,V,J,A,T]") spinbox.grid(row=3, column=1) rotorn1 = Label(frameRotor, text='Slot n°=1:', padx=10, pady=5, background="white") rotorn1.grid(row=0, column=0) rotorn2 = Label(frameRotor, text='Slot n°=2:', padx=10, pady=5, background="white") rotorn2.grid(row=1, column=0) rotorn3 = Label(frameRotor, text='Slot n°=3:', padx=10, pady=5, background="white") rotorn3.grid(row=2, column=0) reflectorn = Label(frameRotor, text='Reflector:', padx=10, pady=5, background="white") reflectorn.grid(row=3, column=0) frameRotor.pack() #frame_to_set_rotor_position frame1 = Frame(frame, borderwidth=0, relief=FLAT, background='white') frame1.pack(side=TOP, padx=10, pady=10) def update1(x): x = int(x) alphabetList = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'] lab1.configure(text='position : {}'.format(alphabetList[x-1])) def update2(x): x = int(x) alphabetList = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'] lab2.configure(text='position : {}'.format(alphabetList[x-1])) def update3(x): x = int(x) alphabetList = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'] lab3.configure(text='position : {}'.format(alphabetList[x-1])) rotor1lab = Label(frame1, text='Rotor 1', padx=10, pady=5, background="white") rotor1lab.grid(row=0, column=0) rotor2lab = Label(frame1, text='Rotor 2', padx=10, pady=5, background="white") rotor2lab.grid(row=0, column=1) rotor3lab = Label(frame1, text='Rotor 3', padx=10, pady=5, background="white") rotor3lab.grid(row=0, column=2) #scales_choose_position var1 = DoubleVar() scale = Scale(frame1, from_=1, to=26, variable = var1, cursor='dot', showvalue=0, command=update1, length= 100, background="white") scale.grid(row=1, column=0, padx=60, pady=10) var2 = DoubleVar() scale = Scale(frame1, from_=1, to=26, variable = var2, cursor='dot', showvalue=0, command=update2, length= 100, background="white") scale.grid(row=1, column=1, padx=60, pady=10) var3 = DoubleVar() scale = Scale(frame1, from_=1, to=26, variable = var3, cursor='dot', showvalue=0, command=update3, length= 100, background="white") scale.grid(row=1, column=2, padx=60, pady=10) lab1 = Label(frame1, background="white") lab1.grid(row=2, column=0) lab2 = Label(frame1, background="white") lab2.grid(row=2, column=1) lab3 = Label(frame1, background="white") lab3.grid(row=2, column=2) #function_code def code(event=None): a = int(var1.get()) b = int(var2.get()) c = int(var3.get()) def rotationRotor(liste1): liste1.append(liste1[0]) del liste1[0] return liste1 def estValide(liste1): if liste1 == []: return False for elt in liste1: if alphabetList.count(elt.upper()) < 1: return False return True sortie = entryvar.get() var4str = var4.get() var4list = list(var4str) var5str = var5.get() var5list = list(var5str) var6str = var6.get() var6list = list(var6str) if var4list[5] == '1': rotor1 = ['J','G','D','Q','O','X','U','S','C','A','M','I','F','R','V','T','P','N','E','W','K','B','L','Z','Y','H'] elif var4list[5] == '2': rotor1 = ['N','T','Z','P','S','F','B','O','K','M','W','R','C','J','D','I','V','L','A','E','Y','U','X','H','G','Q'] elif var4list[5] == '3': rotor1 = ['J','V','I','U','B','H','T','C','D','Y','A','K','E','Q','Z','P','O','S','G','X','N','R','M','W','F','L'] if var5list[5] == '1': rotor2 = ['J','G','D','Q','O','X','U','S','C','A','M','I','F','R','V','T','P','N','E','W','K','B','L','Z','Y','H'] elif var5list[5] == '2': rotor2 = ['N','T','Z','P','S','F','B','O','K','M','W','R','C','J','D','I','V','L','A','E','Y','U','X','H','G','Q'] elif var5list[5] == '3': rotor2 = ['J','V','I','U','B','H','T','C','D','Y','A','K','E','Q','Z','P','O','S','G','X','N','R','M','W','F','L'] if var6list[5] == '1': rotor3 = ['J','G','D','Q','O','X','U','S','C','A','M','I','F','R','V','T','P','N','E','W','K','B','L','Z','Y','H'] elif var6list[5] == '2': rotor3 = ['N','T','Z','P','S','F','B','O','K','M','W','R','C','J','D','I','V','L','A','E','Y','U','X','H','G','Q'] elif var6list[5] == '3': rotor3 = ['J','V','I','U','B','H','T','C','D','Y','A','K','E','Q','Z','P','O','S','G','X','N','R','M','W','F','L'] alphabetList = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',' '] alphabetDict = {'G': 7, 'U': 21, 'T': 20, 'L': 12, 'Y': 25, 'Q': 17, 'V': 22, 'J': 10, 'O': 15, 'W': 23, 'N': 14, 'R': 18, 'Z': 26, 'S': 19, 'X': 24, 'A': 1, 'M': 13, 'E': 5, 'D': 4, 'I': 9, 'F': 6, 'P': 16, 'B': 2, 'H': 8, 'K': 11, 'C': 3} #rotor1 = ['J','G','D','Q','O','X','U','S','C','A','M','I','F','R','V','T','P','N','E','W','K','B','L','Z','Y','H'] #rotor2 = ['N','T','Z','P','S','F','B','O','K','M','W','R','C','J','D','I','V','L','A','E','Y','U','X','H','G','Q'] #rotor3 = ['J','V','I','U','B','H','T','C','D','Y','A','K','E','Q','Z','P','O','S','G','X','N','R','M','W','F','L'] reflector = ['Y', 'R', 'U', 'H', 'Q', 'S', 'L', 'D', 'P', 'X', 'N', 'G', 'O', 'K', 'M', 'I', 'E', 'B', 'F', 'Z', 'C', 'W', 'V', 'J', 'A', 'T'] for loop1 in range(a): rotationRotor(rotor1) for loop2 in range(b): rotationRotor(rotor2) for loop3 in range(c): rotationRotor(rotor3) sortieListe = list(sortie) print(sortieListe) sortieListe = [x for x in sortieListe if x != " "] print(sortieListe) if not estValide(sortieListe): value = StringVar() value.set('Please enter only letters and spaces!') liste.insert(END, value.get()) liste.itemconfig(END, {'bg':'red'}) liste.see("end") elif (var4list[5] == var5list[5] == var6list[5]) or (var4list[5] == var5list[5]) or (var4list[5] == var6list[5]) or (var5list[5] == var6list[5]): value = StringVar() value.set('You can only use a rotor once!') liste.insert(END, value.get()) liste.itemconfig(END, {'bg':'red'}) liste.see("end") else: s = [] for i in range(0,len(sortieListe),1): a = alphabetDict[sortieListe[i].upper()] b = rotor1[a-1] c = alphabetDict[b] d = rotor2[c-1] e = alphabetDict[d] f = rotor3[e-1] g = alphabetDict[f] h = reflector[g-1] j = rotor3.index(h) k = alphabetList[j] l = rotor2.index(k) m = alphabetList[l] n = rotor1.index(m) o = alphabetList[n] s.append(o) if (i+1) % 1 == 0: rotationRotor(rotor1) if (i+1) % 26 == 0: rotationRotor(rotor2) if (i+1) % 676 == 0: rotationRotor(rotor3) value = StringVar() value.set(''.join(s)) liste.insert(END, value.get()) liste.see("end") #text_entry entryvar = StringVar() entry = Entry(frame, textvariable = entryvar, width=50, background="white") entry.focus_set() entry.bind("<Return>", code) entry.pack(padx=10, pady=10) #clear_listbox def clear(): liste.delete(0, END) #button_to_(de)code b1 = Button(frame, text="(de)code", width=10, command=code, background="white") b1.pack() #store_results f1 = Frame(frame) s1 = Scrollbar(f1)<|fim▁hole|>liste.config(yscrollcommand = s1.set) liste.pack(side = LEFT, fill = Y, padx=5, pady=5) s1.pack(side = RIGHT, fill = Y) f1.pack() #button_to_clear_listbox b2 = Button(frame, text="clear list", width=10, command=clear, background='white') b2.pack(padx=5, pady=5) #credits credits = Label(frame, text = "coded with <3 by omnitrogen",background="white") credits.pack(side = BOTTOM, padx=10, pady=10) #quit_button quitButton = Button(frame, text="quit", width=10, command=frame.quit, background='white') quitButton.pack(side = BOTTOM) canvas.create_window(0, 0, anchor=NW, window=frame) frame.update_idletasks() canvas.config(scrollregion=canvas.bbox("all")) mainloop()<|fim▁end|>
liste = Listbox(f1, height=5, width=50, borderwidth=0, background='white') s1.config(command = liste.yview)
<|file_name|>generate.py<|end_file_name|><|fim▁begin|>""" """ import pandas as pd import numpy as np from OfferPandas import Frame, load_offerframe import sys import os import datetime import time def create_fan(energy, reserve, fName=None, return_fan=True, break_tp=False, force_plsr_only=True, verbose=False, *args, **kargs): """ A wrapper which implements some optional filtering arguments to speed up the process, otherwise iterating can take a very large time. Can handle the breakdown as well into trading period pieces. Parameters: ----------- energy: OfferFrame of the energy values reserve: OfferFrame of the reserve values fName: Optional, file to save the resulting fan data to break_tp: Optional, if a save location is specified will break the files into smaller trading period pieces return_fan: Whether to return the Pandas DataFrame containing the Fan. force_plsr_only: Set to True to exclude TWDSR offers *args: Filter arguments, e.g. {"Company": "MRPL"} etc (A dictionary) **kargs: Keyword filter arguments, e.g. Company="MRPL" Returns: -------- fan: The Fan Data as a pandas DataFrame. """ # Set up a time reporting function: begin_time = datetime.datetime.now() filtered_energy = energy.efilter(*args, **kargs) if force_plsr_only: filtered_reserve = reserve.efilter(Product_Type="PLSR", *args, **kargs) else: print """Warning, TWDSR is still a little funky and the visualisation of it in a composite fan diagram can be misleading. Most notably it is difficult to show how it integrates when PLSR is also dispatched\n""" filtered_reserve = reserve.efilter(*args, **kargs) estimate_number = len(filtered_energy[["Node", "Trading_Period_ID"]].drop_duplicates()) * 2 if verbose: print """I'm beginning to create fan curves, I estimate I'll need to do at least %s of these which may take at least %s seconds, hold tight""" % ( estimate_number, estimate_number * 0.008) fan = _create_fan(filtered_energy, filtered_reserve) elapsed_time = datetime.datetime.now() - begin_time number_fans = len(fan[["Node", "Trading_Period_ID", "Reserve_Type", "Reserve Price"]].drop_duplicates()) if verbose: print "I successfully calculated %s fans in %s seconds" % (number_fans, elapsed_time.seconds) if fName: if break_tp: if verbose: print "I'll now begin saving these to individual trading period files" for each in fan["Trading_Period_ID"].unique(): single = fan[fan["Trading_Period_ID"] == each] new_ext = '_' + str(each) + '.csv' single_name = fName.replace('.csv', new_ext) single.to_csv(single_name, header=True, index=False) else: if verbose: print "I'll now begin saving these to a single file" fan.to_csv(fName, header=True, index=False) if return_fan: return fan return None def _create_fan(energy, reserve): """Given an energy and reserve offer frame, PLSR, will construct the full fan curve for these on a station by station, band by band and by reserve type. These fans may then be filtered and visualised using the visualise functionality. Parameters: ----------- energy: An energy offer frame, fans will be created for every permutation in this frame. reserve: The corresponding reserve offer frame. Returns ------- DataFrame: A DataFrame containing the fan object """ station_dates = energy[["Node", "Trading_Period_ID"]].drop_duplicates() fan_assembly = [] for index, station, tpid in station_dates.itertuples(): single_energy = energy.efilter(Trading_Period_ID=tpid, Node=station) for reserve_type in ("FIR", "SIR"): single_reserve = reserve.efilter(Trading_Period_ID=tpid, Node=station, Reserve_Type=reserve_type) fan_assembly.append(station_fan(single_energy, single_reserve, assumed_reserve=reserve_type)) return pd.concat(fan_assembly, ignore_index=True) def station_fan(energy, reserve, assumed_reserve=None): """ Create the fan information for a given station and single reserve type. If multiple reserve types are passed this will fail miserably. Parameters: ----------- energy: Energy OfferFrame containing the information about a single station and trading period reserve: PLSR OfferFrame containing the informaiton about a single station, trading period and reserve type, note TWDSR should work. Returns: -------- DataFrame: A stacked DataFrame object containing the fan data for a particular station. """ energy = energy[energy["Quantity"] > 0] if len(energy) == 0: return None station_metadata = get_station_metadata(energy) # Do an check just in case the reserve is equal to zero. # Will return an energy only version, all reserve set to zero. # Don't need to concat there should only be a single version. if len(reserve) == 0: return create_energy_stack(energy, station_metadata, assumed_reserve=assumed_reserve) if len(reserve["Reserve_Type"].unique()) > 1: raise ValueError("Must only pass a single Reserve Type, you passed\ more than 1") # Create the Energy Stack sorted_energy = energy.sort("Price") energy_stack = incremental_energy_stack( sorted_energy[["Price", "Quantity"]].values) # Get the nameplate capacity of the station, all values are duplicates # so we just take the first one. Set initial remaining capacity equal to # the nameplate capacity nameplate_capacity = remaining_capacity = energy["Max_Output"].values[0] # Filter Reserve Offers, create a band stack for each pairing nonzero_reserve = reserve[reserve["Quantity"] > 0] if len(nonzero_reserve) == 0: return create_energy_stack(energy, station_metadata, assumed_reserve=assumed_reserve) # Do a check for zero priced reserve offers here, # If there aren't any then add one to the band stacks call. # Add a zero reserve stack array as it will have no impact upon # The actual fan created, note this may create additional fans # But the tradeoff is a small one. band_stacks = [] if 0. not in nonzero_reserve["Price"]: band_stacks.append(create_energy_stack(energy, station_metadata, assumed_reserve=assumed_reserve)) for (index, percent, price, quantity, reserve_type, product_type ) in nonzero_reserve[["Percent", "Price", "Quantity", "Reserve_Type", "Product_Type"]].itertuples(): # Check for TWDSR, set percent to essentially infinity. if product_type == "TWDSR": percent = 1000000 reserve_stack = feasible_reserve_region(energy_stack, price, quantity, percent, nameplate_capacity, remaining_capacity, product_type) # Update the remaining capacity remaining_capacity -= quantity # Create a Band DataFrame full_metadata = update_metadata(station_metadata, reserve_type, product_type, percent) band_stacks.append(band_dataframe(reserve_stack, full_metadata)) return pd.concat(band_stacks) def create_energy_stack(energy, station_metadata, assumed_reserve=None): """ Creates an energy version of the stack with zero reserve offers and zero prices. Due to the way the aggregations work this step is required or units which offer reserve at high prices have their energy offers excluded from the low priced ones Parameters: ----------- energy: Energy offers for that station in question. station_metadata: Information about the station assumed_reserve: FIR or SIR, is repeated more than once. Returns: -------- DataFrame: A DataFrame containing an energy only incremental DF with asscociated metadata """ energy_version = energy_only(energy) full_metadata = update_metadata(station_metadata, assumed_reserve, "PLSR", 0) return band_dataframe(energy_version, full_metadata) def energy_only(energy): """ Mimics the fan curve for an energy only station by setting all reserve poritons of the stack to zero. Parameters: ----------- energy: DataFrame of the energy offers Returns: -------- energy_version: Numpy array containing zeros for reserve portions but the full energy information. """ sorted_energy = energy.sort("Price") energy_stack = incremental_energy_stack( sorted_energy[["Price", "Quantity"]].values) length = energy_stack.shape[0] energy_version = np.zeros((length, 8)) energy_version[:, :4] = energy_stack return energy_version def update_metadata(station_metadata, reserve_type, product_type, percent): """ Takes the metadata dictionary and appends some new key value pairs to it. """ full_metadata = station_metadata.copy() full_metadata["Reserve_Type"] = reserve_type full_metadata["Product_Type"] = product_type full_metadata["Reserve_Percent"] = percent return full_metadata def band_dataframe(full_stack, full_metadata): """ Creates a DataFrame for a single band taking into account the full stack along with the metadata for it. Returns this DataFrame which may then be added together to create the station frame. """ columns = ["Energy Price", "Energy Quantity", "Incremental Energy Quantity", "Cumulative Energy Quantity", "Reserve Price", "Reserve Quantity", "Incremental Reserve Quantity", "Cumulative Reserve Quantity"] # Create the DataFrame for a single band df = pd.DataFrame(full_stack, columns=columns) # Add the metadata for key, value in full_metadata.iteritems(): df[key] = value return df def get_station_metadata(offer_data): """ Look into the station offer data and grab out some metadata which will be useful in applying at the end, do not want to work with concatting files together. Inputs: ------- offer_data: A OfferPandas.Frame energy offer frame (preferred) from which to extract useful metadata. Returns: -------- meta_data: Dictionary, contains metadata information about the station. """ excluded_columns = ("Band", "Price", "Quantity", "Product_Type", "Reserve_Type", "Is_Injection", "Is_Hvdc", "Created_Date", "Last_Amended_Date") meta_data = {item: offer_data[item][offer_data.index[0]] for item in offer_data.columns if item not in excluded_columns} return meta_data def incremental_energy_stack(pairs): """ Takes an array of price quantity pairs and returns a numpy array of this transformed into a single increment version (using step size 1) Inputs: ------- pairs: numpy array of Nx2 dimension containing price and quantity pairs. Returns: -------- stack: a (M+1x4) array where M is the sum of the quantities offered in the pairs input. Columns are (Price, Quantity, Incremental Quantity, Cumulative Quantity) """ if pairs.shape[1] != 2: raise ValueError("Shape of the array passed to the function must\ be a Nx2 array, current size is %sx%s" % pairs.shape) partial_arrays = [np.zeros((1,4))] for p, q in pairs: # Incremental Capacity partial = np.zeros((np.ceil(q), 4)) partial[:,2] = np.ones(np.ceil(q)) if np.ceil(q) != q: partial[-1, 2] = q % 1 # Price and Quantity partial[:,0] = p partial[:,1] = q partial_arrays.append(partial) full_array = np.concatenate(partial_arrays) full_array[:,3] = np.cumsum(full_array[:,2]) return full_array def feasible_reserve_region(stack, res_price, res_quantity, res_percent, nameplate_capacity, remaining_capacity, product_type): """ Create a feasible region array with information about energy and reserve prices for a single band. This array contains information on an incremental fashion regarding the energy and reserve tradeoff. Ideally should keep all of the data together in one place: Parameters: ----------- stack: The full energy stack as previously calculated. res_price: The band reserve price res_quantity: Maximum band reserve quantity res_percent: The percentage for the reserve band, note TWDSR will be arbitrarily high nameplate_capacity: The original capacity (nameplate) of the unit remaining_capacity: Subtracting the reserve bands at lower price quantities from the nameplate capacity to leave a residual quantity reserve_type: string, either "PLSR" or "TWDSR". indicates some special behaviour for "TWDSR". Returns: -------- reserve_coupling: numpy array of energy and reserve values. """ length = stack.shape[0] # Update the capacity line to be of the size of the full capacity but # shifted to reflect what capacity has already been used by cheaper reserve # offers. utilised_capacity = nameplate_capacity - remaining_capacity capacity_line = nameplate_capacity - stack[:,3] capacity_line = np.where(capacity_line - utilised_capacity <= 0, 0, capacity_line - utilised_capacity) # Create a line due to the proportionality constraint. # Note percentages are reported as is... # Still need to figure out how to do TWD here... reserve_line = stack[:,3] * res_percent /100. reserve_line = np.where(reserve_line <= res_quantity, reserve_line, res_quantity) # Adjust for the modified capacity line reserve_line = np.where(reserve_line <= capacity_line, reserve_line, capacity_line) # Create an incremental reserve line as well incremental_reserve_line = np.zeros(len(reserve_line)) incremental_reserve_line[1:] = reserve_line[1:] - reserve_line[:-1] # Create a new array and add the values reserve_coupling = np.zeros((length, 8)) reserve_coupling[:, :4] = stack reserve_coupling[:, 4] = res_price reserve_coupling[:, 5] = res_quantity reserve_coupling[:, 6] = incremental_reserve_line reserve_coupling[:, 7] = reserve_line return reserve_coupling if __name__ == '__main__':<|fim▁hole|><|fim▁end|>
pass
<|file_name|>RadioManagement.py<|end_file_name|><|fim▁begin|>from PyQt4.QtCore import * from PyQt4 import QtGui class RadioManagement (): def __init__ (self, radioCol, gridLayout): self.radioGroup = QtGui.QButtonGroup() # To store radio buttons. self.radioCol = radioCol self.gridLayout = gridLayout def initDelAndMovButtons (self, vLayout): # Add hbox for edit buttons. self.editHBox = QtGui.QHBoxLayout() self.editHBox.addStretch (1) vLayout.addLayout (self.editHBox) button = QtGui.QPushButton ("&Delete", self) self.editHBox.addWidget (button) self.connect (button, SIGNAL ("clicked()"), self.deleteButtonClicked) button = QtGui.QPushButton ("Move &Up", self) self.editHBox.addWidget (button) self.connect (button, SIGNAL ("clicked()"), self.moveUpButtonClicked) button = QtGui.QPushButton ("Move Do&wn", self) self.editHBox.addWidget (button) self.connect (button, SIGNAL ("clicked()"), self.moveDownButtonClicked) def buildRow (self, gridLayout, row = 0): # Create the radio button for editing of the app. radio = QtGui.QRadioButton (str (row), self) gridLayout.addWidget (radio, row, self.radioCol) self.radioGroup.addButton(radio, row) def setCheckedRadioButtonByRow (self, row): for radio in self.radioGroup.buttons(): if radio.text() == str (row): radio.setChecked (True) return # Radio button not found. raise RuntimeError ("Could not find radio at row: " + str (row)) def clearGridLayout (self): # This function removes all of the automatically generated # buttons and such from the layout. # Remove the radio buttons fromt "radioGroup". for buttonEntry in self.radioGroup.buttons(): self.radioGroup.removeButton (buttonEntry) for i in range (self.gridLayout.rowCount()): for j in range (self.gridLayout.columnCount()): widgetItem = self.gridLayout.itemAtPosition (i, j) self.deleteWidgetItem (widgetItem) def getWidgetAtCheckedRow (self, column): checkedButtonId = self.radioGroup.checkedId() if checkedButtonId == -1: # No radio buttons are checked. return None # widged at "checkedButtonId"'s row. return self.gridLayout.itemAtPosition (checkedButtonId, column).widget() def deleteRow (self, rowNum): rowCount = self.getRowCount() # What we'll actually do, is leave the radio buttons in tact, but # delete all the other widgets in the row. Then we'll move everything # else up, and finally delete the last radio button. for i in range (self.gridLayout.columnCount()): # Skip the radio button's column. if i == self.radioCol: continue widgetItem = self.gridLayout.itemAtPosition (rowNum, i) # Delete the widget. self.deleteWidgetItem (widgetItem) # Next, move everything up row by row. +1 is to offset from the row we just deleted. for i in range (rowNum + 1, rowCount + 1): for j in range (self.gridLayout.columnCount()): if j == self.radioCol: continue widgetItem = self.gridLayout.itemAtPosition (i, j) self.addWidgetItem (widgetItem, i - 1, j) <|fim▁hole|> # Finally, delete the last row. for i in range (self.gridLayout.columnCount()): widgetItem = self.gridLayout.itemAtPosition (rowCount, i) # Delete the widget. self.deleteWidgetItem (widgetItem) self.gridLayout.invalidate() def swapRows (self, row1, row2): row1Widgets = {} for i in range (self.gridLayout.columnCount()): widgetItem1 = self.gridLayout.itemAtPosition (row1, i) widgetItem2 = self.gridLayout.itemAtPosition (row2, i) if widgetItem1 == None: continue a = widgetItem1.widget() b = widgetItem2.widget() # Is this the radio button widget? if i == self.radioCol: # We don't want to move the radio buttons, but # we do want change which is checked, if applicable. if widgetItem1.widget().isChecked(): widgetItem2.widget().setChecked (True) elif widgetItem2.widget().isChecked(): widgetItem1.widget().setChecked (True) continue self.addWidgetItem (widgetItem2, row1, i) self.addWidgetItem (widgetItem1, row2, i) def deleteWidgetItem (self, widgetItem): # If the item is actually empty. if widgetItem == None: return # Check if it is a widget (and not a layout). widget = widgetItem.widget() if widget != None: # Delete the widget item. widgetItem.widget().setParent (None) return # No? then it must be a layout. layout = widgetItem.layout() if type (layout) != QtGui.QGridLayout: for i in range (len (layout)): self.deleteWidgetItem (layout.itemAt (i)) else: # We'll just be assuming a grid layout here, since there # isn't any convinient method to do otherwise. for i in range (layout.rowCount()): for j in range (layout.columnCount()): self.deleteWidgetItem (layout.itemAtPosition (i, j)) # Finally, delete the empty layout. layout.setParent (None) def addWidgetItem (self, widgetItem, posX, posY): if widgetItem == None: return widget = widgetItem.widget() if widget != None: # Looks like we're processing a widget. self.gridLayout.addWidget (widget, posX, posY) return # We otherwise assume it's a layout. layout = widgetItem.layout() # Bug in PyQt. Causes segfault if I do not do this. # I guess I /could/ go and fix it in the source... layout.setParent (None) self.gridLayout.addLayout (layout, posX, posY) def getRowCount (self): # Unfortunately, gridLayout.rowCount() is unreliable for getting the number # rows in the grid, so we need an alternative method. return len (self.radioGroup.buttons()) def getRowRange (self): # Return the range of values from 1 (first param) to the number of rows, # include the final value (achieved by +1 offset). return range (1, len (self.radioGroup.buttons()) + 1) def deleteButtonClicked (self): pass def moveUpButtonClicked (self): # We are moving up, so we'll swap with the row above us. checkedButtonId = self.radioGroup.checkedId() if checkedButtonId == -1: print "No item selected!" return previousButtonRow = checkedButtonId - 1 if previousButtonRow <= 0: print "Row already at highest position!" return self.swapRows (checkedButtonId, previousButtonRow) def moveDownButtonClicked (self): checkedButtonId = self.radioGroup.checkedId() if checkedButtonId == -1: print "No item selected!" return nextButtonRow = checkedButtonId + 1 if nextButtonRow > len (self.radioGroup.buttons()): print "Row already at lowest position!" return self.swapRows (checkedButtonId, nextButtonRow) def deleteButtonClicked (self): checkedButtonId = self.radioGroup.checkedId() if checkedButtonId == -1: print "No item selected!" return self.deleteRow (checkedButtonId)<|fim▁end|>
# We'll also need to remove the radio button's reference from "radioGroup". lastRadioButon = self.gridLayout.itemAtPosition (rowCount, self.radioCol) self.radioGroup.removeButton (lastRadioButon.widget())
<|file_name|>binaryExpr.js<|end_file_name|><|fim▁begin|>// Copyright 2012 Google Inc. All Rights Reserved. /** * @fileoverview A class representing operations on binary expressions. */ goog.provide('wgxpath.BinaryExpr'); goog.require('wgxpath.DataType'); goog.require('wgxpath.Expr'); goog.require('wgxpath.Node'); /** * Constructor for BinaryExpr. * * @param {!wgxpath.BinaryExpr.Op} op A binary operator. * @param {!wgxpath.Expr} left The left hand side of the expression. * @param {!wgxpath.Expr} right The right hand side of the expression. * @extends {wgxpath.Expr} * @constructor */ wgxpath.BinaryExpr = function(op, left, right) { var opCast = /** @type {!wgxpath.BinaryExpr.Op_} */ (op); wgxpath.Expr.call(this, opCast.dataType_); /** * @private * @type {!wgxpath.BinaryExpr.Op_} */ this.op_ = opCast; /** * @private * @type {!wgxpath.Expr} */ this.left_ = left; /** * @private * @type {!wgxpath.Expr} */ this.right_ = right; this.setNeedContextPosition(left.doesNeedContextPosition() || right.doesNeedContextPosition()); this.setNeedContextNode(left.doesNeedContextNode() || right.doesNeedContextNode()); // Optimize [@id="foo"] and [@name="bar"] if (this.op_ == wgxpath.BinaryExpr.Op.EQUAL) { if (!right.doesNeedContextNode() && !right.doesNeedContextPosition() && right.getDataType() != wgxpath.DataType.NODESET && right.getDataType() != wgxpath.DataType.VOID && left.getQuickAttr()) { this.setQuickAttr({ name: left.getQuickAttr().name, valueExpr: right}); } else if (!left.doesNeedContextNode() && !left.doesNeedContextPosition() && left.getDataType() != wgxpath.DataType.NODESET && left.getDataType() != wgxpath.DataType.VOID && right.getQuickAttr()) { this.setQuickAttr({ name: right.getQuickAttr().name, valueExpr: left}); } } }; goog.inherits(wgxpath.BinaryExpr, wgxpath.Expr); /** * Performs comparison between the left hand side and the right hand side. * * @private * @param {function((string|number|boolean), (string|number|boolean))} * comp A comparison function that takes two parameters. * @param {!wgxpath.Expr} lhs The left hand side of the expression. * @param {!wgxpath.Expr} rhs The right hand side of the expression. * @param {!wgxpath.Context} ctx The context to perform the comparison in. * @param {boolean=} opt_equChk Whether the comparison checks for equality. * @return {boolean} True if comp returns true, false otherwise. */ wgxpath.BinaryExpr.compare_ = function(comp, lhs, rhs, ctx, opt_equChk) { var left = lhs.evaluate(ctx); var right = rhs.evaluate(ctx); var lIter, rIter, lNode, rNode; if (left instanceof wgxpath.NodeSet && right instanceof wgxpath.NodeSet) { lIter = left.iterator(); for (lNode = lIter.next(); lNode; lNode = lIter.next()) { rIter = right.iterator(); for (rNode = rIter.next(); rNode; rNode = rIter.next()) { if (comp(wgxpath.Node.getValueAsString(lNode), wgxpath.Node.getValueAsString(rNode))) { return true; } } } return false; } if ((left instanceof wgxpath.NodeSet) || (right instanceof wgxpath.NodeSet)) { var nodeset, primitive; if ((left instanceof wgxpath.NodeSet)) { nodeset = left, primitive = right; } else { nodeset = right, primitive = left; } var iter = nodeset.iterator(); var type = typeof primitive; for (var node = iter.next(); node; node = iter.next()) { var stringValue; switch (type) { case 'number': stringValue = wgxpath.Node.getValueAsNumber(node); break; case 'boolean': stringValue = wgxpath.Node.getValueAsBool(node); break; case 'string': stringValue = wgxpath.Node.getValueAsString(node); break; default: throw Error('Illegal primitive type for comparison.'); } if (comp(stringValue, /** @type {(string|number|boolean)} */ (primitive))) { return true; } } return false; } if (opt_equChk) { if (typeof left == 'boolean' || typeof right == 'boolean') { return comp(!!left, !!right); } if (typeof left == 'number' || typeof right == 'number') { return comp(+left, +right); } return comp(left, right); } return comp(+left, +right); }; /** * @override * @return {(boolean|number)} The boolean or number result. */ wgxpath.BinaryExpr.prototype.evaluate = function(ctx) { return this.op_.evaluate_(this.left_, this.right_, ctx); }; /** * @override */ wgxpath.BinaryExpr.prototype.toString = function() { var text = 'Binary Expression: ' + this.op_; text += wgxpath.Expr.indent(this.left_); text += wgxpath.Expr.indent(this.right_); return text; }; /** * A binary operator. * * @param {string} opString The operator string. * @param {number} precedence The precedence when evaluated. * @param {!wgxpath.DataType} dataType The dataType to return when evaluated. * @param {function(!wgxpath.Expr, !wgxpath.Expr, !wgxpath.Context)} * evaluate An evaluation function. * @constructor * @private */ wgxpath.BinaryExpr.Op_ = function(opString, precedence, dataType, evaluate) { /** * @private * @type {string} */ this.opString_ = opString; /** * @private * @type {number} */ this.precedence_ = precedence; /** * @private * @type {!wgxpath.DataType} */ this.dataType_ = dataType; /** * @private * @type {function(!wgxpath.Expr, !wgxpath.Expr, !wgxpath.Context)} */ this.evaluate_ = evaluate; }; /** * Returns the precedence for the operator. * * @return {number} The precedence. */ wgxpath.BinaryExpr.Op_.prototype.getPrecedence = function() { return this.precedence_; }; /** * @override */ wgxpath.BinaryExpr.Op_.prototype.toString = function() { return this.opString_; }; /** * A mapping from operator strings to operator objects. * * @private * @type {!Object.<string, !wgxpath.BinaryExpr.Op>} */ wgxpath.BinaryExpr.stringToOpMap_ = {}; /** * Creates a binary operator. * * @param {string} opString The operator string. * @param {number} precedence The precedence when evaluated. * @param {!wgxpath.DataType} dataType The dataType to return when evaluated. * @param {function(!wgxpath.Expr, !wgxpath.Expr, !wgxpath.Context)} * evaluate An evaluation function. * @return {!wgxpath.BinaryExpr.Op} A binary expression operator. * @private */ wgxpath.BinaryExpr.createOp_ = function(opString, precedence, dataType, evaluate) { if (opString in wgxpath.BinaryExpr.stringToOpMap_) { throw new Error('Binary operator already created: ' + opString); } // The upcast and then downcast for the JSCompiler. var op = /** @type {!Object} */ (new wgxpath.BinaryExpr.Op_( opString, precedence, dataType, evaluate)); op = /** @type {!wgxpath.BinaryExpr.Op} */ (op); wgxpath.BinaryExpr.stringToOpMap_[op.toString()] = op; return op; }; <|fim▁hole|> * * @param {string} opString The opString. * @return {!wgxpath.BinaryExpr.Op} The operator. */ wgxpath.BinaryExpr.getOp = function(opString) { return wgxpath.BinaryExpr.stringToOpMap_[opString] || null; }; /** * Binary operator enumeration. * * @enum {{getPrecedence: function(): number}} */ wgxpath.BinaryExpr.Op = { DIV: wgxpath.BinaryExpr.createOp_('div', 6, wgxpath.DataType.NUMBER, function(left, right, ctx) { return left.asNumber(ctx) / right.asNumber(ctx); }), MOD: wgxpath.BinaryExpr.createOp_('mod', 6, wgxpath.DataType.NUMBER, function(left, right, ctx) { return left.asNumber(ctx) % right.asNumber(ctx); }), MULT: wgxpath.BinaryExpr.createOp_('*', 6, wgxpath.DataType.NUMBER, function(left, right, ctx) { return left.asNumber(ctx) * right.asNumber(ctx); }), PLUS: wgxpath.BinaryExpr.createOp_('+', 5, wgxpath.DataType.NUMBER, function(left, right, ctx) { return left.asNumber(ctx) + right.asNumber(ctx); }), MINUS: wgxpath.BinaryExpr.createOp_('-', 5, wgxpath.DataType.NUMBER, function(left, right, ctx) { return left.asNumber(ctx) - right.asNumber(ctx); }), LESSTHAN: wgxpath.BinaryExpr.createOp_('<', 4, wgxpath.DataType.BOOLEAN, function(left, right, ctx) { return wgxpath.BinaryExpr.compare_(function(a, b) {return a < b;}, left, right, ctx); }), GREATERTHAN: wgxpath.BinaryExpr.createOp_('>', 4, wgxpath.DataType.BOOLEAN, function(left, right, ctx) { return wgxpath.BinaryExpr.compare_(function(a, b) {return a > b;}, left, right, ctx); }), LESSTHAN_EQUAL: wgxpath.BinaryExpr.createOp_( '<=', 4, wgxpath.DataType.BOOLEAN, function(left, right, ctx) { return wgxpath.BinaryExpr.compare_(function(a, b) {return a <= b;}, left, right, ctx); }), GREATERTHAN_EQUAL: wgxpath.BinaryExpr.createOp_('>=', 4, wgxpath.DataType.BOOLEAN, function(left, right, ctx) { return wgxpath.BinaryExpr.compare_(function(a, b) {return a >= b;}, left, right, ctx); }), EQUAL: wgxpath.BinaryExpr.createOp_('=', 3, wgxpath.DataType.BOOLEAN, function(left, right, ctx) { return wgxpath.BinaryExpr.compare_(function(a, b) {return a == b;}, left, right, ctx, true); }), NOT_EQUAL: wgxpath.BinaryExpr.createOp_('!=', 3, wgxpath.DataType.BOOLEAN, function(left, right, ctx) { return wgxpath.BinaryExpr.compare_(function(a, b) {return a != b}, left, right, ctx, true); }), AND: wgxpath.BinaryExpr.createOp_('and', 2, wgxpath.DataType.BOOLEAN, function(left, right, ctx) { return left.asBool(ctx) && right.asBool(ctx); }), OR: wgxpath.BinaryExpr.createOp_('or', 1, wgxpath.DataType.BOOLEAN, function(left, right, ctx) { return left.asBool(ctx) || right.asBool(ctx); }) };<|fim▁end|>
/** * Returns the operator with this opString or null if none.
<|file_name|>uuidhelpers.js<|end_file_name|><|fim▁begin|>// Javascript helper functions for parsing and displaying UUIDs in the MongoDB shell. // This is a temporary solution until SERVER-3153 is implemented. // To create BinData values corresponding to the various driver encodings use: // var s = "{00112233-4455-6677-8899-aabbccddeeff}"; // var uuid = UUID(s); // new Standard encoding // var juuid = JUUID(s); // JavaLegacy encoding // var csuuid = CSUUID(s); // CSharpLegacy encoding // var pyuuid = PYUUID(s); // PythonLegacy encoding // To convert the various BinData values back to human readable UUIDs use: // uuid.toUUID() => 'UUID("00112233-4455-6677-8899-aabbccddeeff")' // juuid.ToJUUID() => 'JUUID("00112233-4455-6677-8899-aabbccddeeff")' // csuuid.ToCSUUID() => 'CSUUID("00112233-4455-6677-8899-aabbccddeeff")' // pyuuid.ToPYUUID() => 'PYUUID("00112233-4455-6677-8899-aabbccddeeff")' // With any of the UUID variants you can use toHexUUID to echo the raw BinData with subtype and hex string: // uuid.toHexUUID() => 'HexData(4, "00112233-4455-6677-8899-aabbccddeeff")' // juuid.toHexUUID() => 'HexData(3, "77665544-3322-1100-ffee-ddccbbaa9988")' // csuuid.toHexUUID() => 'HexData(3, "33221100-5544-7766-8899-aabbccddeeff")' // pyuuid.toHexUUID() => 'HexData(3, "00112233-4455-6677-8899-aabbccddeeff")' function HexToBase64(hex) { var base64Digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; var base64 = ""; var group; for (var i = 0; i < 30; i += 6) { group = parseInt(hex.substr(i, 6), 16); base64 += base64Digits[(group >> 18) & 0x3f]; base64 += base64Digits[(group >> 12) & 0x3f]; base64 += base64Digits[(group >> 6) & 0x3f]; base64 += base64Digits[group & 0x3f]; } group = parseInt(hex.substr(30, 2), 16); base64 += base64Digits[(group >> 2) & 0x3f]; base64 += base64Digits[(group << 4) & 0x3f]; base64 += "=="; return base64; } function Base64ToHex(base64) { var base64Digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; var hexDigits = "0123456789abcdef"; var hex = ""; for (var i = 0; i < 24; ) { var e1 = base64Digits.indexOf(base64[i++]); var e2 = base64Digits.indexOf(base64[i++]); var e3 = base64Digits.indexOf(base64[i++]); var e4 = base64Digits.indexOf(base64[i++]); var c1 = (e1 << 2) | (e2 >> 4); var c2 = ((e2 & 15) << 4) | (e3 >> 2); var c3 = ((e3 & 3) << 6) | e4; hex += hexDigits[c1 >> 4]; hex += hexDigits[c1 & 15]; if (e3 != 64) { hex += hexDigits[c2 >> 4]; hex += hexDigits[c2 & 15]; } if (e4 != 64) { hex += hexDigits[c3 >> 4]; hex += hexDigits[c3 & 15]; } } return hex; } function UUID(uuid) { var hex = uuid.replace(/[{}-]/g, ""); // remove extra characters var base64 = HexToBase64(hex); return new BinData(4, base64); // new subtype 4 } function JUUID(uuid) { var hex = uuid.replace(/[{}-]/g, ""); // remove extra characters var msb = hex.substr(0, 16); var lsb = hex.substr(16, 16); msb = msb.substr(14, 2) + msb.substr(12, 2) + msb.substr(10, 2) + msb.substr(8, 2) + msb.substr(6, 2) + msb.substr(4, 2) + msb.substr(2, 2) + msb.substr(0, 2); lsb = lsb.substr(14, 2) + lsb.substr(12, 2) + lsb.substr(10, 2) + lsb.substr(8, 2) + lsb.substr(6, 2) + lsb.substr(4, 2) + lsb.substr(2, 2) + lsb.substr(0, 2); hex = msb + lsb; var base64 = HexToBase64(hex); return new BinData(3, base64); } function CSUUID(uuid) { var hex = uuid.replace(/[{}-]/g, ""); // remove extra characters var a = hex.substr(6, 2) + hex.substr(4, 2) + hex.substr(2, 2) + hex.substr(0, 2); var b = hex.substr(10, 2) + hex.substr(8, 2); var c = hex.substr(14, 2) + hex.substr(12, 2); var d = hex.substr(16, 16); hex = a + b + c + d; var base64 = HexToBase64(hex); return new BinData(3, base64); } function PYUUID(uuid) { var hex = uuid.replace(/[{}-]/g, ""); // remove extra characters var base64 = HexToBase64(hex); return new BinData(3, base64); } BinData.prototype.toUUID = function () { var hex = Base64ToHex(this.base64()); // don't use BinData's hex function because it has bugs in older versions of the shell var uuid = hex.substr(0, 8) + '-' + hex.substr(8, 4) + '-' + hex.substr(12, 4) + '-' + hex.substr(16, 4) + '-' + hex.substr(20, 12); return 'UUID("' + uuid + '")'; } BinData.prototype.toJUUID = function () { var hex = Base64ToHex(this.base64()); // don't use BinData's hex function because it has bugs in older versions of the shell var msb = hex.substr(0, 16); var lsb = hex.substr(16, 16); msb = msb.substr(14, 2) + msb.substr(12, 2) + msb.substr(10, 2) + msb.substr(8, 2) + msb.substr(6, 2) + msb.substr(4, 2) + msb.substr(2, 2) + msb.substr(0, 2); lsb = lsb.substr(14, 2) + lsb.substr(12, 2) + lsb.substr(10, 2) + lsb.substr(8, 2) + lsb.substr(6, 2) + lsb.substr(4, 2) + lsb.substr(2, 2) + lsb.substr(0, 2); hex = msb + lsb; var uuid = hex.substr(0, 8) + '-' + hex.substr(8, 4) + '-' + hex.substr(12, 4) + '-' + hex.substr(16, 4) + '-' + hex.substr(20, 12); return 'JUUID("' + uuid + '")'; } BinData.prototype.toCSUUID = function () { var hex = Base64ToHex(this.base64()); // don't use BinData's hex function because it has bugs in older versions of the shell var a = hex.substr(6, 2) + hex.substr(4, 2) + hex.substr(2, 2) + hex.substr(0, 2); var b = hex.substr(10, 2) + hex.substr(8, 2); var c = hex.substr(14, 2) + hex.substr(12, 2); var d = hex.substr(16, 16); hex = a + b + c + d; var uuid = hex.substr(0, 8) + '-' + hex.substr(8, 4) + '-' + hex.substr(12, 4) + '-' + hex.substr(16, 4) + '-' + hex.substr(20, 12); return 'CSUUID("' + uuid + '")'; } BinData.prototype.toPYUUID = function () { var hex = Base64ToHex(this.base64()); // don't use BinData's hex function because it has bugs var uuid = hex.substr(0, 8) + '-' + hex.substr(8, 4) + '-' + hex.substr(12, 4) + '-' + hex.substr(16, 4) + '-' + hex.substr(20, 12); return 'PYUUID("' + uuid + '")'; } BinData.prototype.toHexUUID = function () { var hex = Base64ToHex(this.base64()); // don't use BinData's hex function because it has bugs var uuid = hex.substr(0, 8) + '-' + hex.substr(8, 4) + '-' + hex.substr(12, 4) + '-' + hex.substr(16, 4) + '-' + hex.substr(20, 12); return 'HexData(' + this.subtype() + ', "' + uuid + '")'; }<|fim▁hole|> var juuid = JUUID(s); var csuuid = CSUUID(s); var pyuuid = PYUUID(s); print(uuid.toUUID()); print(juuid.toJUUID()); print(csuuid.toCSUUID()); print(pyuuid.toPYUUID()); print(uuid.toHexUUID()); print(juuid.toHexUUID()); print(csuuid.toHexUUID()); print(pyuuid.toHexUUID()); }<|fim▁end|>
function TestUUIDHelperFunctions() { var s = "{00112233-4455-6677-8899-aabbccddeeff}"; var uuid = UUID(s);
<|file_name|>lis.py<|end_file_name|><|fim▁begin|>################ Lispy: Scheme Interpreter in Python ## (c) Peter Norvig, 2010-14; See http://norvig.com/lispy.html ################ Types from __future__ import division Symbol = str # A Lisp Symbol is implemented as a Python str List = list # A Lisp List is implemented as a Python list Number = (int, float) # A Lisp Number is implemented as a Python int or float ################ Parsing: parse, tokenize, and read_from_tokens def parse(program): "Read a Scheme expression from a string." return read_from_tokens(tokenize(program)) def tokenize(s): "Convert a string into a list of tokens." return s.replace('(',' ( ').replace(')',' ) ').split() def read_from_tokens(tokens): "Read an expression from a sequence of tokens." if len(tokens) == 0: raise SyntaxError('unexpected EOF while reading') token = tokens.pop(0) if '(' == token: L = [] while tokens[0] != ')': L.append(read_from_tokens(tokens)) tokens.pop(0) # pop off ')' return L elif ')' == token: raise SyntaxError('unexpected )') else: return atom(token) def atom(token): "Numbers become numbers; every other token is a symbol." try: return int(token) except ValueError: try: return float(token) except ValueError: return Symbol(token) ################ Environments def standard_env(): "An environment with some Scheme standard procedures." import math, operator as op env = Env() env.update(vars(math)) # sin, cos, sqrt, pi, ...<|fim▁hole|> '+':op.add, '-':op.sub, '*':op.mul, '/':op.div, '>':op.gt, '<':op.lt, '>=':op.ge, '<=':op.le, '=':op.eq, 'abs': abs, 'append': op.add, 'apply': apply, 'begin': lambda *x: x[-1], 'car': lambda x: x[0], 'cdr': lambda x: x[1:], 'cons': lambda x,y: [x] + y, 'eq?': op.is_, 'equal?': op.eq, 'length': len, 'list': lambda *x: list(x), 'list?': lambda x: isinstance(x,list), 'map': map, 'max': max, 'min': min, 'not': op.not_, 'null?': lambda x: x == [], 'number?': lambda x: isinstance(x, Number), 'procedure?': callable, 'round': round, 'symbol?': lambda x: isinstance(x, Symbol), }) return env class Env(dict): "An environment: a dict of {'var':val} pairs, with an outer Env." def __init__(self, parms=(), args=(), outer=None): self.update(zip(parms, args)) self.outer = outer def find(self, var): "Find the innermost Env where var appears." return self if (var in self) else self.outer.find(var) global_env = standard_env() ################ Interaction: A REPL def repl(prompt='lis.py> '): "A prompt-read-eval-print loop." while True: val = eval(parse(raw_input(prompt))) if val is not None: print(lispstr(val)) def lispstr(exp): "Convert a Python object back into a Lisp-readable string." if isinstance(exp, list): return '(' + ' '.join(map(lispstr, exp)) + ')' else: return str(exp) ################ Procedures class Procedure(object): "A user-defined Scheme procedure." def __init__(self, parms, body, env): self.parms, self.body, self.env = parms, body, env def __call__(self, *args): return eval(self.body, Env(self.parms, args, self.env)) ################ eval def eval(x, env=global_env): "Evaluate an expression in an environment." if isinstance(x, Symbol): # variable reference return env.find(x)[x] elif not isinstance(x, List): # constant literal return x elif x[0] == 'quote': # (quote exp) (_, exp) = x return exp elif x[0] == 'if': # (if test conseq alt) (_, test, conseq, alt) = x exp = (conseq if eval(test, env) else alt) return eval(exp, env) elif x[0] == 'define': # (define var exp) (_, var, exp) = x env[var] = eval(exp, env) elif x[0] == 'set!': # (set! var exp) (_, var, exp) = x env.find(var)[var] = eval(exp, env) elif x[0] == 'lambda': # (lambda (var...) body) (_, parms, body) = x return Procedure(parms, body, env) else: # (proc arg...) proc = eval(x[0], env) args = [eval(exp, env) for exp in x[1:]] return proc(*args)<|fim▁end|>
env.update({
<|file_name|>dev.py<|end_file_name|><|fim▁begin|>from settings.common import Common<|fim▁hole|> 'default': { 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'ffrpg.sql', # Or path to database file if using sqlite3. # The following settings are not used with sqlite3: 'USER': '', 'PASSWORD': '', 'HOST': '', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP. 'PORT': '', # Set to empty string for default. } }<|fim▁end|>
class Dev(Common): DATABASES = {
<|file_name|>kart_racer.py<|end_file_name|><|fim▁begin|>#!/env/python3 import sys import argparse import os import csv import tabix import gzip import io from collections import Counter<|fim▁hole|> with open(hg19_size_file) as file: reader = csv.reader(file, delimiter="\t") for line in reader: results[line[0]] = int(line[1]) return results def kart_racer(sample, genom, base_speed = 0, deceleration = 1, acceleration = 1, allow_negative = False): # get chromosom size sizes = chromosom_sizes(genom) # get tabix variant file tabix_file = tabix.open(sample) # current speed speed = 0.0 + base_speed # test on chromosom 17 chromosom = "chr17" size = sizes[chromosom] # Loop over genoms for pos in range(0, size): # get how many mutation at one position count = len([c for c in tabix_file.query(chromosom, pos, pos + 2)]) if count > 0 : speed += count * acceleration else: if speed > 0: speed -= deceleration else: speed = 0.0 print(chromosom, pos, pos +1, speed, sep="\t") if __name__ == '__main__': parser = argparse.ArgumentParser( description="Compute speed of mutation ", usage="kart_racer.py file.bed.gz -g hg19.sizes -a 1 -b 0.1 " ) parser.add_argument("sample", type=str, help="tabix file") parser.add_argument("-g","--genom", type=str, help="genom size ") parser.add_argument("-b","--base_speed", type=int, default = 0) parser.add_argument("-d","--deceleration", type=float, default = 0.01, help="decrease speed by x each empty base") parser.add_argument("-a","--acceleration", type=float, default = 1, help="accelerate by 1 each variant") args = parser.parse_args() kart_racer(args.sample, args.genom, args.base_speed , args.deceleration , args.acceleration, False )<|fim▁end|>
def chromosom_sizes(hg19_size_file): ''' Return chromosom size range ex: size["chr13"] = 234324 ''' results = {}
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|>
__author__="Joao"
<|file_name|>domquad.rs<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::DOMPointBinding::{DOMPointInit, DOMPointMethods}; use crate::dom::bindings::codegen::Bindings::DOMQuadBinding::{DOMQuadInit, DOMQuadMethods, Wrap}; use crate::dom::bindings::codegen::Bindings::DOMRectReadOnlyBinding::DOMRectInit; use crate::dom::bindings::error::Fallible; use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector}; use crate::dom::bindings::root::{Dom, DomRoot}; use crate::dom::dompoint::DOMPoint; use crate::dom::domrect::DOMRect; use crate::dom::globalscope::GlobalScope; use dom_struct::dom_struct; // https://drafts.fxtf.org/geometry/#DOMQuad #[dom_struct] pub struct DOMQuad { reflector_: Reflector, p1: Dom<DOMPoint>, p2: Dom<DOMPoint>, p3: Dom<DOMPoint>, p4: Dom<DOMPoint>, } impl DOMQuad { fn new_inherited(p1: &DOMPoint, p2: &DOMPoint, p3: &DOMPoint, p4: &DOMPoint) -> DOMQuad { DOMQuad { reflector_: Reflector::new(), p1: Dom::from_ref(p1), p2: Dom::from_ref(p2), p3: Dom::from_ref(p3), p4: Dom::from_ref(p4), } } pub fn new( global: &GlobalScope,<|fim▁hole|> p3: &DOMPoint, p4: &DOMPoint, ) -> DomRoot<DOMQuad> { reflect_dom_object( Box::new(DOMQuad::new_inherited(p1, p2, p3, p4)), global, Wrap, ) } pub fn Constructor( global: &GlobalScope, p1: &DOMPointInit, p2: &DOMPointInit, p3: &DOMPointInit, p4: &DOMPointInit, ) -> Fallible<DomRoot<DOMQuad>> { Ok(DOMQuad::new( global, &*DOMPoint::new_from_init(global, p1), &*DOMPoint::new_from_init(global, p2), &*DOMPoint::new_from_init(global, p3), &*DOMPoint::new_from_init(global, p4), )) } // https://drafts.fxtf.org/geometry/#dom-domquad-fromrect pub fn FromRect(global: &GlobalScope, other: &DOMRectInit) -> DomRoot<DOMQuad> { DOMQuad::new( global, &*DOMPoint::new(global, other.x, other.y, 0f64, 1f64), &*DOMPoint::new(global, other.x + other.width, other.y, 0f64, 1f64), &*DOMPoint::new( global, other.x + other.width, other.y + other.height, 0f64, 1f64, ), &*DOMPoint::new(global, other.x, other.y + other.height, 0f64, 1f64), ) } // https://drafts.fxtf.org/geometry/#dom-domquad-fromquad pub fn FromQuad(global: &GlobalScope, other: &DOMQuadInit) -> DomRoot<DOMQuad> { DOMQuad::new( global, &DOMPoint::new_from_init(global, &other.p1), &DOMPoint::new_from_init(global, &other.p2), &DOMPoint::new_from_init(global, &other.p3), &DOMPoint::new_from_init(global, &other.p4), ) } } impl DOMQuadMethods for DOMQuad { // https://drafts.fxtf.org/geometry/#dom-domquad-p1 fn P1(&self) -> DomRoot<DOMPoint> { DomRoot::from_ref(&self.p1) } // https://drafts.fxtf.org/geometry/#dom-domquad-p2 fn P2(&self) -> DomRoot<DOMPoint> { DomRoot::from_ref(&self.p2) } // https://drafts.fxtf.org/geometry/#dom-domquad-p3 fn P3(&self) -> DomRoot<DOMPoint> { DomRoot::from_ref(&self.p3) } // https://drafts.fxtf.org/geometry/#dom-domquad-p4 fn P4(&self) -> DomRoot<DOMPoint> { DomRoot::from_ref(&self.p4) } // https://drafts.fxtf.org/geometry/#dom-domquad-getbounds fn GetBounds(&self) -> DomRoot<DOMRect> { let left = self .p1 .X() .min(self.p2.X()) .min(self.p3.X()) .min(self.p4.X()); let top = self .p1 .Y() .min(self.p2.Y()) .min(self.p3.Y()) .min(self.p4.Y()); let right = self .p1 .X() .max(self.p2.X()) .max(self.p3.X()) .max(self.p4.X()); let bottom = self .p1 .Y() .max(self.p2.Y()) .max(self.p3.Y()) .max(self.p4.Y()); DOMRect::new(&self.global(), left, top, right - left, bottom - top) } }<|fim▁end|>
p1: &DOMPoint, p2: &DOMPoint,
<|file_name|>nodelog.py<|end_file_name|><|fim▁begin|>from include import IncludeManager from django.apps import apps from django.db import models from django.utils import timezone from osf.models.base import BaseModel, ObjectIDMixin from osf.utils.datetime_aware_jsonfield import DateTimeAwareJSONField from osf.utils.fields import NonNaiveDateTimeField from website.util import api_v2_url class NodeLog(ObjectIDMixin, BaseModel): FIELD_ALIASES = { # TODO: Find a better way 'node': 'node__guids___id', 'user': 'user__guids___id', 'original_node': 'original_node__guids___id' } objects = IncludeManager() DATE_FORMAT = '%m/%d/%Y %H:%M UTC' # Log action constants -- NOTE: templates stored in log_templates.mako CREATED_FROM = 'created_from' PROJECT_CREATED = 'project_created' PROJECT_REGISTERED = 'project_registered' PROJECT_DELETED = 'project_deleted' NODE_CREATED = 'node_created' NODE_FORKED = 'node_forked' NODE_REMOVED = 'node_removed' POINTER_CREATED = NODE_LINK_CREATED = 'pointer_created' POINTER_FORKED = NODE_LINK_FORKED = 'pointer_forked' POINTER_REMOVED = NODE_LINK_REMOVED = 'pointer_removed' WIKI_UPDATED = 'wiki_updated' WIKI_DELETED = 'wiki_deleted' WIKI_RENAMED = 'wiki_renamed' MADE_WIKI_PUBLIC = 'made_wiki_public' MADE_WIKI_PRIVATE = 'made_wiki_private' CONTRIB_ADDED = 'contributor_added' CONTRIB_REMOVED = 'contributor_removed' CONTRIB_REORDERED = 'contributors_reordered' CHECKED_IN = 'checked_in' CHECKED_OUT = 'checked_out' PERMISSIONS_UPDATED = 'permissions_updated' MADE_PRIVATE = 'made_private' MADE_PUBLIC = 'made_public' TAG_ADDED = 'tag_added' TAG_REMOVED = 'tag_removed' FILE_TAG_ADDED = 'file_tag_added' FILE_TAG_REMOVED = 'file_tag_removed'<|fim▁hole|> UPDATED_FIELDS = 'updated_fields' FILE_MOVED = 'addon_file_moved' FILE_COPIED = 'addon_file_copied' FILE_RENAMED = 'addon_file_renamed' FOLDER_CREATED = 'folder_created' FILE_ADDED = 'file_added' FILE_UPDATED = 'file_updated' FILE_REMOVED = 'file_removed' FILE_RESTORED = 'file_restored' ADDON_ADDED = 'addon_added' ADDON_REMOVED = 'addon_removed' COMMENT_ADDED = 'comment_added' COMMENT_REMOVED = 'comment_removed' COMMENT_UPDATED = 'comment_updated' COMMENT_RESTORED = 'comment_restored' CITATION_ADDED = 'citation_added' CITATION_EDITED = 'citation_edited' CITATION_REMOVED = 'citation_removed' MADE_CONTRIBUTOR_VISIBLE = 'made_contributor_visible' MADE_CONTRIBUTOR_INVISIBLE = 'made_contributor_invisible' EXTERNAL_IDS_ADDED = 'external_ids_added' EMBARGO_APPROVED = 'embargo_approved' EMBARGO_CANCELLED = 'embargo_cancelled' EMBARGO_COMPLETED = 'embargo_completed' EMBARGO_INITIATED = 'embargo_initiated' EMBARGO_TERMINATED = 'embargo_terminated' RETRACTION_APPROVED = 'retraction_approved' RETRACTION_CANCELLED = 'retraction_cancelled' RETRACTION_INITIATED = 'retraction_initiated' REGISTRATION_APPROVAL_CANCELLED = 'registration_cancelled' REGISTRATION_APPROVAL_INITIATED = 'registration_initiated' REGISTRATION_APPROVAL_APPROVED = 'registration_approved' PREREG_REGISTRATION_INITIATED = 'prereg_registration_initiated' AFFILIATED_INSTITUTION_ADDED = 'affiliated_institution_added' AFFILIATED_INSTITUTION_REMOVED = 'affiliated_institution_removed' PREPRINT_INITIATED = 'preprint_initiated' PREPRINT_FILE_UPDATED = 'preprint_file_updated' PREPRINT_LICENSE_UPDATED = 'preprint_license_updated' SUBJECTS_UPDATED = 'subjects_updated' VIEW_ONLY_LINK_ADDED = 'view_only_link_added' VIEW_ONLY_LINK_REMOVED = 'view_only_link_removed' actions = ([CHECKED_IN, CHECKED_OUT, FILE_TAG_REMOVED, FILE_TAG_ADDED, CREATED_FROM, PROJECT_CREATED, PROJECT_REGISTERED, PROJECT_DELETED, NODE_CREATED, NODE_FORKED, NODE_REMOVED, NODE_LINK_CREATED, NODE_LINK_FORKED, NODE_LINK_REMOVED, WIKI_UPDATED, WIKI_DELETED, WIKI_RENAMED, MADE_WIKI_PUBLIC, MADE_WIKI_PRIVATE, CONTRIB_ADDED, CONTRIB_REMOVED, CONTRIB_REORDERED, PERMISSIONS_UPDATED, MADE_PRIVATE, MADE_PUBLIC, TAG_ADDED, TAG_REMOVED, EDITED_TITLE, EDITED_DESCRIPTION, UPDATED_FIELDS, FILE_MOVED, FILE_COPIED, FOLDER_CREATED, FILE_ADDED, FILE_UPDATED, FILE_REMOVED, FILE_RESTORED, ADDON_ADDED, ADDON_REMOVED, COMMENT_ADDED, COMMENT_REMOVED, COMMENT_UPDATED, COMMENT_RESTORED, MADE_CONTRIBUTOR_VISIBLE, MADE_CONTRIBUTOR_INVISIBLE, EXTERNAL_IDS_ADDED, EMBARGO_APPROVED, EMBARGO_TERMINATED, EMBARGO_CANCELLED, EMBARGO_COMPLETED, EMBARGO_INITIATED, RETRACTION_APPROVED, RETRACTION_CANCELLED, RETRACTION_INITIATED, REGISTRATION_APPROVAL_CANCELLED, REGISTRATION_APPROVAL_INITIATED, REGISTRATION_APPROVAL_APPROVED, PREREG_REGISTRATION_INITIATED, CITATION_ADDED, CITATION_EDITED, CITATION_REMOVED, AFFILIATED_INSTITUTION_ADDED, AFFILIATED_INSTITUTION_REMOVED, PREPRINT_INITIATED, PREPRINT_FILE_UPDATED, PREPRINT_LICENSE_UPDATED, VIEW_ONLY_LINK_ADDED, VIEW_ONLY_LINK_REMOVED] + list(sum([ config.actions for config in apps.get_app_configs() if config.name.startswith('addons.') ], tuple()))) action_choices = [(action, action.upper()) for action in actions] date = NonNaiveDateTimeField(db_index=True, null=True, blank=True, default=timezone.now) # TODO build action choices on the fly with the addon stuff action = models.CharField(max_length=255, db_index=True) # , choices=action_choices) params = DateTimeAwareJSONField(default=dict) should_hide = models.BooleanField(default=False) user = models.ForeignKey('OSFUser', related_name='logs', db_index=True, null=True, blank=True, on_delete=models.CASCADE) foreign_user = models.CharField(max_length=255, null=True, blank=True) node = models.ForeignKey('AbstractNode', related_name='logs', db_index=True, null=True, blank=True, on_delete=models.CASCADE) original_node = models.ForeignKey('AbstractNode', db_index=True, null=True, blank=True, on_delete=models.CASCADE) def __unicode__(self): return ('({self.action!r}, user={self.user!r},, node={self.node!r}, params={self.params!r}) ' 'with id {self.id!r}').format(self=self) class Meta: ordering = ['-date'] get_latest_by = 'date' @property def absolute_api_v2_url(self): path = '/logs/{}/'.format(self._id) return api_v2_url(path) def get_absolute_url(self): return self.absolute_api_v2_url @property def absolute_url(self): return self.absolute_api_v2_url def _natural_key(self): return self._id<|fim▁end|>
EDITED_TITLE = 'edit_title' EDITED_DESCRIPTION = 'edit_description' CHANGED_LICENSE = 'license_changed'
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>#![allow(unknown_lints)] // Allow clippy lints. extern crate alga; extern crate arrayvec; extern crate decorum; #[macro_use] extern crate failure; #[macro_use] extern crate gfx; extern crate gfx_device_gl; extern crate gfx_window_glutin; extern crate glutin; extern crate image; #[macro_use] extern crate lazy_static; extern crate nalgebra; extern crate num; extern crate plexus; extern crate rand; extern crate winit; pub mod clamp; pub mod cube; pub mod event; pub mod framework; pub mod input; pub mod math; pub mod render; pub mod resource; pub trait BoolExt: Sized { fn into_some<T>(self, some: T) -> Option<T>; } impl BoolExt for bool { fn into_some<T>(self, some: T) -> Option<T> { if self { Some(some) } else { None } } } pub trait OptionExt<T> { fn and_if<F>(self, f: F) -> Self where F: Fn(&T) -> bool; } impl<T> OptionExt<T> for Option<T> { fn and_if<F>(mut self, f: F) -> Self where F: Fn(&T) -> bool, { match self.take() { Some(value) => if f(&value) { Some(value) } else { None }, _ => None, } }<|fim▁hole|><|fim▁end|>
}
<|file_name|>DataStoreFactory.java<|end_file_name|><|fim▁begin|>/******************************************************************************* * Signavio Core Components * Copyright (C) 2012 Signavio GmbH * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package de.hpi.bpmn2_0.factory.node; import org.oryxeditor.server.diagram.generic.GenericShape; import de.hpi.bpmn2_0.annotations.StencilId; import de.hpi.bpmn2_0.exceptions.BpmnConverterException; import de.hpi.bpmn2_0.factory.AbstractShapeFactory; import de.hpi.bpmn2_0.model.BaseElement; import de.hpi.bpmn2_0.model.data_object.DataState; import de.hpi.bpmn2_0.model.data_object.DataStore; import de.hpi.bpmn2_0.model.data_object.DataStoreReference; import de.hpi.diagram.SignavioUUID; /** * Factory for DataStores * * @author Philipp Giese * @author Sven Wagner-Boysen * */ @StencilId("DataStore") public class DataStoreFactory extends AbstractShapeFactory { /* (non-Javadoc) * @see de.hpi.bpmn2_0.factory.AbstractBpmnFactory#createProcessElement(org.oryxeditor.server.diagram.Shape) */ // @Override protected BaseElement createProcessElement(GenericShape shape) throws BpmnConverterException { DataStoreReference dataStoreRef = new DataStoreReference(); this.setCommonAttributes(dataStoreRef, shape); dataStoreRef.setDataStoreRef(new DataStore()); this.setDataStoreRefAttributes(dataStoreRef, shape); return dataStoreRef; } /** * Sets the attributes related to a data store element. * * @param dataStoreRef * The @link {@link DataStoreReference}. * @param shape * The data store {@link GenericShape} */ private void setDataStoreRefAttributes(DataStoreReference dataStoreRef, GenericShape shape) { DataStore dataStore = dataStoreRef.getDataStoreRef(); String dataStateName = shape.getProperty("state"); /* Set attributes of the global data store */ if(dataStore != null) { dataStore.setId(SignavioUUID.generate()); dataStore.setName(shape.getProperty("name")); if(shape.getProperty("capacity") != null && !(shape.getProperty("capacity").length() == 0))<|fim▁hole|> if(isUnlimited != null && isUnlimited.equalsIgnoreCase("true")) dataStore.setUnlimited(true); else dataStore.setUnlimited(false); /* Define DataState element */ if(dataStateName != null && !(dataStateName.length() == 0)) { DataState dataState = new DataState(dataStateName); dataStore.setDataState(dataState); } } /* Set attributes of the data store reference */ dataStoreRef.setName(shape.getProperty("name")); dataStoreRef.setId(shape.getResourceId()); /* Define DataState element */ if(dataStateName != null && !(dataStateName.length() == 0)) { DataState dataState = new DataState(dataStateName); dataStoreRef.setDataState(dataState); } } }<|fim▁end|>
dataStore.setCapacity(Integer.valueOf(shape.getProperty("capacity")).intValue()); /* Set isUnlimited attribute */ String isUnlimited = shape.getProperty("isunlimited");
<|file_name|>remove-block.tsx<|end_file_name|><|fim▁begin|>/** @jsx jsx */ import { jsx } from '../..' export const input = ( <editor> <block> <text /> <inline> <block>one</block> <text>two</text> </inline> <text /> </block> </editor> )<|fim▁hole|> <text /> <inline> <text>two</text> </inline> <text /> </block> </editor> )<|fim▁end|>
export const output = ( <editor> <block>
<|file_name|>main.py<|end_file_name|><|fim▁begin|>import math def square_root ( a ): """Computes squar root of a """ espilon = 0.1e-11 x = a while True: y = ( x + a / x ) / 2.0<|fim▁hole|> x = y def test_square_root(): """Compares custom square and math.sqrt. """ a = 1.0 while a < 10.0: print a, '{:<13}'.format( square_root( a ) ), \ '{:<13}'.format( math.sqrt( a ) ), \ abs( square_root( a ) - math.sqrt( a ) ) a += 1 test_square_root()<|fim▁end|>
if abs( y - x ) < espilon: return y
<|file_name|>scene.py<|end_file_name|><|fim▁begin|>"""Allow users to set and activate scenes.""" from __future__ import annotations import logging from typing import Any, NamedTuple import voluptuous as vol from homeassistant import config as conf_util from homeassistant.components.light import ATTR_TRANSITION from homeassistant.components.scene import DOMAIN as SCENE_DOMAIN, STATES, Scene from homeassistant.const import ( ATTR_ENTITY_ID, ATTR_STATE, CONF_ENTITIES, CONF_ICON, CONF_ID, CONF_NAME, CONF_PLATFORM, SERVICE_RELOAD, STATE_OFF, STATE_ON, ) from homeassistant.core import DOMAIN as HA_DOMAIN, HomeAssistant, State, callback from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers import ( config_per_platform, config_validation as cv, entity_platform, ) from homeassistant.helpers.state import async_reproduce_state from homeassistant.loader import async_get_integration def _convert_states(states): """Convert state definitions to State objects.""" result = {} for entity_id, info in states.items(): entity_id = cv.entity_id(entity_id) if isinstance(info, dict): entity_attrs = info.copy() state = entity_attrs.pop(ATTR_STATE, None) attributes = entity_attrs else: state = info attributes = {} # YAML translates 'on' to a boolean # http://yaml.org/type/bool.html if isinstance(state, bool): state = STATE_ON if state else STATE_OFF elif not isinstance(state, str): raise vol.Invalid(f"State for {entity_id} should be a string") result[entity_id] = State(entity_id, state, attributes) return result def _ensure_no_intersection(value): """Validate that entities and snapshot_entities do not overlap.""" if ( CONF_SNAPSHOT not in value or CONF_ENTITIES not in value or all( entity_id not in value[CONF_SNAPSHOT] for entity_id in value[CONF_ENTITIES] ) ): return value raise vol.Invalid("entities and snapshot_entities must not overlap") CONF_SCENE_ID = "scene_id" CONF_SNAPSHOT = "snapshot_entities" DATA_PLATFORM = "homeassistant_scene" EVENT_SCENE_RELOADED = "scene_reloaded" STATES_SCHEMA = vol.All(dict, _convert_states) PLATFORM_SCHEMA = vol.Schema( { vol.Required(CONF_PLATFORM): HA_DOMAIN, vol.Required(STATES): vol.All( cv.ensure_list, [ vol.Schema( { vol.Optional(CONF_ID): cv.string, vol.Required(CONF_NAME): cv.string, vol.Optional(CONF_ICON): cv.icon, vol.Required(CONF_ENTITIES): STATES_SCHEMA, } ) ], ), }, extra=vol.ALLOW_EXTRA, ) CREATE_SCENE_SCHEMA = vol.All( cv.has_at_least_one_key(CONF_ENTITIES, CONF_SNAPSHOT), _ensure_no_intersection, vol.Schema( { vol.Required(CONF_SCENE_ID): cv.slug, vol.Optional(CONF_ENTITIES, default={}): STATES_SCHEMA, vol.Optional(CONF_SNAPSHOT, default=[]): cv.entity_ids, } ), ) SERVICE_APPLY = "apply" SERVICE_CREATE = "create" _LOGGER = logging.getLogger(__name__) class SceneConfig(NamedTuple): """Object for storing scene config.""" id: str name: str icon: str states: dict @callback def scenes_with_entity(hass: HomeAssistant, entity_id: str) -> list[str]: """Return all scenes that reference the entity.""" if DATA_PLATFORM not in hass.data: return [] platform = hass.data[DATA_PLATFORM] return [ scene_entity.entity_id for scene_entity in platform.entities.values() if entity_id in scene_entity.scene_config.states ] @callback def entities_in_scene(hass: HomeAssistant, entity_id: str) -> list[str]: """Return all entities in a scene.""" if DATA_PLATFORM not in hass.data: return [] platform = hass.data[DATA_PLATFORM] if (entity := platform.entities.get(entity_id)) is None: return [] return list(entity.scene_config.states) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up Home Assistant scene entries.""" _process_scenes_config(hass, async_add_entities, config) # This platform can be loaded multiple times. Only first time register the service. if hass.services.has_service(SCENE_DOMAIN, SERVICE_RELOAD): return # Store platform for later. platform = hass.data[DATA_PLATFORM] = entity_platform.async_get_current_platform() async def reload_config(call): """Reload the scene config.""" try: conf = await conf_util.async_hass_config_yaml(hass) except HomeAssistantError as err: _LOGGER.error(err) return integration = await async_get_integration(hass, SCENE_DOMAIN) conf = await conf_util.async_process_component_config(hass, conf, integration) if not (conf and platform): return await platform.async_reset() # Extract only the config for the Home Assistant platform, ignore the rest. for p_type, p_config in config_per_platform(conf, SCENE_DOMAIN): if p_type != HA_DOMAIN: continue _process_scenes_config(hass, async_add_entities, p_config) hass.bus.async_fire(EVENT_SCENE_RELOADED, context=call.context) hass.helpers.service.async_register_admin_service( SCENE_DOMAIN, SERVICE_RELOAD, reload_config ) async def apply_service(call): """Apply a scene.""" reproduce_options = {} if ATTR_TRANSITION in call.data: reproduce_options[ATTR_TRANSITION] = call.data.get(ATTR_TRANSITION) await async_reproduce_state( hass, call.data[CONF_ENTITIES].values(), context=call.context, reproduce_options=reproduce_options, ) <|fim▁hole|> SCENE_DOMAIN, SERVICE_APPLY, apply_service, vol.Schema( { vol.Optional(ATTR_TRANSITION): vol.All( vol.Coerce(float), vol.Clamp(min=0, max=6553) ), vol.Required(CONF_ENTITIES): STATES_SCHEMA, } ), ) async def create_service(call): """Create a scene.""" snapshot = call.data[CONF_SNAPSHOT] entities = call.data[CONF_ENTITIES] for entity_id in snapshot: if (state := hass.states.get(entity_id)) is None: _LOGGER.warning( "Entity %s does not exist and therefore cannot be snapshotted", entity_id, ) continue entities[entity_id] = State(entity_id, state.state, state.attributes) if not entities: _LOGGER.warning("Empty scenes are not allowed") return scene_config = SceneConfig(None, call.data[CONF_SCENE_ID], None, entities) entity_id = f"{SCENE_DOMAIN}.{scene_config.name}" if (old := platform.entities.get(entity_id)) is not None: if not old.from_service: _LOGGER.warning("The scene %s already exists", entity_id) return await platform.async_remove_entity(entity_id) async_add_entities([HomeAssistantScene(hass, scene_config, from_service=True)]) hass.services.async_register( SCENE_DOMAIN, SERVICE_CREATE, create_service, CREATE_SCENE_SCHEMA ) def _process_scenes_config(hass, async_add_entities, config): """Process multiple scenes and add them.""" # Check empty list if not (scene_config := config[STATES]): return async_add_entities( HomeAssistantScene( hass, SceneConfig( scene.get(CONF_ID), scene[CONF_NAME], scene.get(CONF_ICON), scene[CONF_ENTITIES], ), ) for scene in scene_config ) class HomeAssistantScene(Scene): """A scene is a group of entities and the states we want them to be.""" def __init__(self, hass, scene_config, from_service=False): """Initialize the scene.""" self.hass = hass self.scene_config = scene_config self.from_service = from_service @property def name(self): """Return the name of the scene.""" return self.scene_config.name @property def icon(self): """Return the icon of the scene.""" return self.scene_config.icon @property def unique_id(self): """Return unique ID.""" return self.scene_config.id @property def extra_state_attributes(self): """Return the scene state attributes.""" attributes = {ATTR_ENTITY_ID: list(self.scene_config.states)} if (unique_id := self.unique_id) is not None: attributes[CONF_ID] = unique_id return attributes async def async_activate(self, **kwargs: Any) -> None: """Activate scene. Try to get entities into requested state.""" await async_reproduce_state( self.hass, self.scene_config.states.values(), context=self._context, reproduce_options=kwargs, )<|fim▁end|>
hass.services.async_register(
<|file_name|>FlushScreenCommand.java<|end_file_name|><|fim▁begin|>package spaceinvaders.command.client; import static spaceinvaders.command.ProtocolEnum.UDP; import spaceinvaders.client.mvc.Controller; import spaceinvaders.client.mvc.View; import spaceinvaders.command.Command; /** Flush the screen. */ public class FlushScreenCommand extends Command { private transient Controller executor; public FlushScreenCommand() { super(FlushScreenCommand.class.getName(),UDP); } @Override<|fim▁hole|> public void execute() { for (View view : executor.getViews()) { view.flush(); } } @Override public void setExecutor(Object executor) { if (executor instanceof Controller) { this.executor = (Controller) executor; } else { // This should never happen. throw new AssertionError(); } } }<|fim▁end|>
<|file_name|>setup.py<|end_file_name|><|fim▁begin|>import sys import os.path import subprocess PY3 = sys.version >= '3' from setuptools import setup, find_packages # http://blogs.nopcode.org/brainstorm/2013/05/20/pragmatic-python-versioning-via-setuptools-and-git-tags/ # Fetch version from git tags, and write to version.py. # Also, when git is not available (PyPi package), use stored version.py. version_py = os.path.join(os.path.dirname(__file__), 'dame', 'version.py') try: version_git = subprocess.check_output( ["git", "describe", "--always"]).rstrip() # Convert bytes to str for Python3 if PY3: version_git = version_git.decode() except: with open(version_py, 'r') as fh: version_git = fh.read().strip().split('=')[-1].replace('"', '')<|fim▁hole|>with open(version_py, 'w') as fh: fh.write(version_msg + os.linesep + "__version__='{}'\n".format(version_git)) setup( name="dame", author="Richard Lindsley", version=version_git, packages=find_packages(), license="MIT", entry_points={ 'gui_scripts': [ 'dame = dame.dame:main' ] }, )<|fim▁end|>
version_msg = ("# Do not edit this file, " "pipeline versioning is governed by git tags")
<|file_name|>init_ops_v2.py<|end_file_name|><|fim▁begin|># Copyright 2015 The TensorFlow Authors. 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. # ============================================================================== """Operations often used for initializing tensors. All variable initializers returned by functions in this file should have the following signature: def _initializer(shape, dtype=dtypes.float32): Args: shape: List of `int` representing the shape of the output `Tensor`. Some initializers may also be able to accept a `Tensor`. dtype: (Optional) Type of the output `Tensor`. Returns: A `Tensor` of type `dtype` and `shape`. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import math import numpy as np from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.ops import array_ops from tensorflow.python.ops import gen_linalg_ops from tensorflow.python.ops import linalg_ops_impl from tensorflow.python.ops import math_ops from tensorflow.python.ops import random_ops from tensorflow.python.ops import stateless_random_ops from tensorflow.python.util.tf_export import tf_export class Initializer(object): """Initializer base class: all initializers inherit from this class. """ def __call__(self, shape, dtype=None): """Returns a tensor object initialized as specified by the initializer. Args: shape: Shape of the tensor. dtype: Optional dtype of the tensor. If not provided will return tensor of `tf.float32`. """ raise NotImplementedError def get_config(self): """Returns the configuration of the initializer as a JSON-serializable dict. Returns: A JSON-serializable Python dict. """ return {} @classmethod def from_config(cls, config): """Instantiates an initializer from a configuration dictionary. Example: ```python initializer = RandomUniform(-1, 1) config = initializer.get_config() initializer = RandomUniform.from_config(config) ``` Args: config: A Python dictionary. It will typically be the output of `get_config`. Returns: An Initializer instance. """ config.pop("dtype", None) return cls(**config) @tf_export("zeros_initializer", v1=[]) class Zeros(Initializer): """Initializer that generates tensors initialized to 0.""" def __call__(self, shape, dtype=dtypes.float32): dtype = dtypes.as_dtype(dtype) return array_ops.zeros(shape, dtype) @tf_export("ones_initializer", v1=[]) class Ones(Initializer): """Initializer that generates tensors initialized to 1.""" def __call__(self, shape, dtype=dtypes.float32): """Returns a tensor object initialized as specified by the initializer. Args: shape: Shape of the tensor. dtype: Optional dtype of the tensor. Only numeric or boolean dtypes are supported. Raises: ValuesError: If the dtype is not numeric or boolean. """ dtype = dtypes.as_dtype(dtype) if not dtype.is_numpy_compatible or dtype == dtypes.string: raise ValueError("Expected numeric or boolean dtype, got %s." % dtype) return array_ops.ones(shape, dtype) @tf_export("constant_initializer", v1=[]) class Constant(Initializer): """Initializer that generates tensors with constant values. The resulting tensor is populated with values of type `dtype`, as specified by arguments `value` following the desired `shape` of the new tensor (see examples below). The argument `value` can be a constant value, or a list of values of type `dtype`. If `value` is a list, then the length of the list must be less than or equal to the number of elements implied by the desired shape of the tensor. In the case where the total number of elements in `value` is less than the number of elements required by the tensor shape, the last element in `value` will be used to fill the remaining entries. If the total number of elements in `value` is greater than the number of elements required by the tensor shape, the initializer will raise a `ValueError`. Args: value: A Python scalar, list or tuple of values, or a N-dimensional numpy array. All elements of the initialized variable will be set to the corresponding value in the `value` argument. Raises: TypeError: If the input `value` is not one of the expected types. Examples: The following example can be rewritten using a numpy.ndarray instead of the `value` list, even reshaped, as shown in the two commented lines below the `value` list initialization. ```python >>> import numpy as np >>> import tensorflow as tf >>> value = [0, 1, 2, 3, 4, 5, 6, 7] >>> # value = np.array(value) >>> # value = value.reshape([2, 4]) >>> init = tf.constant_initializer(value) >>> print('fitting shape:') >>> with tf.Session(): >>> x = tf.get_variable('x', shape=[2, 4], initializer=init) >>> x.initializer.run() >>> print(x.eval()) fitting shape: [[ 0. 1. 2. 3.] [ 4. 5. 6. 7.]] >>> print('larger shape:') >>> with tf.Session(): >>> x = tf.get_variable('x', shape=[3, 4], initializer=init) >>> x.initializer.run() >>> print(x.eval()) larger shape: [[ 0. 1. 2. 3.] [ 4. 5. 6. 7.] [ 7. 7. 7. 7.]] >>> print('smaller shape:') >>> with tf.Session(): >>> x = tf.get_variable('x', shape=[2, 3], initializer=init) ValueError: Too many elements provided. Needed at most 6, but received 8 ``` """ def __init__(self, value=0): if not (np.isscalar(value) or isinstance(value, (list, tuple, np.ndarray))): raise TypeError( "Invalid type for initial value: %s (expected Python scalar, list or " "tuple of values, or numpy.ndarray)." % type(value)) self.value = value def __call__(self, shape, dtype=None): """Returns a tensor object initialized as specified by the initializer. Args: shape: Shape of the tensor. dtype: Optional dtype of the tensor. If not provided the dtype of the tensor created will be the type of the inital value. Raises: TypeError: If the initializer cannot create a tensor of the requested dtype. """ if dtype is not None: dtype = dtypes.as_dtype(dtype) return constant_op.constant( self.value, dtype=dtype, shape=shape) def get_config(self): return {"value": self.value} @tf_export("random_uniform_initializer", v1=[]) class RandomUniform(Initializer): """Initializer that generates tensors with a uniform distribution. Args: minval: A python scalar or a scalar tensor. Lower bound of the range of random values to generate. maxval: A python scalar or a scalar tensor. Upper bound of the range of random values to generate. Defaults to 1 for float types. seed: A Python integer. Used to create random seeds. See `tf.set_random_seed` for behavior. """ def __init__(self, minval=-0.05, maxval=0.05, seed=None): self.minval = minval self.maxval = maxval self.seed = seed self._random_generator = _RandomGenerator(seed) def __call__(self, shape, dtype=dtypes.float32): """Returns a tensor object initialized as specified by the initializer. Args: shape: Shape of the tensor. dtype: Optional dtype of the tensor. Only floating point and integer types are supported. Raises: ValueError: If the dtype is not numeric. """ dtype = dtypes.as_dtype(dtype) if not dtype.is_floating and not dtype.is_integer: raise ValueError("Expected float or integer dtype, got %s." % dtype) return self._random_generator.random_uniform(shape, self.minval, self.maxval, dtype) def get_config(self): return { "minval": self.minval, "maxval": self.maxval, "seed": self.seed } @tf_export("random_normal_initializer", v1=[]) class RandomNormal(Initializer): """Initializer that generates tensors with a normal distribution. Args: mean: a python scalar or a scalar tensor. Mean of the random values to generate. stddev: a python scalar or a scalar tensor. Standard deviation of the random values to generate. seed: A Python integer. Used to create random seeds. See `tf.set_random_seed` for behavior. """ def __init__(self, mean=0.0, stddev=0.05, seed=None):<|fim▁hole|> self._random_generator = _RandomGenerator(seed) def __call__(self, shape, dtype=dtypes.float32): """Returns a tensor object initialized as specified by the initializer. Args: shape: Shape of the tensor. dtype: Optional dtype of the tensor. Only floating point types are supported. Raises: ValueError: If the dtype is not floating point """ dtype = _assert_float_dtype(dtype) return self._random_generator.random_normal(shape, self.mean, self.stddev, dtype) def get_config(self): return { "mean": self.mean, "stddev": self.stddev, "seed": self.seed } class TruncatedNormal(Initializer): """Initializer that generates a truncated normal distribution. These values are similar to values from a `random_normal_initializer` except that values more than two standard deviations from the mean are discarded and re-drawn. This is the recommended initializer for neural network weights and filters. Args: mean: a python scalar or a scalar tensor. Mean of the random values to generate. stddev: a python scalar or a scalar tensor. Standard deviation of the random values to generate. seed: A Python integer. Used to create random seeds. See `tf.set_random_seed` for behavior. """ def __init__(self, mean=0.0, stddev=0.05, seed=None): self.mean = mean self.stddev = stddev self.seed = seed self._random_generator = _RandomGenerator(seed) def __call__(self, shape, dtype=dtypes.float32): """Returns a tensor object initialized as specified by the initializer. Args: shape: Shape of the tensor. dtype: Optional dtype of the tensor. Only floating point types are supported. Raises: ValueError: If the dtype is not floating point """ dtype = _assert_float_dtype(dtype) return self._random_generator.truncated_normal(shape, self.mean, self.stddev, dtype) def get_config(self): return { "mean": self.mean, "stddev": self.stddev, "seed": self.seed } class VarianceScaling(Initializer): """Initializer capable of adapting its scale to the shape of weights tensors. With `distribution="truncated_normal" or "untruncated_normal"`, samples are drawn from a truncated/untruncated normal distribution with a mean of zero and a standard deviation (after truncation, if used) `stddev = sqrt(scale / n)` where n is: - number of input units in the weight tensor, if mode = "fan_in" - number of output units, if mode = "fan_out" - average of the numbers of input and output units, if mode = "fan_avg" With `distribution="uniform"`, samples are drawn from a uniform distribution within [-limit, limit], with `limit = sqrt(3 * scale / n)`. Args: scale: Scaling factor (positive float). mode: One of "fan_in", "fan_out", "fan_avg". distribution: Random distribution to use. One of "truncated_normal", "untruncated_normal" and "uniform". seed: A Python integer. Used to create random seeds. See `tf.set_random_seed` for behavior. Raises: ValueError: In case of an invalid value for the "scale", mode" or "distribution" arguments. """ def __init__(self, scale=1.0, mode="fan_in", distribution="truncated_normal", seed=None): if scale <= 0.: raise ValueError("`scale` must be positive float.") if mode not in {"fan_in", "fan_out", "fan_avg"}: raise ValueError("Invalid `mode` argument:", mode) distribution = distribution.lower() if distribution not in {"uniform", "truncated_normal", "untruncated_normal"}: raise ValueError("Invalid `distribution` argument:", distribution) self.scale = scale self.mode = mode self.distribution = distribution self.seed = seed self._random_generator = _RandomGenerator(seed) def __call__(self, shape, dtype=dtypes.float32): """Returns a tensor object initialized as specified by the initializer. Args: shape: Shape of the tensor. dtype: Optional dtype of the tensor. Only floating point types are supported. Raises: ValueError: If the dtype is not floating point """ partition_info = None # Keeps logic so can be readded later if necessary dtype = _assert_float_dtype(dtype) scale = self.scale scale_shape = shape if partition_info is not None: scale_shape = partition_info.full_shape fan_in, fan_out = _compute_fans(scale_shape) if self.mode == "fan_in": scale /= max(1., fan_in) elif self.mode == "fan_out": scale /= max(1., fan_out) else: scale /= max(1., (fan_in + fan_out) / 2.) if self.distribution == "truncated_normal": # constant from scipy.stats.truncnorm.std(a=-2, b=2, loc=0., scale=1.) stddev = math.sqrt(scale) / .87962566103423978 return self._random_generator.truncated_normal(shape, 0.0, stddev, dtype) elif self.distribution == "untruncated_normal": stddev = math.sqrt(scale) return self._random_generator.random_normal(shape, 0.0, stddev, dtype) else: limit = math.sqrt(3.0 * scale) return self._random_generator.random_uniform(shape, -limit, limit, dtype) def get_config(self): return { "scale": self.scale, "mode": self.mode, "distribution": self.distribution, "seed": self.seed } class Orthogonal(Initializer): """Initializer that generates an orthogonal matrix. If the shape of the tensor to initialize is two-dimensional, it is initialized with an orthogonal matrix obtained from the QR decomposition of a matrix of random numbers drawn from a normal distribution. If the matrix has fewer rows than columns then the output will have orthogonal rows. Otherwise, the output will have orthogonal columns. If the shape of the tensor to initialize is more than two-dimensional, a matrix of shape `(shape[0] * ... * shape[n - 2], shape[n - 1])` is initialized, where `n` is the length of the shape vector. The matrix is subsequently reshaped to give a tensor of the desired shape. Args: gain: multiplicative factor to apply to the orthogonal matrix seed: A Python integer. Used to create random seeds. See `tf.set_random_seed` for behavior. References: [Saxe et al., 2014](https://openreview.net/forum?id=_wzZwKpTDF_9C) ([pdf](https://arxiv.org/pdf/1312.6120.pdf)) """ def __init__(self, gain=1.0, seed=None): self.gain = gain self.seed = seed self._random_generator = _RandomGenerator(seed) def __call__(self, shape, dtype=dtypes.float32): """Returns a tensor object initialized as specified by the initializer. Args: shape: Shape of the tensor. dtype: Optional dtype of the tensor. Only floating point types are supported. Raises: ValueError: If the dtype is not floating point or the input shape is not valid. """ dtype = _assert_float_dtype(dtype) # Check the shape if len(shape) < 2: raise ValueError("The tensor to initialize must be " "at least two-dimensional") # Flatten the input shape with the last dimension remaining # its original shape so it works for conv2d num_rows = 1 for dim in shape[:-1]: num_rows *= dim num_cols = shape[-1] flat_shape = (max(num_cols, num_rows), min(num_cols, num_rows)) # Generate a random matrix a = self._random_generator.random_normal(flat_shape, dtype=dtype) # Compute the qr factorization q, r = gen_linalg_ops.qr(a, full_matrices=False) # Make Q uniform d = array_ops.diag_part(r) q *= math_ops.sign(d) if num_rows < num_cols: q = array_ops.matrix_transpose(q) return self.gain * array_ops.reshape(q, shape) def get_config(self): return {"gain": self.gain, "seed": self.seed} class Identity(Initializer): """Initializer that generates the identity matrix. Only use for 2D matrices. Args: gain: Multiplicative factor to apply to the identity matrix. """ def __init__(self, gain=1.0): self.gain = gain def __call__(self, shape, dtype=dtypes.float32): """Returns a tensor object initialized as specified by the initializer. Args: shape: Shape of the tensor. dtype: Optional dtype of the tensor. Only floating point types are supported. Raises: ValueError: If the dtype is not floating point """ partition_info = None # Keeps logic so can be readded later if necessary dtype = _assert_float_dtype(dtype) full_shape = shape if partition_info is None else partition_info.full_shape if len(full_shape) != 2: raise ValueError( "Identity matrix initializer can only be used for 2D matrices.") initializer = linalg_ops_impl.eye(*full_shape, dtype=dtype) if partition_info is not None: initializer = array_ops.slice(initializer, partition_info.var_offset, shape) return self.gain * initializer def get_config(self): return {"gain": self.gain} class GlorotUniform(VarianceScaling): """The Glorot uniform initializer, also called Xavier uniform initializer. It draws samples from a uniform distribution within [-limit, limit] where `limit` is `sqrt(6 / (fan_in + fan_out))` where `fan_in` is the number of input units in the weight tensor and `fan_out` is the number of output units in the weight tensor. Args: seed: A Python integer. Used to create random seeds. See `tf.set_random_seed` for behavior. References: [Glorot et al., 2010](http://proceedings.mlr.press/v9/glorot10a.html) ([pdf](http://jmlr.org/proceedings/papers/v9/glorot10a/glorot10a.pdf)) """ def __init__(self, seed=None): super(GlorotUniform, self).__init__( scale=1.0, mode="fan_avg", distribution="uniform", seed=seed) def get_config(self): return {"seed": self.seed} class GlorotNormal(VarianceScaling): """The Glorot normal initializer, also called Xavier normal initializer. It draws samples from a truncated normal distribution centered on 0 with `stddev = sqrt(2 / (fan_in + fan_out))` where `fan_in` is the number of input units in the weight tensor and `fan_out` is the number of output units in the weight tensor. Args: seed: A Python integer. Used to create random seeds. See `tf.set_random_seed` for behavior. References: [Glorot et al., 2010](http://proceedings.mlr.press/v9/glorot10a.html) ([pdf](http://jmlr.org/proceedings/papers/v9/glorot10a/glorot10a.pdf)) """ def __init__(self, seed=None): super(GlorotNormal, self).__init__( scale=1.0, mode="fan_avg", distribution="truncated_normal", seed=seed) def get_config(self): return {"seed": self.seed} # Aliases. # pylint: disable=invalid-name zeros_initializer = Zeros ones_initializer = Ones constant_initializer = Constant random_uniform_initializer = RandomUniform random_normal_initializer = RandomNormal truncated_normal_initializer = TruncatedNormal variance_scaling_initializer = VarianceScaling glorot_uniform_initializer = GlorotUniform glorot_normal_initializer = GlorotNormal orthogonal_initializer = Orthogonal identity_initializer = Identity # pylint: enable=invalid-name def lecun_normal(seed=None): """LeCun normal initializer. It draws samples from a truncated normal distribution centered on 0 with `stddev = sqrt(1 / fan_in)` where `fan_in` is the number of input units in the weight tensor. Arguments: seed: A Python integer. Used to seed the random generator. Returns: An initializer. References: - Self-Normalizing Neural Networks, [Klambauer et al., 2017] (https://papers.nips.cc/paper/6698-self-normalizing-neural-networks) ([pdf] (https://papers.nips.cc/paper/6698-self-normalizing-neural-networks.pdf)) - Efficient Backprop, [Lecun et al., 1998](http://yann.lecun.com/exdb/publis/pdf/lecun-98b.pdf) """ return VarianceScaling( scale=1., mode="fan_in", distribution="truncated_normal", seed=seed) def lecun_uniform(seed=None): """LeCun uniform initializer. It draws samples from a uniform distribution within [-limit, limit] where `limit` is `sqrt(3 / fan_in)` where `fan_in` is the number of input units in the weight tensor. Arguments: seed: A Python integer. Used to seed the random generator. Returns: An initializer. References: - Self-Normalizing Neural Networks, [Klambauer et al., 2017](https://papers.nips.cc/paper/6698-self-normalizing-neural-networks) # pylint: disable=line-too-long ([pdf](https://papers.nips.cc/paper/6698-self-normalizing-neural-networks.pdf)) - Efficient Backprop, [Lecun et al., 1998](http://yann.lecun.com/exdb/publis/pdf/lecun-98b.pdf) """ return VarianceScaling( scale=1., mode="fan_in", distribution="uniform", seed=seed) def he_normal(seed=None): """He normal initializer. It draws samples from a truncated normal distribution centered on 0 with `stddev = sqrt(2 / fan_in)` where `fan_in` is the number of input units in the weight tensor. Arguments: seed: A Python integer. Used to seed the random generator. Returns: An initializer. References: [He et al., 2015](https://www.cv-foundation.org/openaccess/content_iccv_2015/html/He_Delving_Deep_into_ICCV_2015_paper.html) # pylint: disable=line-too-long ([pdf](https://www.cv-foundation.org/openaccess/content_iccv_2015/papers/He_Delving_Deep_into_ICCV_2015_paper.pdf)) """ return VarianceScaling( scale=2., mode="fan_in", distribution="truncated_normal", seed=seed) def he_uniform(seed=None): """He uniform variance scaling initializer. It draws samples from a uniform distribution within [-limit, limit] where `limit` is `sqrt(6 / fan_in)` where `fan_in` is the number of input units in the weight tensor. Arguments: seed: A Python integer. Used to seed the random generator. Returns: An initializer. References: [He et al., 2015](https://www.cv-foundation.org/openaccess/content_iccv_2015/html/He_Delving_Deep_into_ICCV_2015_paper.html) # pylint: disable=line-too-long ([pdf](https://www.cv-foundation.org/openaccess/content_iccv_2015/papers/He_Delving_Deep_into_ICCV_2015_paper.pdf)) """ return VarianceScaling( scale=2., mode="fan_in", distribution="uniform", seed=seed) # Utility functions. def _compute_fans(shape): """Computes the number of input and output units for a weight shape. Args: shape: Integer shape tuple or TF tensor shape. Returns: A tuple of scalars (fan_in, fan_out). """ if len(shape) < 1: # Just to avoid errors for constants. fan_in = fan_out = 1 elif len(shape) == 1: fan_in = fan_out = shape[0] elif len(shape) == 2: fan_in = shape[0] fan_out = shape[1] else: # Assuming convolution kernels (2D, 3D, or more). # kernel shape: (..., input_depth, depth) receptive_field_size = 1. for dim in shape[:-2]: receptive_field_size *= dim fan_in = shape[-2] * receptive_field_size fan_out = shape[-1] * receptive_field_size return fan_in, fan_out def _assert_float_dtype(dtype): """Validate and return floating point type based on `dtype`. `dtype` must be a floating point type. Args: dtype: The data type to validate. Returns: Validated type. Raises: ValueError: if `dtype` is not a floating point type. """ dtype = dtypes.as_dtype(dtype) if not dtype.is_floating: raise ValueError("Expected floating point type, got %s." % dtype) return dtype class _RandomGenerator(object): """Random generator that selects appropriate random ops.""" def __init__(self, seed=None): super(_RandomGenerator, self).__init__() if seed is not None: # Stateless random ops requires 2-int seed. self.seed = [seed, 0] else: self.seed = None def random_normal(self, shape, mean=0.0, stddev=1, dtype=dtypes.float32): """A deterministic random normal if seed is passed.""" if self.seed: op = stateless_random_ops.stateless_random_normal else: op = random_ops.random_normal return op( shape=shape, mean=mean, stddev=stddev, dtype=dtype, seed=self.seed) def random_uniform(self, shape, minval, maxval, dtype): """A deterministic random uniform if seed is passed.""" if self.seed: op = stateless_random_ops.stateless_random_uniform else: op = random_ops.random_uniform return op( shape=shape, minval=minval, maxval=maxval, dtype=dtype, seed=self.seed) def truncated_normal(self, shape, mean, stddev, dtype): """A deterministic truncated normal if seed is passed.""" if self.seed: op = stateless_random_ops.stateless_truncated_normal else: op = random_ops.truncated_normal return op( shape=shape, mean=mean, stddev=stddev, dtype=dtype, seed=self.seed) # Compatibility aliases # pylint: disable=invalid-name zero = zeros = Zeros one = ones = Ones constant = Constant uniform = random_uniform = RandomUniform normal = random_normal = RandomNormal truncated_normal = TruncatedNormal identity = Identity orthogonal = Orthogonal glorot_normal = GlorotNormal glorot_uniform = GlorotUniform<|fim▁end|>
self.mean = mean self.stddev = stddev self.seed = seed
<|file_name|>env.rs<|end_file_name|><|fim▁begin|>// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Inspection and manipulation of the process's environment. //! //! This module contains methods to inspect various aspects such as //! environment varibles, process arguments, the current directory, and various //! other important directories. #![stable(feature = "env", since = "1.0.0")] use prelude::v1::*; use error::Error; use ffi::{OsStr, OsString}; use fmt; use io; use path::{Path, PathBuf}; use sync::atomic::{AtomicIsize, Ordering}; use sync::StaticMutex; use sys::os as os_imp; /// Returns the current working directory as a `PathBuf`. /// /// # Errors /// /// Returns an `Err` if the current working directory value is invalid. /// Possible cases: /// /// * Current directory does not exist. /// * There are insufficient permissions to access the current directory. /// * The internal buffer is not large enough to hold the path. /// /// # Examples /// /// ``` /// use std::env; /// /// // We assume that we are in a valid directory. /// let p = env::current_dir().unwrap(); /// println!("The current directory is {}", p.display()); /// ``` #[stable(feature = "env", since = "1.0.0")] pub fn current_dir() -> io::Result<PathBuf> { os_imp::getcwd() } /// Changes the current working directory to the specified path, returning /// whether the change was completed successfully or not. /// /// # Examples /// /// ``` /// use std::env; /// use std::path::Path; /// /// let root = Path::new("/"); /// assert!(env::set_current_dir(&root).is_ok()); /// println!("Successfully changed working directory to {}!", root.display()); /// ``` #[stable(feature = "env", since = "1.0.0")] pub fn set_current_dir<P: AsRef<Path>>(p: P) -> io::Result<()> { os_imp::chdir(p.as_ref()) } static ENV_LOCK: StaticMutex = StaticMutex::new(); /// An iterator over a snapshot of the environment variables of this process. /// /// This iterator is created through `std::env::vars()` and yields `(String, /// String)` pairs. #[stable(feature = "env", since = "1.0.0")] pub struct Vars { inner: VarsOs } /// An iterator over a snapshot of the environment variables of this process. /// /// This iterator is created through `std::env::vars_os()` and yields /// `(OsString, OsString)` pairs. #[stable(feature = "env", since = "1.0.0")] pub struct VarsOs { inner: os_imp::Env } /// Returns an iterator of (variable, value) pairs of strings, for all the /// environment variables of the current process. /// /// The returned iterator contains a snapshot of the process's environment /// variables at the time of this invocation, modifications to environment /// variables afterwards will not be reflected in the returned iterator. /// /// # Panics /// /// While iterating, the returned iterator will panic if any key or value in the /// environment is not valid unicode. If this is not desired, consider using the /// `env::vars_os` function. /// /// # Examples /// /// ``` /// use std::env; /// /// // We will iterate through the references to the element returned by /// // env::vars(); /// for (key, value) in env::vars() { /// println!("{}: {}", key, value); /// } /// ``` #[stable(feature = "env", since = "1.0.0")] pub fn vars() -> Vars { Vars { inner: vars_os() } } /// Returns an iterator of (variable, value) pairs of OS strings, for all the /// environment variables of the current process. /// /// The returned iterator contains a snapshot of the process's environment /// variables at the time of this invocation, modifications to environment /// variables afterwards will not be reflected in the returned iterator. /// /// # Examples<|fim▁hole|>/// /// // We will iterate through the references to the element returned by /// // env::vars_os(); /// for (key, value) in env::vars_os() { /// println!("{:?}: {:?}", key, value); /// } /// ``` #[stable(feature = "env", since = "1.0.0")] pub fn vars_os() -> VarsOs { let _g = ENV_LOCK.lock(); VarsOs { inner: os_imp::env() } } #[stable(feature = "env", since = "1.0.0")] impl Iterator for Vars { type Item = (String, String); fn next(&mut self) -> Option<(String, String)> { self.inner.next().map(|(a, b)| { (a.into_string().unwrap(), b.into_string().unwrap()) }) } fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() } } #[stable(feature = "env", since = "1.0.0")] impl Iterator for VarsOs { type Item = (OsString, OsString); fn next(&mut self) -> Option<(OsString, OsString)> { self.inner.next() } fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() } } /// Fetches the environment variable `key` from the current process. /// /// The returned result is `Ok(s)` if the environment variable is present and is /// valid unicode. If the environment variable is not present, or it is not /// valid unicode, then `Err` will be returned. /// /// # Examples /// /// ``` /// use std::env; /// /// let key = "HOME"; /// match env::var(key) { /// Ok(val) => println!("{}: {:?}", key, val), /// Err(e) => println!("couldn't interpret {}: {}", key, e), /// } /// ``` #[stable(feature = "env", since = "1.0.0")] pub fn var<K: AsRef<OsStr>>(key: K) -> Result<String, VarError> { match var_os(key) { Some(s) => s.into_string().map_err(VarError::NotUnicode), None => Err(VarError::NotPresent) } } /// Fetches the environment variable `key` from the current process, returning /// None if the variable isn't set. /// /// # Examples /// /// ``` /// use std::env; /// /// let key = "HOME"; /// match env::var_os(key) { /// Some(val) => println!("{}: {:?}", key, val), /// None => println!("{} is not defined in the environment.", key) /// } /// ``` #[stable(feature = "env", since = "1.0.0")] pub fn var_os<K: AsRef<OsStr>>(key: K) -> Option<OsString> { let _g = ENV_LOCK.lock(); os_imp::getenv(key.as_ref()) } /// Possible errors from the `env::var` method. #[derive(Debug, PartialEq, Eq, Clone)] #[stable(feature = "env", since = "1.0.0")] pub enum VarError { /// The specified environment variable was not present in the current /// process's environment. #[stable(feature = "env", since = "1.0.0")] NotPresent, /// The specified environment variable was found, but it did not contain /// valid unicode data. The found data is returned as a payload of this /// variant. #[stable(feature = "env", since = "1.0.0")] NotUnicode(OsString), } #[stable(feature = "env", since = "1.0.0")] impl fmt::Display for VarError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { VarError::NotPresent => write!(f, "environment variable not found"), VarError::NotUnicode(ref s) => { write!(f, "environment variable was not valid unicode: {:?}", s) } } } } #[stable(feature = "env", since = "1.0.0")] impl Error for VarError { fn description(&self) -> &str { match *self { VarError::NotPresent => "environment variable not found", VarError::NotUnicode(..) => "environment variable was not valid unicode", } } } /// Sets the environment variable `k` to the value `v` for the currently running /// process. /// /// Note that while concurrent access to environment variables is safe in Rust, /// some platforms only expose inherently unsafe non-threadsafe APIs for /// inspecting the environment. As a result extra care needs to be taken when /// auditing calls to unsafe external FFI functions to ensure that any external /// environment accesses are properly synchronized with accesses in Rust. /// /// Discussion of this unsafety on Unix may be found in: /// /// - [Austin Group Bugzilla](http://austingroupbugs.net/view.php?id=188) /// - [GNU C library Bugzilla](https://sourceware.org/bugzilla/show_bug.cgi?id=15607#c2) /// /// # Examples /// /// ``` /// use std::env; /// /// let key = "KEY"; /// env::set_var(key, "VALUE"); /// assert_eq!(env::var(key), Ok("VALUE".to_string())); /// ``` #[stable(feature = "env", since = "1.0.0")] pub fn set_var<K: AsRef<OsStr>, V: AsRef<OsStr>>(k: K, v: V) { let _g = ENV_LOCK.lock(); os_imp::setenv(k.as_ref(), v.as_ref()) } /// Removes an environment variable from the environment of the currently running process. /// /// Note that while concurrent access to environment variables is safe in Rust, /// some platforms only expose inherently unsafe non-threadsafe APIs for /// inspecting the environment. As a result extra care needs to be taken when /// auditing calls to unsafe external FFI functions to ensure that any external /// environment accesses are properly synchronized with accesses in Rust. /// /// Discussion of this unsafety on Unix may be found in: /// /// - [Austin Group Bugzilla](http://austingroupbugs.net/view.php?id=188) /// - [GNU C library Bugzilla](https://sourceware.org/bugzilla/show_bug.cgi?id=15607#c2) /// /// # Examples /// /// ``` /// use std::env; /// /// let key = "KEY"; /// env::set_var(key, "VALUE"); /// assert_eq!(env::var(key), Ok("VALUE".to_string())); /// /// env::remove_var(key); /// assert!(env::var(key).is_err()); /// ``` #[stable(feature = "env", since = "1.0.0")] pub fn remove_var<K: AsRef<OsStr>>(k: K) { let _g = ENV_LOCK.lock(); os_imp::unsetenv(k.as_ref()) } /// An iterator over `Path` instances for parsing an environment variable /// according to platform-specific conventions. /// /// This structure is returned from `std::env::split_paths`. #[stable(feature = "env", since = "1.0.0")] pub struct SplitPaths<'a> { inner: os_imp::SplitPaths<'a> } /// Parses input according to platform conventions for the `PATH` /// environment variable. /// /// Returns an iterator over the paths contained in `unparsed`. /// /// # Examples /// /// ``` /// use std::env; /// /// let key = "PATH"; /// match env::var_os(key) { /// Some(paths) => { /// for path in env::split_paths(&paths) { /// println!("'{}'", path.display()); /// } /// } /// None => println!("{} is not defined in the environment.", key) /// } /// ``` #[stable(feature = "env", since = "1.0.0")] pub fn split_paths<T: AsRef<OsStr> + ?Sized>(unparsed: &T) -> SplitPaths { SplitPaths { inner: os_imp::split_paths(unparsed.as_ref()) } } #[stable(feature = "env", since = "1.0.0")] impl<'a> Iterator for SplitPaths<'a> { type Item = PathBuf; fn next(&mut self) -> Option<PathBuf> { self.inner.next() } fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() } } /// Error type returned from `std::env::join_paths` when paths fail to be /// joined. #[derive(Debug)] #[stable(feature = "env", since = "1.0.0")] pub struct JoinPathsError { inner: os_imp::JoinPathsError } /// Joins a collection of `Path`s appropriately for the `PATH` /// environment variable. /// /// Returns an `OsString` on success. /// /// Returns an `Err` (containing an error message) if one of the input /// `Path`s contains an invalid character for constructing the `PATH` /// variable (a double quote on Windows or a colon on Unix). /// /// # Examples /// /// ``` /// use std::env; /// use std::path::PathBuf; /// /// if let Some(path) = env::var_os("PATH") { /// let mut paths = env::split_paths(&path).collect::<Vec<_>>(); /// paths.push(PathBuf::from("/home/xyz/bin")); /// let new_path = env::join_paths(paths).unwrap(); /// env::set_var("PATH", &new_path); /// } /// ``` #[stable(feature = "env", since = "1.0.0")] pub fn join_paths<I, T>(paths: I) -> Result<OsString, JoinPathsError> where I: IntoIterator<Item=T>, T: AsRef<OsStr> { os_imp::join_paths(paths.into_iter()).map_err(|e| { JoinPathsError { inner: e } }) } #[stable(feature = "env", since = "1.0.0")] impl fmt::Display for JoinPathsError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.inner.fmt(f) } } #[stable(feature = "env", since = "1.0.0")] impl Error for JoinPathsError { fn description(&self) -> &str { self.inner.description() } } /// Optionally returns the path to the current user's home directory if known. /// /// # Unix /// /// Returns the value of the 'HOME' environment variable if it is set /// and not equal to the empty string. /// /// # Windows /// /// Returns the value of the 'HOME' environment variable if it is /// set and not equal to the empty string. Otherwise, returns the value of the /// 'USERPROFILE' environment variable if it is set and not equal to the empty /// string. /// /// # Examples /// /// ``` /// use std::env; /// /// match env::home_dir() { /// Some(ref p) => println!("{}", p.display()), /// None => println!("Impossible to get your home dir!") /// } /// ``` #[stable(feature = "env", since = "1.0.0")] pub fn home_dir() -> Option<PathBuf> { os_imp::home_dir() } /// Returns the path to a temporary directory. /// /// On Unix, returns the value of the 'TMPDIR' environment variable if it is /// set, otherwise for non-Android it returns '/tmp'. If Android, since there /// is no global temporary folder (it is usually allocated per-app), we return /// '/data/local/tmp'. /// /// On Windows, returns the value of, in order, the 'TMP', 'TEMP', /// 'USERPROFILE' environment variable if any are set and not the empty /// string. Otherwise, tmpdir returns the path to the Windows directory. /// /// ``` /// use std::env; /// use std::fs::File; /// /// # fn foo() -> std::io::Result<()> { /// let mut dir = env::temp_dir(); /// dir.push("foo.txt"); /// /// let f = try!(File::create(dir)); /// # Ok(()) /// # } /// ``` #[stable(feature = "env", since = "1.0.0")] pub fn temp_dir() -> PathBuf { os_imp::temp_dir() } /// Optionally returns the filesystem path to the current executable which is /// running but with the executable name. /// /// The path returned is not necessarily a "real path" to the executable as /// there may be intermediate symlinks. /// /// # Errors /// /// Acquiring the path to the current executable is a platform-specific operation /// that can fail for a good number of reasons. Some errors can include, but not /// be limited to filesystem operations failing or general syscall failures. /// /// # Examples /// /// ``` /// use std::env; /// /// match env::current_exe() { /// Ok(exe_path) => println!("Path of this executable is: {}", /// exe_path.display()), /// Err(e) => println!("failed to get current exe path: {}", e), /// }; /// ``` #[stable(feature = "env", since = "1.0.0")] pub fn current_exe() -> io::Result<PathBuf> { os_imp::current_exe() } static EXIT_STATUS: AtomicIsize = AtomicIsize::new(0); /// Sets the process exit code /// /// Sets the exit code returned by the process if all supervised threads /// terminate successfully (without panicking). If the current root thread panics /// and is supervised by the scheduler then any user-specified exit status is /// ignored and the process exits with the default panic status. /// /// Note that this is not synchronized against modifications of other threads. #[unstable(feature = "exit_status", reason = "managing the exit status may change")] #[deprecated(since = "1.2.0", reason = "use process::exit instead")] pub fn set_exit_status(code: i32) { EXIT_STATUS.store(code as isize, Ordering::SeqCst) } /// Fetches the process's current exit code. This defaults to 0 and can change /// by calling `set_exit_status`. #[unstable(feature = "exit_status", reason = "managing the exit status may change")] #[deprecated(since = "1.2.0", reason = "use process::exit instead")] pub fn get_exit_status() -> i32 { EXIT_STATUS.load(Ordering::SeqCst) as i32 } /// An iterator over the arguments of a process, yielding a `String` value /// for each argument. /// /// This structure is created through the `std::env::args` method. #[stable(feature = "env", since = "1.0.0")] pub struct Args { inner: ArgsOs } /// An iterator over the arguments of a process, yielding an `OsString` value /// for each argument. /// /// This structure is created through the `std::env::args_os` method. #[stable(feature = "env", since = "1.0.0")] pub struct ArgsOs { inner: os_imp::Args } /// Returns the arguments which this program was started with (normally passed /// via the command line). /// /// The first element is traditionally the path to the executable, but it can be /// set to arbitrary text, and it may not even exist, so this property should /// not be relied upon for security purposes. /// /// # Panics /// /// The returned iterator will panic during iteration if any argument to the /// process is not valid unicode. If this is not desired it is recommended to /// use the `args_os` function instead. /// /// # Examples /// /// ``` /// use std::env; /// /// // Prints each argument on a separate line /// for argument in env::args() { /// println!("{}", argument); /// } /// ``` #[stable(feature = "env", since = "1.0.0")] pub fn args() -> Args { Args { inner: args_os() } } /// Returns the arguments which this program was started with (normally passed /// via the command line). /// /// The first element is traditionally the path to the executable, but it can be /// set to arbitrary text, and it may not even exist, so this property should /// not be relied upon for security purposes. /// /// # Examples /// /// ``` /// use std::env; /// /// // Prints each argument on a separate line /// for argument in env::args_os() { /// println!("{:?}", argument); /// } /// ``` #[stable(feature = "env", since = "1.0.0")] pub fn args_os() -> ArgsOs { ArgsOs { inner: os_imp::args() } } #[stable(feature = "env", since = "1.0.0")] impl Iterator for Args { type Item = String; fn next(&mut self) -> Option<String> { self.inner.next().map(|s| s.into_string().unwrap()) } fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() } } #[stable(feature = "env", since = "1.0.0")] impl ExactSizeIterator for Args { fn len(&self) -> usize { self.inner.len() } } #[stable(feature = "env", since = "1.0.0")] impl Iterator for ArgsOs { type Item = OsString; fn next(&mut self) -> Option<OsString> { self.inner.next() } fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() } } #[stable(feature = "env", since = "1.0.0")] impl ExactSizeIterator for ArgsOs { fn len(&self) -> usize { self.inner.len() } } /// Returns the page size of the current architecture in bytes. #[unstable(feature = "page_size", reason = "naming and/or location may change")] pub fn page_size() -> usize { os_imp::page_size() } /// Constants associated with the current target #[stable(feature = "env", since = "1.0.0")] pub mod consts { /// A string describing the architecture of the CPU that this is currently /// in use. /// /// Some possible values: /// /// - x86 /// - x86_64 /// - arm /// - aarch64 /// - mips /// - mipsel /// - powerpc #[stable(feature = "env", since = "1.0.0")] pub const ARCH: &'static str = super::arch::ARCH; /// The family of the operating system. In this case, `unix`. /// /// Some possible values: /// /// - unix /// - windows #[stable(feature = "env", since = "1.0.0")] pub const FAMILY: &'static str = super::os::FAMILY; /// A string describing the specific operating system in use: in this /// case, `linux`. /// /// Some possible values: /// /// - linux /// - macos /// - ios /// - freebsd /// - dragonfly /// - bitrig /// - openbsd /// - android /// - windows #[stable(feature = "env", since = "1.0.0")] pub const OS: &'static str = super::os::OS; /// Specifies the filename prefix used for shared libraries on this /// platform: in this case, `lib`. /// /// Some possible values: /// /// - lib /// - `""` (an empty string) #[stable(feature = "env", since = "1.0.0")] pub const DLL_PREFIX: &'static str = super::os::DLL_PREFIX; /// Specifies the filename suffix used for shared libraries on this /// platform: in this case, `.so`. /// /// Some possible values: /// /// - .so /// - .dylib /// - .dll #[stable(feature = "env", since = "1.0.0")] pub const DLL_SUFFIX: &'static str = super::os::DLL_SUFFIX; /// Specifies the file extension used for shared libraries on this /// platform that goes after the dot: in this case, `so`. /// /// Some possible values: /// /// - .so /// - .dylib /// - .dll #[stable(feature = "env", since = "1.0.0")] pub const DLL_EXTENSION: &'static str = super::os::DLL_EXTENSION; /// Specifies the filename suffix used for executable binaries on this /// platform: in this case, the empty string. /// /// Some possible values: /// /// - exe /// - `""` (an empty string) #[stable(feature = "env", since = "1.0.0")] pub const EXE_SUFFIX: &'static str = super::os::EXE_SUFFIX; /// Specifies the file extension, if any, used for executable binaries /// on this platform: in this case, the empty string. /// /// Some possible values: /// /// - exe /// - `""` (an empty string) #[stable(feature = "env", since = "1.0.0")] pub const EXE_EXTENSION: &'static str = super::os::EXE_EXTENSION; } #[cfg(target_os = "linux")] mod os { pub const FAMILY: &'static str = "unix"; pub const OS: &'static str = "linux"; pub const DLL_PREFIX: &'static str = "lib"; pub const DLL_SUFFIX: &'static str = ".so"; pub const DLL_EXTENSION: &'static str = "so"; pub const EXE_SUFFIX: &'static str = ""; pub const EXE_EXTENSION: &'static str = ""; } #[cfg(target_os = "macos")] mod os { pub const FAMILY: &'static str = "unix"; pub const OS: &'static str = "macos"; pub const DLL_PREFIX: &'static str = "lib"; pub const DLL_SUFFIX: &'static str = ".dylib"; pub const DLL_EXTENSION: &'static str = "dylib"; pub const EXE_SUFFIX: &'static str = ""; pub const EXE_EXTENSION: &'static str = ""; } #[cfg(target_os = "ios")] mod os { pub const FAMILY: &'static str = "unix"; pub const OS: &'static str = "ios"; pub const DLL_PREFIX: &'static str = "lib"; pub const DLL_SUFFIX: &'static str = ".dylib"; pub const DLL_EXTENSION: &'static str = "dylib"; pub const EXE_SUFFIX: &'static str = ""; pub const EXE_EXTENSION: &'static str = ""; } #[cfg(target_os = "freebsd")] mod os { pub const FAMILY: &'static str = "unix"; pub const OS: &'static str = "freebsd"; pub const DLL_PREFIX: &'static str = "lib"; pub const DLL_SUFFIX: &'static str = ".so"; pub const DLL_EXTENSION: &'static str = "so"; pub const EXE_SUFFIX: &'static str = ""; pub const EXE_EXTENSION: &'static str = ""; } #[cfg(target_os = "dragonfly")] mod os { pub const FAMILY: &'static str = "unix"; pub const OS: &'static str = "dragonfly"; pub const DLL_PREFIX: &'static str = "lib"; pub const DLL_SUFFIX: &'static str = ".so"; pub const DLL_EXTENSION: &'static str = "so"; pub const EXE_SUFFIX: &'static str = ""; pub const EXE_EXTENSION: &'static str = ""; } #[cfg(target_os = "bitrig")] mod os { pub const FAMILY: &'static str = "unix"; pub const OS: &'static str = "bitrig"; pub const DLL_PREFIX: &'static str = "lib"; pub const DLL_SUFFIX: &'static str = ".so"; pub const DLL_EXTENSION: &'static str = "so"; pub const EXE_SUFFIX: &'static str = ""; pub const EXE_EXTENSION: &'static str = ""; } #[cfg(target_os = "openbsd")] mod os { pub const FAMILY: &'static str = "unix"; pub const OS: &'static str = "openbsd"; pub const DLL_PREFIX: &'static str = "lib"; pub const DLL_SUFFIX: &'static str = ".so"; pub const DLL_EXTENSION: &'static str = "so"; pub const EXE_SUFFIX: &'static str = ""; pub const EXE_EXTENSION: &'static str = ""; } #[cfg(target_os = "android")] mod os { pub const FAMILY: &'static str = "unix"; pub const OS: &'static str = "android"; pub const DLL_PREFIX: &'static str = "lib"; pub const DLL_SUFFIX: &'static str = ".so"; pub const DLL_EXTENSION: &'static str = "so"; pub const EXE_SUFFIX: &'static str = ""; pub const EXE_EXTENSION: &'static str = ""; } #[cfg(target_os = "windows")] mod os { pub const FAMILY: &'static str = "windows"; pub const OS: &'static str = "windows"; pub const DLL_PREFIX: &'static str = ""; pub const DLL_SUFFIX: &'static str = ".dll"; pub const DLL_EXTENSION: &'static str = "dll"; pub const EXE_SUFFIX: &'static str = ".exe"; pub const EXE_EXTENSION: &'static str = "exe"; } #[cfg(target_arch = "x86")] mod arch { pub const ARCH: &'static str = "x86"; } #[cfg(target_arch = "x86_64")] mod arch { pub const ARCH: &'static str = "x86_64"; } #[cfg(target_arch = "arm")] mod arch { pub const ARCH: &'static str = "arm"; } #[cfg(target_arch = "aarch64")] mod arch { pub const ARCH: &'static str = "aarch64"; } #[cfg(target_arch = "mips")] mod arch { pub const ARCH: &'static str = "mips"; } #[cfg(target_arch = "mipsel")] mod arch { pub const ARCH: &'static str = "mipsel"; } #[cfg(target_arch = "powerpc")] mod arch { pub const ARCH: &'static str = "powerpc"; } #[cfg(test)] mod tests { use prelude::v1::*; use super::*; use iter::repeat; use rand::{self, Rng}; use ffi::{OsString, OsStr}; use path::{Path, PathBuf}; fn make_rand_name() -> OsString { let mut rng = rand::thread_rng(); let n = format!("TEST{}", rng.gen_ascii_chars().take(10) .collect::<String>()); let n = OsString::from(n); assert!(var_os(&n).is_none()); n } fn eq(a: Option<OsString>, b: Option<&str>) { assert_eq!(a.as_ref().map(|s| &**s), b.map(OsStr::new).map(|s| &*s)); } #[test] fn test_set_var() { let n = make_rand_name(); set_var(&n, "VALUE"); eq(var_os(&n), Some("VALUE")); } #[test] fn test_remove_var() { let n = make_rand_name(); set_var(&n, "VALUE"); remove_var(&n); eq(var_os(&n), None); } #[test] fn test_set_var_overwrite() { let n = make_rand_name(); set_var(&n, "1"); set_var(&n, "2"); eq(var_os(&n), Some("2")); set_var(&n, ""); eq(var_os(&n), Some("")); } #[test] fn test_var_big() { let mut s = "".to_string(); let mut i = 0; while i < 100 { s.push_str("aaaaaaaaaa"); i += 1; } let n = make_rand_name(); set_var(&n, &s); eq(var_os(&n), Some(&s)); } #[test] fn test_self_exe_path() { let path = current_exe(); assert!(path.is_ok()); let path = path.unwrap(); // Hard to test this function assert!(path.is_absolute()); } #[test] fn test_env_set_get_huge() { let n = make_rand_name(); let s = repeat("x").take(10000).collect::<String>(); set_var(&n, &s); eq(var_os(&n), Some(&s)); remove_var(&n); eq(var_os(&n), None); } #[test] fn test_env_set_var() { let n = make_rand_name(); let mut e = vars_os(); set_var(&n, "VALUE"); assert!(!e.any(|(k, v)| { &*k == &*n && &*v == "VALUE" })); assert!(vars_os().any(|(k, v)| { &*k == &*n && &*v == "VALUE" })); } #[test] fn test() { assert!((!Path::new("test-path").is_absolute())); current_dir().unwrap(); } #[test] #[cfg(windows)] fn split_paths_windows() { fn check_parse(unparsed: &str, parsed: &[&str]) -> bool { split_paths(unparsed).collect::<Vec<_>>() == parsed.iter().map(|s| PathBuf::from(*s)).collect::<Vec<_>>() } assert!(check_parse("", &mut [""])); assert!(check_parse(r#""""#, &mut [""])); assert!(check_parse(";;", &mut ["", "", ""])); assert!(check_parse(r"c:\", &mut [r"c:\"])); assert!(check_parse(r"c:\;", &mut [r"c:\", ""])); assert!(check_parse(r"c:\;c:\Program Files\", &mut [r"c:\", r"c:\Program Files\"])); assert!(check_parse(r#"c:\;c:\"foo"\"#, &mut [r"c:\", r"c:\foo\"])); assert!(check_parse(r#"c:\;c:\"foo;bar"\;c:\baz"#, &mut [r"c:\", r"c:\foo;bar\", r"c:\baz"])); } #[test] #[cfg(unix)] fn split_paths_unix() { fn check_parse(unparsed: &str, parsed: &[&str]) -> bool { split_paths(unparsed).collect::<Vec<_>>() == parsed.iter().map(|s| PathBuf::from(*s)).collect::<Vec<_>>() } assert!(check_parse("", &mut [""])); assert!(check_parse("::", &mut ["", "", ""])); assert!(check_parse("/", &mut ["/"])); assert!(check_parse("/:", &mut ["/", ""])); assert!(check_parse("/:/usr/local", &mut ["/", "/usr/local"])); } #[test] #[cfg(unix)] fn join_paths_unix() { fn test_eq(input: &[&str], output: &str) -> bool { &*join_paths(input.iter().cloned()).unwrap() == OsStr::new(output) } assert!(test_eq(&[], "")); assert!(test_eq(&["/bin", "/usr/bin", "/usr/local/bin"], "/bin:/usr/bin:/usr/local/bin")); assert!(test_eq(&["", "/bin", "", "", "/usr/bin", ""], ":/bin:::/usr/bin:")); assert!(join_paths(["/te:st"].iter().cloned()).is_err()); } #[test] #[cfg(windows)] fn join_paths_windows() { fn test_eq(input: &[&str], output: &str) -> bool { &*join_paths(input.iter().cloned()).unwrap() == OsStr::new(output) } assert!(test_eq(&[], "")); assert!(test_eq(&[r"c:\windows", r"c:\"], r"c:\windows;c:\")); assert!(test_eq(&["", r"c:\windows", "", "", r"c:\", ""], r";c:\windows;;;c:\;")); assert!(test_eq(&[r"c:\te;st", r"c:\"], r#""c:\te;st";c:\"#)); assert!(join_paths([r#"c:\te"st"#].iter().cloned()).is_err()); } }<|fim▁end|>
/// /// ``` /// use std::env;
<|file_name|>hashdb.rs<|end_file_name|><|fim▁begin|>// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. //! Database of byte-slices keyed to their Keccak hash. use hash::*; use std::collections::HashMap; use elastic_array::ElasticArray128; /// `HashDB` value type. pub type DBValue = ElasticArray128<u8>; <|fim▁hole|>pub trait HashDB: AsHashDB + Send + Sync { /// Get the keys in the database together with number of underlying references. fn keys(&self) -> HashMap<H256, i32>; /// Look up a given hash into the bytes that hash to it, returning None if the /// hash is not known. /// /// # Examples /// ```rust /// extern crate ethcore_util; /// use ethcore_util::hashdb::*; /// use ethcore_util::memorydb::*; /// fn main() { /// let mut m = MemoryDB::new(); /// let hello_bytes = "Hello world!".as_bytes(); /// let hash = m.insert(hello_bytes); /// assert_eq!(m.get(&hash).unwrap(), hello_bytes); /// } /// ``` fn get(&self, key: &H256) -> Option<DBValue>; /// Check for the existance of a hash-key. /// /// # Examples /// ```rust /// extern crate ethcore_util; /// use ethcore_util::hashdb::*; /// use ethcore_util::memorydb::*; /// use ethcore_util::sha3::*; /// fn main() { /// let mut m = MemoryDB::new(); /// let hello_bytes = "Hello world!".as_bytes(); /// assert!(!m.contains(&hello_bytes.sha3())); /// let key = m.insert(hello_bytes); /// assert!(m.contains(&key)); /// m.remove(&key); /// assert!(!m.contains(&key)); /// } /// ``` fn contains(&self, key: &H256) -> bool; /// Insert a datum item into the DB and return the datum's hash for a later lookup. Insertions /// are counted and the equivalent number of `remove()`s must be performed before the data /// is considered dead. /// /// # Examples /// ```rust /// extern crate ethcore_util; /// use ethcore_util::hashdb::*; /// use ethcore_util::memorydb::*; /// use ethcore_util::hash::*; /// fn main() { /// let mut m = MemoryDB::new(); /// let key = m.insert("Hello world!".as_bytes()); /// assert!(m.contains(&key)); /// } /// ``` fn insert(&mut self, value: &[u8]) -> H256; /// Like `insert()` , except you provide the key and the data is all moved. fn emplace(&mut self, key: H256, value: DBValue); /// Remove a datum previously inserted. Insertions can be "owed" such that the same number of `insert()`s may /// happen without the data being eventually being inserted into the DB. /// /// # Examples /// ```rust /// extern crate ethcore_util; /// use ethcore_util::hashdb::*; /// use ethcore_util::memorydb::*; /// use ethcore_util::sha3::*; /// fn main() { /// let mut m = MemoryDB::new(); /// let d = "Hello world!".as_bytes(); /// let key = &d.sha3(); /// m.remove(key); // OK - we now owe an insertion. /// assert!(!m.contains(key)); /// m.insert(d); // OK - now it's "empty" again. /// assert!(!m.contains(key)); /// m.insert(d); // OK - now we've /// assert_eq!(m.get(key).unwrap(), d); /// } /// ``` fn remove(&mut self, key: &H256); } /// Upcast trait. pub trait AsHashDB { /// Perform upcast to HashDB for anything that derives from HashDB. fn as_hashdb(&self) -> &HashDB; /// Perform mutable upcast to HashDB for anything that derives from HashDB. fn as_hashdb_mut(&mut self) -> &mut HashDB; } impl<T: HashDB> AsHashDB for T { fn as_hashdb(&self) -> &HashDB { self } fn as_hashdb_mut(&mut self) -> &mut HashDB { self } }<|fim▁end|>
/// Trait modelling datastore keyed by a 32-byte Keccak hash.
<|file_name|>manage.py<|end_file_name|><|fim▁begin|>""" RUN RUN RUN ! """ from buttersalt import create_app from flask_script import Manager, Shell<|fim▁hole|> app = create_app('default') manager = Manager(app) def make_shell_context(): return dict(app=app) manager.add_command("shell", Shell(make_context=make_shell_context)) @manager.command def test(): """Run the unit tests.""" import unittest tests = unittest.TestLoader().discover('tests') unittest.TextTestRunner(verbosity=2).run(tests) if __name__ == "__main__": manager.run()<|fim▁end|>
<|file_name|>IfcElementType.cpp<|end_file_name|><|fim▁begin|>// IFC SDK : IFC2X3 C++ Early Classes // Copyright (C) 2009 CSTB // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // The full license is in Licence.txt file included with this // distribution or is available at : // http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. #include <ifc2x3/IfcElementType.h> #include <ifc2x3/CopyOp.h> #include <ifc2x3/IfcTypeProduct.h> #include <ifc2x3/Visitor.h> #include <Step/BaseObject.h> #include <Step/ClassType.h> #include <Step/String.h> #include <string> #include "precompiled.h" using namespace ifc2x3; IfcElementType::IfcElementType(Step::Id id, Step::SPFData *args) : IfcTypeProduct(id, args) { m_elementType = Step::getUnset(m_elementType); } IfcElementType::~IfcElementType() { } bool IfcElementType::acceptVisitor(Step::BaseVisitor *visitor) { return static_cast< Visitor * > (visitor)->visitIfcElementType(this); } const std::string &IfcElementType::type() const { return IfcElementType::s_type.getName(); } const Step::ClassType &IfcElementType::getClassType() { return IfcElementType::s_type; } const Step::ClassType &IfcElementType::getType() const { return IfcElementType::s_type; } bool IfcElementType::isOfType(const Step::ClassType &t) const { return IfcElementType::s_type == t ? true : IfcTypeProduct::isOfType(t); } IfcLabel IfcElementType::getElementType() { if (Step::BaseObject::inited()) { return m_elementType; } else { return Step::getUnset(m_elementType); } } const IfcLabel IfcElementType::getElementType() const { IfcElementType * deConstObject = const_cast< IfcElementType * > (this); return deConstObject->getElementType(); } void IfcElementType::setElementType(const IfcLabel &value) { m_elementType = value; } void IfcElementType::unsetElementType() { m_elementType = Step::getUnset(getElementType()); } bool IfcElementType::testElementType() const { return !Step::isUnset(getElementType()); } bool IfcElementType::init() { bool status = IfcTypeProduct::init(); std::string arg; if (!status) { return false; } arg = m_args->getNext(); if (arg == "$" || arg == "*") {<|fim▁hole|> m_elementType = Step::getUnset(m_elementType); } else { m_elementType = Step::String::fromSPF(arg); } return true; } void IfcElementType::copy(const IfcElementType &obj, const CopyOp &copyop) { IfcTypeProduct::copy(obj, copyop); setElementType(obj.m_elementType); return; } IFC2X3_EXPORT Step::ClassType IfcElementType::s_type("IfcElementType");<|fim▁end|>