text:
import {Injectable, ɵRuntimeError as RuntimeError} from '@angular/core';

import {RuntimeErrorCode} from './errors';
import {convertToParamMap, ParamMap, Params, PRIMARY_OUTLET} from './shared';
import {equalArraysOrString, forEach, shallowEqual} from './utils/collection';

const NG_DEV_MODE = typeof ngDevMode === 'undefined' || ngDevMode;

/**
 * A set of options which specify how to determine if a `UrlTree` is active, given the `UrlTree`
 * for the current router state.
 *
 * @publicApi
 * @see Router.isActive
 */
export interface IsActiveMatchOptions {
  /**
   * Defines the strategy for comparing the matrix parameters of two `UrlTree`s.
   *
   * The matrix parameter matching is dependent on the strategy for matching the
   * segments. That is, if the `paths` option is set to `'subset'`, only
   * the matrix parameters of the matching segments will be compared.
   *
   * - `'exact'`: Requires that matching segments also have exact matrix parameter
   * matches.
   * - `'subset'`: The matching segments in the router's active `UrlTree` may contain
   * extra matrix parameters, but those that exist in the `UrlTree` in question must match.
   * - `'ignored'`: When comparing `UrlTree`s, matrix params will be ignored.
   */
  matrixParams: 'exact'|'subset'|'ignored';
  /**
   * Defines the strategy for comparing the query parameters of two `UrlTree`s.
   *
   * - `'exact'`: the query parameters must match exactly.
   * - `'subset'`: the active `UrlTree` may contain extra parameters,
   * but must match the key and value of any that exist in the `UrlTree` in question.
   * - `'ignored'`: When comparing `UrlTree`s, query params will be ignored.
   */
  queryParams: 'exact'|'subset'|'ignored';
  /**
   * Defines the strategy for comparing the `UrlSegment`s of the `UrlTree`s.
   *
   * - `'exact'`: all segments in each `UrlTree` must match.
   * - `'subset'`: a `UrlTree` will be determined to be active if it
   * is a subtree of the active route. That is, the active route may contain extra
   * segments, but must at least have all the segments of the `UrlTree` in question.
   */
  paths: 'exact'|'subset';
  /**
   * - `'exact'`: indicates that the `UrlTree` fragments must be equal.
   * - `'ignored'`: the fragments will not be compared when determining if a
   * `UrlTree` is active.
   */
  fragment: 'exact'|'ignored';
}

type ParamMatchOptions = 'exact'|'subset'|'ignored';

type PathCompareFn =
    (container: UrlSegmentGroup, containee: UrlSegmentGroup, matrixParams: ParamMatchOptions) =>
        boolean;
type ParamCompareFn = (container: Params, containee: Params) => boolean;

const pathCompareMap: Record<IsActiveMatchOptions['paths'], PathCompareFn> = {
  'exact': equalSegmentGroups,
  'subset': containsSegmentGroup,
};
const paramCompareMap: Record<ParamMatchOptions, ParamCompareFn> = {
  'exact': equalParams,
  'subset': containsParams,
  'ignored': () => true,
};

export function containsTree(
    container: UrlTree, containee: UrlTree, options: IsActiveMatchOptions): boolean {
  return pathCompareMap[options.paths](container.root, containee.root, options.matrixParams) &&
      paramCompareMap[options.queryParams](container.queryParams, containee.queryParams) &&
      !(options.fragment === 'exact' && container.fragment !== containee.fragment);
}

function equalParams(container: Params, containee: Params): boolean {
  // TODO: This does not handle array params correctly.
  return shallowEqual(container, containee);
}

function equalSegmentGroups(
    container: UrlSegmentGroup, containee: UrlSegmentGroup,
    matrixParams: ParamMatchOptions): boolean {
  if (!equalPath(container.segments, containee.segments)) return false;
  if (!matrixParamsMatch(container.segments, containee.segments, matrixParams)) {
    return false;
  }
  if (container.numberOfChildren !== containee.numberOfChildren) return false;
  for (const c in containee.children) {
    if (!container.children[c]) return false;
    if (!equalSegmentGroups(container.children[c], containee.children[c], matrixParams))
      return false;
  }
  return true;
}

function containsParams(container: Params, containee: Params): boolean {
  return Object.keys(containee).length <= Object.keys(container).length &&
      Object.keys(containee).every(key => equalArraysOrString(container[key], containee[key]));
}

function containsSegmentGroup(
    container: UrlSegmentGroup, containee: UrlSegmentGroup,
    matrixParams: ParamMatchOptions): boolean {
  return containsSegmentGroupHelper(container, containee, containee.segments, matrixParams);
}

function containsSegmentGroupHelper(
    container: UrlSegmentGroup, containee: UrlSegmentGroup, containeePaths: UrlSegment[],
    matrixParams: ParamMatchOptions): boolean {
  if (container.segments.length > containeePaths.length) {
    const current = container.segments.slice(0, containeePaths.length);
    if (!equalPath(current, containeePaths)) return false;
    if (containee.hasChildren()) return false;
    if (!matrixParamsMatch(current, containeePaths, matrixParams)) return false;
    return true;

  } else if (container.segments.length === containeePaths.length) {
    if (!equalPath(container.segments, containeePaths)) return false;
    if (!matrixParamsMatch(container.segments, containeePaths, matrixParams)) return false;
    for (const c in containee.children) {
      if (!container.children[c]) return false;
      if (!containsSegmentGroup(container.children[c], containee.children[c], matrixParams)) {
        return false;
      }
    }
    return true;

  } else {
    const current = containeePaths.slice(0, container.segments.length);
    const next = containeePaths.slice(container.segments.length);
    if (!equalPath(container.segments, current)) return false;
    if (!matrixParamsMatch(container.segments, current, matrixParams)) return false;
    if (!container.children[PRIMARY_OUTLET]) return false;
    return containsSegmentGroupHelper(
        container.children[PRIMARY_OUTLET], containee, next, matrixParams);
  }
}

function matrixParamsMatch(
    containerPaths: UrlSegment[], containeePaths: UrlSegment[], options: ParamMatchOptions) {
  return containeePaths.every((containeeSegment, i) => {
    return paramCompareMap[options](containerPaths[i].parameters, containeeSegment.parameters);
  });
}

/**
 * @description
 *
 * Represents the parsed URL.
 *
 * Since a router state is a tree, and the URL is nothing but a serialized state, the URL is a
 * serialized tree.
 * UrlTree is a data structure that provides a lot of affordances in dealing with URLs
 *
 * @usageNotes
 * ### Example
 *
 * ```
 * @Component({templateUrl:'template.html'})
 * class MyComponent {
 *   constructor(router: Router) {
 *     const tree: UrlTree =
 *       router.parseUrl('/team/33/(user/victor//support:help)?debug=true#fragment');
 *     const f = tree.fragment; // return 'fragment'
 *     const q = tree.queryParams; // returns {debug: 'true'}
 *     const g: UrlSegmentGroup = tree.root.children[PRIMARY_OUTLET];
 *     const s: UrlSegment[] = g.segments; // returns 2 segments 'team' and '33'
 *     g.children[PRIMARY_OUTLET].segments; // returns 2 segments 'user' and 'victor'
 *     g.children['support'].segments; // return 1 segment 'help'
 *   }
 * }
 * ```
 *
 * @publicApi
 */
export class UrlTree {
  /** @internal */
  // TODO(issue/24571): remove '!'.
  _queryParamMap!: ParamMap;

  constructor(
      /** The root segment group of the URL tree */
      public root: UrlSegmentGroup = new UrlSegmentGroup([], {}),
      /** The query params of the URL */
      public queryParams: Params = {},
      /** The fragment of the URL */
      public fragment: string|null = null) {
    if (NG_DEV_MODE) {
      if (root.segments.length > 0) {
        throw new RuntimeError(
            RuntimeErrorCode.INVALID_ROOT_URL_SEGMENT,
            'The root `UrlSegmentGroup` should not contain `segments`. ' +
                'Instead, these segments belong in the `children` so they can be associated with a named outlet.');
      }
    }
  }

  get queryParamMap(): ParamMap {
    if (!this._queryParamMap) {
      this._queryParamMap = convertToParamMap(this.queryParams);
    }
    return this._queryParamMap;
  }

  /** @docsNotRequired */
  toString(): string {
    return DEFAULT_SERIALIZER.serialize(this);
  }
}

/**
 * @description
 *
 * Represents the parsed URL segment group.
 *
 * See `UrlTree` for more information.
 *
 * @publicApi
 */
export class UrlSegmentGroup {
  /** @internal */
  _sourceSegment?: UrlSegmentGroup;
  /** @internal */
  _segmentIndexShift?: number;
  /**
   * @internal
   *
   * Used only in dev mode to detect if application relies on `relativeLinkResolution: 'legacy'`
   * Should be removed in when `relativeLinkResolution` is removed.
   */
  _segmentIndexShiftCorrected?: number;
  /** The parent node in the url tree */
  parent: UrlSegmentGroup|null = null;

  constructor(
      /** The URL segments of this group. See `UrlSegment` for more information */
      public segments: UrlSegment[],
      /** The list of children of this group */
      public children: {[key: string]: UrlSegmentGroup}) {
    forEach(children, (v: any, k: any) => v.parent = this);
  }

  /** Whether the segment has child segments */
  hasChildren(): boolean {
    return this.numberOfChildren > 0;
  }

  /** Number of child segments */
  get numberOfChildren(): number {
    return Object.keys(this.children).length;
  }

  /** @docsNotRequired */
  toString(): string {
    return serializePaths(this);
  }
}

/**
 * @description
 *
 * Represents a single URL segment.
 *
 * A UrlSegment is a part of a URL between the two slashes. It contains a path and the matrix
 * parameters associated with the segment.
 *
 * @usageNotes
 * ### Example
 *
 * ```
 * @Component({templateUrl:'template.html'})
 * class MyComponent {
 *   constructor(router: Router) {
 *     const tree: UrlTree = router.parseUrl('/team;id=33');
 *     const g: UrlSegmentGroup = tree.root.children[PRIMARY_OUTLET];
 *     const s: UrlSegment[] = g.segments;
 *     s[0].path; // returns 'team'
 *     s[0].parameters; // returns {id: 33}
 *   }
 * }
 * ```
 *
 * @publicApi
 */
export class UrlSegment {
  /** @internal */
  // TODO(issue/24571): remove '!'.
  _parameterMap!: ParamMap;

  constructor(
      /** The path part of a URL segment */
      public path: string,

      /** The matrix parameters associated with a segment */
      public parameters: {[name: string]: string}) {}

  get parameterMap(): ParamMap {
    if (!this._parameterMap) {
      this._parameterMap = convertToParamMap(this.parameters);
    }
    return this._parameterMap;
  }

  /** @docsNotRequired */
  toString(): string {
    return serializePath(this);
  }
}

export function equalSegments(as: UrlSegment[], bs: UrlSegment[]): boolean {
  return equalPath(as, bs) && as.every((a, i) => shallowEqual(a.parameters, bs[i].parameters));
}

export function equalPath(as: UrlSegment[], bs: UrlSegment[]): boolean {
  if (as.length !== bs.length) return false;
  return as.every((a, i) => a.path === bs[i].path);
}

export function mapChildrenIntoArray<T>(
    segment: UrlSegmentGroup, fn: (v: UrlSegmentGroup, k: string) => T[]): T[] {
  let res: T[] = [];
  forEach(segment.children, (child: UrlSegmentGroup, childOutlet: string) => {
    if (childOutlet === PRIMARY_OUTLET) {
      res = res.concat(fn(child, childOutlet));
    }
  });
  forEach(segment.children, (child: UrlSegmentGroup, childOutlet: string) => {
    if (childOutlet !== PRIMARY_OUTLET) {
      res = res.concat(fn(child, childOutlet));
    }
  });
  return res;
}

/**
 * @description
 *
 * Serializes and deserializes a URL string into a URL tree.
 *
 * The url serialization strategy is customizable. You can
 * make all URLs case insensitive by providing a custom UrlSerializer.
 *
 * See `DefaultUrlSerializer` for an example of a URL serializer.
 *
 * @publicApi
 */
@Injectable({providedIn: 'root', useFactory: () => new DefaultUrlSerializer()})
export abstract class UrlSerializer {
  /** Parse a url into a `UrlTree` */
  abstract parse(url: string): UrlTree;

  /** Converts a `UrlTree` into a url */
  abstract serialize(tree: UrlTree): string;
}

/**
 * @description
 *
 * A default implementation of the `UrlSerializer`.
 *
 * Example URLs:
 *
 * ```
 * /inbox/33(popup:compose)
 * /inbox/33;open=true/messages/44
 * ```
 *
 * DefaultUrlSerializer uses parentheses to serialize secondary segments (e.g., popup:compose), the
 * colon syntax to specify the outlet, and the ';parameter=value' syntax (e.g., open=true) to
 * specify route specific parameters.
 *
 * @publicApi
 */
export class DefaultUrlSerializer implements UrlSerializer {
  /** Parses a url into a `UrlTree` */
  parse(url: string): UrlTree {
    const p = new UrlParser(url);
    return new UrlTree(p.parseRootSegment(), p.parseQueryParams(), p.parseFragment());
  }

  /** Converts a `UrlTree` into a url */
  serialize(tree: UrlTree): string {
    const segment = `/${serializeSegment(tree.root, true)}`;
    const query = serializeQueryParams(tree.queryParams);
    const fragment =
        typeof tree.fragment === `string` ? `#${encodeUriFragment(tree.fragment)}` : '';

    return `${segment}${query}${fragment}`;
  }
}

const DEFAULT_SERIALIZER = new DefaultUrlSerializer();

export function serializePaths(segment: UrlSegmentGroup): string {
  return segment.segments.map(p => serializePath(p)).join('/');
}

function serializeSegment(segment: UrlSegmentGroup, root: boolean): string {
  if (!segment.hasChildren()) {
    return serializePaths(segment);
  }

  if (root) {
    const primary = segment.children[PRIMARY_OUTLET] ?
        serializeSegment(segment.children[PRIMARY_OUTLET], false) :
        '';
    const children: string[] = [];

    forEach(segment.children, (v: UrlSegmentGroup, k: string) => {
      if (k !== PRIMARY_OUTLET) {
        children.push(`${k}:${serializeSegment(v, false)}`);
      }
    });

    return children.length > 0 ? `${primary}(${children.join('//')})` : primary;

  } else {
    const children = mapChildrenIntoArray(segment, (v: UrlSegmentGroup, k: string) => {
      if (k === PRIMARY_OUTLET) {
        return [serializeSegment(segment.children[PRIMARY_OUTLET], false)];
      }

      return [`${k}:${serializeSegment(v, false)}`];
    });

    // use no parenthesis if the only child is a primary outlet route
    if (Object.keys(segment.children).length === 1 && segment.children[PRIMARY_OUTLET] != null) {
      return `${serializePaths(segment)}/${children[0]}`;
    }

    return `${serializePaths(segment)}/(${children.join('//')})`;
  }
}

/**
 * Encodes a URI string with the default encoding. This function will only ever be called from
 * `encodeUriQuery` or `encodeUriSegment` as it's the base set of encodings to be used. We need
 * a custom encoding because encodeURIComponent is too aggressive and encodes stuff that doesn't
 * have to be encoded per https://url.spec.whatwg.org.
 */
function encodeUriString(s: string): string {
  return encodeURIComponent(s)
      .replace(/%40/g, '@')
      .replace(/%3A/gi, ':')
      .replace(/%24/g, '$')
      .replace(/%2C/gi, ',');
}

/**
 * This function should be used to encode both keys and values in a query string key/value. In
 * the following URL, you need to call encodeUriQuery on "k" and "v":
 *
 * http://www.site.org/html;mk=mv?k=v#f
 */
export function encodeUriQuery(s: string): string {
  return encodeUriString(s).replace(/%3B/gi, ';');
}

/**
 * This function should be used to encode a URL fragment. In the following URL, you need to call
 * encodeUriFragment on "f":
 *
 * http://www.site.org/html;mk=mv?k=v#f
 */
export function encodeUriFragment(s: string): string {
  return encodeURI(s);
}

/**
 * This function should be run on any URI segment as well as the key and value in a key/value
 * pair for matrix params. In the following URL, you need to call encodeUriSegment on "html",
 * "mk", and "mv":
 *
 * http://www.site.org/html;mk=mv?k=v#f
 */
export function encodeUriSegment(s: string): string {
  return encodeUriString(s).replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/%26/gi, '&');
}

export function decode(s: string): string {
  return decodeURIComponent(s);
}

// Query keys/values should have the "+" replaced first, as "+" in a query string is " ".
// decodeURIComponent function will not decode "+" as a space.
export function decodeQuery(s: string): string {
  return decode(s.replace(/\+/g, '%20'));
}

export function serializePath(path: UrlSegment): string {
  return `${encodeUriSegment(path.path)}${serializeMatrixParams(path.parameters)}`;
}

function serializeMatrixParams(params: {[key: string]: string}): string {
  return Object.keys(params)
      .map(key => `;${encodeUriSegment(key)}=${encodeUriSegment(params[key])}`)
      .join('');
}

function serializeQueryParams(params: {[key: string]: any}): string {
  const strParams: string[] =
      Object.keys(params)
          .map((name) => {
            const value = params[name];
            return Array.isArray(value) ?
                value.map(v => `${encodeUriQuery(name)}=${encodeUriQuery(v)}`).join('&') :
                `${encodeUriQuery(name)}=${encodeUriQuery(value)}`;
          })
          .filter(s => !!s);

  return strParams.length ? `?${strParams.join('&')}` : '';
}

const SEGMENT_RE = /^[^\/()?;=#]+/;
function matchSegments(str: string): string {
  const match = str.match(SEGMENT_RE);
  return match ? match[0] : '';
}

const QUERY_PARAM_RE = /^[^=?&#]+/;
// Return the name of the query param at the start of the string or an empty string
function matchQueryParams(str: string): string {
  const match = str.match(QUERY_PARAM_RE);
  return match ? match[0] : '';
}

const QUERY_PARAM_VALUE_RE = /^[^&#]+/;
// Return the value of the query param at the start of the string or an empty string
function matchUrlQueryParamValue(str: string): string {
  const match = str.match(QUERY_PARAM_VALUE_RE);
  return match ? match[0] : '';
}

class UrlParser {
  private remaining: string;

  constructor(private url: string) {
    this.remaining = url;
  }

  parseRootSegment(): UrlSegmentGroup {
    this.consumeOptional('/');

    if (this.remaining === '' || this.peekStartsWith('?') || this.peekStartsWith('#')) {
      return new UrlSegmentGroup([], {});
    }

    // The root segment group never has segments
    return new UrlSegmentGroup([], this.parseChildren());
  }

  parseQueryParams(): Params {
    const params: Params = {};
    if (this.consumeOptional('?')) {
      do {
        this.parseQueryParam(params);
      } while (this.consumeOptional('&'));
    }
    return params;
  }

  parseFragment(): string|null {
    return this.consumeOptional('#') ? decodeURIComponent(this.remaining) : null;
  }

  private parseChildren(): {[outlet: string]: UrlSegmentGroup} {
    if (this.remaining === '') {
      return {};
    }

    this.consumeOptional('/');

    const segments: UrlSegment[] = [];
    if (!this.peekStartsWith('(')) {
      segments.push(this.parseSegment());
    }

    while (this.peekStartsWith('/') && !this.peekStartsWith('//') && !this.peekStartsWith('/(')) {
      this.capture('/');
      segments.push(this.parseSegment());
    }

    let children: {[outlet: string]: UrlSegmentGroup} = {};
    if (this.peekStartsWith('/(')) {
      this.capture('/');
      children = this.parseParens(true);
    }

    let res: {[outlet: string]: UrlSegmentGroup} = {};
    if (this.peekStartsWith('(')) {
      res = this.parseParens(false);
    }

    if (segments.length > 0 || Object.keys(children).length > 0) {
      res[PRIMARY_OUTLET] = new UrlSegmentGroup(segments, children);
    }

    return res;
  }

  // parse a segment with its matrix parameters
  // ie `name;k1=v1;k2`
  private parseSegment(): UrlSegment {
    const path = matchSegments(this.remaining);
    if (path === '' && this.peekStartsWith(';')) {
      throw new RuntimeError(
          RuntimeErrorCode.EMPTY_PATH_WITH_PARAMS,
          NG_DEV_MODE && `Empty path url segment cannot have parameters: '${this.remaining}'.`);
    }

    this.capture(path);
    return new UrlSegment(decode(path), this.parseMatrixParams());
  }

  private parseMatrixParams(): {[key: string]: string} {
    const params: {[key: string]: string} = {};
    while (this.consumeOptional(';')) {
      this.parseParam(params);
    }
    return params;
  }

  private parseParam(params: {[key: string]: string}): void {
    const key = matchSegments(this.remaining);
    if (!key) {
      return;
    }
    this.capture(key);
    let value: any = '';
    if (this.consumeOptional('=')) {
      const valueMatch = matchSegments(this.remaining);
      if (valueMatch) {
        value = valueMatch;
        this.capture(value);
      }
    }

    params[decode(key)] = decode(value);
  }

  // Parse a single query parameter `name[=value]`
  private parseQueryParam(params: Params): void {
    const key = matchQueryParams(this.remaining);
    if (!key) {
      return;
    }
    this.capture(key);
    let value: any = '';
    if (this.consumeOptional('=')) {
      const valueMatch = matchUrlQueryParamValue(this.remaining);
      if (valueMatch) {
        value = valueMatch;
        this.capture(value);
      }
    }

    const decodedKey = decodeQuery(key);
    const decodedVal = decodeQuery(value);

    if (params.hasOwnProperty(decodedKey)) {
      // Append to existing values
      let currentVal = params[decodedKey];
      if (!Array.isArray(currentVal)) {
        currentVal = [currentVal];
        params[decodedKey] = currentVal;
      }
      currentVal.push(decodedVal);
    } else {
      // Create a new value
      params[decodedKey] = decodedVal;
    }
  }

  // parse `(a/b//outlet_name:c/d)`
  private parseParens(allowPrimary: boolean): {[outlet: string]: UrlSegmentGroup} {
    const segments: {[key: string]: UrlSegmentGroup} = {};
    this.capture('(');

    while (!this.consumeOptional(')') && this.remaining.length > 0) {
      const path = matchSegments(this.remaining);

      const next = this.remaining[path.length];

      // if is is not one of these characters, then the segment was unescaped
      // or the group was not closed
      if (next !== '/' && next !== ')' && next !== ';') {
        throw new RuntimeError(
            RuntimeErrorCode.UNPARSABLE_URL, NG_DEV_MODE && `Cannot parse url '${this.url}'`);
      }

      let outletName: string = undefined!;
      if (path.indexOf(':') > -1) {
        outletName = path.slice(0, path.indexOf(':'));
        this.capture(outletName);
        this.capture(':');
      } else if (allowPrimary) {
        outletName = PRIMARY_OUTLET;
      }

      const children = this.parseChildren();
      segments[outletName] = Object.keys(children).length === 1 ? children[PRIMARY_OUTLET] :
                                                                  new UrlSegmentGroup([], children);
      this.consumeOptional('//');
    }

    return segments;
  }

  private peekStartsWith(str: string): boolean {
    return this.remaining.startsWith(str);
  }

  // Consumes the prefix when it is present and returns whether it has been consumed
  private consumeOptional(str: string): boolean {
    if (this.peekStartsWith(str)) {
      this.remaining = this.remaining.substring(str.length);
      return true;
    }
    return false;
  }

  private capture(str: string): void {
    if (!this.consumeOptional(str)) {
      throw new RuntimeError(
          RuntimeErrorCode.UNEXPECTED_VALUE_IN_URL, NG_DEV_MODE && `Expected "${str}".`);
    }
  }
}

export function createRoot(rootCandidate: UrlSegmentGroup) {
  return rootCandidate.segments.length > 0 ?
      new UrlSegmentGroup([], {[PRIMARY_OUTLET]: rootCandidate}) :
      rootCandidate;
}

/**
 * Recursively merges primary segment children into their parents and also drops empty children
 * (those which have no segments and no children themselves). The latter prevents serializing a
 * group into something like `/a(aux:)`, where `aux` is an empty child segment.
 */
export function squashSegmentGroup(segmentGroup: UrlSegmentGroup): UrlSegmentGroup {
  const newChildren = {} as any;
  for (const childOutlet of Object.keys(segmentGroup.children)) {
    const child = segmentGroup.children[childOutlet];
    const childCandidate = squashSegmentGroup(child);
    // don't add empty children
    if (childCandidate.segments.length > 0 || childCandidate.hasChildren()) {
      newChildren[childOutlet] = childCandidate;
    }
  }
  const s = new UrlSegmentGroup(segmentGroup.segments, newChildren);
  return mergeTrivialChildren(s);
}

/**
 * When possible, merges the primary outlet child into the parent `UrlSegmentGroup`.
 *
 * When a segment group has only one child which is a primary outlet, merges that child into the
 * parent. That is, the child segment group's segments are merged into the `s` and the child's
 * children become the children of `s`. Think of this like a 'squash', merging the child segment
 * group into the parent.
 */
function mergeTrivialChildren(s: UrlSegmentGroup): UrlSegmentGroup {
  if (s.numberOfChildren === 1 && s.children[PRIMARY_OUTLET]) {
    const c = s.children[PRIMARY_OUTLET];
    return new UrlSegmentGroup(s.segments.concat(c.segments), c.children);
  }

  return s;
}

export function isUrlTree(v: any): v is UrlTree {
  return v instanceof UrlTree;
}


text:
using System;
using System.Diagnostics;
using System.Text;

namespace LibWorkbooks.Model
{
    /// <summary>
    /// Defines a reference to some Cell instance, whether it exists or not.
    /// </summary>
    /// <remarks>
    /// Static methods are provided for conversion of column names etc.
    /// </remarks>
    public sealed class CellRef : IComparable, IComparable<CellRef>
    {
        /// <summary>
        /// Constructor for the class: CellRef
        /// </summary>
        /// <param name="sheetName">Name of the sheet where the cell belongs.</param>
        /// <param name="coordinate">Coordinate (column, row) for the cell in the sheet.</param>
        public CellRef(string sheetName, (int col1, int row1) coordinate)
        {
            SheetName = sheetName;
            Coordinate = coordinate;
            LocalAddress = ConvertCoordToAddress(coordinate);
        }

        /// <summary>
        /// Maximum number of rows, to e compatible with Excel.
        /// </summary>
        private const int MaxRows = 1048576;

        /// <summary>
        /// Maximum number of columns, to be compatible with Excel.
        /// </summary>
        private const int MaxColumns = 16384;

        // NOTE: Worksheet and workbook specifications and limits
        // http://office.microsoft.com/en-gb/excel-help/excel-specifications-and-limits-HP010342495.aspx
        //
        //      Worksheet size: 1,048,576 rows by 16,384 columns.
        //          * 1048575 is the highest number representable in 20 bits.
        //          * 16383 is the highest number representable in 14 bits. That leaves 2 spare bits in a 16-bit word.
        //      Column width: 255 characters (I'm not sure what the real significance of this is).
        //      Total number of characters that a cell can contain: 32,767 characters
        //          * 32766 is the highest number representable in 15 bits. That leaves 1 spare bit in a 16-bit word.
        //

        /// <summary>
        /// Name of the sheet where the cell belongs.
        /// </summary>
        /// <remarks>
        /// All cells belong to some Sheet instance, so this name must never be null or empty.
        /// </remarks>
        public string SheetName { get; }

        /// <summary>
        /// Coordinate (column, row) for the cell in the sheet.
        /// </summary>
        public (int col1, int row1) Coordinate { get; }

        public CellRef Offset(int columnOffset, int rowOffset)
        {
            return new CellRef(SheetName,(Column + columnOffset, Row + rowOffset));
        }

        public int Column => Coordinate.col1;

        public int Row => Coordinate.row1;

        public string LocalAddress { get; internal set; }

        #region Address conversion

        /// <summary>
        /// Converts a column identifier, using letters, to a column number.
        /// </summary>
        /// <param name="columnName">Column identifier using letters.</param>
        /// <returns>Column number.</returns>
        /// <exception cref="ArgumentOutOfRangeException">When column number exceeds maximum.</exception>
        public static int ConvertToColumnNumber(string columnName)
        {
            var number = 0;
            var pow = 1;
            for (var i = columnName.Length - 1; i >= 0; i--)
            {
                number += (columnName[i] - 'A' + 1) * pow;
                pow *= 26;
            }

            if (number > MaxColumns)
            {
                throw new ArgumentOutOfRangeException(nameof(columnName),
                    "Column number from columnName exceeds maximum");
            }

            return number;
        }

        /// <summary>
        /// Converts a column number to a column identifier using letters.
        /// </summary>
        /// <param name="columnNumber">Column number.</param>
        /// <returns>Column identifier using letters.</returns>
        /// <exception cref="ArgumentOutOfRangeException">When column number is invalid.</exception>
        public static string ConvertToColumnName(int columnNumber)
        {
            if (columnNumber < 1 || columnNumber > MaxColumns)
            {
                throw new ArgumentOutOfRangeException(nameof(columnNumber),
                    "Invalid column number");
            }

            var dividend = columnNumber;
            var columnName = string.Empty;
            while (dividend > 0)
            {
                var modulo = (dividend - 1) % 26;
                columnName = Convert.ToChar(65 + modulo) + columnName;
                dividend = (dividend - modulo) / 26;
            }

            return columnName;
        }

        /// <summary>
        /// Converts an address, like "A1", to a cell coordinate.
        /// </summary>
        /// <param name="address">Cell address, like "A1".</param>
        /// <returns>Coordinate of cell on sheet.</returns>
        /// <exception cref="ArgumentNullException">When address argument is null.</exception>
        /// <exception cref="ArgumentException">When address is invalid.</exception>
        public static (int col1, int row1) ConvertAddressToCoord(string address)
        {
            if (address == null)
            {
                throw new ArgumentNullException(nameof(address));
            }

            address = address.Replace("$", string.Empty);
            address = address.ToUpper();

            var letters = new StringBuilder();
            foreach (var c in address)
            {
                if (c < 'A' || c > 'Z')
                {
                    break;
                }
                letters.Append(c);
            }

            if (letters.Length == 0 || letters.Length > 3)
            {
                throw new ArgumentException(
                    "Column name requires 1 to 3 letters",
                    nameof(address));
            }

            var numbers = address.Substring(letters.Length);
            if (numbers.Length == 0)
            {
                throw new ArgumentException("Row number is required", nameof(address));
            }

            Debug.Assert(letters.Length + numbers.Length == address.Length);

            var row1 = int.Parse(numbers);
            var col1 = ConvertToColumnNumber(letters.ToString());

            return (col1, row1);
        }

        /// <summary>
        /// Convert cell coordinate to cell address, like "A1".
        /// </summary>
        /// <param name="coordinate">Coordinate of cell on sheet.</param>
        /// <param name="absolute">Provide absolute address, like "$A$1".</param>
        /// <returns>Cell address, like "A1", or optionally like "$A$1".</returns>
        /// <exception cref="ArgumentOutOfRangeException"></exception>
        public static string ConvertCoordToAddress((int col1, int row1) coordinate, bool absolute = false)
        {
            if (coordinate.row1 < 1 || coordinate.row1 > MaxRows ||
                coordinate.col1 < 1 || coordinate.col1 > MaxColumns)
            {
                throw new ArgumentOutOfRangeException(nameof(coordinate),
                    "Invalid coordinate");
            }

            var (col1, row1) = coordinate;
            return absolute
                ? $"${ConvertToColumnName(col1)}${row1}"
                : $"{ConvertToColumnName(col1)}{row1}";
        }

        #endregion

        #region IComparable

        public int CompareTo(CellRef other)
        {
            if (other == null) return -1;
            return string.Compare(ToString(), other.ToString(),
                StringComparison.Ordinal);
        }

        public int CompareTo(object obj)
        {
            if (obj.GetType() != GetType()) return -1;
            return CompareTo((CellRef) obj);
        }

        #endregion

        #region HashCode & Equals

        /// <returns>Unique key</returns>
        public override string ToString()
        {
            return $"'{SheetName}'!{LocalAddress}";
        }

        public override int GetHashCode()
        {
            return ToString().GetHashCode();
        }

        public override bool Equals(object obj)
        {
            if (obj == null) return false;

            if (obj != null && !(obj is CellRef))
                throw new ArgumentException("Object must be of type CellRef.");

            return GetHashCode().Equals(obj.GetHashCode());
        }

        #endregion
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.kde;

import org.freedesktop.dbus.DBusInterface;
import org.freedesktop.dbus.DBusSignal;
import org.freedesktop.dbus.exceptions.DBusException;

public interface StatusNotifierItem extends DBusInterface {

	//METHODS
	public void ContextMenu(int x, int y);
	public void Activate(int x, int y);
	public void SecondaryActivate(int x, int y);
	public void Scroll(int delta, String orientation);

	//SIGNALS
	public static class NewTitle extends DBusSignal {
		public NewTitle(String path) throws DBusException {
			super(path);
	    }
	}

	public static class NewIcon extends DBusSignal {
		public NewIcon(String path) throws DBusException {
			super(path);
	    }
	}

	public static class NewAttentionIcon extends DBusSignal {
		public NewAttentionIcon(String path) throws DBusException {
			super(path);
	    }
	}

	public static class NewOverlayIcon extends DBusSignal {
		public NewOverlayIcon(String path) throws DBusException {
	         super(path);
	    }
	}

	public static class NewToolTip extends DBusSignal {
		public NewToolTip(String path) throws DBusException {
	         super(path);
	    }
	}

	public static class NewStatus extends DBusSignal {
		public final String status;

		public NewStatus(String path, String status) throws DBusException {
	         super(path, status);
	         this.status = status;
	    }
	}
}


text:
<?php

namespace WebsiteMonitoring\Checker;

use WebsiteMonitoring\WebsiteConfig;
use Zend\Http\Client;

class Content implements CheckerInterface
{
    public function check(WebsiteConfig $config, array $checkerConfig = [])
    {
        $failures = [];
        foreach ($checkerConfig as $page) {
            if (empty($page['page'])) {
                $failures[] = 'Config error, no page defined';
                continue;
            }
            $link = $config->getUrl() . $page['page'];
            $response = (new Client($link))->send();
            if (!$response->isOk()) {
                $failures = array_merge($failures, [
                    'Can not request the sitemap at ' . $link . '.',
                    'The following error occurs: ' . $response->getStatusCode() . ' ' . $response->getReasonPhrase(),
                ]);
            }
            $failures = array_merge($failures, $this->checkPage($response->getBody(), $page));
        }
        return $failures;
    }

    private function checkPage($html, array $pageConfig)
    {
        $failures = [];
        $text = strip_tags(html_entity_decode($html));
        if (!empty($pageConfig['text_present'])) {
            foreach ((array)$pageConfig['text_present'] as $item) {
                strpos($text, $item) === false
                    && $failures[] = 'Can not find ' . $item . ' on page ' . $pageConfig['page'];
            }
        }
        if (!empty($pageConfig['text_not_present'])) {
            foreach ((array)$pageConfig['text_not_present'] as $item) {
                strpos($text, $item) !== false
                    && $failures[] = 'Found ' . $item . ' on page ' . $pageConfig['page'];
            }
        }
        if (!empty($pageConfig['html_present'])) {
            foreach ((array)$pageConfig['html_present'] as $item) {
                strpos($html, $item) === false
                    && $failures[] = 'Can not find  ' . $item . ' on page ' . $pageConfig['page'];
            }
        }
        if (!empty($pageConfig['html_not_present'])) {
            foreach ((array)$pageConfig['html_not_present'] as $item) {
                strpos($html, $item) !== false
                && $failures[] = 'Found ' . $item . ' on page ' . $pageConfig['page'];
            }
        }
        return $failures;
    }

    public function parse(WebsiteConfig $config, array $checkerConfig = [])
    {
        $result = [];

        foreach ($checkerConfig as $page) {
            if (empty($page['page'])) {
                return 'Config error, no page defined';
            }
            $result[] = 'Check page ' . $page['page'];
            if (!empty($page['text_present'])) {
                $result[] = 'For following text(s) are present: ' . implode(', ', (array)$page['text_present']);
            }
            if (!empty($page['text_not_present'])) {
                $result[] = 'For following text(s) are not present: ' . implode(', ', (array)$page['text_not_present']);
            }
            if (!empty($page['html_present'])) {
                $result[] = 'For following html are present: ' . implode(', ', (array)$page['html_present']);
            }
            if (!empty($page['html_not_present'])) {
                $result[] = 'For following html are not present: ' . implode(', ', (array)$page['html_not_present']);
            }
            return $result;
        }
    }
}


text:
/* |===================================|
 * | Bibliothèque de communication i2c |
 * |===================================|
 */
/**
 *    \file i2cCommunication.h
 *    \brief Bibliothèque de communication i2c
 *	  \author Nicolas SOBCZAK
 *    \date Octobre 2016
 */

/* ======================================================================================================
 *      Include
 * ======================================================================================================
 */
#include <Wire.h>
#include "Arduino.h"

#ifndef I2CCOMMUNICATION_H
#define	I2CCOMMUNICATION_H

#ifdef	__cplusplus
extern "C" {
#endif

/* =============================================================================
 *      *** Definition des ordres ***
 * =============================================================================
 */

// _____________________________________________________________________________
// # LEDs:
// Eteint une led
void ledOff(int);

// Allume une led
void ledOn(int);

// Allume une led si order = 1, eteint la led si order = 0
void ledControl(int, int);

// _____________________________________________________________________________
// # Ordres:

// Fonction qui affiche l'octet reçu
void byteReceived(byte);

// Execute l'ordre dont le numéro est entrée en parametre
void orderNumber(uint8_t);

// Fonction qui change la variable du tableau correspondace envoyée
void changeData(byte data[], int correspondance[], int numberOfVariables);

/* =============================================================================
 *      *** i2c ***
 * =============================================================================
 */

// _____________________________________________________________________________
// # Envoi:

// Fonction d'envoi d'1 octet via l'i2c
void i2csend(uint8_t, int);

// Fonction d'envoi de 3 octets via l'i2c avec initialisation
void i2csend3bytes(uint8_t, uint8_t, uint8_t, int);

// _____________________________________________________________________________
// # Réception:

// Fonction qui est exécutée lorsque des données sont envoyées par le Maître.
// Cette fonction est enregistrée comme un événement ("event" en anglais), voir la fonction setup()
void receiveEvent(int);
// Fonction qui demande l'envoi d'une certaine variable à un esclave
void i2creceive(int);

// _____________________________________________________________________________
// # Request

// Fonction d'envoi d'1 octet via l'i2c
byte* i2crequest(int adresse, int nbBytes, int variable, int numberOfVariables);

// _____________________________________________________________________________
// # Conversion:

// Fonction qui convertit un entier en 2 bytes - low ici
byte getLowByte(int);

// Fonction qui convertit un entier en 2 bytes - high ici
byte getHighByte(int n);

// Fonction qui affiche les 2 bytes d'un nombre entier convertit en binaire
void intTo2Bytes(byte[], int);

// Fonction qui affiche un entier ayant ete convertit en 2 bytes binaire
int recoverIntFrom2Bytes(byte[]);

// =============================================================================
// =============================================================================
#ifdef	__cplusplus
}
#endif

#endif	/* I2CCOMMUNICATION_H */


text:
package tracker

import (
	"encoding/binary"
	"fmt"
	"github.com/yorirou/gotorrent/bencode"
	"log"
)

func ParseResponse(resp []byte) (*Response, error) {
	compact := new(CompactResponse)
	if err := bencode.Unmarshal(resp, compact); err != nil {
		log.Print(err)
		dictcompact := new(Response)
		if errd := bencode.Unmarshal(resp, dictcompact); err != nil {
			return nil, errd
		}
		return dictcompact, nil
	}

	return compact.Convert(), nil
}

type ResponseBase struct {
	FailureReason  string
	WarningMessage string
	Interval       uint64
	MinInterval    uint64
	TrackerID      string
	Complete       uint32
	Incomplete     uint32
}

func (rb *ResponseBase) GetInterval(min bool) uint64 {
	if min {
		return rb.MinInterval
	}

	return rb.Interval
}

func (rb *ResponseBase) Seeders() uint32 {
	return rb.Complete
}

func (rb *ResponseBase) Leechers() uint32 {
	return rb.Incomplete
}

type CompactResponse struct {
	ResponseBase
	Peers []byte
	Peers6 []byte
}

func (cr *CompactResponse) Convert() *Response {
	dr := new(Response)
	dr.ResponseBase = cr.ResponseBase

	peerdata := []byte(cr.Peers)

	if len(peerdata)%6 != 0 {
		log.Print("peer data is not divisible with 6")
	}

	peernum := len(peerdata) / 6
	dr.Peers = make([]*Peer, peernum)
	for i := 0; i < peernum; i++ {
		p := new(Peer)

		p.PeerID = ""
		p.IP = fmt.Sprintf("%d.%d.%d.%d", peerdata[i*6+0], peerdata[i*6+1], peerdata[i*6+2], peerdata[i*6+3])
		p.Port = binary.BigEndian.Uint16(peerdata[i*6+4 : i*6+6])

		dr.Peers[i] = p
	}

	return dr
}

type Response struct {
	ResponseBase
	Peers []*Peer
}


text: module B023.C where


text:
<!DOCTYPE html>

<meta charset="utf-8" />
<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, width=device-width" />
<link rel="stylesheet" type="text/css" href="../../css/bootstrap.css">
<link rel="stylesheet" type="text/css" href="../../css/main.css">

Note

It's only for Cordova version 4.x

Test Steps

Get cordova4.x_sampleapp.zip from internal release link, then unzip it to /tmp/cordova-sampleapp/

Install statusbar.apk

        $ adb install /tmp/cordova-sampleapp/xwalkCommandLine.apk

Launch and Run the app

Pull down the app page

Check the app screen


text:
(function($) {
    $.fn.file = function(options) {
        var defaults = {
            fileImage: '/images/jquery/plugins/file/button.gif'
        };
        var options = $.extend(defaults, options);
        var fakeFileUpload = $('

');
        var input = $('<input />');
        var image = $('');

        input.attr('readonly', true);
        fakeFileUpload.addClass('fakefile').append(input);
        image.attr('src', options.fileImage);
        fakeFileUpload.append(image);
        return this.each(function() {
            if ($(this).parent().hasClass('fileinputs')) {
                $(this).addClass('file');
                $(this).addClass('hidden');
                $(this).parent().append(fakeFileUpload);
                $(this).change(function(){
                    input.val($(this).val());
                });
                $(this).mouseout(function(){
                    input.val($(this).val());
                });
            }
        });
    };
})(jQuery);


text:
using System.Collections.Generic;
using System;

namespace TagLib.Asf {
	/// <summary>
	///    This class extends <see cref="Object" /> to provide a
	///    representation of an ASF Header Extension object which can be
	///    read from and written to disk.
	/// </summary>
	public class HeaderExtensionObject : Object
	{
		#region Private Fields

		/// <summary>
		///    Contains the child objects.
		/// </summary>
		private List<Object> children = new List<Object> ();

		#endregion

		#region Constructors

		/// <summary>
		///    Constructs and initializes a new instance of <see
		///    cref="HeaderExtensionObject" /> by reading the contents
		///    from a specified position in a specified file.
		/// </summary>
		/// <param name="file">
		///    A <see cref="Asf.File" /> object containing the file from
		///    which the contents of the new instance are to be read.
		/// </param>
		/// <param name="position">
		///    A <see cref="long" /> value specify at what position to
		///    read the object.
		/// </param>
		/// <exception cref="ArgumentNullException">
		///    <paramref name="file" /> is <see langword="null" />.
		/// </exception>
		/// <exception cref="ArgumentOutOfRangeException">
		///    <paramref name="position" /> is less than zero or greater
		///    than the size of the file.
		/// </exception>
		/// <exception cref="CorruptFileException">
		///    The object read from disk does not have the correct GUID
		///    or contents.
		/// </exception>
		public HeaderExtensionObject (Asf.File file, long position)
			: base (file, position)
		{
			if (!Guid.Equals (Asf.Guid.AsfHeaderExtensionObject))
				throw new CorruptFileException (
					"Object GUID incorrect.");

			if (file.ReadGuid () != Asf.Guid.AsfReserved1)
				throw new CorruptFileException (
					"Reserved1 GUID expected.");

			if (file.ReadWord () != 6)
				throw new CorruptFileException (
					"Invalid reserved WORD. Expected '6'.");

			uint size_remaining = file.ReadDWord ();
			position += 0x170 / 8;

			while (size_remaining > 0) {
				Object obj = file.ReadObject (position);
				position += (long) obj.OriginalSize;
				size_remaining -= (uint) obj.OriginalSize;
				children.Add (obj);
			}
		}

		#endregion

		#region Public Properties

		/// <summary>
		///    Gets the child objects contained in the current instance.
		/// </summary>
		/// <value>
		///    A <see cref="T:System.Collections.Generic.IEnumerable`1" /> object enumerating
		///    through the children of the current instance.
		/// </value>
		public IEnumerable<Object> Children {
			get {return children;}
		}

		#endregion

		#region Public Methods

		/// <summary>
		///    Renders the current instance as a raw ASF object.
		/// </summary>
		/// <returns>
		///    A <see cref="ByteVector" /> object containing the
		///    rendered version of the current instance.
		/// </returns>
		public override ByteVector Render ()
		{
			ByteVector output = new ByteVector ();

			foreach (Object child in children)
				output.Add (child.Render ());

			output.Insert (0, RenderDWord ((uint) output.Count));
			output.Insert (0, RenderWord (6));
			output.Insert (0, Asf.Guid.AsfReserved1.ToByteArray ());

			return Render (output);
		}

		/// <summary>
		///    Adds a child object to the current instance.
		/// </summary>
		/// <param name="obj">
		///    A <see cref="Object" /> object to add to the current
		///    instance.
		/// </param>
		public void AddObject (Object obj)
		{
			children.Add (obj);
		}

		/// <summary>
		///    Adds a child unique child object to the current instance,
		///    replacing and existing child if present.
		/// </summary>
		/// <param name="obj">
		///    A <see cref="Object" /> object to add to the current
		///    instance.
		/// </param>
		public void AddUniqueObject (Object obj)
		{
			for (int i = 0; i < children.Count; i ++)
				if (((Object) children [i]).Guid == obj.Guid) {
					children [i] = obj;
					return;
				}

			children.Add (obj);
		}

		#endregion
	}
}


text:
Stackdriver Error Reporting gromadzi i wyświetla błędy generowane przez usługi chmurowe.

W tym samouczku przedstawiamy interfejs internetowy usługi Error Reporting. Dowiesz się, jak wyświetlić listę błędów aplikacji, zapoznać się ze szczegółami tych błędów i podjąć odpowiednie działania.

## Konfiguracja projektu

<walkthrough-project-setup></walkthrough-project-setup>

## Generowanie błędów

Zanim przejdziesz dalej, musisz zgłosić sztucznie wygenerowane błędy. Użyjesz do tego celu polecenia `gcloud`.

W rzeczywistości błędy te byłyby zgłaszane bezpośrednio z uruchomionej aplikacji. Po zakończeniu tego samouczka możesz zapoznać się z dodatkowymi informacjami na temat konfigurowania usługi Error Reporting.

### Otwieranie Google Cloud Shell

Kliknij [ikonę][spotlight-open-devshell] <walkthrough-cloud-shell-icon></walkthrough-cloud-shell-icon> na pasku nawigacyjnym u góry konsoli, aby otworzyć Cloud Shell.

### Zgłaszanie przykładowych błędów

Kliknij przycisk **Kopiuj do schowka** w prawym górnym rogu poniższego skryptu i uruchom go w Cloud Shell, aby wygenerować przykładowe błędy.

```bash
COUNTER=0
while [  $COUNTER -lt 11 ]; do
    gcloud beta error-reporting events report --service tutorial --service-version v$((COUNTER/10+1)) \
        --message "java.lang.RuntimeException: Error rendering template $COUNTER
          at com.example.TestClass.test(TestClass.java:51)
          at com.example.AnotherClass(AnotherClass.java:25)
          at javax.servlet.http.HttpServlet.service (HttpServlet.java:617)
          at javax.servlet.http.HttpServlet.service (HttpServlet.java:717)"
    if [ $COUNTER -lt 3 ]; then
      gcloud beta error-reporting events report --service tutorial --service-version v1 \
          --message "java.lang.ArrayIndexOutOfBoundsException: $COUNTER
            at com.example.AppController.createUser(AppController.java:42)
            at com.example.User(User.java:31)
            at javax.servlet.http.HttpServlet.service (HttpServlet.java:617)
            at javax.servlet.http.HttpServlet.service (HttpServlet.java:717)"
    fi
    if [ $COUNTER -eq 10 ]; then
      echo "All artificial errors reported."
    fi
    let COUNTER=COUNTER+1
done
```

### Zamknięcie Cloud Shell

Zamknij Cloud Shell, a potem kliknij *Dalej*.

## Wyświetlanie listy błędów aplikacji

Za pomocą usługi Stackdriver Error Reporting zobaczysz zgłoszone błędy.

### Otwieranie usługi Error Reporting

Otwórz [menu][spotlight-console-menu] po lewej stronie konsoli.

Następnie przewiń stronę do kategorii **Stackdriver** i wybierz **Error Reporting**.

<walkthrough-menu-navigation sectionid="CRASH_SECTION"></walkthrough-menu-navigation>

### Sortowanie według *pierwszego zarejestrowanego*

Błędy występujące w aplikacji są grupowane, a duplikaty usuwane na podstawie analizy zrzutów stosu. Każdy wpis na tej liście zawiera podsumowanie, które pomaga określić, kiedy aplikacja zaczęła generować błąd, jak często ten błąd występował i kiedy pojawił się ostatni raz.

Domyślnie błędy są sortowane według liczby *wystąpień*. Kliknij nagłówek kolumny *Pierwszy zarejestrowany*, aby wyświetlić błędy, które zaczęły pojawiać się ostatnio.

### Opcja otrzymywania powiadomień o nowych błędach

Po pojawieniu się nowych błędów w projekcie możesz otrzymywać e-maile i powiadomienia push na komórkę. Aby otrzymywać te powiadomienia, kliknij *Włącz powiadomienia*.

Na koniec kliknij *Dalej*.

## Poznawanie szczegółów błędu

### Otwarcie raportu o błędach

Kliknij błąd z tej listy, aby zobaczyć szczegóły.

### Powiązanie problemu z wybranym błędem

Zbadaj na tej stronie informacje dotyczące konkretnego błędu i zapoznaj się z jego historią.

Gdy zauważasz nowy błąd, zwykle następnym krokiem jest zgłoszenie go w narzędziu do śledzenia problemów używanym przez Twój zespół. Wpis w tym narzędziu możesz połączyć z błędem w usłudze Stackdriver Error Reporting.

Aby to zrobić:

  *  Kliknij *Powiąż z problemem* u góry (aby wyświetlić ten link, może być konieczne otwarcie menu **Więcej działań**).
  *  W wyświetlonym oknie wpisz adres `http://example.com/issues/1234`.
  *  Kliknij *Zapisz*.

### Badanie zrzutów stosów

Aby ułatwić Ci skoncentrowanie się na kodzie, ukrywamy ramki zrzutu stosu, które nie pochodzą z kodu Twojej aplikacji.

Kliknij *Pokaż wszystko* w przykładowym błędzie, aby wyświetlić ramki stosów platformy.

## Podsumowanie

<walkthrough-conclusion-trophy></walkthrough-conclusion-trophy>

Gratulacje! Masz już za sobą samouczek dotyczący usługi Stackdriver Error Reporting.

Oto, co możesz teraz zrobić:

### Skonfiguruj usługę Error Reporting dla swojego projektu

Dowiedz się z [dokumentacji konfiguracji][errors-setup], jak skonfigurować usługę Error Reporting dla swoich działających usług.

### Zapoznaj się z innymi samouczkami poświęconymi usłudze Stackdriver

Dowiedz się, jak debugować aplikację produkcyjną – przeczytaj krótkie wprowadzenie do usługi [Stackdriver Debugger][debug-quickstart].

Zapoznaj się z przyczynami opóźnień w działaniu aplikacji dzięki krótkiemu wprowadzeniu do usługi [Stackdriver Trace][trace-quickstart].

[debug-quickstart]: https://cloud.google.com/debugger/docs/quickstart
[errors-setup]: https://cloud.google.com/error-reporting/docs/how-to
[spotlight-console-menu]: walkthrough://spotlight-pointer?spotlightId=console-nav-menu
[spotlight-open-devshell]: walkthrough://spotlight-pointer?spotlightId=devshell-activate-button
[trace-quickstart]: https://cloud.google.com/trace/docs/quickstart


text:
package java.lang.annotation;

/**
 * Indicates that a field defining a constant value may be referenced
 * from native code.
 *
 * The annotation may be used as a hint by tools that generate native
 * header files to determine whether a header file is required, and
 * if so, what declarations it should contain.
 *
 * @since 1.8
 */
@Documented
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.SOURCE)
public @interface Native {
}


text:
<?php

namespace Recca0120\AllPay\Message\Traits;

trait ExtraPaidInfoBarcode
{
    public function setPaymentNo($value)
    {
        return $this->setParameter('PaymentNo', $value);
    }

    public function getPaymentNo()
    {
        return $this->getParameter('PaymentNo');
    }

    public function setPayFrom($value)
    {
        return $this->setParameter('PayFrom', $value);
    }

    public function getPayFrom()
    {
        return $this->getParameter('PayFrom');
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<title>MAIL->Subject()</title>

MAIL -> boolean subject ( string content [, string charset [, string encoding ]] )

Return TRUE if has been successfully set, FALSE if not.

Default values are:
string charset: utf-8
string encoding: quoted-printable

string encoding possible values are: quoted-printable or base64

Example (verification):

$m = new MAIL;

// set "Subject" mail header value
$s = $m->Subject('Hello World!');

echo $s ? 'success' : 'error';

Example (deprecated):

$m = new MAIL;

// set "Subject" mail header value, charset and encoding
$m->Subject = array(
'content'  => 'Hello World!', // required
'charset'  => 'utf-8', // optional
'encoding' => 'base64' // optional
);

See Also: MAIL->AddHeader()

[ Comments ]

Last update: Sunday, June 17, 2007


text:
{% extends 'welcomepage/base.html' %}
{%load staticfiles%}
{% block content %}

	<form method="POST" id="ismForm" action="">{% csrf_token %}

{{ hide.as_p }}

	<input class="w3-btn w3-xxlarge w3-round-xxlarge w3-blue w3-hover-teal" value="Mail Push Notification" onclick="send_hidden_form()"></input>
	</form>

	Other Promotion Platforms

{% endblock %}


text:
from django import VERSION
from django.conf import settings as django_settings
from django.core.exceptions import ImproperlyConfigured
import warnings
from six import string_types

# TODO: Don't use wildcards
from .article import *
from .urlpath import *

# TODO: Should the below stuff be executed a more logical place?
# Follow Django's default_settings.py / settings.py pattern and put these in d_s.py? That might be confusing, though.

######################
# Configuration stuff
######################

if not 'mptt' in django_settings.INSTALLED_APPS:
    raise ImproperlyConfigured('django-wiki: needs mptt in INSTALLED_APPS')

if not 'sekizai' in django_settings.INSTALLED_APPS:
    raise ImproperlyConfigured('django-wiki: needs sekizai in INSTALLED_APPS')

#if not 'django_nyt' in django_settings.INSTALLED_APPS:
#    raise ImproperlyConfigured('django-wiki: needs django_nyt in INSTALLED_APPS')

if not 'django.contrib.humanize' in django_settings.INSTALLED_APPS:
    raise ImproperlyConfigured('django-wiki: needs django.contrib.humanize in INSTALLED_APPS')

if not 'django.contrib.contenttypes' in django_settings.INSTALLED_APPS:
    raise ImproperlyConfigured('django-wiki: needs django.contrib.contenttypes in INSTALLED_APPS')

if not 'django.contrib.auth.context_processors.auth' in django_settings.TEMPLATE_CONTEXT_PROCESSORS:
    raise ImproperlyConfigured('django-wiki: needs django.contrib.auth.context_processors.auth in TEMPLATE_CONTEXT_PROCESSORS')

if not 'django.core.context_processors.request' in django_settings.TEMPLATE_CONTEXT_PROCESSORS:
    raise ImproperlyConfigured('django-wiki: needs django.core.context_processors.request in TEMPLATE_CONTEXT_PROCESSORS')

######################
# Warnings
######################

if VERSION < (1, 7):
    if not 'south' in django_settings.INSTALLED_APPS:
        warnings.warn("django-wiki: No south in your INSTALLED_APPS. This is highly discouraged.")

from django.core import urlresolvers

original_django_reverse = urlresolvers.reverse

def reverse(*args, **kwargs):
    """Now this is a crazy and silly hack, but it is basically here to
    enforce that an empty path always takes precedence over an article_id
    such that the root article doesn't get resolved to /ID/ but /.

    Another crazy hack that this supports is transforming every wiki url
    by a function. If _transform_url is set on this function, it will
    return the result of calling reverse._transform_url(reversed_url)
    for every url in the wiki namespace.
    """
    if isinstance(args[0], string_types) and args[0].startswith('wiki:'):
        url_kwargs = kwargs.get('kwargs', {})
        path = url_kwargs.get('path', False)
        # If a path is supplied then discard the article_id
        if path != False:
            url_kwargs.pop('article_id', None)
            url_kwargs['path'] = path
            kwargs['kwargs'] = url_kwargs

        url = original_django_reverse(*args, **kwargs)
        if hasattr(reverse, '_transform_url'):
            url = reverse._transform_url(url)
    else:
        url = original_django_reverse(*args, **kwargs)

    return url

# Now we redefine reverse method
urlresolvers.reverse = reverse


text:
.class Landroid/os/StrictMode$AndroidBlockGuardPolicy$1;
.super Ljava/lang/Object;
.source "StrictMode.java"

# interfaces
.implements Ljava/lang/Runnable;

# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
    value = Landroid/os/StrictMode$AndroidBlockGuardPolicy;->handleViolationWithTimingAttempt(Landroid/os/StrictMode$ViolationInfo;)V
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$0:Landroid/os/StrictMode$AndroidBlockGuardPolicy;

.field final synthetic val$records:Ljava/util/ArrayList;

.field final synthetic val$windowManager:Landroid/view/IWindowManager;

# direct methods
.method constructor <init>(Landroid/os/StrictMode$AndroidBlockGuardPolicy;Landroid/view/IWindowManager;Ljava/util/ArrayList;)V
    .locals 0
    .parameter
    .parameter
    .parameter

    .prologue
    .line 1195
    iput-object p1, p0, Landroid/os/StrictMode$AndroidBlockGuardPolicy$1;->this$0:Landroid/os/StrictMode$AndroidBlockGuardPolicy;

    iput-object p2, p0, Landroid/os/StrictMode$AndroidBlockGuardPolicy$1;->val$windowManager:Landroid/view/IWindowManager;

    iput-object p3, p0, Landroid/os/StrictMode$AndroidBlockGuardPolicy$1;->val$records:Ljava/util/ArrayList;

    invoke-direct/range {p0 .. p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public run()V
    .locals 6

    .prologue
    .line 1197
    invoke-static {}, Landroid/os/SystemClock;->uptimeMillis()J

    move-result-wide v0

    .line 1203
    .local v0, loopFinishTime:J
    iget-object v4, p0, Landroid/os/StrictMode$AndroidBlockGuardPolicy$1;->val$windowManager:Landroid/view/IWindowManager;

    if-eqz v4, :cond_0

    .line 1205
    :try_start_0
    iget-object v4, p0, Landroid/os/StrictMode$AndroidBlockGuardPolicy$1;->val$windowManager:Landroid/view/IWindowManager;

    const/4 v5, 0x0

    invoke-interface {v4, v5}, Landroid/view/IWindowManager;->showStrictModeViolation(Z)V
    :try_end_0
    .catch Landroid/os/RemoteException; {:try_start_0 .. :try_end_0} :catch_0

    .line 1210
    :cond_0
    :goto_0
    const/4 v2, 0x0

    .local v2, n:I
    :goto_1
    iget-object v4, p0, Landroid/os/StrictMode$AndroidBlockGuardPolicy$1;->val$records:Ljava/util/ArrayList;

    invoke-virtual {v4}, Ljava/util/ArrayList;->size()I

    move-result v4

    if-ge v2, v4, :cond_1

    .line 1211
    iget-object v4, p0, Landroid/os/StrictMode$AndroidBlockGuardPolicy$1;->val$records:Ljava/util/ArrayList;

    invoke-virtual {v4, v2}, Ljava/util/ArrayList;->get(I)Ljava/lang/Object;

    move-result-object v3

    check-cast v3, Landroid/os/StrictMode$ViolationInfo;

    .line 1212
    .local v3, v:Landroid/os/StrictMode$ViolationInfo;
    add-int/lit8 v4, v2, 0x1

    iput v4, v3, Landroid/os/StrictMode$ViolationInfo;->violationNumThisLoop:I

    .line 1213
    iget-wide v4, v3, Landroid/os/StrictMode$ViolationInfo;->violationUptimeMillis:J

    sub-long v4, v0, v4

    long-to-int v4, v4

    iput v4, v3, Landroid/os/StrictMode$ViolationInfo;->durationMillis:I

    .line 1215
    iget-object v4, p0, Landroid/os/StrictMode$AndroidBlockGuardPolicy$1;->this$0:Landroid/os/StrictMode$AndroidBlockGuardPolicy;

    invoke-virtual {v4, v3}, Landroid/os/StrictMode$AndroidBlockGuardPolicy;->handleViolation(Landroid/os/StrictMode$ViolationInfo;)V

    .line 1210
    add-int/lit8 v2, v2, 0x1

    goto :goto_1

    .line 1217
    .end local v3           #v:Landroid/os/StrictMode$ViolationInfo;
    :cond_1
    iget-object v4, p0, Landroid/os/StrictMode$AndroidBlockGuardPolicy$1;->val$records:Ljava/util/ArrayList;

    invoke-virtual {v4}, Ljava/util/ArrayList;->clear()V

    .line 1218
    return-void

    .line 1206
    .end local v2           #n:I
    :catch_0
    move-exception v4

    goto :goto_0
.end method


text:
from __future__ import print_function, division, absolute_import
import warnings

class SciServerError(Exception):
    pass

class SciServerAPIError(SciServerError):
    def __init__(self, message=None):

        if not message:
            message = 'Error with Http Response from SciServer API'
        else:
            message = 'Http response error from SciServer API. {0}'.format(message)

        super(SciServerAPIError, self).__init__(message)

class SciServerWarning(Warning):
    pass

class SciServerDeprecationWarning(DeprecationWarning, SciServerWarning):
    """A warning for deprecated features."""
    pass


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>材质与纹理</title>
  <link type="text/css" rel="stylesheet" href="../../public/css/materialize.min.css" media="screen,projection" />

      ECharts & WebVR 学院学习记录

        回到首页

        <canvas id="mainCanvas" height="500px" width="750px"></canvas>


text:
<?php

namespace Google\Service\CloudAsset;

class ListSavedQueriesResponse extends \Google\Collection
{
  protected $collection_key = 'savedQueries';
  /**
   * @var string
   */
  public $nextPageToken;
  protected $savedQueriesType = SavedQuery::class;
  protected $savedQueriesDataType = 'array';

  /**
   * @param string
   */
  public function setNextPageToken($nextPageToken)
  {
    $this->nextPageToken = $nextPageToken;
  }
  /**
   * @return string
   */
  public function getNextPageToken()
  {
    return $this->nextPageToken;
  }
  /**
   * @param SavedQuery[]
   */
  public function setSavedQueries($savedQueries)
  {
    $this->savedQueries = $savedQueries;
  }
  /**
   * @return SavedQuery[]
   */
  public function getSavedQueries()
  {
    return $this->savedQueries;
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(ListSavedQueriesResponse::class, 'Google_Service_CloudAsset_ListSavedQueriesResponse');


text:
/**
 * Autogenerated by Avro
 *
 * DO NOT EDIT DIRECTLY
 */
package org.kaaproject.kaa.server.appenders.cassandra.config.gen;

@SuppressWarnings("all")
@org.apache.avro.specific.AvroGenerated
public enum CassandraExecuteRequestType {
  SYNC, ASYNC;
  public static final org.apache.avro.Schema SCHEMA$ = new org.apache.avro.Schema.Parser().parse("{\"type\":\"enum\",\"name\":\"CassandraExecuteRequestType\",\"namespace\":\"org.kaaproject.kaa.server.appenders.cassandra.config.gen\",\"symbols\":[\"SYNC\",\"ASYNC\"]}");

  public static org.apache.avro.Schema getClassSchema() {
    return SCHEMA$;
  }
}


text:
<?xml version="1.0" encoding="UTF-8" ?>
<dt-example table-type="html" order="1" framework="bootstrap">

<css lib="datatables fixedheader" />
<js lib="jquery datatables fixedheader">
<![CDATA[
$(document).ready(function() {
	var table = $('#example').DataTable( {
		fixedHeader: true
	} );
} );
]]>
</js>

<title lib="FixedHeader">Bootstrap</title>

<info><![CDATA[

This example shows FixedHeader being styling by the Bootstrap CSS framework.

]]></info>

</dt-example>


text:
/* eslint-disable no-template-curly-in-string */
import { AnnotationCommand, IndentListCommand } from 'substance'
import {
  BasePackage, EditorBasePackage, ModelComponentPackage, FindAndReplacePackage
} from '../../kit'
import ArticleToolbarPackage from './ArticleToolbarPackage'
import ManuscriptContentPackage from './ManuscriptContentPackage'
import PersistencePackage from '../../shared/PersistencePackage'

import {
  AddAuthorCommand, AddAffiliationCommand, AddEntityCommand,
  AddFigureMetadataFieldCommand, AddFigurePanelCommand,
  AddReferenceCommand,
  MoveMetadataFieldCommand, RemoveMetadataFieldCommand,
  InsertExtLinkCommand,
  DecreaseHeadingLevelCommand,
  DeleteCellsCommand,
  DownloadSupplementaryFileCommand,
  EditAuthorCommand, EditReferenceCommand,
  IncreaseHeadingLevelCommand,
  InsertBlockFormulaCommand,
  InsertBlockQuoteCommand,
  InsertCellsCommand,
  InsertFigureCommand,
  InsertNodeFromWorkflowCommand,
  InsertFootnoteCommand,
  InsertInlineFormulaCommand,
  InsertInlineGraphicCommand,
  InsertTableCommand,
  InsertCrossReferenceCommand,
  InsertFootnoteCrossReferenceCommand,
  MoveFigurePanelCommand,
  OpenFigurePanelImageCommand,
  RemoveFigurePanelCommand,
  RemoveFootnoteCommand,
  ReplaceFigurePanelImageCommand,
  ReplaceSupplementaryFileCommand,
  TableSelectAllCommand,
  ToggleCellHeadingCommand,
  ToggleCellMergeCommand,
  ChangeListTypeCommand,
  CreateListCommand,
  EditMetadataCommand
} from '../commands'

import {
  AddSupplementaryFileWorkflow,
  ManuscriptTOC, InsertFigurePanelTool,
  DownloadSupplementaryFileTool, InsertFigureTool, InsertInlineGraphicTool,
  OpenFigurePanelImageTool, ReplaceFigurePanelTool,
  ReplaceSupplementaryFileTool, InsertTableTool, ManuscriptEditor
} from '../components'

import { BlockFormula, Figure, Reference, SupplementaryFile, Table } from '../nodes'

import DropFigure from './DropFigure'

import { AddAuthorWorkflow, AddAffiliationWorkflow, AddReferenceWorkflow } from '../workflows'
import EditMetadataWorkflow from '../metadata/EditMetadataWorkflow'

export default {
  name: 'ManuscriptEditor',
  configure (config) {
    config.import(BasePackage)
    config.import(EditorBasePackage)
    config.import(ModelComponentPackage)
    config.import(ManuscriptContentPackage)
    config.import(ArticleToolbarPackage)
    config.import(PersistencePackage)
    config.import(FindAndReplacePackage)

    config.addComponent('add-supplementary-file', AddSupplementaryFileWorkflow)
    config.addComponent('toc', ManuscriptTOC)

    config.addCommand('add-author', AddAuthorCommand)
    config.addCommand('add-figure-panel', AddFigurePanelCommand, {
      commandGroup: 'figure-panel'
    })
    config.addCommand('add-metadata-field', AddFigureMetadataFieldCommand, {
      commandGroup: 'metadata-fields'
    })
    config.addCommand('add-affiliation', AddAffiliationCommand)
    config.addCommand('add-reference', AddReferenceCommand)

    config.addCommand('create-external-link', InsertExtLinkCommand, {
      nodeType: 'external-link',
      accelerator: 'CommandOrControl+K',
      commandGroup: 'formatting'
    })
    config.addCommand('decrease-heading-level', DecreaseHeadingLevelCommand, {
      commandGroup: 'text'
    })
    config.addCommand('dedent-list', IndentListCommand, {
      spec: { action: 'dedent' },
      commandGroup: 'list'
    })
    config.addCommand('delete-columns', DeleteCellsCommand, {
      spec: { dim: 'col' },
      commandGroup: 'table-delete'
    })
    config.addCommand('delete-rows', DeleteCellsCommand, {
      spec: { dim: 'row' },
      commandGroup: 'table-delete'
    })
    config.addCommand('download-file', DownloadSupplementaryFileCommand, {
      commandGroup: 'file'
    })
    config.addCommand('edit-author', EditAuthorCommand, {
      commandGroup: 'entities'
    })
    config.addCommand('edit-metadata', EditMetadataCommand)
    config.addCommand('edit-reference', EditReferenceCommand, {
      commandGroup: 'entities'
    })
    config.addCommand('increase-heading-level', IncreaseHeadingLevelCommand, {
      commandGroup: 'text'
    })
    config.addCommand('indent-list', IndentListCommand, {
      spec: { action: 'indent' },
      commandGroup: 'list'
    })
    config.addCommand('insert-block-formula', InsertBlockFormulaCommand, {
      nodeType: 'block-formula',
      commandGroup: 'insert'
    })
    config.addCommand('insert-block-quote', InsertBlockQuoteCommand, {
      nodeType: 'block-quote',
      commandGroup: 'insert'
    })
    config.addCommand('insert-columns-left', InsertCellsCommand, {
      spec: { dim: 'col', pos: 'left' },
      commandGroup: 'table-insert'
    })
    config.addCommand('insert-columns-right', InsertCellsCommand, {
      spec: { dim: 'col', pos: 'right' },
      commandGroup: 'table-insert'
    })
    config.addCommand('insert-figure', InsertFigureCommand, {
      nodeType: 'figure',
      commandGroup: 'insert'
    })
    config.addCommand('insert-file', InsertNodeFromWorkflowCommand, {
      workflow: 'add-supplementary-file',
      nodeType: 'supplementary-file',
      commandGroup: 'insert'
    })
    config.addCommand('insert-footnote', InsertFootnoteCommand, {
      commandGroup: 'insert'
    })
    config.addCommand('insert-inline-formula', InsertInlineFormulaCommand, {
      commandGroup: 'insert'
    })
    config.addCommand('insert-inline-graphic', InsertInlineGraphicCommand, {
      nodeType: 'inline-graphic',
      commandGroup: 'insert'
    })
    config.addCommand('insert-rows-above', InsertCellsCommand, {
      spec: { dim: 'row', pos: 'above' },
      commandGroup: 'table-insert'
    })
    config.addCommand('insert-rows-below', InsertCellsCommand, {
      spec: { dim: 'row', pos: 'below' },
      commandGroup: 'table-insert'
    })
    config.addCommand('insert-table', InsertTableCommand, {
      nodeType: 'table-figure',
      commandGroup: 'insert'
    })
    config.addCommand('insert-xref-bibr', InsertCrossReferenceCommand, {
      refType: Reference.refType,
      commandGroup: 'insert-xref'
    })
    config.addCommand('insert-xref-figure', InsertCrossReferenceCommand, {
      refType: Figure.refType,
      commandGroup: 'insert-xref'
    })
    config.addCommand('insert-xref-file', InsertCrossReferenceCommand, {
      refType: SupplementaryFile.refType,
      commandGroup: 'insert-xref'
    })
    // Note: footnote cross-references are special, because they take the current scope into account
    // i.e. whether to create a footnote on article level, or inside a table-figure
    config.addCommand('insert-xref-footnote', InsertFootnoteCrossReferenceCommand, {
      commandGroup: 'insert-xref'
    })
    config.addCommand('insert-xref-formula', InsertCrossReferenceCommand, {
      refType: BlockFormula.refType,
      commandGroup: 'insert-xref'
    })
    config.addCommand('insert-xref-table', InsertCrossReferenceCommand, {
      refType: Table.refType,
      commandGroup: 'insert-xref'
    })
    config.addCommand('move-down-metadata-field', MoveMetadataFieldCommand, {
      direction: 'down',
      commandGroup: 'metadata-fields'
    })
    config.addCommand('move-down-figure-panel', MoveFigurePanelCommand, {
      direction: 'down',
      commandGroup: 'figure-panel'
    })
    config.addCommand('move-up-metadata-field', MoveMetadataFieldCommand, {
      direction: 'up',
      commandGroup: 'metadata-fields'
    })
    config.addCommand('move-up-figure-panel', MoveFigurePanelCommand, {
      direction: 'up',
      commandGroup: 'figure-panel'
    })
    config.addCommand('open-figure-panel-image', OpenFigurePanelImageCommand, {
      commandGroup: 'figure-panel'
    })
    config.addCommand('remove-metadata-field', RemoveMetadataFieldCommand, {
      commandGroup: 'metadata-fields'
    })
    config.addCommand('remove-figure-panel', RemoveFigurePanelCommand, {
      commandGroup: 'figure-panel'
    })
    config.addCommand('remove-footnote', RemoveFootnoteCommand, {
      nodeType: 'footnote',
      commandGroup: 'footnote'
    })
    config.addCommand('replace-figure-panel-image', ReplaceFigurePanelImageCommand, {
      commandGroup: 'figure-panel'
    })
    config.addCommand('replace-file', ReplaceSupplementaryFileCommand, {
      commandGroup: 'file'
    })
    config.addCommand('table:select-all', TableSelectAllCommand)
    config.addCommand('toggle-bold', AnnotationCommand, {
      nodeType: 'bold',
      accelerator: 'CommandOrControl+B',
      commandGroup: 'formatting'
    })
    config.addCommand('toggle-cell-heading', ToggleCellHeadingCommand, {
      commandGroup: 'table'
    })
    config.addCommand('toggle-cell-merge', ToggleCellMergeCommand, {
      commandGroup: 'table'
    })
    config.addCommand('toggle-italic', AnnotationCommand, {
      nodeType: 'italic',
      accelerator: 'CommandOrControl+I',
      commandGroup: 'formatting'
    })
    config.addCommand('toggle-monospace', AnnotationCommand, {
      nodeType: 'monospace',
      commandGroup: 'formatting'
    })
    config.addCommand('toggle-ordered-list', ChangeListTypeCommand, {
      spec: { listType: 'order' },
      commandGroup: 'list'
    })
    config.addCommand('toggle-overline', AnnotationCommand, {
      nodeType: 'overline',
      commandGroup: 'formatting'
    })
    config.addCommand('toggle-small-caps', AnnotationCommand, {
      nodeType: 'small-caps',
      commandGroup: 'formatting'
    })
    config.addCommand('toggle-strike-through', AnnotationCommand, {
      nodeType: 'strike-through',
      commandGroup: 'formatting'
    })
    config.addCommand('toggle-subscript', AnnotationCommand, {
      nodeType: 'subscript',
      commandGroup: 'formatting'
    })
    config.addCommand('toggle-superscript', AnnotationCommand, {
      nodeType: 'superscript',
      commandGroup: 'formatting'
    })
    config.addCommand('toggle-underline', AnnotationCommand, {
      nodeType: 'underline',
      commandGroup: 'formatting'
    })
    config.addCommand('toggle-unordered-list', ChangeListTypeCommand, {
      spec: { listType: 'bullet' },
      commandGroup: 'list'
    })

    // Workflows
    config.addComponent('add-affiliation-workflow', AddAffiliationWorkflow)
    config.addComponent('add-author-workflow', AddAuthorWorkflow)
    config.addComponent('add-reference-workflow', AddReferenceWorkflow)
    config.addComponent('edit-metadata-workflow', EditMetadataWorkflow)

    // Labels
    config.addLabel('add-author', 'Add Author')
    config.addLabel('add-ref', 'Add Reference')
    config.addLabel('article-info', 'Article Information')
    config.addLabel('article-record', 'Article Record')
    config.addLabel('contributors', 'Authors & Contributors')
    config.addLabel('create-unordered-list', 'Bulleted list')
    config.addLabel('create-ordered-list', 'Numbered list')
    config.addLabel('edit-metadata', 'Edit Metadata')
    config.addLabel('edit-ref', 'Edit Reference')
    config.addLabel('file-location', 'File location')
    config.addLabel('file-name', 'File name')
    config.addLabel('manuscript-start', 'Article starts here')
    config.addLabel('manuscript-end', 'Article ends here')
    config.addLabel('no-authors', 'No Authors')
    config.addLabel('no-editors', 'No Editors')
    config.addLabel('no-references', 'No References')
    config.addLabel('no-footnotes', 'No Footnotes')
    config.addLabel('open-link', 'Open Link')
    config.addLabel('pub-data', 'Publication Data')
    config.addLabel('sig-block-start', 'Signature Block starts here')
    config.addLabel('sig-block-end', 'Signature Block ends here')
    config.addLabel('structure', 'Structure')
    config.addLabel('toc', 'Table of Contents')
    config.addLabel('remove-ref', 'Remove')
    config.addLabel('toggle-unordered-list', 'Bulleted list')
    config.addLabel('toggle-ordered-list', 'Numbered list')
    config.addLabel('enter-custom-field-name', 'Enter name')
    config.addLabel('enter-custom-field-value', 'Enter value')
    config.addLabel('add-action', 'Add')
    config.addLabel('enter-url-placeholder', 'Enter url')

    // These labels are used by the AddReferenceWorkflow only
    config.addLabel('add-reference-title', 'Add Reference(s)')
    config.addLabel('add-ref-manually', 'Or create manually')
    config.addLabel('fetch-datacite', 'Fetch from DataCite')
    config.addLabel('enter-doi-placeholder', 'Enter one or more DOIs')
    config.addLabel('import-refs', 'Import')

    // Icons
    config.addIcon('create-unordered-list', { 'fontawesome': 'fa-list-ul' })
    config.addIcon('create-ordered-list', { 'fontawesome': 'fa-list-ol' })
    config.addIcon('open-link', { 'fontawesome': 'fa-external-link' })
    config.addIcon('pencil', { 'fontawesome': 'fa-pencil' })
    config.addIcon('toggle-unordered-list', { 'fontawesome': 'fa-list-ul' })
    config.addIcon('toggle-ordered-list', { 'fontawesome': 'fa-list-ol' })
    config.addIcon('trash', { 'fontawesome': 'fa-trash' })
    config.addIcon('input-loading', { 'fontawesome': 'fa-spinner fa-spin' })
    config.addIcon('input-error', { 'fontawesome': 'fa-exclamation-circle' })
    config.addIcon('left-control', { 'fontawesome': 'fa-chevron-left' })
    config.addIcon('right-control', { 'fontawesome': 'fa-chevron-right' })

    // Tools
    config.addComponent('add-figure-panel', InsertFigurePanelTool)
    config.addComponent('download-file', DownloadSupplementaryFileTool)
    config.addComponent('insert-figure', InsertFigureTool)
    config.addComponent('insert-inline-graphic', InsertInlineGraphicTool)
    config.addComponent('open-figure-panel-image', OpenFigurePanelImageTool)
    config.addComponent('replace-figure-panel-image', ReplaceFigurePanelTool)
    config.addComponent('replace-file', ReplaceSupplementaryFileTool)
    config.addComponent('insert-table', InsertTableTool)

    // DropDownHandler
    config.addDropHandler(DropFigure)

    // SwitchTextTypes
    config.addTextTypeTool({
      name: 'switch-to-heading1',
      commandGroup: 'text-types',
      nodeSpec: {
        type: 'heading',
        level: 1
      },
      icon: 'fa-header',
      label: 'Heading 1',
      accelerator: 'CommandOrControl+Alt+1'
    })
    config.addTextTypeTool({
      name: 'switch-to-heading2',
      commandGroup: 'text-types',
      nodeSpec: {
        type: 'heading',
        level: 2
      },
      icon: 'fa-header',
      label: 'Heading 2',
      accelerator: 'CommandOrControl+Alt+2'
    })
    config.addTextTypeTool({
      name: 'switch-to-heading3',
      commandGroup: 'text-types',
      nodeSpec: {
        type: 'heading',
        level: 3
      },
      icon: 'fa-header',
      label: 'Heading 3',
      accelerator: 'CommandOrControl+Alt+3'
    })
    config.addTextTypeTool({
      name: 'switch-to-paragraph',
      commandGroup: 'text-types',
      nodeSpec: {
        type: 'paragraph'
      },
      icon: 'fa-paragraph',
      label: 'Paragraph',
      accelerator: 'CommandOrControl+Alt+0'
    })
    config.addCommand('create-unordered-list', CreateListCommand, {
      spec: { listType: 'bullet' },
      commandGroup: 'text-types'
    })
    config.addCommand('create-ordered-list', CreateListCommand, {
      spec: { listType: 'order' },
      commandGroup: 'text-types'
    })
    config.addTextTypeTool({
      name: 'switch-to-preformat',
      commandGroup: 'text-types',
      nodeSpec: {
        type: 'preformat'
      },
      icon: 'fa-font',
      label: 'Preformat',
      accelerator: 'CommandOrControl+E'
    })

    // Toolpanels
    config.addToolPanel('main-overlay', [
      {
        name: 'prompt',
        type: 'prompt',
        style: 'minimal',
        hideDisabled: true,
        items: [
          { type: 'command-group', name: 'prompt' }
        ]
      }
    ])

    config.addToolPanel('workflow', [
      {
        name: 'workflow',
        type: 'group',
        items: [
          { type: 'command-group', name: 'workflows' }
        ]
      }
    ])

    // KeyboardShortcuts
    config.addKeyboardShortcut('CommandOrControl+a', { command: 'table:select-all' })

    // Register commands and keyboard shortcuts for collections
    // registerCollectionCommand(config, 'author', ['metadata', 'authors'], { keyboardShortcut: 'CommandOrControl+Alt+A', nodeType: 'person' })
    registerCollectionCommand(config, 'funder', ['metadata', 'funders'], { keyboardShortcut: 'CommandOrControl+Alt+Y' })
    registerCollectionCommand(config, 'editor', ['metadata', 'editors'], { keyboardShortcut: 'CommandOrControl+Alt+E', nodeType: 'person' })
    registerCollectionCommand(config, 'group', ['metadata', 'groups'], { keyboardShortcut: 'CommandOrControl+Alt+G' })
    registerCollectionCommand(config, 'keyword', ['metadata', 'keywords'], { keyboardShortcut: 'CommandOrControl+Alt+K' })
    registerCollectionCommand(config, 'affiliation', ['metadata', 'affiliations'], { keyboardShortcut: 'CommandOrControl+Alt+O' })
    registerCollectionCommand(config, 'subject', ['metadata', 'subjects'])
  },
  ManuscriptEditor,
  // legacy
  Editor: ManuscriptEditor
}

// For now we just switch view and do the same action as in metadata editor
// TODO: later we will probably have just one set of commands for register collection
function registerCollectionCommand (config, itemType, collectionPath, options = {}) {
  let nodeType = options.nodeType || itemType
  config.addCommand(`insert-${itemType}`, AddEntityCommand, {
    type: nodeType,
    collection: collectionPath,
    commandGroup: 'add-entity',
    metadataOnly: true
  })
  if (options.keyboardShortcut) {
    config.addKeyboardShortcut(options.keyboardShortcut, { command: `add-${itemType}` })
  }
}


text:
#ifndef MINKOWSKI_PENETRATION_DEPTH_SOLVER_H
#define MINKOWSKI_PENETRATION_DEPTH_SOLVER_H

#include "SpuConvexPenetrationDepthSolver.h"

class btStackAlloc;
class btIDebugDraw;
class SpuVoronoiSimplexSolver;

///MinkowskiPenetrationDepthSolver implements bruteforce penetration depth estimation.
///Implementation is based on sampling the depth using support mapping, and using GJK step to get the witness points.
class SpuMinkowskiPenetrationDepthSolver : public SpuConvexPenetrationDepthSolver
{
public:

	virtual bool calcPenDepth( SpuVoronoiSimplexSolver& simplexSolver,
	        void* convexA,void* convexB,int shapeTypeA, int shapeTypeB, float marginA, float marginB,
            btTransform& transA,const btTransform& transB,
			btVector3& v, btVector3& pa, btVector3& pb,
			class btIDebugDraw* debugDraw,btStackAlloc* stackAlloc,
			struct SpuConvexPolyhedronVertexData* convexVertexDataA,
			struct SpuConvexPolyhedronVertexData* convexVertexDataB
			) const;

};

#endif //MINKOWSKI_PENETRATION_DEPTH_SOLVER_H


text:
using System;

namespace WPWebSockets.Events
{
    public class JSONFrameEventArgs : EventArgs
    {
        public string JSON { get; set; }
        public JSONFrameEventArgs(string json)
        {
            JSON = json;
        }
    }
}


text:
TODO: Write a gem description

## Installation

Add this line to your application's Gemfile:

```ruby
gem 'activemessenger'
```

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install activemessenger

## Usage

Write sub-class of `ActiveMessenger::Base` and put under `app/massengers/`
sub-class like...
```ruby
class ReportMessenger < ActiveMessenger::Base
  adapter :adapter_name

  # something action...
  # def all_report
  #   @reports = Report.all
  # end
end
```

Create messenger instance and call action on your code.

```ruby
messenger = ReportMessenger.new

messenger.send!("Hello, World") # Send message "Hello, World"

# comming soon...
# messenger.post!(:all_reoprt) # Rendering 'app/views/messengers/report/all_report.html.haml' and send it
```

## Configure
### Hipchat
Set class attributes
```ruby
class YourMessenger < ActiveMessenger::Base
  adapter :hipchat

  self.api_token = 'XXXXXXX'
  self.room_id   = 123456
  self.user_name = 'hoge'
end
```
Or write and put on config file

```yaml
# config/active_messenger.yml
development:
  hipchat:
    api_token: XXXXXXX
    room_id: 123456
    user_name: dev
production:
  hipchat:
    api_token: XXXXXXX
    room_id: 123456
    user_name: hoge
test:
  hipchat:
    api_token: XXXXXXX
    room_id: 123456
    user_name: test
```

## Contributing

1. Fork it ( https://github.com/[my-github-username]/activemessenger/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create a new Pull Request


text:
class FaultsController < ApplicationController
  require 'net/http'
  require 'json'
  require 'util'

  def find_faults(query, skip = 0, limit = Rails.configuration.page_size)
    q = {
      'query' => ActiveSupport::JSON.encode(query),
      'skip' => skip,
      'limit' => limit
    }
    http = create_api_conn()
    res = http.get("/faults/?#{q.to_query}")
    @total = res['Total'].to_i
    return ActiveSupport::JSON.decode(res.body)
  end

  # GET /faults
  # GET /faults.json
  def index
    can?(:read, 'faults') do
      skip = params.include?(:page) ? (Integer(params[:page]) - 1) * Rails.configuration.page_size : 0
      if params.has_key?('query')
        @query = ActiveSupport::JSON.decode(URI.unescape(params['query']))
      else
        @query = {}
      end

      @faults = find_faults(@query, skip, Rails.configuration.page_size)
      respond_to do |format|
        format.html # index.html.erb
        format.json { render json: @faults }
      end
    end
  end

  # DELETE /faults/1
  # DELETE /faults/1.json
  def destroy
    can?(:delete, 'faults') do
      http = create_api_conn()
      res = http.delete("/faults/#{URI.escape(params[:id])}", nil)
      if res.code == '200'
        flash[:success] = 'Fault deleted'
      else
        flash[:error] = "Unexpected error (#{res.code}): #{res.body}"
      end

      redirect_back(fallback_location: root_path)
    end
  end

  # POST /tasks/:id/retry
  def retry_task
    can?(:update, 'tasks/retry') do
      http = create_api_conn()
      res = http.post("/tasks/#{params[:id]}/retry", nil)
      if res.code == '200'
        flash[:success] = 'Task updated'
      else
        flash[:error] = "Unexpected error (#{res.code}): #{res.body}"
      end

      redirect_back(fallback_location: root_path)
    end
  end

  # DELETE /tasks/1
  # DELETE /tasks/1.json
  def destroy_task
    can?(:delete, 'tasks') do
      http = create_api_conn()
      res = http.delete("/tasks/#{params[:id]}", nil)
      if res.code == '200'
        flash[:success] = 'Faulty task deleted'
      else
        flash[:error] = "Unexpected error (#{res.code}): #{res.body}"
      end

      redirect_back(fallback_location: root_path)
    end
  end
end


text:
function doAction(aobj)
{
    var prevAltAction = document.getElementsByName("prevAlternatesAction");
    var altAction = document.getElementsByName("alternatesAction");
    prevAltAction[0].value = altAction[0].value;
    altAction[0].value = aobj;
    doSubmit();
}

// Directly perform a general action. The previous action is not remembered.

function doActionDirect(aobj)
{
    var altAction = document.getElementsByName("alternatesAction");
    altAction[0].value = aobj;
    doSubmit();
}

// Perform a Cancel during an Add/Edit

function doActionCancel()
{
    var prevAltAction = document.getElementsByName("prevAlternatesAction");
    var altAction = document.getElementsByName("alternatesAction");
    altAction[0].value = prevAltAction[0].value;
    doSubmit();
}

// Submit the form for processing

function doSubmit()
{
    eobj = document.getElementById("process");
    eobj.innerText = "working...";
    eobj.textContent = "working...";
    document.alternatesForm.submit();
}
// Manage the selection of the CSI on the Add/Edit page

function selCSI(aobj)
{
    var pn = aobj.parentNode.parentNode;
    var sel = getAlreadySelCSI(pn);
    if(sel != null) {
    	sel.setAttribute("selected","none");
    	sel.style.backgroundColor="";
    }
    aobj.style.backgroundColor = "#ffff00"
    aobj.setAttribute("selected","selected");
}

// Post process the Add/Edit page load

function loaded()
{
    // Set focus to the Name/Definition field
    eobj = document.getElementsByName(parmNameDef);
    eobj[0].focus();

    // Filter the CSI tree using the previous text
    eobj = document.getElementsByName(parmFilterText);
    filterCSI(eobj[0]);
}

// Utility function to find the root of the tree displayed as an HTML Table

function findRoot(eobj)
{
    if (eobj.getAttribute(nodeLevel) != null)
        return eobj.parentNode;

    for (var i = 0; i < eobj.children.length; ++i)
    {
        var xobj = findRoot(eobj.children[i]);
        if (xobj != null)
            return xobj;
    }

    return null;
}

// Filter the CSI tree dynamically as the user types in the Filter Text

function filterCSI(tobj)
{
    var tlow = tobj.value.toLowerCase();
    var eobj = findTable();
      // Go through all the rows in the table (nodes in the tree)
    for (var i = 0; i < eobj.rows.length; ++i)
    {
        // If the text entered by the user appears in the row.
        var tt = eobj.rows[i];
        var text = (tt.innerText) ? tt.innerText: tt.textContent;
        if ((text.toLowerCase().indexOf(tlow) > -1))
        {
            // Make the row visible as well as its ancetors and
            // offspring
            var b;
            tt.style.display = "block";
            var level = parseInt(tt.getAttribute(nodeLevel));
            var compLevel = level;
            for (b = i - 1; b >= 0; --b)
            {
                var prev = eobj.rows[b];
                var prevLevel = parseInt(prev.getAttribute(nodeLevel));
                if (prevLevel < compLevel)
                {
                    prev.style.display = "block";
                    compLevel = prevLevel;
                }
                if (prevLevel == 1)
                    break;
            }
            for (b = i + 1; b < eobj.rows.length; ++b)
            {
                var prev = eobj.rows[b];
                var prevLevel = parseInt(prev.getAttribute(nodeLevel));
                if (prevLevel <= level)
                    break;
                prev.style.display = "block";
            }
            i = b - 1;
        }

        // If the text doesn't appear, hide the row.
        else
        {
            tt.style.display = "none";
        }
    }
}

// Save the Add/Edit data.

function doSave()
{
    // Have to enter a Name/Definition
    eobj = document.getElementsByName(parmNameDef);
    if (eobj[0].value == null || eobj[0].value.length == 0)
    {
        if (nameFlag)
        {
            alert("Please enter a Name.");
        }
        else
        {
            alert("Please enter a Definition.");
        }
        eobj[0].focus();
        return;
    }

    // Have to enter a Type
    eobj = document.getElementsByName(parmType);
    if (eobj[0].selectedIndex < 1)
    {
        alert("Please select a Type.");
        eobj[0].focus();
        return;
    }

    // Have to enter a Language
    eobj = document.getElementsByName(parmLang);
    if (eobj[0].selectedIndex < 1)
    {
        alert("Please enter a Language.");
        eobj[0].focus();
        return;
    }

    // All good do the Save
    doActionDirect(actionSaveName);
}

// Perform a Classify on a Name/Definition from the Add/Edit page.

function doClassify()
{
    //verify the user selected a CSI and not a CS
    var tobj = findTable();
    var eobj = getAlreadySelCSI(tobj);
    if (eobj == null)
    {
        alert("Please select a Class Scheme Item from the hierarchy at the bottom of the page.");
        return;
    }
    else
    {
        var level = parseInt(eobj.getAttribute(nodeLevel));
        if (level == 1)
        {
            alert("You have selected a Classification Scheme, please select a Class Scheme Item.");
            return;
        }
    }

    var rsrvd = eobj.getAttribute(nodeCsiType);
    if (rsrvd != null && rsrvd == parmReserved)
    {
        alert("Class Scheme Item type " + parmReserved + " is reserved by the caDSR Tools and can not be chosen for Classify. Please make a different selection.");
        return;
    }

    // Do the Classify
    var aobj = document.getElementsByName(parmIdseq);
    aobj[0].value = eobj.getAttribute(nodeValue);
    doActionDirect(actionClassify);
}

// Get the special application node value for the row.

function getNodeValue(aobj)
{
    var last = aobj;
    var idseq = last.getAttribute(nodeValue);
    while (last != null && idseq == null)
    {
        last = last.parentNode;
        idseq = last.getAttribute(nodeValue);
    }

    return idseq;
}

// Get the special application node name for the row.

function getNodeName(aobj)
{
    var last = aobj;
    var name = last.getAttribute(nodeName);
    while (last != null && name == null)
    {
        last = last.parentNode;
        name = last.getAttribute(nodeName);
    }

    return name;
}

// Perform a remove association on the Add/Edit page

function removeAssoc(aobj)
{
    var idseq = getNodeValue(aobj);

    var eobj = document.getElementsByName(parmIdseq);
    eobj[0].value = idseq;
    doActionDirect(actionRemoveAssoc);
}

// Perform a restore association to undo a previous remove

function restoreAssoc(aobj)
{
    var idseq = getNodeValue(aobj);

    var eobj = document.getElementsByName(parmIdseq);
    eobj[0].value = idseq;
    doActionDirect(actionRestoreAssoc);
}

// Perform an Edit on a Name/Definition from one of the "View ..." pages

function doEdit(aobj)
{
    var idseq = getNodeValue(aobj);

    var eobj = document.getElementsByName(parmIdseq);
    eobj[0].value = idseq;
    doAction(actionEditNameDef);
}

// Perform a Delete on a Name/Definition from one of the "View ..." pages

function doDelete(aobj)
{
    // Always confirm a delete even if you can undo it.
    var idseq = getNodeName(aobj);
    if (confirm("Are you sure you want to delete " + idseq + "?"))
    {
	    idseq = getNodeValue(aobj);

	    var eobj = document.getElementsByName(parmIdseq);
	    eobj[0].value = idseq;
	    doAction(actionDelNameDef);
    }
}

// Perform a Restore on a Name/Definition that was previously deleted

function doRestore(aobj)
{
    var idseq = getNodeValue(aobj);

    var eobj = document.getElementsByName(parmIdseq);
    eobj[0].value = idseq;
    doAction(actionRestoreNameDef);
}

function findTable(){
   var tobj;
   if (navigator.userAgent.indexOf('Firefox') != -1){
        var div = document.getElementById("csiList");
        if (div.childNodes[1]!= null)
           tobj = div.childNodes[1];

    }else{
       eobj = findRoot(document.getElementById("csiList"));
       tobj = eobj.parentNode;
    }
  return tobj;
}

function getAlreadySelCSI(tobj){
 for (var i=0; i<tobj.rows.length; i++){
	       var robj = tobj.rows[i];
	       if (robj.getAttribute("selected") == "selected")
	         return robj;
	    }
}