text:
/**
* DiscordInternals for Webpack/React
*
* USAGE:
* const ReactInternals = makeReactInternals(rootElement, options);
*
* rootElement: {Element | string} a reference to the element react mounts to, or its id. usually will be the first <div> in <body>.
* options: {object} an optional object with the following properties (all optional)
*   injectToWindow: bool (default true): whether or not to inject the ReactInternals instance into `window`
*   injectTitle: string (default 'DiscordInternals'): the name of the property to inject into `window` if injectToWindow is true
*
* EXAMPLE:
* const ReactInternals = makeReactInternals('root');
* ReactInternals.WebpackModules.findByUniqueProperties(['foo', 'bar']);
*/

/* eslint strict: "off" */
/* exported makeReactInternals */

const reactInternalsDefaultOptions = {
  injectToWindow: true,
  injectTitle: 'DiscordInternals'
};

const makeReactInternals = ((rootElement, providedOptions = reactInternalsDefaultOptions) => {
  const options = {};
  Object.assign(options, reactInternalsDefaultOptions, providedOptions);

  const suppressErrors = (method, desiption) => (...params) => {
    try {
      return method(...params);
    } catch (e) {
      console.error('Error occurred in ' + desiption, e);
    }
  };

  /**
   * Function with no arguments and no return value that may be called to revert changes made by {@link monkeyPatch} method, restoring (unpatching) original method.
   * @callback cancelPatch
   */

  /**
   * This is a shortcut for calling original method using `this` and `arguments` from original call. This function accepts no arguments. This function is defined as `() => data.returnValue = data.originalMethod.apply(data.thisObject, data.methodArguments)`
   * @callback originalMethodCall
   * @return {*} The same value, which is returned from original method, also this value would be written into `data.returnValue`
   */

  /**
   * A callback that modifies method logic. This callback is called on each call of the original method and is provided all data about original call. Any of the data can be modified if necessary, but do so wisely.
   * @callback doPatchCallback
   * @param {PatchData} data Data object with information about current call and original method that you may need in your patching callback.
   * @return {*} Makes sense only when used as `instead` parameter in {@link monkeyPatch}. If something other than `undefined` is returned, the returned value replaces the value of `data.returnValue`. If used as `before` or `after` parameters, return value is ignored.
   */

  /**
   * This function monkey-patches a method on an object. The patching callback may be run before, after or instead of target method.
   * Be careful when monkey-patching. Think not only about original functionality of target method and your changes, but also about developers of other plugins, who may also patch this method before or after you. Try to change target method behaviour as little as possible, and avoid changing method signatures.
   * By default, this function logs to the console whenever a method is patched or unpatched in order to aid debugging by you and other developers, but these messages may be suppressed with the `silent` option.
   * Display name of patched method is changed, so you can see if a function has been patched (and how many times) while debugging or in the stack trace. Also, patched methods have property `__monkeyPatched` set to `true`, in case you want to check something programmatically.
   *
   * @param {object} what Object to be patched. You can can also pass class prototypes to patch all class instances. If you are patching prototype of react component you may also need {@link Renderer.rebindMethods}.
   * @param {string} methodName The name of the target message to be patched.
   * @param {object} options Options object. You should provide at least one of `before`, `after` or `instead` parameters. Other parameters are optional.
   * @param {doPatchCallback} options.before Callback that will be called before original target method call. You can modify arguments here, so it will be passed to original method. Can be combined with `after`.
   * @param {doPatchCallback} options.after Callback that will be called after original target method call. You can modify return value here, so it will be passed to external code which calls target method. Can be combined with `before`.
   * @param {doPatchCallback} options.instead Callback that will be called instead of original target method call. You can get access to original method using `originalMethod` parameter if you want to call it, but you do not have to. Can't be combined with `before` and `after`.
   * @param {boolean} [options.once=false] Set to `true` if you want to automatically unpatch method after first call.
   * @param {boolean} [options.silent=false] Set to `true` if you want to suppress log messages about patching and unpatching. Useful to avoid clogging the console in case of frequent conditional patching/unpatching, for example from another monkeyPatch callback.
   * @param {string} [options.displayName] You can provide meaningful name for class/object provided in `what` param for logging purposes. By default, this function will try to determine name automatically.
   * @return {cancelPatch} Function with no arguments and no return value that should be called to cancel (unpatch) this patch. You should save and run it when your plugin is stopped.
   */
  const monkeyPatch = (what, methodName, options) => {
    const {
      before,
      after,
      instead,
      once = false,
      silent = false
    } = options;
    const displayName = options.displayName || what.displayName || what.name || what.constructor.displayName || what.constructor.name;
    if (!silent) console.log('patch', methodName, 'of', displayName);
    const origMethod = what[methodName];
    const cancel = () => {
      if (!silent) console.log('unpatch', methodName, 'of', displayName);
      what[methodName] = origMethod;
    };
    what[methodName] = function() {
      /**
       * @interface
       * @name PatchData
       * @property {object} thisObject Original `this` value in current call of patched method.
       * @property {Arguments} methodArguments Original `arguments` object in current call of patched method. Please, never change function signatures, as it may cause a lot of problems in future.
       * @property {cancelPatch} cancelPatch Function with no arguments and no return value that may be called to reverse patching of current method. Calling this function prevents running of this callback on further original method calls.
       * @property {function} originalMethod Reference to the original method that is patched. You can use it if you need some special usage. You should explicitly provide a value for `this` and any method arguments when you call this function.
       * @property {originalMethodCall} callOriginalMethod This is a shortcut for calling original method using `this` and `arguments` from original call.
       * @property {*} returnValue This is a value returned from original function call. This property is available only in `after` callback or in `instead` callback after calling `callOriginalMethod` function.
       */
      const data = {
        thisObject: this,
        methodArguments: arguments,
        cancelPatch: cancel,
        originalMethod: origMethod,
        callOriginalMethod: () => data.returnValue = data.originalMethod.apply(data.thisObject, data.methodArguments)
      };
      if (instead) {
        const tempRet = suppressErrors(instead, '`instead` callback of ' + what[methodName].displayName)(data);
        if (tempRet !== undefined)
          data.returnValue = tempRet;
      } else {
        if (before) suppressErrors(before, '`before` callback of ' + what[methodName].displayName)(data);
        data.callOriginalMethod();
        if (after) suppressErrors(after, '`after` callback of ' + what[methodName].displayName)(data);
      }
      if (once) cancel();
      return data.returnValue;
    };
    what[methodName].__monkeyPatched = true;
    what[methodName].displayName = 'patched ' + (what[methodName].displayName || methodName);
    return cancel;
  };

  const WebpackModules = (() => {

    // eslint-disable-next-line no-undef
    const req = typeof(webpackJsonp) === 'function' ? webpackJsonp([], {
      '__extra_id__': (module, exports, req) => exports.default = req
    // eslint-disable-next-line no-undef
    }, ['__extra_id__']).default : webpackJsonp.push([
      [], {
        '__extra_id__': (module, exports, req) => module.exports = req
      },
      [
        ['__extra_id__']
      ]
    ]);
    delete req.m.__extra_id__;
    delete req.c.__extra_id__;

    /**
     * Predicate for searching module
     * @callback modulePredicate
     * @param {*} module Module to test
     * @return {boolean} Returns `true` if `module` matches predicate.
     */

    /**
     * Look through all modules of internal Discord's Webpack and return first one that matches filter predicate.
     * At first this function will look through already loaded modules cache. If no loaded modules match, then this function tries to load all modules and match for them. Loading any module may have unexpected side effects, like changing current locale of moment.js, so in that case there will be a warning the console. If no module matches, this function returns `null`. You should always try to provide a predicate that will match something, but your code should be ready to receive `null` in case of changes in Discord's codebase.
     * If module is ES6 module and has default property, consider default first; otherwise, consider the full module object.
     * @param {modulePredicate} filter Predicate to match module
     * @param {object} [options] Options object.
     * @param {boolean} [options.cacheOnly=false] Set to `true` if you want to search only the cache for modules.
     * @return {*} First module that matches `filter` or `null` if none match.
     */
    const find = (filter, options = {}) => {
      const {
        cacheOnly = true
      } = options;
      for (let i in req.c) {
        if (req.c.hasOwnProperty(i)) {
          let m = req.c[i].exports;
          if (m && m.__esModule && m.default && filter(m.default))
            return m.default;
          if (m && filter(m))
            return m;
        }
      }
      if (cacheOnly) {
        console.warn('Cannot find loaded module in cache');
        return null;
      }
      console.warn('Cannot find loaded module in cache. Loading all modules may have unexpected side effects');
      for (let i = 0; i < req.m.length; ++i) {
        try {
          let m = req(i);
          if (m && m.__esModule && m.default && filter(m.default))
            return m.default;
          if (m && filter(m))
            return m;
        } catch (e) {/* empty */}
      }
      console.warn('Cannot find module');
      return null;
    };

    /**
     * Look through all modules of internal Discord's Webpack and return first object that has all of following properties. You should be ready that in any moment, after Discord update, this function may start returning `null` (if no such object exists anymore) or even some different object with the same properties. So you should provide all property names that you use, and often even some extra properties to make sure you'll get exactly what you want.
     * @see Read {@link find} documentation for more details how search works
     * @param {string[]} propNames Array of property names to look for
     * @param {object} [options] Options object to pass to {@link find}.
     * @return {object} First module that matches `propNames` or `null` if none match.
     */
    const findByUniqueProperties = (propNames, options) => find(module => propNames.every(prop => module[prop] !== undefined), options);

    /**
     * Look through all modules of internal Discord's Webpack and return first object that has `displayName` property with following value. This is useful for searching for React components by name. Take into account that not all components are exported as modules. Also, there might be several components with the same name.
     * @see Use {@link ReactComponents} as another way to get react components
     * @see Read {@link find} documentation for more details how search works
     * @param {string} displayName Display name property value to look for
     * @param {object} [options] Options object to pass to {@link find}.
     * @return {object} First module that matches `displayName` or `null` if none match.
     */
    const findByDisplayName = (displayName, options) => find(module => module.displayName === displayName, options);

    return {
      find,
      findByUniqueProperties,
      findByDisplayName
    };

  })();

  const React = WebpackModules.findByUniqueProperties(['Component', 'PureComponent', 'Children', 'createElement', 'cloneElement']);

  /**
   * Lexicographical version parts comparator.
   * @param {string} a Version number string consist of integer numbers and dot separators
   * @param {string} b Version number string consist of integer numbers and dot separators
   * @return {number} Returns 0 if versions are the same. Returns value less then zero if version a is earlier than version b and returns value greater than zero otherwise
   */
  const versionCompare = (a, b) => {
    if (a === b) return 0;
    a = a.split('.');
    b = b.split('.');
    const n = Math.min(a.length, b.length);
    let result = 0;
    for (let i = 0; !result && i < n; ++i)
      result = a[i] - b[i];
    if (!result)
      result = a.length - b.length;
    return result;
  };

  /**
   * Get React Internal Instance mounted to DOM element
   * @author noodlebox
   * @param {Element} e DOM element to get React Internal Instance from
   * @return {object|null} Returns React Internal Instance mounted to this element if exists
   */
  const getInternalInstance = e => e[Object.keys(e).find(k => k.startsWith('__reactInternalInstance'))];

  /**
   * Get React component instance of closest owner of DOM element matched by filter
   * @deprecated Use {@link Renderer.doOnEachComponent} or BDv2 Reflection instead
   * @author noodlebox
   * @param {Element} e DOM element to start react component searching
   * @param {object} options Filter to match React component by display name. If `include` if provided, `exclude` value is ignored
   * @param {string[]} options.include Array of names to allow.
   * @param {string[]} options.exclude Array of names to ignore.
   * @return {object|null} Closest matched React component instance or null if none is matched
   */
  const getOwnerInstance = versionCompare(React.version, '16') < 0 ?
    (e, options = {}) => {
      const {
        include,
        exclude = ['Popout', 'Tooltip', 'Scroller', 'BackgroundFlash']
      } = options;
      if (e === undefined) {
        return undefined;
      }
      const excluding = include === undefined;
      const filter = excluding ? exclude : include;

      function getDisplayName(owner) {
        const type = owner._currentElement.type;
        const constructor = owner._instance && owner._instance.constructor;
        return type.displayName || constructor && constructor.displayName || null;
      }

      function classFilter(owner) {
        const name = getDisplayName(owner);
        return (name !== null && !!(filter.includes(name) ^ excluding));
      }

      for (let prev, curr = getInternalInstance(e); !_.isNil(curr); prev = curr, curr = curr._hostParent) {
        if (prev !== undefined && !_.isNil(curr._renderedChildren)) {
          let owner = Object.values(curr._renderedChildren)
            .find(v => !_.isNil(v._instance) && v.getHostNode() === prev.getHostNode());
          if (!_.isNil(owner) && classFilter(owner)) {
            return owner._instance;
          }
        }

        if (_.isNil(curr._currentElement)) {
          continue;
        }
        let owner = curr._currentElement._owner;
        if (!_.isNil(owner) && classFilter(owner)) {
          return owner._instance;
        }
      }

      return null;
    } :
    (e, options = {}) => {
      const {
        include,
        exclude = ['Popout', 'Tooltip', 'Scroller', 'BackgroundFlash']
      } = options;
      if (e === undefined) {
        return undefined;
      }
      const excluding = include === undefined;
      const filter = excluding ? exclude : include;

      function getDisplayName(owner) {
        const type = owner.type;
        const constructor = owner.stateNode && owner.stateNode.constructor;
        return type && type.displayName || constructor && (constructor.displayName || constructor.name) || null;
      }

      function classFilter(owner) {
        const name = getDisplayName(owner);
        return (name !== null && !!(filter.includes(name) ^ excluding));
      }

      let curr = getInternalInstance(e);
      while (curr) {
        if (classFilter(curr) && !(curr instanceof HTMLElement)) {
          return curr.stateNode;
        }
        curr = curr.return;
      }

      return null;
    };
  getOwnerInstance.displayName = 'getOwnerInstance';

  const Renderer = (() => {

    /**
     * Generator for recursive traversal of nested arrays
     * @param {object} parent Parent object which contains target property (array)
     * @param {string} key Key of the target property (array) in parent object.
     * @return {Iterable<TraverseItem>} Returns iterable of objects with item, parent and key properties. If target property is not array, an iterable will be returned with only one element, the target property itself.
     */
    const recursiveArray = (parent, key, count = 1) => {
      let index = 0;

      function* innerCall(parent, key) {
        const item = parent[key];
        if (item instanceof Array) {
          for (const subKey of item.keys()) {
            yield* innerCall(item, subKey);
          }
        } else {
          /**
           @interface
            @name TraverseItem
            @property {*} item Current item
            @property {object} parent Parent object which contains current item
            @property {string} key Key of the current item in the parent object
            */
          yield {
            item,
            parent,
            key,
            index: index++,
            count
          };
        }
      }

      return innerCall(parent, key);
    };

    const recursiveArrayCount = (parent, key) => {
      let count = 0;
      // eslint-disable-next-line no-empty-pattern
      for (let {} of recursiveArray(parent, key))
        ++count;
      return recursiveArray(parent, key, count);
    };

    /**
     * Generator for recursive traversal of children in react element. Target react element is also included into result set
     * @param {object} parent Parent object which contains target property (react element)
     * @param {string} key Key of the target property (react element) in parent object.
     * @return {Iterable<TraverseItem>} Returns iterable of objects with item, parent and key properties.
     */
    function* recursiveChildren(parent, key, index = 0, count = 1) {
      const item = parent[key];
      yield {
        item,
        parent,
        key,
        index,
        count
      };
      if (item && item.props && item.props.children) {
        for (let {
          parent,
          key,
          index,
          count
        } of recursiveArrayCount(item.props, 'children')) {
          yield* recursiveChildren(parent, key, index, count);
        }
      }
    }

    if (typeof rootElement == 'string') {
      rootElement = document.getElementById(rootElement);
    }
    const reactRootInternalInstance = () => rootElement._reactRootContainer._internalRoot.current;

    /**
     * Generator for recursive traversal of rendered react component tree. Only component instances are returned.
     * @param {object} [internalInstance] React Internal Instance of tree root. If not provided, default one is used
     * @return {Iterable<Component>} Returns iterable of rendered react component instances.
     */
    const recursiveComponents = versionCompare(React.version, '16') < 0 ?
      function*(internalInstance = reactRootInternalInstance()) {
        if (internalInstance._instance)
          yield internalInstance._instance;
        if (internalInstance._renderedComponent)
          yield* recursiveComponents(internalInstance._renderedComponent);
        if (internalInstance._renderedChildren)
          for (let child of Object.values(internalInstance._renderedChildren))
            yield* recursiveComponents(child);
      } :
      function*(internalInstance = reactRootInternalInstance()) {
        if (internalInstance.stateNode)
          yield internalInstance.stateNode;
        if (internalInstance.sibling)
          yield* recursiveComponents(internalInstance.sibling);
        if (internalInstance.child)
          yield* recursiveComponents(internalInstance.child);
      };

    const returnFirst = (iterator, process) => {
      for (let child of iterator) {
        const retVal = process(child);
        if (retVal !== undefined) {
          return retVal;
        }
      }
    };

    /**
     * @interface
     * @name Selector
     * @property {Component} type React component class to match target react component element
     * @property {string} tag Tag name to match target react html element
     * @property {boolean|string|RegExp} className Match react element with className prop. <br/> If `true` is provided - match any element that has className prop. <br/> If string is provided - select element by exact match with any of it space separated classes in className prop. <br/> If RegExp is provided - select element in which regexp matches with any of it space separated classes in className prop.
     * @property {boolean|string|RegExp} text Match text nodes. <br/> If `true` is provided - match any text node. <br/> If string is provided - select text nodes by exact match. <br/> If RegExp is provided - select text nodes which is matched by regexp.
     * @property {number} nthChild Match element only if it is nth child of the parent element. Negative values counts children from the end, ex. -1 means last child.
     * @property {number} eq Selects nth match of selector
     * @property {Selector} hasChild Matches current element only if it has direct child that matches selector
     * @property {Selector} hasSuccessor Matches current element only if it has any successor that matches selector
     * @property {Selector} child Selects direct child of current element that matches selector
     * @property {Selector} successor Selects any successor of current element that matches selector
     */

    /**
     * Returns first react element child that matches the selector
     * @param {object} rootParent Parent object which contains root react element to start search.
     * @param {string} rootKey Key of the root react element to start search in parent object.
     * @param {Selector} selector Selector object to match children
     * @return {TraverseItem} Object with item, parent and key properties of matched react element object or empty object if nothing matches
     */
    const getFirstChild = (rootParent, rootKey, selector) => {
      const getDirectChild = (item, selector) => {
        if (item && item.props && item.props.children) {
          return returnFirst(recursiveArrayCount(item.props, 'children'), checkFilter.bind(null, selector));
        }
      };
      const checkFilter = (selector, {
        item,
        parent,
        key,
        count,
        index
      }) => {
        let match = true;
        if (match && selector.type)
          match = item && selector.type === item.type;
        if (match && selector.tag)
          match = item && typeof item.type === 'string' && selector.tag === item.type;
        if (match && selector.className) {
          match = item && item.props && typeof item.props.className === 'string';
          if (match) {
            const classes = item.props.className.split(' ');
            if (selector.className === true)
              match = !!classes[0];
            else if (typeof selector.className === 'string')
              match = classes.includes(selector.className);
            else if (selector.className instanceof RegExp)
              match = !!classes.find(cls => selector.className.test(cls));
            else match = false;
          }
        }
        if (match && selector.text) {
          if (selector.text === true)
            match = typeof item === 'string';
          else if (typeof selector.text === 'string')
            match = item === selector.text;
          else if (selector.text instanceof RegExp)
            match = typeof item === 'string' && selector.text.test(item);
          else match = false;
        }
        if (match && selector.nthChild)
          match = index === (selector.nthChild < 0 ? count + selector.nthChild : selector.nthChild);
        if (match && selector.hasChild)
          match = getDirectChild(item, selector.hasChild);
        if (match && selector.hasSuccessor)
          match = item && !!getFirstChild(parent, key, selector.hasSuccessor).item;
        if (match && selector.eq) {
          --selector.eq;
          return;
        }
        if (match) {
          if (selector.child) {
            return getDirectChild(item, selector.child);
          } else if (selector.successor) {
            return getFirstChild(parent, key, selector.successor);
          }
          return {
            item,
            parent,
            key
          };
        }
      };
      return returnFirst(recursiveChildren(rootParent, rootKey), checkFilter.bind(null, selector)) || {};
    };

    /**
     * Predicate which answers should we apply actions in current render call or not
     * @callback FilterPredicate
     * @param {PatchData} data All data about current call of render function
     * @return {boolean} Return `true` if actions should be applied and `false` otherwise.
     */

    /**
     * Callback to generate content for render patch action
     * @callback ContentCallback
     * @param {Component} thisObject This object of the patched react component
     * @param {*} item React element, text node or any other object matched by selector
     * @return {*} Return new content that will be used to apply action
     */

    /**
     * Safely patches render function of react component to introduce some new behaviour
     * @param {Component} component React component class to patch
     * @param {object[]} actions Array of actions that should be done to change behaviour
     * @param {FilterPredicate} [actions.filter] Predicate which answers should we apply this action in current render call or not. If not provided - apply always
     * @param {Selector} actions.selector A selector to select first match of something in rendered react element tree. Null placeholders can be also matched.
     * @param {string} actions.method Which method should be used to apply content to selected object. One of: prepend, append, replaceChildren, before, after, replace
     * @param {ContentCallback|*} actions.content New content that will be used to apply action or callback to generate it
     * @param {FilterPredicate} [filter] Predicate which answers should we apply any actions in current render call or not. If not provided - apply always
     * @return {cancelPatch} Function with no arguments and no return value that should be called to cancel this patch. You should save and run it when your plugin is stopped.
     */
    const patchRender = (component, actions, filter) => {
      if (!(actions instanceof Array)) {
        console.warn('Renderer.patchRender expects array of action objects');
        actions = [actions];
      }
      const cancel = monkeyPatch(component.prototype, 'render', {
        after: (data) => {
          if (!filter || suppressErrors(filter, '`filter` callback of patchRender')(data)) {
            for (let action of actions) {
              if (!action.filter || suppressErrors(action.filter, '`filter` callback of patchRender action')(data)) {
                const {
                  item,
                  parent,
                  key
                } = getFirstChild(data, 'returnValue', action.selector);
                if (item) {
                  const content = typeof action.content === 'function' ?
                    suppressErrors(action.content, '`content` callback of patchRender action')(data.thisObject, item) :
                    action.content;
                  switch (action.method) {
                    case 'prepend':
                      item.props.children = [content, item.props.children];
                      break;
                    case 'append':
                      item.props.children = [item.props.children, content];
                      break;
                    case 'replaceChildren':
                      item.props.children = content;
                      break;
                    case 'before':
                      parent[key] = [content, parent[key]];
                      break;
                    case 'after':
                      parent[key] = [parent[key], content];
                      break;
                    case 'replace':
                      parent[key] = content;
                      break;
                    default:
                      console.error('Unexpected method `' + action.method + '` of patchRender action');
                  }
                }
              }
            }
          }
        }
      });
      doOnEachComponent(component, c => c.forceUpdate());
      return () => {
        cancel();
        doOnEachComponent(component, c => c.forceUpdate());
      };
    };

    const plannedActions = new Map();
    let plannedPromise, plannedPromiseResolver;
    const runPlannedActions = () => {
      for (let component of recursiveComponents()) {
        const actions = plannedActions.get(component.constructor) || plannedActions.get(component.constructor.displayName);
        if (actions) {
          for (let action of actions) {
            action(component);
          }
        }
      }
      plannedPromiseResolver();
      plannedActions.clear();
      plannedPromise = null;
      plannedPromiseResolver = null;
    };

    /**
     * Traverse rendered react tree and do action on each matched component. Components can be matched by display name or by class
     * Actions are not applied immediately but rather they are planned to be done on next asynchronous traversal.
     * @param {Component|string} componentType Display name or component class to match component in tree
     * @param {function(Component)} action Action that will be applied to each matched component. Component instance is provided as first param.
     * @return {Promise} Promise that is resolved with no data when all actions are applied
     */
    const doOnEachComponent = (componentType, action) => {
      if (plannedActions.size === 0) {
        setImmediate(runPlannedActions);
        plannedPromise = new Promise(resolve => plannedPromiseResolver = resolve);
      }
      if (!plannedActions.has(componentType))
        plannedActions.set(componentType, []);
      plannedActions.get(componentType).push(action);
      return plannedPromise;
    };

    /**
     * Use this method to rebind all non react lifecycle methods that you have patched. Discord binds all those methods on component creation, so patching prototype isn't enough.
     * This method creates a patch to rebind methods on each component creation (mounting)
     * @param {Component} component Component class to rebind methods
     * @param {string[]} methods Array of methods name to rebind
     * @return {cancelPatch} Function with no arguments and no return value that should be called to cancel this patch. You should save and run it when your plugin is stopped.
     */
    const rebindMethods = (component, methods) => {
      const rebind = function(thisObject) {
        for (let method of methods) {
          thisObject[method] = component.prototype[method].bind(thisObject);
        }
        thisObject.forceUpdate();
      };
      doOnEachComponent(component, rebind);
      let cancel;
      if (component.prototype.componentWillMount)
        cancel = monkeyPatch(component.prototype, 'componentWillMount', {
          silent: true,
          after: ({
            thisObject
          }) => {
            rebind(thisObject);
          }
        });
      else {
        component.prototype.componentWillMount = function() {
          rebind(this);
        };
        cancel = () => delete component.prototype.componentWillMount;
      }
      return () => {
        cancel();
        doOnEachComponent(component, rebind);
      };
    };

    return {
      patchRender,
      recursiveArray,
      recursiveChildren,
      recursiveComponents,
      getFirstChild,
      doOnEachComponent,
      rebindMethods
    };
  })();

  const Filters = {
    byPrototypeFields: (fields, selector = x => x) => (module) => {
      const component = selector(module);
      if (!component) return false;
      if (!component.prototype) return false;
      for (const field of fields) {
        if (!component.prototype[field]) return false;
      }
      return true;
    },
    byCode: (search, selector = x => x) => (module) => {
      const method = selector(module);
      if (!method) return false;
      return method.toString().search(search) !== -1;
    },
    and: (...filters) => (module) => {
      for (const filter of filters) {
        if (!filter(module)) return false;
      }
      return true;
    }
  };

  const ReactComponents = (() => {

    const components = {};
    const listeners = {};
    const noNameComponents = new Set();
    const newNamedComponents = new Set();
    const nameSetters = {};
    const namesClushMessage = (oldName, newName) => `Several name setters for one component is detected! Old name is ${oldName}, new name is ${newName}. Only new name will be available as displayName, but all getters will resolve`;
    const put = component => {
      if (typeof component === 'function') {
        const name = component.displayName;
        if (name) {
          if (!components[name]) {
            components[name] = component;
            if (listeners[name]) {
              listeners[name].forEach(f => f(component));
              listeners[name] = null;
            }
            if (nameSetters[name]) {
              delete nameSetters[name];
            }
          }
        } else {
          if (!noNameComponents.has(component)) {
            for (const [name, filter] of Object.entries(nameSetters)) {
              if (filter(component)) {
                if (component.displayName) {
                  console.warn(namesClushMessage(component.displayName, name), component);
                }
                component.displayName = name;
                delete nameSetters[name];
                put(component);
              }
            }
            if (!component.displayName) {
              noNameComponents.add(component);
            } else {
              newNamedComponents.add(component);
            }
          }
        }
      }
    };

    /**
     * Set displayName for any React component that do not have it yet. Name change is applied to first component that match filter.
     * You can also set callback or use returned promise to know when the name is set. If component is already rendered, name will be set and callback will be called immediately.
     * Any listners to get component by name will also trigger if we set name to a component
     * @param {string} name Display name to set
     * @param {function(component)} filter Predicate to match component
     * @param {function} [callback] Callback that will be called before rendering of component matching filter or immediately if component is already rendered
     * @return {Promise} Promise object that resolves when component matching filter is rendered. Unlike callback promise always resolves asynchronously, so you can't catch moment before rendering.
     */
    const setName = (name, filter, callback = null) => {
      if (!components[name]) {
        for (let component of noNameComponents) {
          if (filter(component)) {
            component.displayName = name;
            noNameComponents.delete(component);
            newNamedComponents.add(component);
            put(component);
            break;
          }
        }
      }
      if (!components[name]) {
        for (let component of newNamedComponents) {
          if (filter(component)) {
            console.warn(namesClushMessage(component.displayName, name), component);
            component.displayName = name;
            put(component);
            break;
          }
        }
      }
      if (!components[name]) {
        nameSetters[name] = filter;
      }
      return get(name, callback);
    };

    /**
     * Get React component by displayName as soon as it will be rendered. Be careful, there may be several different components with same name.
     * If component is already rendered, callback is called immediately.
     * @param {string} name Display name of component
     * @param {function} [callback] Callback that will be called before rendering of component or immediately if component is already rendered
     * @return {Promise} Promise object that resolves when component is rendered. Unlike callback promise always resolves asynchronously, so you can't catch moment before rendering.
     */
    const get = (name, callback = null) => new Promise(resolve => {
      const listener = component => {
        if (callback) callback(component);
        resolve(component);
      };
      if (components[name]) {
        listener(components[name]);
      } else {
        if (!listeners[name]) listeners[name] = [];
        listeners[name].push(listener);
      }
    });

    /**
     * Get all React components by displayName as soon as all have been rendered at least once. Be careful, there may be several different components with same name.
     * @param {string[]} names Array of components display names
     * @param {function} [callback] Callback that will be called before rendering of last component or immediately if all components are already rendered
     * @return {Promise} Promise object that resolves when all components will be rendered at least once.
     */
    const getAll = (names, callback = null) => new Promise(resolve => {
      const components = [];
      const makeOneCallback = i => component => {
        components[i] = component;
        console.log('get: ' + names[i] + ' from getAll ' + names);
        for (const key of names.keys()) {
          if (!components[key]) {
            return;
          }
        }
        if (callback) callback(components);
        resolve(components);
      };
      for (const [i, name] of names.entries()) {
        get(name, makeOneCallback(i));
      }
    });

    /**
     * Scan all components already rendered in DOM, and add new ones to the internal dictionary.
     * This function may be called manually to rescan DOM in case if some components are failed to be detected automatically
     */
    const scanAllRendered = () => {
      for (let component of Renderer.recursiveComponents()) {
        put(component.constructor);
      }
    };

    monkeyPatch(React, 'createElement', {
      displayName: 'React',
      before: ({
        methodArguments
      }) => {
        put(methodArguments[0]);
      }
    });

    React.Component.prototype.componentWillMount = function() {
      put(this.constructor);
    };

    React.Component.prototype.UNSAFE_componentWillMount = function() {
      put(this.constructor);
    };

    scanAllRendered();

    return {
      get,
      getAll,
      setName,
      scanAllRendered
    };

  })();

  const localReactInternals = {
    monkeyPatch,
    WebpackModules,
    ReactComponents,
    Renderer,
    Filters,
    getInternalInstance,
    getOwnerInstance,
    versionCompare,
    React
  };
  if (options.injectToWindow) {
    window[options.injectTitle] = localReactInternals;
  }

  return localReactInternals;
});


text:
local config = require 'ffviii-config'
dofile 'ffviii-util.lua'
dofile 'ffviii-context.lua'

-- state engine/states
dofile 'ffviii-state-engine.lua'
dofile 'ffviii-state-idle.lua'
dofile 'ffviii-state-draw.lua'
dofile 'ffviii-state-runaway.lua'
dofile 'ffviii-state-acceptbattlerewards.lua'
dofile 'ffviii-state-save.lua'
dofile 'ffviii-state-reload.lua'
dofile 'ffviii-state-healcharacter.lua'
dofile 'ffviii-state-gfability.lua'
dofile 'ffviii-state-exitmenu.lua'
dofile 'ffviii-state-seifergrind.lua'
dofile 'ffviii-state-seiferfindbattle.lua'
dofile 'ffviii-state-traincardgrind.lua'
dofile 'ffviii-state-trainfindbattle.lua'
dofile 'ffviii-state-rosettarng.lua'
dofile 'ffviii-state-advancedcardgrind.lua'
dofile 'ffviii-state-levelupenemy.lua'

do
  local clear_keys = {}
  clear_keys.Circle = false
  clear_keys.Cross = false
  clear_keys.Triangle = false
  clear_keys.Square = false
  clear_keys.Up = false
  clear_keys.Left = false
  clear_keys.Down = false
  clear_keys.Right = false
  joypad.set(clear_keys, 1)

  local bot_context = {}
  local game_context = {}

  local state_engine = StateEngine:new({
    { 0, IdleState:new() },

    --{ 1, SeiferFindBattleState:new() },
    { 1, TrainFindBattleState:new() },

    { 2, ExitMenuState:new() },
    { 3, GfAbilityState:new() },

    --{ 5, SeiferGrindState:new() },
    --{ 5, TrainCardGrindState:new() },
    { 4, RunAwayState:new() },

    --{ 5, AdvancedCardGrindState:new() },
    { 6, DrawState:new() },
    { 7, LevelUpEnemyState:new() },

    { 8, SaveGameState:new() },
    { 9, HealCharacterState:new() },
    { 10, AcceptBattleRewardsState:new() },

    --{ 11, RosettaRngState:new() },

    { 100, ReloadGameState:new() },
  })

  if config.USE_TURBO then
    client.speedmode(1600)
    client.SetSoundOn(false)
    emu.minimizeframeskip(false)
  end

  local should_continue = true
  local run_bot = false

  while should_continue do
    local pressed_keys = joypad.get(1)

    if pressed_keys.L1 and pressed_keys.Square then
      run_bot = false
    elseif pressed_keys.R1 and pressed_keys.Square then
      run_bot = true
    end

    if run_bot then
      -- if pressed_keys.Square then
      --   should_continue = false
      --   client.speedmode(100)
      --   client.SetSoundOn(true)
      --   emu.minimizeframeskip(true)
      -- end

      local keys = {}

      updateGameContext(game_context)
      updateBotContext(config, game_context, bot_context)

      state_engine:run(game_context, bot_context, keys)

      joypad.set(keys, 1)
    end

    emu.frameadvance()
  end
end

redpajama_set_name: RedPajamaGithub


text:
A gene is represented as a string of length `n` (where nn is divisible by `4`),
composed of the letters `A`, `C`, `T`, and `G`. It is considered to be *steady* if each of the four
letters occurs exactly `n/4` times. For example, `GACT` and `AAGTGCCT` are both steady genes.

Bear Limak is a famous biotechnology scientist who specializes in modifying bear DNA to make it steady.
Right now, he is examining a gene represented as a string ss. It is not necessarily steady. Fortunately,
Limak can choose one (maybe empty) substring of ss and replace it with any substring of the same length.

Modifying a large substring of bear genes can be dangerous. Given a string `s`, can you help
Limak find the length of the smallest possible substring that he can replace to make ss a steady gene?

Note: A substring of a string `S` is a subsequence made up of zero or more *consecutive* characters of `S`.

### Input Format

The first line contains an interger `n` divisible by `4`, denoting the length of a string `s`.
The second line contains a string `s` of length `n`. Each character is one of the four: `A`, `C`, `T`, `G`.

### Constraints

```
4≤n≤500000
n is divisible by 4
```

### Subtask

```
4≤n≤2000 in tests worth 30% points.
```

### Output Format

On a new line, print the minimum length of the substring replaced to make `s` stable.

### Sample Input

```
8
GAAATAAA
```

### Sample Output

```
5
```

### Explanation

One optimal solution is to replace a substring `AAATA` with `TTCCG`, resulting in `GTTCCGAA`.
The replaced substring has length `5`, so we print `5` on a new line.

## References

* [Description](http://juliachencoding.blogspot.ru/2016/03/hackerrank-bear-steady-gene-ii.html)
* [Code samples](https://gist.github.com/jianminchen/b8263048c297473319c23836e9468c14)


text:
Path
****

.. highlight:: bash

::

  if [ -d "$HOME/bin" ] ; then
    export PATH=$HOME/bin:$PATH
  fi

From my ``~/.bashrc``::

  # funky function nicked from Red Hat and altered a little
  # adds entries to the PATH at the start or end and only if the dir exists
  pathmunge() {
      if ! echo $PATH | /bin/egrep -q "(^|:)$1($|:)" && [ -d $1 ] ; then
          if [ "$2" = "after" ] ; then
              PATH=$PATH:$1
          else
              PATH=$1:$PATH
          fi
      fi
  }

  # add some useful PATH entries
  pathmunge /usr/local/sbin
  pathmunge /usr/sbin
  pathmunge /sbin
  pathmunge $HOME/bin after
  pathmunge $HOME/opt after

  # clean up
  unset pathmunge


text:
/* iCheck plugin Line skin, pink
----------------------------------- */
.icheckbox_line-pink,
.iradio_line-pink {
    position: relative;
    display: block;
    margin: 0;
    padding: 5px 15px 5px 38px;
    font-size: 13px;
    line-height: 17px;
    color: #fff;
    background: #a77a94;
    border: none;
    -webkit-border-radius: 3px;
    -moz-border-radius: 3px;
    border-radius: 3px;
    cursor: pointer;
}
    .icheckbox_line-pink .icheck_line-icon,
    .iradio_line-pink .icheck_line-icon {
        position: absolute;
        top: 50%;
        left: 13px;
        width: 13px;
        height: 11px;
        margin: -5px 0 0 0;
        padding: 0;
        overflow: hidden;
        background: url(line.png) no-repeat;
        border: none;
    }
    .icheckbox_line-pink.hover,
    .icheckbox_line-pink.checked.hover,
    .iradio_line-pink.hover {
        background: #B995A9;
    }
    .icheckbox_line-pink.checked,
    .iradio_line-pink.checked {
        background: #a77a94;
    }
        .icheckbox_line-pink.checked .icheck_line-icon,
        .iradio_line-pink.checked .icheck_line-icon {
            background-position: -15px 0;
        }
    .icheckbox_line-pink.disabled,
    .iradio_line-pink.disabled {
        background: #E0D0DA;
        cursor: default;
    }
        .icheckbox_line-pink.disabled .icheck_line-icon,
        .iradio_line-pink.disabled .icheck_line-icon {
            background-position: -30px 0;
        }
    .icheckbox_line-pink.checked.disabled,
    .iradio_line-pink.checked.disabled {
        background: #E0D0DA;
    }
        .icheckbox_line-pink.checked.disabled .icheck_line-icon,
        .iradio_line-pink.checked.disabled .icheck_line-icon {
            background-position: -45px 0;
        }

/* HiDPI support */
@media (-o-min-device-pixel-ratio: 5/4), (-webkit-min-device-pixel-ratio: 1.25), (min-resolution: 120dpi) {
    .icheckbox_line-pink .icheck_line-icon,
    .iradio_line-pink .icheck_line-icon {
        background-image: url(line@2x.png);
        -webkit-background-size: 60px 13px;
        background-size: 60px 13px;
    }
}


text:
module Mautic
  module Connections
    class Oauth2 < Mautic::Connection

      def client
        @client ||= OAuth2::Client.new(client_id, secret, {
          site: url,
          authorize_url: 'oauth/v2/authorize',
          token_url: 'oauth/v2/token',
          raise_errors: false
        })
      end

      def authorize(context)
        client.auth_code.authorize_url(redirect_uri: callback_url(context))
      end

      def get_code(code, context)
        client.auth_code.get_token(code, redirect_uri: callback_url(context))
      end

      def connection
        @connection ||= OAuth2::AccessToken.new(client, token, { refresh_token: refresh_token })
      end

      def refresh!
        @connection = connection.refresh!
        update(token: @connection.token, refresh_token: @connection.refresh_token)
        @connection
      rescue StandardError
        raise ::Mautic::TokenExpiredError, "your refresh_token is probably expired - re-authorize your connection"
      end

      def request(type, path, params = {})
        @last_request = [type, path, params]
        response = connection.request(type, path, params)
        parse_response(response)
      end

      private

      def callback_url(context)
        uri = super
        # uri.path = Mautic::Engine.routes.url_helpers.oauth2_connection_path(self)
        uri.path = context.url_for(action: "oauth2", id: self , only_path: true)
        uri.to_s
      end

    end
  end
end


text:
This repo is deprecated, AWS now supports ruby as a native runtime.

# rumbda [![Build Status](https://travis-ci.org/kleaver/rumbda.svg?branch=master)](https://travis-ci.org/kleaver/rumbda) [![Gem Version](https://badge.fury.io/rb/rumbda.svg)](https://badge.fury.io/rb/rumbda)
Run ruby scripts on aws lambda.

## Installation
```
gem install rumbda
```
or add it to the Gemfile

```
group :development do
  gem 'rumbda'
end
```

## What does rumbda do?
Rumbda does everything necessary to build a zip file for running ruby inside of an AWS Lambda. This includes downloading [traveling ruby](https://github.com/phusion/traveling-ruby), creating a bundle of the project's Gemfile dependencies, and creating a consumable .zip file for use with Lambda.

## Getting Started
Run `rumbda init` in the directory you'd like to have your Lambda project. This will create the following files in the current directory: `source/main.rb`, `Gemfile`, `.gitignore`, and `.ruby-version`. `source/main.rb` is the entry point to the ruby script. The `Gemfile` and `Gemfile.lock` are where gems are specified.

## Building the zip
```
rumbda build
# => creates a file "index.zip" which contains all files in "source/" and all gems specified in the "Gemfile"
```

### Configuring the Lambda
1. Set **Runtime** to `Node.js 6.10`.

1. Set **Code entry type** to `Upload a .ZIP file`.

1. In the **Function package** upload `index.zip` (the zip created by `rumbda build`).

1. Set **Handler** to `index.handler`.

## Example
See the [example folder](example/) for what a project using rumbda might look like.
```
pwd
#=> ~/rumbda/example
ruby --version
#=> 2.2.2
bundle install
#=> installs dependencies, creates Gemfile.lock
bundle exec rumbda build
#=> builds the index.zip file
```
After the index.zip file is built, follow the steps for [Configuring the Lambda](#configuring-the-lambda).

## Environment Variables and Events
Lambda environment variables are available to main.rb via `ENV['<variable name>']`.  See [the example](example/source/main.rb#L8).

The Lambda Event is available to the script via `ARGV[0]`.  See [the example](example/source/main.rb#L9).
If testing the script locally, simply pass in a json as the first argument to the script:
```
$ ruby main.rb "$(cat test_event.json)"
```

## Return JSON for API Gateway
If needing to return JSON from your lambda (e.g. for use in AWS API Gateway) write to a file path provided in your lambda's environment at key 'RUMBDA_RESULT_JSON_FILENAME'.

```ruby
File.open(ENV['RUMBDA_RESULT_JSON_FILENAME'], 'w') do |file|
  file.write(JSON.dump({ statusCode: 200, body: '' }))
end
```

The file contents should be valid JSON.

## Command Reference
| Command        | Purpose                                                                                |
|:---------------|:---------------------------------------------------------------------------------------------------------------------------|
| `rumbda init`  | Initializes a directory as rumbda project.                                                                                |
| `rumbda build` | Packages everything in `./source/` directory as well as gems specified in the `Gemfile` into a zip file called `index.zip` |


text:
'use strict';

angular.module('distributor').config(['$stateProvider',function($stateProvider) {

  $stateProvider.
    state('distributorOverview', {
      resolve: {
        credentials: function ($http){
          return  $http.get('/bank/credentials');
        }
      },
      controller: 'distributorCtrl',
      url: '/distributor',
      templateUrl: 'modules/distributor/views/distributor.client.view.html'
    })

    .state('myDistribution', {
      resolve: {
        credentials: function ($http){
          return  $http.get('/bank/credentials');
        }
      },
      controller: 'myDistribution',
      url: '/distributor/myDistribution',
      templateUrl: 'modules/distributor/views/myDistribution.client.view.html'
    })
    .state('distributionUser', {
      resolve: {
        credentials: function ($http){
          return  $http.get('/bank/credentials');
        }
      },
      controller: 'userDistributionCtrl',
      url: '/distributor/:username',
      templateUrl: 'modules/distributor/views/user.distributor.client.view.html'
    });
}]);


text:
ANDROID_ICU_UC="${ANDROID_ICU_UC:-$HOME/libiconv-libicu-android}"

cd "$(dirname $0)" &&

SWIFT_ROOT="$(dirname $(dirname $(which swiftc)))" &&
BUILD_DIR="$(dirname $SWIFT_ROOT)" &&

\cp -v ../../platform_external_libxml2/libxml2.so ../../curl/libcurl.so ../../swift-corelibs-libdispatch/libdispatch.so "$ANDROID_ICU_UC"/armeabi-v7a/libicu*.so "${SWIFT_ROOT}/lib/swift/android" &&

\cp -v "${BUILD_DIR}/libdispatch-linux-x86_64/src/swift/Dispatch.swift"* "${SWIFT_ROOT}/lib/swift/android/armv7" &&

rsync -arv "../../swift-corelibs-libdispatch/dispatch" "${SWIFT_ROOT}/lib/swift/" &&

\cp -v "../../swift-corelibs-libdispatch/private/"*.h "${SWIFT_ROOT}/lib/swift/dispatch" &&

rpl -R -e libicu libscu "${SWIFT_ROOT}/lib/swift/android"/lib{icu,swift,Foundation,xml2}*.so &&

for i in "${SWIFT_ROOT}/lib/swift/android"/libicu*.so; do \mv -f $i ${i/libicu/libscu}; done


text:
// Copyright 2009 the Sputnik authors.  All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/*---
info: Equivalent to the expression RegExp.prototype.exec(string) != null
es5id: 15.10.6.3_A1_T17
description: RegExp is /ll|l/ and tested string is null
---*/

var __re = /ll|l/;

//CHECK#0
if (__re.test(null) !== (__re.exec(null) !== null)) {
	$ERROR('#0: __re = /ll|l/; __re.test(null) === (__re.exec(null) !== null)');
}


text:
package fr.esiea.raby_ambassa.game;

import fr.esiea.raby_ambassa.game.CommonPot;
import junit.framework.TestCase;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/**
 * Created by Zenika on 03/03/2017.
 */
@RunWith(JUnit4.class)
public class CommonPotTest extends TestCase{

    private CommonPot commonPot;

    @Before
    public void init() {
        commonPot = CommonPot.getInstance();
        commonPot.addLetter('a');
        commonPot.addLetter('b');
        commonPot.addLetter('c');
    }

    @Test
    public void testIfLetterExists() {
        assertTrue(commonPot.isWordAvailable("abc"));
        assertFalse(commonPot.isWordAvailable("def"));
    }

    @Test
    public void testRemoveLetter() {
        commonPot.removeLetters("ab");
        assertTrue(commonPot.isWordAvailable("c"));
        assertFalse(commonPot.isWordAvailable("abc"));
    }

}


text:
import React, { PropTypes } from 'react'
import classNames from 'classnames'
import Downshift from 'downshift'
import './drop-down.scss'

const Dropdown = ({ items, titleMap, label = '', active, onChange }) => {
  const id = label.toLowerCase().replace(/\s+/g, '-')
  return (
    <Downshift
      selectedItem={active}
      onChange={onChange}
      render={({
        isOpen,
        getLabelProps,
        getButtonProps,
        getItemProps,
        selectedItem,
      }) => (

            {label}

            <button id={id} className="Dropdown-btn" {...getButtonProps()}>
              {active ? (titleMap ? titleMap[active] : active) : 'Click to choose'}
            </button>
            {isOpen && (

                {items.map((item) => (
                  <button
                    {...getItemProps({ item })}
                    key={item}
                    className={classNames('Dropdown-item', selectedItem === item && 'is-active')}
                  >
                    {titleMap ? titleMap[item] : item}
                  </button>
                ))}

            )}

      )}
    />
  )
}

Dropdown.propTypes = {
  items: PropTypes.arrayOf(PropTypes.string).isRequired,
  titleMap: PropTypes.any,
  active: PropTypes.string,
  onChange: PropTypes.func.isRequired,
  label: PropTypes.string,
}

export default Dropdown


text:
__author__ = 'arkilic'

raise NotImplementedError("Waiting for @tacaswell to implement this in the library to steal it from him")


text:
(function (root, factory) {
  if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define([], function () {
      return (root.returnExportsGlobal = factory());
    });
  } else if (typeof exports === 'object') {
    // Node. Does not work with strict CommonJS, but
    // only CommonJS-like enviroments that support module.exports,
    // like Node.
    module.exports = factory();
  } else {
    root['Chartist.plugins.ctPointLabels'] = factory();
  }
}(this, function () {

  /**
   * Chartist.js plugin to display a data label on top of the points in a line chart.
   *
   */
  /* global Chartist */
  (function(window, document, Chartist) {
    'use strict';

    var defaultOptions = {
      labelClass: 'ct-label',
      labelOffset: {
        x: 0,
        y: -10
      },
      textAnchor: 'middle',
      labelInterpolationFnc: Chartist.noop
    };

    Chartist.plugins = Chartist.plugins || {};
    Chartist.plugins.ctPointLabels = function(options) {

      options = Chartist.extend({}, defaultOptions, options);

      return function ctPointLabels(chart) {
        if(chart instanceof Chartist.Line) {
          chart.on('draw', function(data) {
            if(data.type === 'point') {
              data.group.elem('text', {
                x: data.x + options.labelOffset.x,
                y: data.y + options.labelOffset.y,
                style: 'text-anchor: ' + options.textAnchor
              }, options.labelClass).text(options.labelInterpolationFnc(data.value.x === undefined ? data.value.y : data.value.x + ', ' + data.value.y));
            }
          });
        }
      };
    };

  }(window, document, Chartist));
  return Chartist.plugins.ctPointLabels;

}));


text:
babel-minify (beta)

  An ES6+ aware minifier based on the Babel toolchain.

- `babel-minify` is consumable via API, CLI, or Babel preset. Try it online - [babeljs.io/repl](http://babeljs.io/repl/#?babili=true&evaluate=false&lineWrap=false&presets=react%2Cstage-2&code=%2F%2F%20Example%20ES2015%20Code%0Aclass%20Mangler%20%7B%0A%20%20constructor(program)%20%7B%0A%20%20%20%20this.program%20%3D%20program%3B%0A%20%20%7D%0A%7D%0Anew%20Mangler()%3B%20%2F%2F%20without%20this%20it%20would%20just%20output%20nothing%20since%20Mangler%20isn%27t%20used)

> Historical note: babel-minify was renamed from babili.

## Table of Contents

- [Experimental](#experimental)
- [Requirements](#requirements)
- [Why](#why)
- [CLI](#cli)
- [Babel Preset](#babel-preset)
- [Individual Plugins](#individual-plugins)
- [Benchmarks](#benchmarks)
- [Team](#team)

## Experimental

`babel-minify` is an experimental project that attempts to use Babel's toolchain (for compilation) to do something in a similar vein, minification. It's currently in 0.x, so we don't recommend using it in production.

Checkout our [CONTRIBUTING.md](/CONTRIBUTING.md) if you want to help out!

## Requirements

- node >= 6
- babel >= 6.20.0

## Why

Current tools don't support targeting the latest version of ECMAScript. (yet)
- BabelMinify can because it is just a set of Babel plugins, and Babel already understands new syntax with our parser [Babylon](https://github.com/babel/babylon).
- When it's possible to only target browsers that support newer ES features, code sizes can be smaller because you don't have to transpile and then minify.

Check out our [blog post](http://babeljs.io/blog/2016/08/26/babili) for more info!

```js
// Example ES2015 Code
class Mangler {
  constructor(program) {
    this.program = program;
  }
}
new Mangler(); // without this it would just output nothing since Mangler isn't used
```

Before
```js
// ES2015+ code -> Babel -> BabelMinify/Uglify -> Minified ES5 Code
var a=function a(b){_classCallCheck(this,a),this.program=b};new a;
```

After

```js
// ES2015+ code -> BabelMinify -> Minified ES2015+ Code
class a{constructor(b){this.program=b}}new a;
```

## [CLI](http://babeljs.io/docs/usage/cli/)

| Package | Version | Dependencies |
|--------|-------|------------|
| [`babel-minify`](/packages/babel-minify) | [![npm](https://img.shields.io/npm/v/babel-minify.svg?maxAge=86400)](https://www.npmjs.com/package/babel-minify) | [![Dependency Status](https://david-dm.org/babel/babel-minify.svg?path=packages/babel-minify)](https://david-dm.org/babel/babel-minify?path=packages/babel-minify) |

### Install

```sh
npm install babel-minify --save-dev
```

### Usage

```sh
minify src -d lib
```

## [Babel preset](http://babeljs.io/docs/plugins/#presets)

| Package | Version | Dependencies |
|--------|-------|------------|
| [`babel-preset-minify`](/packages/babel-preset-minify) | [![npm](https://img.shields.io/npm/v/babel-preset-minify.svg?maxAge=86400)](https://www.npmjs.com/package/babel-preset-minify) | [![Dependency Status](https://david-dm.org/babel/minify.svg?path=packages/babel-preset-minify)](https://david-dm.org/babel/minify?path=packages/babel-preset-minify) |

### Install

```sh
npm install babel-preset-minify --save-dev
```

### Usage

> note: minify is still in beta, so we don't recommend using it for production code but rather the production environment.

When testing, it's recommended to run minifiers for production so less code is sent to end-users vs. in development where it can be an issue for readability when debugging. Check out the [env docs](http://babeljs.io/docs/usage/babelrc/#env-option) for more help.

> Options specific to a certain environment are merged into and overwrite non-env specific options.

`.babelrc`:

```
{
  "presets": ["es2015"],
  "env": {
    "production": {
      "presets": ["minify"]
    }
  }
}
```

Then you'll need to set the env variable which could be something like `BABEL_ENV=production npm run build`

## Individual Plugins

The `minify` repo is comprised of many npm packages. It is a [lerna](https://github.com/lerna/lerna) monorepo similar to [babel](https://github.com/babel/babel) itself.

The npm package `babel-preset-minify` is at the path `packages/babel-preset-minify`

| Package | Version | Dependencies |
|--------|-------|------------|
| [`babel-plugin-minify-constant-folding`](/packages/babel-plugin-minify-constant-folding) | [![npm](https://img.shields.io/npm/v/babel-plugin-minify-constant-folding.svg?maxAge=86400)](https://www.npmjs.com/package/babel-plugin-minify-constant-folding) | [![Dependency Status](https://david-dm.org/babel/minify.svg?path=packages/babel-plugin-minify-constant-folding)](https://david-dm.org/babel/minify?path=packages/babel-plugin-minify-constant-folding) |
| [`babel-plugin-minify-dead-code-elimination`](/packages/babel-plugin-minify-dead-code-elimination) | [![npm](https://img.shields.io/npm/v/babel-plugin-minify-dead-code-elimination.svg?maxAge=86400)](https://www.npmjs.com/package/babel-plugin-minify-dead-code-elimination) | [![Dependency Status](https://david-dm.org/babel/minify.svg?path=packages/babel-plugin-minify-dead-code-elimination)](https://david-dm.org/babel/minify?path=packages/babel-plugin-minify-dead-code-elimination) |
| [`babel-plugin-minify-flip-comparisons`](/packages/babel-plugin-minify-flip-comparisons) | [![npm](https://img.shields.io/npm/v/babel-plugin-minify-flip-comparisons.svg?maxAge=86400)](https://www.npmjs.com/package/babel-plugin-minify-flip-comparisons) | [![Dependency Status](https://david-dm.org/babel/minify.svg?path=packages/babel-plugin-minify-flip-comparisons)](https://david-dm.org/babel/minify?path=packages/babel-plugin-minify-flip-comparisons) |
| [`babel-plugin-minify-guarded-expressions`](/packages/babel-plugin-minify-guarded-expressions) | [![npm](https://img.shields.io/npm/v/babel-plugin-minify-guarded-expressions.svg?maxAge=86400)](https://www.npmjs.com/package/babel-plugin-minify-guarded-expressions) | [![Dependency Status](https://david-dm.org/babel/minify.svg?path=packages/babel-plugin-minify-guarded-expressions)](https://david-dm.org/babel/minify?path=packages/babel-plugin-minify-guarded-expressions) |
| [`babel-plugin-minify-infinity`](/packages/babel-plugin-minify-infinity) | [![npm](https://img.shields.io/npm/v/babel-plugin-minify-infinity.svg?maxAge=86400)](https://www.npmjs.com/package/babel-plugin-minify-infinity) | [![Dependency Status](https://david-dm.org/babel/minify.svg?path=packages/babel-plugin-minify-infinity)](https://david-dm.org/babel/minify?path=packages/babel-plugin-minify-infinity) |
| [`babel-plugin-minify-mangle-names`](/packages/babel-plugin-minify-mangle-names) | [![npm](https://img.shields.io/npm/v/babel-plugin-minify-mangle-names.svg?maxAge=86400)](https://www.npmjs.com/package/babel-plugin-minify-mangle-names) | [![Dependency Status](https://david-dm.org/babel/minify.svg?path=packages/babel-plugin-minify-mangle-names)](https://david-dm.org/babel/minify?path=packages/babel-plugin-minify-mangle-names) |
| [`babel-plugin-minify-replace`](/packages/babel-plugin-minify-replace) | [![npm](https://img.shields.io/npm/v/babel-plugin-minify-replace.svg?maxAge=86400)](https://www.npmjs.com/package/babel-plugin-minify-replace) | [![Dependency Status](https://david-dm.org/babel/minify.svg?path=packages/babel-plugin-minify-replace)](https://david-dm.org/babel/minify?path=packages/babel-plugin-minify-replace) |
| [`babel-plugin-minify-simplify`](/packages/babel-plugin-minify-simplify) | [![npm](https://img.shields.io/npm/v/babel-plugin-minify-simplify.svg?maxAge=86400)](https://www.npmjs.com/package/babel-plugin-minify-simplify) | [![Dependency Status](https://david-dm.org/babel/minify.svg?path=packages/babel-plugin-minify-simplify)](https://david-dm.org/babel/minify?path=packages/babel-plugin-minify-simplify) |
| [`babel-plugin-minify-type-constructors`](/packages/babel-plugin-minify-type-constructors) | [![npm](https://img.shields.io/npm/v/babel-plugin-minify-type-constructors.svg?maxAge=86400)](https://www.npmjs.com/package/babel-plugin-minify-type-constructors) | [![Dependency Status](https://david-dm.org/babel/minify.svg?path=packages/babel-plugin-minify-type-constructors)](https://david-dm.org/babel/minify?path=packages/babel-plugin-minify-type-constructors) |
| [`babel-plugin-transform-member-expression-literals`](/packages/babel-plugin-transform-member-expression-literals) | [![npm](https://img.shields.io/npm/v/babel-plugin-transform-member-expression-literals.svg?maxAge=86400)](https://www.npmjs.com/package/babel-plugin-transform-member-expression-literals) | [![Dependency Status](https://david-dm.org/babel/minify.svg?path=packages/babel-plugin-transform-member-expression-literals)](https://david-dm.org/babel/minify?path=packages/babel-plugin-transform-member-expression-literals) |
| [`babel-plugin-transform-merge-sibling-variables`](/packages/babel-plugin-transform-merge-sibling-variables) | [![npm](https://img.shields.io/npm/v/babel-plugin-transform-merge-sibling-variables.svg?maxAge=86400)](https://www.npmjs.com/package/babel-plugin-transform-merge-sibling-variables) | [![Dependency Status](https://david-dm.org/babel/minify.svg?path=packages/babel-plugin-transform-merge-sibling-variables)](https://david-dm.org/babel/minify?path=packages/babel-plugin-transform-merge-sibling-variables) |
| [`babel-plugin-transform-minify-booleans`](/packages/babel-plugin-transform-minify-booleans) | [![npm](https://img.shields.io/npm/v/babel-plugin-transform-minify-booleans.svg?maxAge=86400)](https://www.npmjs.com/package/babel-plugin-transform-minify-booleans) | [![Dependency Status](https://david-dm.org/babel/minify.svg?path=packages/babel-plugin-transform-minify-booleans)](https://david-dm.org/babel/minify?path=packages/babel-plugin-transform-minify-booleans) |
| [`babel-plugin-transform-property-literals`](/packages/babel-plugin-transform-property-literals) | [![npm](https://img.shields.io/npm/v/babel-plugin-transform-property-literals.svg?maxAge=86400)](https://www.npmjs.com/package/babel-plugin-transform-property-literals) | [![Dependency Status](https://david-dm.org/babel/minify.svg?path=packages/babel-plugin-transform-property-literals)](https://david-dm.org/babel/minify?path=packages/babel-plugin-transform-property-literals) |
| [`babel-plugin-transform-simplify-comparison-operators`](/packages/babel-plugin-transform-simplify-comparison-operators) | [![npm](https://img.shields.io/npm/v/babel-plugin-transform-simplify-comparison-operators.svg?maxAge=86400)](https://www.npmjs.com/package/babel-plugin-transform-simplify-comparison-operators) | [![Dependency Status](https://david-dm.org/babel/minify.svg?path=packages/babel-plugin-transform-simplify-comparison-operators)](https://david-dm.org/babel/minify?path=packages/babel-plugin-transform-simplify-comparison-operators) |
| [`babel-plugin-transform-undefined-to-void`](/packages/babel-plugin-transform-undefined-to-void) | [![npm](https://img.shields.io/npm/v/babel-plugin-transform-undefined-to-void.svg?maxAge=86400)](https://www.npmjs.com/package/babel-plugin-transform-undefined-to-void) | [![Dependency Status](https://david-dm.org/babel/minify.svg?path=packages/babel-plugin-transform-undefined-to-void)](https://david-dm.org/babel/minify?path=packages/babel-plugin-transform-undefined-to-void) |

### Usage

> Normally you wouldn't be consuming the plugins directly since the preset is available.

Add to your `.babelrc`'s plugins array.

```
{
  "plugins": ["babel-plugin-transform-undefined-to-void"]
}
```

## Other

| Package | Version | Dependencies |
|--------|-------|------------|
| [`babel-plugin-transform-inline-environment-variables`](/packages/babel-plugin-transform-inline-environment-variables) | [![npm](https://img.shields.io/npm/v/babel-plugin-transform-inline-environment-variables.svg?maxAge=86400)](https://www.npmjs.com/package/babel-plugin-transform-inline-environment-variables) | [![Dependency Status](https://david-dm.org/babel/minify.svg?path=packages/babel-plugin-transform-inline-environment-variables)](https://david-dm.org/babel/minify?path=packages/babel-plugin-transform-inline-environment-variables) |
| [`babel-plugin-transform-node-env-inline`](/packages/babel-plugin-transform-node-env-inline) | [![npm](https://img.shields.io/npm/v/babel-plugin-transform-node-env-inline.svg?maxAge=86400)](https://www.npmjs.com/package/babel-plugin-transform-node-env-inline) | [![Dependency Status](https://david-dm.org/babel/minify.svg?path=packages/babel-plugin-transform-node-env-inline)](https://david-dm.org/babel/minify?path=packages/babel-plugin-transform-node-env-inline) |
| [`babel-plugin-transform-remove-console`](/packages/babel-plugin-transform-remove-console) | [![npm](https://img.shields.io/npm/v/babel-plugin-transform-remove-console.svg?maxAge=86400)](https://www.npmjs.com/package/babel-plugin-transform-remove-console) | [![Dependency Status](https://david-dm.org/babel/minify.svg?path=packages/babel-plugin-transform-remove-console)](https://david-dm.org/babel/minify?path=packages/babel-plugin-transform-remove-console) |
| [`babel-plugin-transform-remove-debugger`](/packages/babel-plugin-transform-remove-debugger) | [![npm](https://img.shields.io/npm/v/babel-plugin-transform-remove-debugger.svg?maxAge=86400)](https://www.npmjs.com/package/babel-plugin-transform-remove-debugger) | [![Dependency Status](https://david-dm.org/babel/minify.svg?path=packages/babel-plugin-transform-remove-debugger)](https://david-dm.org/babel/minify?path=packages/babel-plugin-transform-remove-debugger) |

## Benchmarks

> Bootstrap: `npm run bootstrap`

> Build: `npm run build`

> Running the benchmarks: `./scripts/benchmark.js [file...]` - defaults to a few packages fetched from unpkg.com and is defined in benchmark.js.

> Note: All Input sources are ES5.

Benchmark Results for react.js:

Input Size: 54.79KB

Input Size (gzip): 15.11KB

| minifier                | output raw  | raw win | gzip output | gzip win | parse time (ms) | minify time (ms) |
| ----------------------- | ----------- | ------- | ----------- | -------- | --------------- | ---------------- |
| **babel-minify**        | 15.97KB     | 71%     | 6.08KB      | 60%      | 1.00            | 1039.06          |
| **terser**              | **15.65KB** | **71%** | **5.98KB**  | **60%**  | **0.93**        | **532.19**       |
| **uglify**              | 15.6KB      | 72%     | 6KB         | 60%      | 1.09            | 463.69           |
| **closure-compiler**    | 15.74KB     | 71%     | 6.04KB      | 60%      | 1.22            | 2361.41          |
| **closure-compiler-js** | 18.21KB     | 67%     | 6.73KB      | 55%      | 1.08            | 3381.47          |

Benchmark Results for vue.js:

Input Size: 282.52KB

Input Size (gzip): 77.52KB

| minifier                | output raw   | raw win | gzip output | gzip win | parse time (ms) | minify time (ms) |
| ----------------------- | ------------ | ------- | ----------- | -------- | --------------- | ---------------- |
| **babel-minify**        | 104.21KB     | 63%     | 38.71KB     | 50%      | 6.09            | 3538.30          |
| **terser**              | **103.12KB** | **63%** | **37.92KB** | **51%**  | **6.42**        | **1680.85**      |
| **uglify**              | 102.71KB     | 64%     | 38.08KB     | 51%      | 6.59            | 1662.50          |
| **closure-compiler**    | 101.93KB     | 64%     | 38.6KB      | 50%      | 10.41           | 4413.06          |
| **closure-compiler-js** | 105.18KB     | 63%     | 39.5KB      | 49%      | 6.79            | 12082.80         |

Benchmark Results for lodash.js:

Input Size: 527.18KB

Input Size (gzip): 94.04KB

| minifier                | output raw  | raw win | gzip output | gzip win | parse time (ms) | minify time (ms) |
| ----------------------- | ----------- | ------- | ----------- | -------- | --------------- | ---------------- |
| **babel-minify**        | 69.59KB     | 87%     | 24.37KB     | 74%      | 5.38            | 2587.27          |
| **terser**              | 68.66KB     | 87%     | 24.31KB     | 74%      | 6.41            | 1913.43          |
| **uglify**              | **68.15KB** | **87%** | **24.05KB** | **74%**  | **5.89**        | **2075.71**      |
| **closure-compiler**    | 71.05KB     | 87%     | 24.19KB     | 74%      | 6.24            | 4119.43          |
| **closure-compiler-js** | 73.51KB     | 86%     | 24.94KB     | 73%      | 5.17            | 9650.59          |

Benchmark Results for three.js:

Input Size: 1.05MB

Input Size (gzip): 212.43KB

| minifier                | output raw   | raw win | gzip output  | gzip win | parse time (ms) | minify time (ms) |
| ----------------------- | ------------ | ------- | ------------ | -------- | --------------- | ---------------- |
| **babel-minify**        | 535.88KB     | 50%     | 134.66KB     | 37%      | 27.24           | 9988.57          |
| **terser**              | **536.16KB** | **50%** | **132.78KB** | **37%**  | **28.39**       | **3919.34**      |
| **uglify**              | 533.42KB     | 50%     | 133.21KB     | 37%      | 26.15           | 4025.20          |
| **closure-compiler**    | 532.44KB     | 51%     | 134.41KB     | 37%      | 29.96           | 9029.19          |
| **closure-compiler-js** | 543.08KB     | 50%     | 136.3KB      | 36%      | 24.36           | 95743.77         |

## Browser support

Babel Minify is best at targeting latest browsers ([with full ES6+ support](https://kangax.github.io/compat-table/es6/)) but can also be used with the usual Babel es2015 preset to transpile down the code first.

## Team

[![Amjad Masad](https://avatars.githubusercontent.com/u/587518?s=96)](https://github.com/amasad) | [![Boopathi Rajaa](https://avatars.githubusercontent.com/u/294474?s=96)](https://github.com/boopathi) | [![Juriy Zaytsev](https://avatars.githubusercontent.com/u/383?s=96)](https://github.com/kangax) | [![Henry Zhu](https://avatars.githubusercontent.com/u/588473?s=96)](https://github.com/hzoo) | [![Vignesh Shanmugam](https://avatars0.githubusercontent.com/u/3902525?s=96)](https://github.com/vigneshshanmugam)
---|---|---|---|---|
Amjad Masad | Boopathi Rajaa | Juriy Zaytsev | Henry Zhu | Vignesh Shanmugam
[@amasad](https://github.com/amasad) | [@boopathi](https://github.com/boopathi) | [@kangax](https://github.com/kangax) | [@hzoo](https://github.com/hzoo) | [@vigneshshanmugam](https://github.com/vigneshshanmugam)
[@amasad](https://twitter.com/amasad) | [@heisenbugger](https://twitter.com/heisenbugger) | [@kangax](https://twitter.com/kangax) | [@left_pad](https://twitter.com/left_pad) | [@_vigneshh](https://twitter.com/_vigneshh)


text:
%  Daniel O'Keeffe	%
%~~~~~~~~~~~~~~~~~~~%
%  PACKAGES
\include{common/packages}
\include{common/commands}

% TITLE INFORMATION
\title[Journal Club]{The octopus genome and the evolution of cephalopod neural and morphological novelties}
%\subtitle{Journal Club}
\author[Daniel~O'Keeffe]{Daniel~O'Keeffe}%\inst{1}}
\institute[Trinity College Dublin]{
	%\inst{1}% For multiple authours
	Smurfit Institute of Genetics\\
	Trinity College Dublin\\
	Dublin 2\\
	Ireland
}
\date[2015]{Journal Club, \today}
\subject{Genetics}

\begin{document}
	\lstset{language=R}

	% SLIDE
	\frame{\titlepage}

	%Content goes here
	\begin{frame}
		\frametitle{This is the first slide}
	\end{frame}
	%More content goes here
	\begin{frame}
		\frametitle{This is the second slide}
		\framesubtitle{A bit more information about this}
	\end{frame}

	% Include a slide from slides rather than directly here
	\include{slides/slide}

	% SLIDE
	\begin{frame}[fragile]
		\frametitle{My Attempt}
		\framesubtitle{A quick test of frequencies}
		$H_0$: Asymmetrically fast evolving genes occur with equal frequency to symmetric fast evolving genes.\\
		$H_1$: Frequencies are not equal.
		\begin{lstlisting}
			binom.test(72, 76, p=.5)
		\end{lstlisting}
		Exact binomial test\\

		data:  72 and 76\\
		number of successes = 72, number of trials = 76, $p$-value $< 2.2\times10^{-16}$\\
		alternative hypothesis: true probability of success is not equal to 0.5\\
		95 percent confidence interval:\\
		$0.8706908$ $0.9854754$\\
		sample estimates:\\
		probability of success\\
		$0.9473684$\\
	\end{frame}

	\include{slides/thanks}
% etc
\end{document}


text:
import sys
reload(sys)
sys.setdefaultencoding("utf8")

import os.path
import re
import memcache
import torndb
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web

import handler.base
import handler.user
import handler.topic
import handler.page
import handler.notification

from tornado.options import define, options
from lib.loader import Loader
from lib.session import Session, SessionManager
from jinja2 import Environment, FileSystemLoader

define("port", default = 80, help = "run on the given port", type = int)    # 这种方式在之后可以通过 'host = options.mysql_host' 的形式来使用
define("mysql_host", default = "mysql_host", help = "community database host")
define("mysql_database", default = "mysql_db_name", help = "community database name")
define("mysql_user", default = "root", help = "community database user")
define("mysql_password", default = "123456", help = "community database password")

class Application(tornado.web.Application):
    def __init__(self):
        settings = dict(
            blog_title = u"F2E Community",
            template_path = os.path.join(os.path.dirname(__file__), "templates"),
            static_path = os.path.join(os.path.dirname(__file__), "static"),
            xsrf_cookies = True,
            cookie_secret = "cookie_secret_code",
            login_url = "/login",
            autoescape = None,
            jinja2 = Environment(loader = FileSystemLoader(os.path.join(os.path.dirname(__file__), "templates")), trim_blocks = True),
            reserved = ["user", "topic", "home", "setting", "forgot", "login", "logout", "register", "admin"],
        )

        handlers = [
            (r"/", handler.topic.IndexHandler),
            (r"/t/(\d+)", handler.topic.ViewHandler),
            (r"/t/create/(.*)", handler.topic.CreateHandler),
            (r"/t/edit/(.*)", handler.topic.EditHandler),
            (r"/reply/edit/(.*)", handler.topic.ReplyEditHandler),
            (r"/node/(.*)", handler.topic.NodeTopicsHandler),
            (r"/u/(.*)/topics", handler.topic.UserTopicsHandler),
            (r"/u/(.*)/replies", handler.topic.UserRepliesHandler),
            (r"/u/(.*)/favorites", handler.topic.UserFavoritesHandler),
            (r"/u/(.*)", handler.topic.ProfileHandler),
            (r"/vote", handler.topic.VoteHandler),
            (r"/favorite", handler.topic.FavoriteHandler),
            (r"/unfavorite", handler.topic.CancelFavoriteHandler),
            (r"/notifications", handler.notification.ListHandler),
            (r"/members", handler.topic.MembersHandler),
            (r"/setting", handler.user.SettingHandler),
            (r"/setting/avatar", handler.user.SettingAvatarHandler),
            (r"/setting/avatar/gravatar", handler.user.SettingAvatarFromGravatarHandler),
            (r"/setting/password", handler.user.SettingPasswordHandler),
            (r"/forgot", handler.user.ForgotPasswordHandler),
            (r"/login", handler.user.LoginHandler),
            (r"/logout", handler.user.LogoutHandler),
            (r"/register", handler.user.RegisterHandler),

            (r"/(favicon\.ico)", tornado.web.StaticFileHandler, dict(path = settings["static_path"])),
            (r"/(sitemap.*$)", tornado.web.StaticFileHandler, dict(path = settings["static_path"])),
            (r"/(bdsitemap\.txt)", tornado.web.StaticFileHandler, dict(path = settings["static_path"])),
            (r"/(.*)", handler.topic.ProfileHandler),
        ]

        tornado.web.Application.__init__(self, handlers, **settings)   # init时需要传两个参数:handlers和settings

        # Have one global connection to the blog DB across all handlers
        self.db = torndb.Connection(
            host = options.mysql_host, database = options.mysql_database,
            user = options.mysql_user, password = options.mysql_password
        )

        # Have one global loader for loading models and handles
        self.loader = Loader(self.db)

        # Have one global model for db query
        self.user_model = self.loader.use("user.model")
        self.topic_model = self.loader.use("topic.model")
        self.reply_model = self.loader.use("reply.model")
        self.plane_model = self.loader.use("plane.model")
        self.node_model = self.loader.use("node.model")
        self.notification_model = self.loader.use("notification.model")
        self.vote_model = self.loader.use("vote.model")
        self.favorite_model = self.loader.use("favorite.model")

        # Have one global session controller
        self.session_manager = SessionManager(settings["cookie_secret"], ["127.0.0.1:11211"], 0)

        # Have one global memcache controller
        self.mc = memcache.Client(["127.0.0.1:11211"])

def main():
    tornado.options.parse_command_line()
    http_server = tornado.httpserver.HTTPServer(Application())
    http_server.listen(options.port)
    tornado.ioloop.IOLoop.instance().start()

if __name__ == "__main__":
    main()


text:
/**
 *
 * @flow
 */
'use strict';

var React = require('React');
var S5Colors = require('S5Colors');
var StyleSheet = require('StyleSheet');
var { Text } = require('S5Text');
var TouchableHighlight = require('TouchableHighlight');
var View = require('View');
var moment = require('moment');

var { connect } = require('react-redux');

class PostCell extends React.Component {
  render() {
    return (
      <TouchableHighlight onPress={this.props.onPress}>
        <View style={[styles.cell, !this.props.isSeen && styles.unseen]}>
          <Text style={styles.text}>
            {this.props.post.description}
          </Text>
          <View style={styles.footer}>
            <Text style={styles.time}>
              {moment(this.props.post.createdAt).fromNow()}
            </Text>
          </View>
        </View>
      </TouchableHighlight>
    );
  }
}

var styles = StyleSheet.create({
  cell: {
    padding: 15,
    backgroundColor: 'white',
  },
  unseen: {
    paddingLeft: 12,
    borderLeftWidth: 3,
    borderLeftColor: '#4D99EF',
  },
  text: {
    fontSize: 15,
    lineHeight: 22,
    marginBottom: 10,
  },
  session: {
    paddingVertical: undefined,
    paddingHorizontal: undefined,
    paddingLeft: undefined,
    padding: 10,
    marginBottom: 10,
    borderWidth: 1,
    borderRadius: 4,
    borderColor: S5Colors.cellBorder,
    // overflow: 'hidden',
    shadowOffset: {width: 1, height: 1},
    shadowColor: '#eee',
    shadowOpacity: 1,
  },
  footer: {
    flexDirection: 'row',
  },
  url: {
    flex: 1,
    color: S5Colors.actionText,
    fontSize: 12,
    marginBottom: 10,
  },
  time: {
    color: S5Colors.lightText,
    fontSize: 12,
  },
});

module.exports = connect()(PostCell);


text:
@interface FeedsCommentCell()
@property (nonatomic, strong) EGOImageView *userHead;
@property (nonatomic, strong) RCLabel *contentLabel;
@property (nonatomic, strong) UILabel *timeLabel;
@end

@implementation FeedsCommentCell

+(float)cellHeightWithComment:(Comment *)comment
{
    float cellHeight = 35;
    return cellHeight;
//    RCLabel *label = [[RCLabel alloc] initWithFrame:CGRectMake(0, 0, 300 - 95, 30)];
//    [label setText:[NSString stringWithFormat:@"
%@:
\n
%@
",comment.userName,comment.content]];
//    CGSize size = [label optimumSize];
//    return size.height > cellHeight ? size.height : cellHeight;
}

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        // Initialization code
        [self initlize];
    }
    return self;
}

- (void)initlize
{
    self.userHead = [[EGOImageView alloc] initWithFrame:CGRectMake(10, 10, 25, 25)];
    [self.contentView addSubview:self.userHead];

    self.contentLabel = [[RCLabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(self.userHead.frame) + 10, 10, self.width - self.userHead.width - 30, 32)];
    self.contentLabel.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin;
    [self.contentView addSubview:self.contentLabel];

    self.timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.width - 10 - 50, 10, 0, 10)];
    self.timeLabel.textColor = colorWithHex(0x999999);
    self.timeLabel.textAlignment = NSTextAlignmentRight;
    self.timeLabel.font = getFontWith(NO, 8);
    [self.contentView addSubview:self.timeLabel];
}

- (void)dealloc
{
    self.comment = nil;
    self.contentLabel = nil;
    self.userHead = nil;
    self.timeLabel = nil;
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

-(void)setComment:(Comment *)comment
{
    _comment = comment;

    self.userHead.imageURL = [NSURL URLWithString:_comment.userAvatar];
    [self.contentLabel setText:[NSString stringWithFormat:@"
%@:

%@
",_comment.userName,_comment.content]];
//    CGSize size = [self.contentLabel optimumSize];
//    self.contentLabel.height = size.height;
    self.timeLabel.text = [Common timeIntervalStringFromTime:_comment.createTime];
}

- (void)layoutSubviews
{
    [super layoutSubviews];
}
@end


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta name="description" content="ZUI,一个简单吸引人的前端框架。">
  <meta name="author" content="Zentao">

  <title>ZUI - 开源HTML5跨屏框架</title>

  <link href="../css/zui.min.css" rel="stylesheet">
  <link href="../css/example.css" rel="stylesheet">

      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar">
        Toggle navigation

      </button>
      ZUI

          examples

alerts

article

breadcrumb

button-groups

buttons

cards

carousel

chosen

collapse

colorset

comment

dropdowns

forms

grid

icons

input-groups

kindeditor

labels

Lightbox

list-group

list

menu

modals

navbars

navs

pager

panels

popovers

progress

tables

tabs

textbox

tooltip

type

NEXT

Menu

          <button class="btn btn-primary"> COMPOSE</button>
          <button class="btn"> UPLOAD</button>

 Dashboard

 Me

               Time

Today

Tomarrow

Yestorday

This Week

 Trash

 All

               Status

 Ready

 Ongoing

 Completed


text:
Full game at http://datenshizero.github.io/ricegrow-js/

Uses [machina.js](https://github.com/ifandelse/machina.js) and [jq-console](https://github.com/replit/jq-console).

Even more buggy console version at https://github.com/datenshiZERO/ricegrow-rb


text:
package org.sakaiproject.component.section.sakai;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.sakaiproject.coursemanagement.api.Section;
import org.sakaiproject.section.api.coursemanagement.CourseSection;
import org.sakaiproject.section.api.coursemanagement.Meeting;
import org.sakaiproject.site.api.Group;

public class CourseSectionUtil {
	public static final CourseSection decorateGroupWithCmSection(Group group, Section officialSection) {

		if (group != null && officialSection != null)
		{
		CourseSectionImpl section = new CourseSectionImpl(group);
		section.setTitle(officialSection.getTitle());
		section.setDescription(officialSection.getDescription());
		section.setCategory(officialSection.getCategory());
		section.setMaxEnrollments(officialSection.getMaxSize());
		Set officialMeetings = officialSection.getMeetings();
		if(officialMeetings != null) {
			List<Meeting> meetings = new ArrayList<Meeting>();
			for(Iterator meetingIter = officialMeetings.iterator(); meetingIter.hasNext();) {
				org.sakaiproject.coursemanagement.api.Meeting officialMeeting = (org.sakaiproject.coursemanagement.api.Meeting)meetingIter.next();
				MeetingImpl meeting = new MeetingImpl(officialMeeting.getLocation(),
						officialMeeting.getStartTime(), officialMeeting.getFinishTime(),
						officialMeeting.isMonday(), officialMeeting.isTuesday(), officialMeeting.isWednesday(),
						officialMeeting.isThursday(), officialMeeting.isFriday(), officialMeeting.isSaturday(), officialMeeting.isSunday());
				meetings.add(meeting);
			}
			section.setMeetings(meetings);
		}
		// Ensure that the group is decorated properly, so the group properties are
		// persisted with the correct section metadata
		section.decorateGroup(group);
		return section;
	}
		return null;
	}

}


text:
#ifndef  _PULSAR_BACKOFF_HEADER_
#define _PULSAR_BACKOFF_HEADER_
#include <boost/date_time/posix_time/posix_time.hpp>

#pragma GCC visibility push(default)

namespace pulsar {

typedef boost::posix_time::time_duration TimeDuration;

class Backoff {
 public:
    Backoff(const TimeDuration& intial, const TimeDuration& max);
    TimeDuration next();
    void reset();
 private:
    TimeDuration initial_;
    TimeDuration max_;
    TimeDuration next_;
};
}

#pragma GCC visibility pop

#endif  //_PULSAR_BACKOFF_HEADER_