text:
import {AbstractType, ApplicationInitStatus, CompilerOptions, Component, Directive, InjectFlags, InjectionToken, Injector, NgModule, NgModuleFactory, NgModuleRef, NgZone, Optional, Pipe, PlatformRef, Provider, SchemaMetadata, SkipSelf, StaticProvider, Type, ɵDepFlags as DepFlags, ɵINJECTOR_SCOPE as INJECTOR_SCOPE, ɵNodeFlags as NodeFlags, ɵclearOverrides as clearOverrides, ɵgetInjectableDef as getInjectableDef, ɵivyEnabled as ivyEnabled, ɵoverrideComponentView as overrideComponentView, ɵoverrideProvider as overrideProvider, ɵstringify as stringify, ɵɵInjectableDef} from '@angular/core';

import {AsyncTestCompleter} from './async_test_completer';
import {ComponentFixture} from './component_fixture';
import {MetadataOverride} from './metadata_override';
import {TestBedRender3, _getTestBedRender3} from './r3_test_bed';
import {ComponentFixtureAutoDetect, ComponentFixtureNoNgZone, TestBedStatic, TestComponentRenderer, TestModuleMetadata} from './test_bed_common';
import {TestingCompiler, TestingCompilerFactory} from './test_compiler';

const UNDEFINED = new Object();

let _nextRootElementId = 0;

/**
 * @publicApi
 */
export interface TestBed {
  platform: PlatformRef;

  ngModule: Type<any>|Type<any>[];

  /**
   * Initialize the environment for testing with a compiler factory, a PlatformRef, and an
   * angular module. These are common to every test in the suite.
   *
   * This may only be called once, to set up the common providers for the current test
   * suite on the current platform. If you absolutely need to change the providers,
   * first use `resetTestEnvironment`.
   *
   * Test modules and platforms for individual platforms are available from
   * '@angular/<platform_name>/testing'.
   */
  initTestEnvironment(
      ngModule: Type<any>|Type<any>[], platform: PlatformRef, aotSummaries?: () => any[]): void;

  /**
   * Reset the providers for the test injector.
   */
  resetTestEnvironment(): void;

  resetTestingModule(): void;

  configureCompiler(config: {providers?: any[], useJit?: boolean}): void;

  configureTestingModule(moduleDef: TestModuleMetadata): void;

  compileComponents(): Promise<any>;

  inject<T>(
      token: Type<T>|InjectionToken<T>|AbstractType<T>, notFoundValue?: T, flags?: InjectFlags): T;
  inject<T>(
      token: Type<T>|InjectionToken<T>|AbstractType<T>, notFoundValue: null, flags?: InjectFlags): T
      |null;

  /** @deprecated from v9.0.0 use TestBed.inject */
  get<T>(token: Type<T>|InjectionToken<T>, notFoundValue?: T, flags?: InjectFlags): any;
  /** @deprecated from v9.0.0 use TestBed.inject */
  get(token: any, notFoundValue?: any): any;

  execute(tokens: any[], fn: Function, context?: any): any;

  overrideModule(ngModule: Type<any>, override: MetadataOverride<NgModule>): void;

  overrideComponent(component: Type<any>, override: MetadataOverride<Component>): void;

  overrideDirective(directive: Type<any>, override: MetadataOverride<Directive>): void;

  overridePipe(pipe: Type<any>, override: MetadataOverride<Pipe>): void;

  /**
   * Overwrites all providers for the given token with the given provider definition.
   */
  overrideProvider(token: any, provider: {
    useFactory: Function,
    deps: any[],
  }): void;
  overrideProvider(token: any, provider: {useValue: any;}): void;
  overrideProvider(token: any, provider: {useFactory?: Function, useValue?: any, deps?: any[]}):
      void;

  overrideTemplateUsingTestingModule(component: Type<any>, template: string): void;

  createComponent<T>(component: Type<T>): ComponentFixture<T>;
}

/**
 * @description
 * Configures and initializes environment for unit testing and provides methods for
 * creating components and services in unit tests.
 *
 * `TestBed` is the primary api for writing unit tests for Angular applications and libraries.
 *
 * Note: Use `TestBed` in tests. It will be set to either `TestBedViewEngine` or `TestBedRender3`
 * according to the compiler used.
 */
export class TestBedViewEngine implements TestBed {
  /**
   * Initialize the environment for testing with a compiler factory, a PlatformRef, and an
   * angular module. These are common to every test in the suite.
   *
   * This may only be called once, to set up the common providers for the current test
   * suite on the current platform. If you absolutely need to change the providers,
   * first use `resetTestEnvironment`.
   *
   * Test modules and platforms for individual platforms are available from
   * '@angular/<platform_name>/testing'.
   */
  static initTestEnvironment(
      ngModule: Type<any>|Type<any>[], platform: PlatformRef,
      aotSummaries?: () => any[]): TestBedViewEngine {
    const testBed = _getTestBedViewEngine();
    testBed.initTestEnvironment(ngModule, platform, aotSummaries);
    return testBed;
  }

  /**
   * Reset the providers for the test injector.
   */
  static resetTestEnvironment(): void { _getTestBedViewEngine().resetTestEnvironment(); }

  static resetTestingModule(): TestBedStatic {
    _getTestBedViewEngine().resetTestingModule();
    return TestBedViewEngine as any as TestBedStatic;
  }

  /**
   * Allows overriding default compiler providers and settings
   * which are defined in test_injector.js
   */
  static configureCompiler(config: {providers?: any[]; useJit?: boolean;}): TestBedStatic {
    _getTestBedViewEngine().configureCompiler(config);
    return TestBedViewEngine as any as TestBedStatic;
  }

  /**
   * Allows overriding default providers, directives, pipes, modules of the test injector,
   * which are defined in test_injector.js
   */
  static configureTestingModule(moduleDef: TestModuleMetadata): TestBedStatic {
    _getTestBedViewEngine().configureTestingModule(moduleDef);
    return TestBedViewEngine as any as TestBedStatic;
  }

  /**
   * Compile components with a `templateUrl` for the test's NgModule.
   * It is necessary to call this function
   * as fetching urls is asynchronous.
   */
  static compileComponents(): Promise<any> { return getTestBed().compileComponents(); }

  static overrideModule(ngModule: Type<any>, override: MetadataOverride<NgModule>): TestBedStatic {
    _getTestBedViewEngine().overrideModule(ngModule, override);
    return TestBedViewEngine as any as TestBedStatic;
  }

  static overrideComponent(component: Type<any>, override: MetadataOverride<Component>):
      TestBedStatic {
    _getTestBedViewEngine().overrideComponent(component, override);
    return TestBedViewEngine as any as TestBedStatic;
  }

  static overrideDirective(directive: Type<any>, override: MetadataOverride<Directive>):
      TestBedStatic {
    _getTestBedViewEngine().overrideDirective(directive, override);
    return TestBedViewEngine as any as TestBedStatic;
  }

  static overridePipe(pipe: Type<any>, override: MetadataOverride<Pipe>): TestBedStatic {
    _getTestBedViewEngine().overridePipe(pipe, override);
    return TestBedViewEngine as any as TestBedStatic;
  }

  static overrideTemplate(component: Type<any>, template: string): TestBedStatic {
    _getTestBedViewEngine().overrideComponent(component, {set: {template, templateUrl: null !}});
    return TestBedViewEngine as any as TestBedStatic;
  }

  /**
   * Overrides the template of the given component, compiling the template
   * in the context of the TestingModule.
   *
   * Note: This works for JIT and AOTed components as well.
   */
  static overrideTemplateUsingTestingModule(component: Type<any>, template: string): TestBedStatic {
    _getTestBedViewEngine().overrideTemplateUsingTestingModule(component, template);
    return TestBedViewEngine as any as TestBedStatic;
  }

  /**
   * Overwrites all providers for the given token with the given provider definition.
   *
   * Note: This works for JIT and AOTed components as well.
   */
  static overrideProvider(token: any, provider: {
    useFactory: Function,
    deps: any[],
  }): TestBedStatic;
  static overrideProvider(token: any, provider: {useValue: any;}): TestBedStatic;
  static overrideProvider(token: any, provider: {
    useFactory?: Function,
    useValue?: any,
    deps?: any[],
  }): TestBedStatic {
    _getTestBedViewEngine().overrideProvider(token, provider as any);
    return TestBedViewEngine as any as TestBedStatic;
  }

  static inject<T>(
      token: Type<T>|InjectionToken<T>|AbstractType<T>, notFoundValue?: T, flags?: InjectFlags): T;
  static inject<T>(
      token: Type<T>|InjectionToken<T>|AbstractType<T>, notFoundValue: null, flags?: InjectFlags): T
      |null;
  static inject<T>(
      token: Type<T>|InjectionToken<T>|AbstractType<T>, notFoundValue?: T|null,
      flags?: InjectFlags): T|null {
    return _getTestBedViewEngine().inject(token, notFoundValue, flags);
  }

  /** @deprecated from v9.0.0 use TestBed.inject */
  static get<T>(token: Type<T>|InjectionToken<T>, notFoundValue?: T, flags?: InjectFlags): any;
  /**
   * @deprecated from v9.0.0 use TestBed.inject
   * @suppress {duplicate}
   */
  static get(token: any, notFoundValue?: any): any;
  /** @deprecated from v9.0.0 use TestBed.inject */
  static get(
      token: any, notFoundValue: any = Injector.THROW_IF_NOT_FOUND,
      flags: InjectFlags = InjectFlags.Default): any {
    return _getTestBedViewEngine().inject(token, notFoundValue, flags);
  }

  static createComponent<T>(component: Type<T>): ComponentFixture<T> {
    return _getTestBedViewEngine().createComponent(component);
  }

  private _instantiated: boolean = false;

  private _compiler: TestingCompiler = null !;
  private _moduleRef: NgModuleRef<any> = null !;
  private _moduleFactory: NgModuleFactory<any> = null !;

  private _compilerOptions: CompilerOptions[] = [];

  private _moduleOverrides: [Type<any>, MetadataOverride<NgModule>][] = [];
  private _componentOverrides: [Type<any>, MetadataOverride<Component>][] = [];
  private _directiveOverrides: [Type<any>, MetadataOverride<Directive>][] = [];
  private _pipeOverrides: [Type<any>, MetadataOverride<Pipe>][] = [];

  private _providers: Provider[] = [];
  private _declarations: Array<Type<any>|any[]|any> = [];
  private _imports: Array<Type<any>|any[]|any> = [];
  private _schemas: Array<SchemaMetadata|any[]> = [];
  private _activeFixtures: ComponentFixture<any>[] = [];

  private _testEnvAotSummaries: () => any[] = () => [];
  private _aotSummaries: Array<() => any[]> = [];
  private _templateOverrides: Array<{component: Type<any>, templateOf: Type<any>}> = [];

  private _isRoot: boolean = true;
  private _rootProviderOverrides: Provider[] = [];

  platform: PlatformRef = null !;

  ngModule: Type<any>|Type<any>[] = null !;

  /**
   * Initialize the environment for testing with a compiler factory, a PlatformRef, and an
   * angular module. These are common to every test in the suite.
   *
   * This may only be called once, to set up the common providers for the current test
   * suite on the current platform. If you absolutely need to change the providers,
   * first use `resetTestEnvironment`.
   *
   * Test modules and platforms for individual platforms are available from
   * '@angular/<platform_name>/testing'.
   */
  initTestEnvironment(
      ngModule: Type<any>|Type<any>[], platform: PlatformRef, aotSummaries?: () => any[]): void {
    if (this.platform || this.ngModule) {
      throw new Error('Cannot set base providers because it has already been called');
    }
    this.platform = platform;
    this.ngModule = ngModule;
    if (aotSummaries) {
      this._testEnvAotSummaries = aotSummaries;
    }
  }

  /**
   * Reset the providers for the test injector.
   */
  resetTestEnvironment(): void {
    this.resetTestingModule();
    this.platform = null !;
    this.ngModule = null !;
    this._testEnvAotSummaries = () => [];
  }

  resetTestingModule(): void {
    clearOverrides();
    this._aotSummaries = [];
    this._templateOverrides = [];
    this._compiler = null !;
    this._moduleOverrides = [];
    this._componentOverrides = [];
    this._directiveOverrides = [];
    this._pipeOverrides = [];

    this._isRoot = true;
    this._rootProviderOverrides = [];

    this._moduleRef = null !;
    this._moduleFactory = null !;
    this._compilerOptions = [];
    this._providers = [];
    this._declarations = [];
    this._imports = [];
    this._schemas = [];
    this._instantiated = false;
    this._activeFixtures.forEach((fixture) => {
      try {
        fixture.destroy();
      } catch (e) {
        console.error('Error during cleanup of component', {
          component: fixture.componentInstance,
          stacktrace: e,
        });
      }
    });
    this._activeFixtures = [];
  }

  configureCompiler(config: {providers?: any[], useJit?: boolean}): void {
    this._assertNotInstantiated('TestBed.configureCompiler', 'configure the compiler');
    this._compilerOptions.push(config);
  }

  configureTestingModule(moduleDef: TestModuleMetadata): void {
    this._assertNotInstantiated('TestBed.configureTestingModule', 'configure the test module');
    if (moduleDef.providers) {
      this._providers.push(...moduleDef.providers);
    }
    if (moduleDef.declarations) {
      this._declarations.push(...moduleDef.declarations);
    }
    if (moduleDef.imports) {
      this._imports.push(...moduleDef.imports);
    }
    if (moduleDef.schemas) {
      this._schemas.push(...moduleDef.schemas);
    }
    if (moduleDef.aotSummaries) {
      this._aotSummaries.push(moduleDef.aotSummaries);
    }
  }

  compileComponents(): Promise<any> {
    if (this._moduleFactory || this._instantiated) {
      return Promise.resolve(null);
    }

    const moduleType = this._createCompilerAndModule();
    return this._compiler.compileModuleAndAllComponentsAsync(moduleType)
        .then((moduleAndComponentFactories) => {
          this._moduleFactory = moduleAndComponentFactories.ngModuleFactory;
        });
  }

  private _initIfNeeded(): void {
    if (this._instantiated) {
      return;
    }
    if (!this._moduleFactory) {
      try {
        const moduleType = this._createCompilerAndModule();
        this._moduleFactory =
            this._compiler.compileModuleAndAllComponentsSync(moduleType).ngModuleFactory;
      } catch (e) {
        const errorCompType = this._compiler.getComponentFromError(e);
        if (errorCompType) {
          throw new Error(
              `This test module uses the component ${stringify(errorCompType)} which is using a "templateUrl" or "styleUrls", but they were never compiled. ` +
              `Please call "TestBed.compileComponents" before your test.`);
        } else {
          throw e;
        }
      }
    }
    for (const {component, templateOf} of this._templateOverrides) {
      const compFactory = this._compiler.getComponentFactory(templateOf);
      overrideComponentView(component, compFactory);
    }

    const ngZone = new NgZone({enableLongStackTrace: true});
    const providers: StaticProvider[] = [{provide: NgZone, useValue: ngZone}];
    const ngZoneInjector = Injector.create({
      providers: providers,
      parent: this.platform.injector,
      name: this._moduleFactory.moduleType.name
    });
    this._moduleRef = this._moduleFactory.create(ngZoneInjector);
    // ApplicationInitStatus.runInitializers() is marked @internal to core. So casting to any
    // before accessing it.
    (this._moduleRef.injector.get(ApplicationInitStatus) as any).runInitializers();
    this._instantiated = true;
  }

  private _createCompilerAndModule(): Type<any> {
    const providers = this._providers.concat([{provide: TestBed, useValue: this}]);
    const declarations =
        [...this._declarations, ...this._templateOverrides.map(entry => entry.templateOf)];

    const rootScopeImports = [];
    const rootProviderOverrides = this._rootProviderOverrides;
    if (this._isRoot) {
      @NgModule({
        providers: [
          ...rootProviderOverrides,
        ],
        jit: true,
      })
      class RootScopeModule {
      }
      rootScopeImports.push(RootScopeModule);
    }
    providers.push({provide: INJECTOR_SCOPE, useValue: this._isRoot ? 'root' : null});

    const imports = [rootScopeImports, this.ngModule, this._imports];
    const schemas = this._schemas;

    @NgModule({providers, declarations, imports, schemas, jit: true})
    class DynamicTestModule {
    }

    const compilerFactory = this.platform.injector.get(TestingCompilerFactory);
    this._compiler = compilerFactory.createTestingCompiler(this._compilerOptions);
    for (const summary of [this._testEnvAotSummaries, ...this._aotSummaries]) {
      this._compiler.loadAotSummaries(summary);
    }
    this._moduleOverrides.forEach((entry) => this._compiler.overrideModule(entry[0], entry[1]));
    this._componentOverrides.forEach(
        (entry) => this._compiler.overrideComponent(entry[0], entry[1]));
    this._directiveOverrides.forEach(
        (entry) => this._compiler.overrideDirective(entry[0], entry[1]));
    this._pipeOverrides.forEach((entry) => this._compiler.overridePipe(entry[0], entry[1]));
    return DynamicTestModule;
  }

  private _assertNotInstantiated(methodName: string, methodDescription: string) {
    if (this._instantiated) {
      throw new Error(
          `Cannot ${methodDescription} when the test module has already been instantiated. ` +
          `Make sure you are not using \`inject\` before \`${methodName}\`.`);
    }
  }

  inject<T>(
      token: Type<T>|InjectionToken<T>|AbstractType<T>, notFoundValue?: T, flags?: InjectFlags): T;
  inject<T>(
      token: Type<T>|InjectionToken<T>|AbstractType<T>, notFoundValue: null, flags?: InjectFlags): T
      |null;
  inject<T>(
      token: Type<T>|InjectionToken<T>|AbstractType<T>, notFoundValue?: T|null,
      flags?: InjectFlags): T|null {
    this._initIfNeeded();
    if (token as unknown === TestBed) {
      return this as any;
    }
    // Tests can inject things from the ng module and from the compiler,
    // but the ng module can't inject things from the compiler and vice versa.
    const result = this._moduleRef.injector.get(token, UNDEFINED, flags);
    return result === UNDEFINED ? this._compiler.injector.get(token, notFoundValue, flags) as any :
                                  result;
  }

  /** @deprecated from v9.0.0 use TestBed.inject */
  get<T>(token: Type<T>|InjectionToken<T>, notFoundValue?: T, flags?: InjectFlags): any;
  /** @deprecated from v9.0.0 use TestBed.inject */
  get(token: any, notFoundValue?: any): any;
  /** @deprecated from v9.0.0 use TestBed.inject */
  get(token: any, notFoundValue: any = Injector.THROW_IF_NOT_FOUND,
      flags: InjectFlags = InjectFlags.Default): any {
    return this.inject(token, notFoundValue, flags);
  }

  execute(tokens: any[], fn: Function, context?: any): any {
    this._initIfNeeded();
    const params = tokens.map(t => this.inject(t));
    return fn.apply(context, params);
  }

  overrideModule(ngModule: Type<any>, override: MetadataOverride<NgModule>): void {
    this._assertNotInstantiated('overrideModule', 'override module metadata');
    this._moduleOverrides.push([ngModule, override]);
  }

  overrideComponent(component: Type<any>, override: MetadataOverride<Component>): void {
    this._assertNotInstantiated('overrideComponent', 'override component metadata');
    this._componentOverrides.push([component, override]);
  }

  overrideDirective(directive: Type<any>, override: MetadataOverride<Directive>): void {
    this._assertNotInstantiated('overrideDirective', 'override directive metadata');
    this._directiveOverrides.push([directive, override]);
  }

  overridePipe(pipe: Type<any>, override: MetadataOverride<Pipe>): void {
    this._assertNotInstantiated('overridePipe', 'override pipe metadata');
    this._pipeOverrides.push([pipe, override]);
  }

  /**
   * Overwrites all providers for the given token with the given provider definition.
   */
  overrideProvider(token: any, provider: {
    useFactory: Function,
    deps: any[],
  }): void;
  overrideProvider(token: any, provider: {useValue: any;}): void;
  overrideProvider(token: any, provider: {useFactory?: Function, useValue?: any, deps?: any[]}):
      void {
    this.overrideProviderImpl(token, provider);
  }

  private overrideProviderImpl(
      token: any, provider: {
        useFactory?: Function,
        useValue?: any,
        deps?: any[],
      },
      deprecated = false): void {
    let def: ɵɵInjectableDef<any>|null = null;
    if (typeof token !== 'string' && (def = getInjectableDef(token)) && def.providedIn === 'root') {
      if (provider.useFactory) {
        this._rootProviderOverrides.push(
            {provide: token, useFactory: provider.useFactory, deps: provider.deps || []});
      } else {
        this._rootProviderOverrides.push({provide: token, useValue: provider.useValue});
      }
    }
    let flags: NodeFlags = 0;
    let value: any;
    if (provider.useFactory) {
      flags |= NodeFlags.TypeFactoryProvider;
      value = provider.useFactory;
    } else {
      flags |= NodeFlags.TypeValueProvider;
      value = provider.useValue;
    }
    const deps = (provider.deps || []).map((dep) => {
      let depFlags: DepFlags = DepFlags.None;
      let depToken: any;
      if (Array.isArray(dep)) {
        dep.forEach((entry: any) => {
          if (entry instanceof Optional) {
            depFlags |= DepFlags.Optional;
          } else if (entry instanceof SkipSelf) {
            depFlags |= DepFlags.SkipSelf;
          } else {
            depToken = entry;
          }
        });
      } else {
        depToken = dep;
      }
      return [depFlags, depToken];
    });
    overrideProvider({token, flags, deps, value, deprecatedBehavior: deprecated});
  }

  overrideTemplateUsingTestingModule(component: Type<any>, template: string) {
    this._assertNotInstantiated('overrideTemplateUsingTestingModule', 'override template');

    @Component({selector: 'empty', template, jit: true})
    class OverrideComponent {
    }

    this._templateOverrides.push({component, templateOf: OverrideComponent});
  }

  createComponent<T>(component: Type<T>): ComponentFixture<T> {
    this._initIfNeeded();
    const componentFactory = this._compiler.getComponentFactory(component);

    if (!componentFactory) {
      throw new Error(
          `Cannot create the component ${stringify(component)} as it was not imported into the testing module!`);
    }

    // TODO: Don't cast as `InjectionToken<boolean>`, declared type is boolean[]
    const noNgZone = this.inject(ComponentFixtureNoNgZone as InjectionToken<boolean>, false);
    // TODO: Don't cast as `InjectionToken<boolean>`, declared type is boolean[]
    const autoDetect: boolean =
        this.inject(ComponentFixtureAutoDetect as InjectionToken<boolean>, false);
    const ngZone: NgZone|null = noNgZone ? null : this.inject(NgZone, null);
    const testComponentRenderer: TestComponentRenderer = this.inject(TestComponentRenderer);
    const rootElId = `root${_nextRootElementId++}`;
    testComponentRenderer.insertRootElement(rootElId);

    const initComponent = () => {
      const componentRef =
          componentFactory.create(Injector.NULL, [], `#${rootElId}`, this._moduleRef);
      return new ComponentFixture<T>(componentRef, ngZone, autoDetect);
    };

    const fixture = !ngZone ? initComponent() : ngZone.run(initComponent);
    this._activeFixtures.push(fixture);
    return fixture;
  }
}

/**
 * @description
 * Configures and initializes environment for unit testing and provides methods for
 * creating components and services in unit tests.
 *
 * `TestBed` is the primary api for writing unit tests for Angular applications and libraries.
 *
 * Note: Use `TestBed` in tests. It will be set to either `TestBedViewEngine` or `TestBedRender3`
 * according to the compiler used.
 *
 * @publicApi
 */
export const TestBed: TestBedStatic =
    ivyEnabled ? TestBedRender3 as any as TestBedStatic : TestBedViewEngine as any as TestBedStatic;

/**
 * Returns a singleton of the applicable `TestBed`.
 *
 * It will be either an instance of `TestBedViewEngine` or `TestBedRender3`.
 *
 * @publicApi
 */
export const getTestBed: () => TestBed = ivyEnabled ? _getTestBedRender3 : _getTestBedViewEngine;

let testBed: TestBedViewEngine;

function _getTestBedViewEngine(): TestBedViewEngine {
  return testBed = testBed || new TestBedViewEngine();
}

/**
 * Allows injecting dependencies in `beforeEach()` and `it()`.
 *
 * Example:
 *
 * ```
 * beforeEach(inject([Dependency, AClass], (dep, object) => {
 *   // some code that uses `dep` and `object`
 *   // ...
 * }));
 *
 * it('...', inject([AClass], (object) => {
 *   object.doSomething();
 *   expect(...);
 * })
 * ```
 *
 * Notes:
 * - inject is currently a function because of some Traceur limitation the syntax should
 * eventually
 *   becomes `it('...', @Inject (object: AClass, async: AsyncTestCompleter) => { ... });`
 *
 * @publicApi
 */
export function inject(tokens: any[], fn: Function): () => any {
  const testBed = getTestBed();
  if (tokens.indexOf(AsyncTestCompleter) >= 0) {
    // Not using an arrow function to preserve context passed from call site
    return function(this: unknown) {
      // Return an async test method that returns a Promise if AsyncTestCompleter is one of
      // the injected tokens.
      return testBed.compileComponents().then(() => {
        const completer = testBed.inject(AsyncTestCompleter);
        testBed.execute(tokens, fn, this);
        return completer.promise;
      });
    };
  } else {
    // Not using an arrow function to preserve context passed from call site
    return function(this: unknown) { return testBed.execute(tokens, fn, this); };
  }
}

/**
 * @publicApi
 */
export class InjectSetupWrapper {
  constructor(private _moduleDef: () => TestModuleMetadata) {}

  private _addModule() {
    const moduleDef = this._moduleDef();
    if (moduleDef) {
      getTestBed().configureTestingModule(moduleDef);
    }
  }

  inject(tokens: any[], fn: Function): () => any {
    const self = this;
    // Not using an arrow function to preserve context passed from call site
    return function(this: unknown) {
      self._addModule();
      return inject(tokens, fn).call(this);
    };
  }
}

/**
 * @publicApi
 */
export function withModule(moduleDef: TestModuleMetadata): InjectSetupWrapper;
export function withModule(moduleDef: TestModuleMetadata, fn: Function): () => any;
export function withModule(moduleDef: TestModuleMetadata, fn?: Function | null): (() => any)|
    InjectSetupWrapper {
  if (fn) {
    // Not using an arrow function to preserve context passed from call site
    return function(this: unknown) {
      const testBed = getTestBed();
      if (moduleDef) {
        testBed.configureTestingModule(moduleDef);
      }
      return fn.apply(this);
    };
  }
  return new InjectSetupWrapper(() => moduleDef);
}


text:
package net.roarsoftware.lastfm;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;

import net.roarsoftware.xml.DomElement;

/**
 * Provides nothing more than a namespace for the API methods starting with group.
 *
 * @author Janni Kovacs
 */
public class Group {

	private Group() {
	}

	public static Chart<Album> getWeeklyAlbumChart(String group, String apiKey) {
		return getWeeklyAlbumChart(group, null, null, -1, apiKey);
	}

	public static Chart<Album> getWeeklyAlbumChart(String group, int limit, String apiKey) {
		return getWeeklyAlbumChart(group, null, null, limit, apiKey);
	}

	public static Chart<Album> getWeeklyAlbumChart(String group, String from, String to, int limit, String apiKey) {
		return Chart.getChart("group.getWeeklyAlbumChart", "group", group, "album", from, to, limit, apiKey);
	}

	public static Chart<Artist> getWeeklyArtistChart(String group, String apiKey) {
		return getWeeklyArtistChart(group, null, null, -1, apiKey);
	}

	public static Chart<Artist> getWeeklyArtistChart(String group, int limit, String apiKey) {
		return getWeeklyArtistChart(group, null, null, limit, apiKey);
	}

	public static Chart<Artist> getWeeklyArtistChart(String group, String from, String to, int limit, String apiKey) {
		return Chart.getChart("group.getWeeklyArtistChart", "group", group, "artist", from, to, limit, apiKey);
	}

	public static Chart<Track> getWeeklyTrackChart(String group, String apiKey) {
		return getWeeklyTrackChart(group, null, null, -1, apiKey);
	}

	public static Chart<Track> getWeeklyTrackChart(String group, int limit, String apiKey) {
		return getWeeklyTrackChart(group, null, null, limit, apiKey);
	}

	public static Chart<Track> getWeeklyTrackChart(String group, String from, String to, int limit, String apiKey) {
		return Chart.getChart("group.getWeeklyTrackChart", "group", group, "track", from, to, limit, apiKey);
	}

	public static LinkedHashMap<String, String> getWeeklyChartList(String group, String apiKey) {
		return Chart.getWeeklyChartList("group", group, apiKey);
	}

	public static Collection<Chart> getWeeklyChartListAsCharts(String group, String apiKey) {
		return Chart.getWeeklyChartListAsCharts("group", group, apiKey);
	}

	public static PaginatedResult<User> getMembers(String group, String apiKey) {
		return getMembers(group, 1, apiKey);
	}

	public static PaginatedResult<User> getMembers(String group, int page, String apiKey) {
		Result result = Caller.getInstance()
				.call("group.getMembers", apiKey, "group", group, "page", String.valueOf(page));
		if (!result.isSuccessful())
			return new PaginatedResult<User>(0, 0, Collections.<User>emptyList());
		DomElement root = result.getContentElement();
		Collection<DomElement> children = root.getChildren("user");
		List<User> users = new ArrayList<User>(children.size());
		for (DomElement child : children) {
			users.add(User.userFromElement(child));
		}
		page = Integer.parseInt(root.getAttribute("page"));
		int total = Integer.parseInt(root.getAttribute("totalPages"));
		return new PaginatedResult<User>(page, total, users);
	}
}

redpajama_set_name: RedPajamaGithub


text:
module Automux
  module Core
    class Blueprint < Base
      attr_reader :name, :path, :source_blueprint

      def initialize(path)
        @name = File.basename(path, '.yml')
        @path = path
      end

      def read(options = [])
        Automux::Library::YamlParser.load_file(path, options)
      end

      def get_binding # :nodoc:
        binding
      end

      def source=(blueprint)
        @source_blueprint = blueprint
      end

      class << self
        def build_by_name(name)
          path = File.join(Automux::Paths.blueprints_container, "#{ name }.yml")
          new(path)
        end
      end
    end
  end
end


text:
package org.elasticsearch.snapshots;

public final class AbortedSnapshotException extends RuntimeException {
    public AbortedSnapshotException() {
        super("aborted");
    }
}


text:
using System.Collections.Generic;
using Velyo.Web.Security.Models;

namespace Velyo.Web.Security.Store
{
    /// <summary>
    ///
    /// </summary>
    public class XmlRoleStore : XmlStore<List<Role>>
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="XmlRoleStore"/> class.
        /// </summary>
        /// <param name="fileName">Name of the file.</param>
        public XmlRoleStore(string fileName)
            : base(fileName)
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="XmlRoleStore"/> class.
        /// </summary>
        protected XmlRoleStore()
            : base(null)
        {
        }

        /// <summary>
        /// Gets the roles.
        /// </summary>
        /// <value>The roles.</value>
        public virtual List<Role> Roles
        {
            get
            {
                return Value;
            }
        }
    }
}


text:
<!DOCTYPE html>

                <button type="button" class="navbar-toggle" data-toggle="offcanvas" data-target=".sidebar-nav">

                </button>
                Indoor Positioning Application


text:
/// <template path="template.tmpl.html"/>
/// <template path="template2.tmpl.html"/>
/// <reference path="../jquery-1.7.1.min.js" />
/// <reference path="mocha.js" />
/// <reference path="../chai.js" />

describe("Html Template Test - Mocha", function () {
    it("Will load html template", function () {

        // Grab template text, convert to html, append to body
        $($("#testTemplateId").text()).appendTo("body");

        var templateDiv = $("#testTemplateDiv");

        // Templatediv2 should already be in the body since it is not wrapped
        var templateDiv2 = $("#testTemplateDiv2");

        chai.expect(templateDiv.length).to.equal(1);
        chai.expect(templateDiv2.length).to.equal(1);
    });
});


text:
namespace Serilog.PerformanceTests.Support;

class NullTextWriter : TextWriter
{
    public override void Write(char value)
    {
    }

    public override Encoding Encoding { get; } = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false);

    public override void Write(bool value)
    {
    }

    public override void Write(char[]? buffer)
    {
    }

    public override void Write(char[] buffer, int index, int count)
    {
    }

    public override void Write(decimal value)
    {
    }

    public override void Write(double value)
    {
    }

    public override void Write(int value)
    {
    }

    public override void Write(long value)
    {
    }

    public override void Write(object? value)
    {
    }

    public override void Write(float value)
    {
    }

    public override void Write(string? value)
    {
    }

    public override void Write(string format, object? arg0)
    {
    }

    public override void Write(string format, object? arg0, object? arg1)
    {
    }

    public override void Write(string format, object? arg0, object? arg1, object? arg2)
    {
    }

    public override void Write(string format, params object?[] arg)
    {
    }

    public override void Write(uint value)
    {
    }

    public override void Write(ulong value)
    {
    }

    public override string ToString() => string.Empty;

    public override void Flush()
    {
    }

    public override void WriteLine()
    {
    }

    public override void WriteLine(bool value)
    {
    }

    public override void WriteLine(char value)
    {
    }

    public override void WriteLine(char[]? buffer)
    {
    }

    public override void WriteLine(char[] buffer, int index, int count)
    {
    }

    public override void WriteLine(decimal value)
    {
    }

    public override void WriteLine(double value)
    {
    }

    public override void WriteLine(int value)
    {
    }

    public override void WriteLine(long value)
    {
    }

    public override void WriteLine(object? value)
    {
    }

    public override void WriteLine(float value)
    {
    }

    public override void WriteLine(string? value)
    {
    }

    public override void WriteLine(string format, object? arg0)
    {
    }

    public override void WriteLine(string format, object? arg0, object? arg1)
    {
    }

    public override void WriteLine(string format, object? arg0, object? arg1, object? arg2)
    {
    }

    public override void WriteLine(string format, params object?[] arg)
    {
    }

    public override void WriteLine(uint value)
    {
    }

    public override void WriteLine(ulong value)
    {
    }
}


text:
#ifndef RunLoop_h
#define RunLoop_h

#include <wtf/Deque.h>
#include <wtf/Forward.h>
#include <wtf/FunctionDispatcher.h>
#include <wtf/Functional.h>
#include <wtf/HashMap.h>
#include <wtf/RetainPtr.h>
#include <wtf/Threading.h>

#if USE(GLIB)
#include <wtf/gobject/GRefPtr.h>
#endif

#if PLATFORM(EFL)
#include <Ecore.h>
#endif

namespace WebCore {

class RunLoop : public FunctionDispatcher {
public:
    // Must be called from the main thread (except for the Mac platform, where it
    // can be called from any thread).
    static void initializeMainRunLoop();

    // Must be called before entering main run loop. If called, application style run loop will be used, handling events.
    static void setUseApplicationRunLoopOnMainRunLoop();

    static RunLoop* current();
    static RunLoop* main();
    static bool isMain();
    ~RunLoop();

    virtual void dispatch(const Function<void()>&) OVERRIDE;

    static void run();
    void stop();
    void wakeUp();

#if PLATFORM(MAC)
    void runForDuration(double duration);
#endif

    class TimerBase {
        friend class RunLoop;
    public:
        explicit TimerBase(RunLoop*);
        virtual ~TimerBase();

        void startRepeating(double repeatInterval) { start(repeatInterval, true); }
        void startOneShot(double interval) { start(interval, false); }

        void stop();
        bool isActive() const;

        virtual void fired() = 0;

    private:
        void start(double nextFireInterval, bool repeat);

        RunLoop* m_runLoop;

#if PLATFORM(WIN)
        static void timerFired(RunLoop*, uint64_t ID);
        uint64_t m_ID;
        bool m_isRepeating;
#elif PLATFORM(MAC)
        static void timerFired(CFRunLoopTimerRef, void*);
        RetainPtr<CFRunLoopTimerRef> m_timer;
#elif PLATFORM(QT)
        static void timerFired(RunLoop*, int ID);
        int m_ID;
        bool m_isRepeating;
#elif PLATFORM(EFL)
        static bool timerFired(void* data);
        Ecore_Timer* m_timer;
        bool m_isRepeating;
#elif USE(GLIB)
        static gboolean timerFiredCallback(RunLoop::TimerBase*);
        gboolean isRepeating() const { return m_isRepeating; }
        void clearTimerSource();
        GRefPtr<GSource> m_timerSource;
        gboolean m_isRepeating;
#endif
    };

    template <typename TimerFiredClass>
    class Timer : public TimerBase {
    public:
        typedef void (TimerFiredClass::*TimerFiredFunction)();

        Timer(RunLoop* runLoop, TimerFiredClass* o, TimerFiredFunction f)
            : TimerBase(runLoop)
            , m_object(o)
            , m_function(f)
        {
        }

    private:
        virtual void fired() { (m_object->*m_function)(); }

        TimerFiredClass* m_object;
        TimerFiredFunction m_function;
    };

    class Holder;

private:
    RunLoop();

    void performWork();

    Mutex m_functionQueueLock;
    Deque<Function<void()> > m_functionQueue;

#if PLATFORM(WIN)
    static bool registerRunLoopMessageWindowClass();
    static LRESULT CALLBACK RunLoopWndProc(HWND, UINT, WPARAM, LPARAM);
    LRESULT wndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);
    HWND m_runLoopMessageWindow;

    typedef HashMap<uint64_t, TimerBase*> TimerMap;
    TimerMap m_activeTimers;
#elif PLATFORM(MAC)
    static void performWork(void*);
    RetainPtr<CFRunLoopRef> m_runLoop;
    RetainPtr<CFRunLoopSourceRef> m_runLoopSource;
    int m_nestingLevel;
#elif PLATFORM(QT)
    typedef HashMap<int, TimerBase*> TimerMap;
    TimerMap m_activeTimers;
    class TimerObject;
    TimerObject* m_timerObject;
#elif PLATFORM(EFL)
    bool m_initEfl;

    Mutex m_pipeLock;
    OwnPtr<Ecore_Pipe> m_pipe;

    Mutex m_wakeUpEventRequestedLock;
    bool m_wakeUpEventRequested;

    static void wakeUpEvent(void* data, void*, unsigned int);
#elif USE(GLIB)
public:
    static gboolean queueWork(RunLoop*);
    GMainLoop* innermostLoop();
    void pushNestedMainLoop(GMainLoop*);
    void popNestedMainLoop();
private:
    GRefPtr<GMainContext> m_runLoopContext;
    Vector<GRefPtr<GMainLoop> > m_runLoopMainLoops;
#endif
};

} // namespace WebCore

#endif // RunLoop_h


text:
title: "unpause"
description: "The unpause command description and usage"
keywords: "cgroups, suspend, container"
---

<!-- This file is maintained within the docker/cli Github
     repository at https://github.com/docker/cli/. Make all
     pull requests against that repo. If you see this file in
     another repository, consider it read-only there, as it will
     periodically be overwritten by the definitive file. Pull
     requests which include edits to this file in other repositories
     will be rejected.
-->

# unpause

```markdown
Usage:  docker unpause CONTAINER [CONTAINER...]

Unpause all processes within one or more containers

Options:
      --help   Print usage
```

## Description

The `docker unpause` command un-suspends all processes in the specified containers.
On Linux, it does this using the cgroups freezer.

See the
[cgroups freezer documentation](https://www.kernel.org/doc/Documentation/cgroup-v1/freezer-subsystem.txt)
for further details.

## Examples

```bash
$ docker unpause my_container
```

## Related commands

* [pause](pause.md)


text:
function varargout = dual( varargin )

%DUAL Declares one or more dual variables.
%
%   DUAL VARIABLE x
%   where x is a valid MATLAB variable name, declares a dual variable
%   for the current cvx problem. A dual variable with that name is added
%   to the problem and a cvxdual object with that name is created in
%   the current worksapce. An error is generated if a cvx problem is not
%   in the current workspace.
%
%   Note that a dual variable initially has no size; i.e., SIZE(x) returns
%   [0,0]. This is because the size of a dual variable is determined by the
%   constraint to which it is attached. To attach a dual variable to a
%   constraint, use the colon notation as follows:
%
%      variable x(n)
%      dual variable z
%      A * x == b : z
%
%   In this example, the dual variable z is attached to the equality
%   constraint A * x == b. Assuming SIZE(A) = [m,n] and SIZE(B) = [m,1],
%   the size of z will be set at [m,1] by this operation.
%
%   DUAL VARIABLES x1 x2 ... xk
%   where x1, x2, ..., xk are valid MATLAB variable names, declares
%   multiple dual variables.
%
%   DUAL VARIABLE x{s1,s2,...,sk}
%   DUAL VARIABLES x1{s1,s2,...,sk} x2{...
%   creates a cell array of dual variables, of dimension [s1,s2,..,sk].
%   This is useful if you want to create a sequence of related constraints,
%   using a FOR loop for example, and assign a separate dual variable to
%   each one; for example:
%
%       variable x(n)
%       dual variables z{10}
%       for k = 1 : 10,
%           A(:,:,k) * x <= b(:,k) : z{k}
%       end
%
%   Assuming SIZE(A) = [m,n,10] and SIZE(B) = [m,10], this loop assigns
%   each of the dual variables z{k} to a constraint and sets their sizes
%   to [m,1]. Note that the elements of the dual variable cell array need
%   not end up the same size.
%
%   See also VARIABLE, VARIABLES.

if ~evalin( 'caller', 'exist(''cvx_problem'',''var'')', '0' ),
    error( 'A cvx problem does not exist in this scope.' );
elseif ~iscellstr( varargin ),
    error( 'All arguments must be strings.' );
end

prob = evalin( 'caller', 'cvx_problem' );
if strcmp( varargin{1}, 'variable' ),
    error( nargchk( 2, 2, nargin ) ); %#ok
    varargin(1) = [];
elseif strcmp( varargin{1}, 'variables' ),
    error( nargchk( 2, Inf, nargin ) ); %#ok
    varargin(1) = [];
end

nargs = length( varargin );
if nargout > 0,
    error( nargoutchk( nargs, nargs, nargout ) ); %#ok
end

for k = 1 : nargs,
    nm = varargin{k};
    xt = find( nm == '{' );
    if isempty( xt ),
        x.name = nm;
        x.size = [];
    elseif nm(end) ~= '}',
        error( 'Invalid dual variable specification: %s', nm );
    else
        x.name = nm( 1 : xt( 1 ) - 1 );
        x.size = nm( xt( 1 ) + 1 : end - 1 );
    end
    if ~isvarname( x.name ),
        error( 'Invalid dual variable specification: %s', nm );
    elseif x.name( end ) == '_',
        error( 'Invalid dual variable specification: %s\n   Variables ending in underscores are reserved for internal use.', nm );
    end
    if ischar( x.size ),
        x.size = evalin( 'caller', [ '[', x.size, '];' ], 'NaN' );
        [ temp, x.size ] = cvx_check_dimlist( x.size, true );
        if ~temp,
            error( 'Invalid variable specification: %s\n   Dimension list must be a vector of finite nonnegative integers.', nm );
        end
    end
    temp = newdual( prob, x.name, x.size );
    if nargout > 0,
        varargout{k} = temp; %#ok
    end
    assignin( 'caller', x.name, temp );
end

% Copyright 2012 CVX Research, Inc.
% See the file COPYING.txt for full copyright information.
% The command 'cvx_where' will show where this file is located.


text:
mkdir -p work
mkdir -p work/arma
mkdir -p work/bin
mkdir -p work/www

# Binaries
cd work/bin
go build github.com/blang/mantis
go build github.com/blang/stinger
go build github.com/blang/httpserv
cd ../..

# Build fake arma
cd work/arma
go build github.com/blang/runner
cp runner arma2oa.exe
cp runner arma2oaserver.exe
mkdir -p "@he_beta"
cp arma2oa.exe "@he_beta/"
cp arma2oaserver.exe "@he_beta/"
cd ../../

# Build webfrontend
LPWD=$PWD
cd $HOME/projects/mantis-webfrontend
grunt build
mv dist/* $LPWD/work/www
cd $LPWD

docker build -t mantisstinger .

rm -rf "./work"


text:
/** A symbol to represent built in types such int, float primitive types */
public class BuiltInTypeSymbol extends Symbol implements Type {
    int typeIndex;
    public BuiltInTypeSymbol(String name, int typeIndex) {
        super(name);
        this.typeIndex = typeIndex;
    }
    public int getTypeIndex() { return typeIndex; }
    public String toString() { return getName(); }
}


text:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using System.Web.Security.AntiXss;
using System.Net;

using Blog.Models.Blog;
using Blog.Models.Dashboard;
using Blog.Models.Widget;
using DataRepository.Models;
using DataRepository.Repository;

namespace Blog
{
    /// <summary>
    /// Helper class to assist with retrieving and sending data to the repository
    /// Handles HTTP functionality to 'scrub' and data posted or retrieved from the database
    /// </summary>
    public class DataHelper
    {
        private readonly IBlogRepository blogRepository;
        public DataHelper(IBlogRepository repository)
        {
            blogRepository = repository;
        }

        #region search methods

        /// <summary>
        /// Retrieves posts and builds a view model for display
        /// </summary>
        /// <param name="postCount">number of posts per page</param>
        /// <param name="page">page being requested</param>
        /// <param name="filter">search filter</param>
        /// <param name="orderBy">sort for posts</param>
        /// <returns></returns>
        public async Task<BlogListVM> BuildPostListModelAsync(int itemsPerPage = 10, int page = 1, Expression<Func<BlogPost, bool>> filter = null,
                                Func<IQueryable<BlogPost>, IOrderedQueryable<BlogPost>> orderBy = null)
        {
            var postCount = await blogRepository.GetPostCountAsync(filter);

            // retrieve a 'page' of items
            var startingPoint = page > 1 ? itemsPerPage * (page - 1) : 0;
            List<BlogPost> posts = await blogRepository.GetPostsAsync(startingPoint, itemsPerPage, filter, orderBy);

            // build BlogListViewModel
            return BuildBlogListModel(itemsPerPage, page, postCount, DecodeBlogList(posts));
        }

        public async Task<BlogListVM> SearchPostsAsync(string searchTerm)
        {
            // TODO:  for full text search no paging for now, assuming not more than 100 hits
            var startingPoint = 0;
            var itemsPerPage = 100;
            List<BlogPost> posts = await blogRepository.SearchPostsAsync(searchTerm, startingPoint, itemsPerPage);

            return BuildBlogListModel(itemsPerPage, 1, itemsPerPage, posts);
        }

        /// <summary>
        /// Retrieves post based on the date posted and post title
        /// </summary>
        /// <param name="dateFilter">date to filter by</param>
        /// <param name="title">title to filter by</param>
        /// <returns></returns>
        public async Task<BlogEntryVM> FindPostAsync(DateTime dateFilter, string title)
        {
            var post = await blogRepository.FindPostAsync(dateFilter, title);

            var model = BlogEntryVM.BuildViewModel(DecodeHtmlForDisplay(post));
            model.PageTitle = model.Title;

            return model;
        }

        /// <summary>
        /// Retrieves a list of all of the unique tags, along with the amount of times
        /// those tags were used.  Grouped by amount
        /// </summary>
        /// <returns></returns>
        public async Task<List<TagLinkVM>> GetTagsAsync()
        {
            var tags = await blogRepository.GetDistinctTagsAsync();
            return tags.Select(t => TagLinkVM.BuildTagLinkVM(t)).ToList();
        }

        /// <summary>
        /// Retrieves a list of the month and date of all of the active posts, ordered
        /// and grouped by amount
        /// </summary>
        /// <returns></returns>
        public async Task<List<ArchiveLinkVM>> GetArchiveLinksAsync()
        {
            var links = await blogRepository.GetArchiveItemsAsync();
            return links.Select(l => ArchiveLinkVM.BuildArchiveLinkVM(l)).ToList();
        }

        /// <summary>
        /// Retrieves a list of the last 5 recent posts.
        /// </summary>
        /// <returns></returns>
        public async Task<List<RecentPostLinkVM>> GetRecentPostLinksAsync()
        {
            var posts = await blogRepository.GetPostsAsync(skip: 0, pageSize: 3,
                                                    orderBy: q => q.OrderByDescending(p => p.DateTimePosted),
                                                    includeChildren: false);

            return posts.Select(p => RecentPostLinkVM.BuildRecentPostLinkVM(p)).ToList();
        }

        /// <summary>
        /// Retrieves a list of blog posts based on the page properties.  For display in the
        /// dashboard
        /// </summary>
        /// <param name="itemsPerPage">number of items to retrieve</param>
        /// <param name="page">page of items to retrieve</param>
        /// <returns></returns>
        public async Task<BlogTableVM> GetBlogItemsAsync(int itemsPerPage = 10, int page = 1)
        {
            var postCount = await blogRepository.GetPostCountAsync();

            // retrieve a 'page' of items
            var startingPoint = page > 1 ? itemsPerPage * (page - 1) : 0;

            var posts = await blogRepository.GetPostsAsync(skip: startingPoint, pageSize: itemsPerPage,
                                        orderBy: q => q.OrderByDescending(p => p.DateTimePosted),
                                        includeChildren: true);

            var viewModel = new BlogTableVM(itemsPerPage)
            {
                CurrentPage = page,
                PostCount = postCount,
                Posts = posts.Select(p => BlogItemVM.BuildViewModel(p)).ToList()
            };

            return viewModel;
        }

        #endregion

        #region CRUD methods

        public Task<int> InsertOrUpdateAsync(BlogPost blogPost){

            ScrubPostForStorage(blogPost);
            return blogRepository.InsertOrUpdateAsync(blogPost);
        }

        public int InsertOrUpdate(BlogPost blogPost)
        {

            ScrubPostForStorage(blogPost);
            return blogRepository.InsertOrUpdate(blogPost);
        }

        public BlogPost GetNewPost()
        {
            return blogRepository.GetNewPost();
        }

        public BlogPost RetrievePost(int id)
        {
            var post = blogRepository.RetrievePost(id);
            return DecodeHtmlForDisplay(post);
        }

        #endregion

        #region scrubbing and decoding

        /// <summary>
        /// encodes fields so content is safe for storage
        /// </summary>
        /// <param name="post">blog post</param>
        /// <returns>scrubbed post</returns>
        private static void ScrubPostForStorage(BlogPost post)
        {
            post.Author = AntiXssEncoder.HtmlEncode(post.Author, true);
            post.BlogText = AntiXssEncoder.HtmlEncode(post.BlogText, true);
            post.Title = AntiXssEncoder.HtmlEncode(post.Title, true);
            post.MainImageId = AntiXssEncoder.UrlEncode(post.MainImageId);
        }

        private static List<BlogPost> DecodeBlogList(List<BlogPost> blogs)
        {
            foreach (var blog in blogs)
            {
                DecodeHtmlForDisplay(blog);
            }
            return blogs;
        }

        /// <summary>
        /// Decodes previously encoded posts for display in an html page
        /// </summary>
        /// <param name="post">post from storage</param>
        /// <returns>displayable post</returns>
        private static BlogPost DecodeHtmlForDisplay(BlogPost post)
        {
            post.Author = WebUtility.HtmlDecode(post.Author);
            post.BlogText = WebUtility.HtmlDecode(post.BlogText);
            post.Title = WebUtility.HtmlDecode(post.Title);
            post.MainImageId = WebUtility.UrlDecode(post.MainImageId);

            return post;
        }

        #endregion

        #region view model building

        private BlogListVM BuildBlogListModel(int itemsPerPage, int page, int totalPostCount, IList<BlogPost> posts)
        {
            return new BlogListVM(itemsPerPage, page, totalPostCount, posts)
            {
                Heading = ConfigurationManager.AppSettings["Heading"],
                SubHeading = ConfigurationManager.AppSettings["SubHeading"],
                PageTitle = ConfigurationManager.AppSettings["PageTitle"]
            };
        }

        #endregion
    }

    public class TagComparer : IEqualityComparer<BlogTag>
    {
        public bool Equals(BlogTag x, BlogTag y)
        {
            return x.TagValue.Equals(y.TagValue);
        }

        public int GetHashCode(BlogTag obj)
        {
            return obj.TagValue.GetHashCode();
        }
    }
}


text:
<?php if($typeView === 'print') : ?>
<p>
    <?php $this->view('template/complInfo/input/item_creator', array('label' => 'Auteur')); ?> -
    <?php $this->view('template/complInfo/input/item_universe'); ?> -
    <?php $this->view('template/complInfo/input/item_idx_sibling'); ?> -
    <?php $this->view('template/complInfo/input/item_editor'); ?> -
    <?php $this->view('template/complInfo/input/item_release'); ?>
</p>
<?php else : ?>
    <?php $this->view('template/complInfo/input/collection_creator', array('label' => 'Auteur')); ?>
    <?php $this->view('template/complInfo/input/collection_universe'); ?>
    <?php $this->view('template/complInfo/input/collection_editor'); ?>
    <?php $this->view('template/complInfo/input/collection_release'); ?>
    <?php $this->view('template/complInfo/input/collection_total'); ?>
<?php endif; ?>


text:
/*
 * This source file is part of MyGUI. For the latest info, see http://mygui.info/
 * Distributed under the MIT License
 * (See accompanying file COPYING.MIT or copy at http://opensource.org/licenses/MIT)
 */

#ifndef __MYGUI_COMMON_H__
#define __MYGUI_COMMON_H__

#include "MyGUI_Prerequest.h"

#include <string>
#include <list>
#include <set>
#include <map>
#include <vector>
#include <deque>
#include <exception>
#include <math.h>

#ifdef MYGUI_CUSTOM_ALLOCATOR
#    include "MyGUI_CustomAllocator.h"
#else // MYGUI_CUSTOM_ALLOCATOR
#    include "MyGUI_Allocator.h"
#endif // MYGUI_CUSTOM_ALLOCATOR

// этот дефайн для того чтобы в самом гуе показывалось имя файла где вызывается new
#if MYGUI_COMPILER == MYGUI_COMPILER_MSVC
#	ifdef MYGUI_CHECK_MEMORY_LEAKS
#		define DEBUG_NEW new (_NORMAL_BLOCK, __FILE__, __LINE__)
#		define new DEBUG_NEW
#	endif
#endif

#include "MyGUI_Macros.h"
#include "MyGUI_Diagnostic.h"
#include "MyGUI_LogManager.h"
#include "MyGUI_Singleton.h"
#include "MyGUI_Types.h"
#include "MyGUI_StringUtility.h"
#include "MyGUI_MouseButton.h"
#include "MyGUI_KeyCode.h"
#include "MyGUI_Version.h"
#include "MyGUI_WidgetStyle.h"
#include "MyGUI_UString.h"
#include "MyGUI_Delegate.h"

#endif // __MYGUI_COMMON_H__


text:
import unittest
import numpy

import random
from rewardbuffer import PositiveReserveBuffer

class PositiveTestSuite(unittest.TestCase):

    def test_random_ensure(self):
        N = 1000
        R = 0.5
        MAXP = int(R*N)
        MAXN = int((1-R)*N)

        r = PositiveReserveBuffer('test', 1, maxposratio=0.5, buffersize=int(N/2))

        lastnegatives = 0
        lastpositives = 0
        for i in range(N):
            toadd = 1 if random.randint(0,1) == 0 else -1

            rew(r, toadd)
            uniques, counts = numpy.unique(r.rewards[:i+1], return_counts=True)

            # Make sure only -1 and 1
            self.assertLessEqual(len(uniques),2, msg="Only 1/-1 allowed in {}".format(uniques))

            newpositives = 0
            newnegatives = 0
            for item, count in zip(uniques, counts):
                if item < 0:
                    newnegatives = count
                elif item > 0:
                    newpositives = count

            if toadd > 0:
                self.assertTrue(lastpositives == newpositives or lastpositives == newpositives - 1,
                                "Positive didn't increase or maintain count: {}-{}".format(lastpositives,newpositives))
                # Positive may evict negative, otherwise would include
                # self.assertTrue(lastnegatives == newnegatives,
                #                 "Positive changed negative count")
            elif toadd < 0:
                self.assertTrue(lastnegatives == newnegatives or lastnegatives == newnegatives - 1,
                                "Negative didn't increase or maintain count: {}-{}".format(lastnegatives,newnegatives))
                self.assertTrue(lastpositives == newpositives,
                                "Negative changed positive count: {}-{}".format(lastpositives,newpositives))

            lastnegatives, lastpositives = newnegatives, newpositives

def rew(r,x):
    r.reward({0: 0}, {0: 0}, {0: x}, {0: 0})

if __name__ == '__main__':
    unittest.main()


text:
<?php

namespace Embed;

use Embed\Adapters\Adapter;
use Embed\Http\CurlDispatcher;
use Embed\Http\DispatcherInterface;
use Embed\Http\Url;

abstract class Embed
{
    /**
     * @var array
     */
    public static $default_config = [
        'min_image_width' => 1,
        'min_image_height' => 1,
        'images_blacklist' => [],
        'url_blacklist' => [
            '?&ns_campaign=*',
            '?&ns_source=*',
            '?&utm_campaign=*',
            '?&utm_medium=*',
            '?&utm_source=*',
        ],
        'choose_bigger_image' => false,

        'html' => [
            'max_images' => 0,
            'external_images' => false
        ],

        'oembed' => [
            'parameters' => [],
            'embedly_key' => null,
            'iframely_key' => null,
        ],

        'google' => [
            'key' => null,
        ],

        'soundcloud' => [
            'key' => null,
        ],
    ];

    /**
     * Gets the info from an url.
     *
     * @param Url|string $url
     * @param array|null $config
     * @param DispatcherInterface|null $dispatcher
     *
     * @return Adapter
     */
    public static function create($url, array $config = null, DispatcherInterface $dispatcher = null)
    {
        if (!($url instanceof Url)) {
            $url = Url::create($url);
        }

        if ($config === null) {
            $config = self::$default_config;
        }

        if ($dispatcher === null) {
            $dispatcher = new CurlDispatcher();
        }

        $info = self::process($url, $config, $dispatcher);

        // Repeat the process if:
        // - The canonical url is different
        // - No embed code has found
        $from = preg_replace('|^(\w+://)|', '', rtrim((string) $info->getResponse()->getUrl(), '/'));
        $to = preg_replace('|^(\w+://)|', '', rtrim($info->url, '/'));

        if ($from !== $to && empty($info->code)) {
            return self::process(Url::create($info->url), $config, $dispatcher);
        }

        return $info;
    }

    /**
     * Process the url.
     *
     * @param Url $url
     * @param array   $config
     * @param DispatcherInterface   $dispatcher
     *
     * @throws Exceptions\InvalidUrlException If the urls is not valid
     *
     * @return Adapter
     */
    private static function process(Url $url, array $config, DispatcherInterface $dispatcher)
    {
        $response = $dispatcher->dispatch($url);

        //If is a file use File Adapter
        if (Adapters\File::check($response)) {
            return new Adapters\File($response, $config, $dispatcher);
        }

        //Search the adapter using the domain
        $adapter = 'Embed\\Adapters\\'.$response->getUrl()->getClassNameForDomain();

        if (class_exists($adapter) && $adapter::check($response)) {
            return new $adapter($response, $config, $dispatcher);
        }

        //Use the default webpage adapter
        if (Adapters\Webpage::check($response)) {
            return new Adapters\Webpage($response, $config, $dispatcher);
        }

        if ($response->getError() === null) {
            $exception = new Exceptions\InvalidUrlException(sprintf("Invalid url '%s' (Status code %s)", (string) $url, $response->getStatusCode()));
        } else {
            $exception = new Exceptions\InvalidUrlException($response->getError());
        }

        $exception->setResponse($response);

        throw $exception;
    }
}


text:
/**
 * External dependencies
 */
import { useEffect, memo } from '@googleforcreators/react';
import PropTypes from 'prop-types';

/**
 * Internal dependencies
 */
import objectWithout from '../../utils/objectWithout';
import { useStory } from '../story';

function PageCanvasCacheValidator({ pageId, clearPageCanvasCache }) {
  const page = useStory(({ state }) =>
    objectWithout(
      state.pages.find(({ id }) => id === pageId),
      ['animations']
    )
  );

  // clear pageCanvas whenever a page is updated.
  useEffect(() => {
    clearPageCanvasCache({ pageId: page.id });
  }, [page, clearPageCanvasCache]);

  // clear pageCanvas if the page gets deleted
  useEffect(() => {
    return () => clearPageCanvasCache({ pageId });
  }, [clearPageCanvasCache, pageId]);

  return null;
}

PageCanvasCacheValidator.propTypes = {
  pageId: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
  clearPageCanvasCache: PropTypes.func,
};

export default memo(PageCanvasCacheValidator);


text:
package com.akjava.gwt.three.client.gwt.extras;

import com.akjava.gwt.three.client.gwt.JSParameter;

public class TextGeometryParameter extends JSParameter{
		protected TextGeometryParameter(){}
		public final static TextGeometryParameter create(){
			return (TextGeometryParameter) TextGeometryParameter.createObject();
		}

		public final native TextGeometryParameter size(double size)/*-{
		this.size=size;
		return this;
		}-*/;

	public final native TextGeometryParameter height(double height)/*-{
		this.height=height;
		return this;
		}-*/;

	public final native TextGeometryParameter curveSegments(double curveSegments)/*-{
		this.curveSegments=curveSegments;
		return this;
		}-*/;

	public final native TextGeometryParameter font(String font)/*-{
		this.font=font;
		return this;
		}-*/;

	public final native TextGeometryParameter weight(String weight)/*-{
		this.weight=weight;
		return this;
		}-*/;

	public final native TextGeometryParameter style(String style)/*-{
		this.style=style;
		return this;
		}-*/;

	public final native TextGeometryParameter bevelThickness(double bevelThickness)/*-{
		this.bevelThickness=bevelThickness;
		return this;
		}-*/;

	public final native TextGeometryParameter bevelSize(double bevelSize)/*-{
		this.bevelSize=bevelSize;
		return this;
		}-*/;

	public final native TextGeometryParameter bevelEnabled(boolean bevelEnabled)/*-{
		this.bevelEnabled=bevelEnabled;
		return this;
		}-*/;

}


text:
module SpecHelper

  def test_douban_token
    ENV.fetch 'DOUFURU_TEST_DOUBAN_TOKEN'
  end

  def test_douban_client_id
    ENV.fetch 'DOUFURU_TEST_DOUBAN_CLIENT_ID'
  end

  def test_douban_client_secret
    ENV.fetch 'DOUFURU_TEST_DOUBAN_CLIENT_SECRET'
  end

  def fixture_path
    File.expand_path('../../fixtures', __FILE__)
  end

  def fixture(file)
    File.new(File.join(fixture_path, file))
  end

  def json_response(file)
    {
      body: fixture(file),
      headers: {
        content_type: 'application/json; charset=utf-8'
      }
    }
  end

  def oauth_client
    Doufuru::Client.new(access_token: ENV.fetch('DOUFURU_TEST_DOUBAN_TOKEN'))
  end

end


text:
from rmake.lib.ninamori import error as nerror
from rmake.lib.ninamori import timeline
from rmake.lib.ninamori.decorators import protected

class Script(timeline.ScriptBase):

    def before(self):
        # Create plpgsql if it doesn't exist. It might be there due to being in
        # template1 or enabled by default in a future version of postgres.
        self.create_lang()

        # Test if a UUID type is available. If not, create it as a domain of
        # text.
        try:
            self.test_uuid()
        except nerror.UndefinedObjectError:
            self.create_uuid()

    @protected
    def create_lang(self, cu):
        cu.execute("SELECT COUNT(*) FROM pg_language WHERE lanname ='plpgsql'")
        if cu.fetchone()[0]:
            return
        cu.execute("CREATE LANGUAGE plpgsql")

    @protected
    def test_uuid(self, cu):
        cu.execute("SELECT 'uuid'::regtype")

    @protected
    def create_uuid(self, cu):
        cu.execute("CREATE DOMAIN uuid text")


text:
<?xml version="1.0" encoding="UTF-8"?>
<MetaDataObject xmlns="http://v8.1c.ru/8.3/MDClasses" xmlns:app="http://v8.1c.ru/8.2/managed-application/core" xmlns:cfg="http://v8.1c.ru/8.1/data/enterprise/current-config" xmlns:cmi="http://v8.1c.ru/8.2/managed-application/cmi" xmlns:ent="http://v8.1c.ru/8.1/data/enterprise" xmlns:lf="http://v8.1c.ru/8.2/managed-application/logform" xmlns:style="http://v8.1c.ru/8.1/data/ui/style" xmlns:sys="http://v8.1c.ru/8.1/data/ui/fonts/system" xmlns:v8="http://v8.1c.ru/8.1/data/core" xmlns:v8ui="http://v8.1c.ru/8.1/data/ui" xmlns:web="http://v8.1c.ru/8.1/data/ui/colors/web" xmlns:win="http://v8.1c.ru/8.1/data/ui/colors/windows" xmlns:xen="http://v8.1c.ru/8.3/xcf/enums" xmlns:xpr="http://v8.1c.ru/8.3/xcf/predef" xmlns:xr="http://v8.1c.ru/8.3/xcf/readable" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.1">
	<CommonModule uuid="b953eafc-20be-4463-8c3e-903184e18402">
		<Properties>
			<Name>СообщенияАдминистрированиеОбменаДаннымиУправлениеИнтерфейс</Name>
			<Synonym>
				<v8:item>
					<v8:lang>ru</v8:lang>
					<v8:content>Сообщения администрирование обмена данными управление интерфейс</v8:content>
				</v8:item>
			</Synonym>
			<Comment/>
			<Global>false</Global>
			<ClientManagedApplication>false</ClientManagedApplication>
			<Server>true</Server>
			<ExternalConnection>true</ExternalConnection>
			<ClientOrdinaryApplication>true</ClientOrdinaryApplication>
			<ServerCall>false</ServerCall>
			<Privileged>false</Privileged>
			<ReturnValuesReuse>DontUse</ReturnValuesReuse>
		</Properties>
	</CommonModule>
</MetaDataObject>


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright (C) 2009 The Android Open Source Project

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>com.google.gerrit</groupId>
    <artifactId>gerrit-parent</artifactId>
    <version>2.6</version>
  </parent>

  <artifactId>gerrit-launcher</artifactId>
  <name>Gerrit Code Review - Launcher</name>

  <description>
    Bootstraps the rest of our classpath after Main
  </description>
</project>


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>BinaryInteractionFactory (PSI :: JAMI - Java framework for molecular interactions 3.2.12 API)</title>
<meta name="date" content="2021-08-20">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

psidev.psi.mi.jami.factory

Interface BinaryInteractionFactory

All Known Implementing Classes:

DefaultBinaryInteractionFactory, XmlBinaryInteractionFactory, XmlBinaryInteractionFactory

public interface BinaryInteractionFactory

An interface for a factory of BinaryInteractions

Since:

16/10/13

Version:

$Id$

Author:

Marine Dumousseau (marine@ebi.ac.uk)

Method Summary

All Methods Instance Methods Abstract Methods

Modifier and Type
Method and Description

BinaryInteraction
createBasicBinaryInteractionFrom(Interaction interaction,
                                Participant p1,
                                Participant p2,
                                CvTerm expansionMethod)

Create a new BinaryInteraction object from an Interaction parent and two participants

BinaryInteractionEvidence
createBinaryInteractionEvidenceFrom(InteractionEvidence interaction,
                                   ParticipantEvidence p1,
                                   ParticipantEvidence p2,
                                   CvTerm expansionMethod)

Create a new BinaryInteractionEvidence object from an InteractionEvidence parent and two participants evidences

BinaryInteractionEvidence
createBinaryInteractionEvidenceWrapperFrom(InteractionEvidence interaction)

Creates a BinaryInteractionEvidence that wraps the given interaction

BinaryInteraction
createBinaryInteractionWrapperFrom(Interaction interaction)

Creates a BinaryInteraction that wraps the given interaction

ModelledBinaryInteraction
createModelledBinaryInteractionFrom(ModelledInteraction interaction,
                                   ModelledParticipant p1,
                                   ModelledParticipant p2,
                                   CvTerm expansionMethod)

Create a new ModelledBinaryInteraction object from a ModelledInteraction parent and two modelled participants

ModelledBinaryInteraction
createModelledBinaryInteractionWrapperFrom(ModelledInteraction interaction)

Creates a ModelledBinaryInteraction that wraps the given interaction

BinaryInteractionEvidence
createSelfBinaryInteractionEvidenceFrom(InteractionEvidence interaction)

Creates a BinaryInteractionEvidence representing a self interaction

BinaryInteraction
createSelfBinaryInteractionFrom(Interaction interaction)

Create a binary interaction representing a self interaction

ModelledBinaryInteraction
createSelfModelledBinaryInteractionFrom(ModelledInteraction interaction)

Creates a ModelledInteraction representing a self interaction

BinaryInteraction
instantiateNewBinaryInteraction()

Instantiate a new BinaryInteraction

BinaryInteractionEvidence
instantiateNewBinaryInteractionEvidence()

Instantiate a new BinaryInteraction evidence

ModelledBinaryInteraction
instantiateNewModelledBinaryInteraction()

Instantiate a new modelled binary interaction

Method Detail

createBasicBinaryInteractionFrom

BinaryInteraction createBasicBinaryInteractionFrom(Interaction interaction,
                                                   Participant p1,
                                                   Participant p2,
                                                   CvTerm expansionMethod)

Create a new BinaryInteraction object from an Interaction parent and two participants

Parameters:

interaction - : the original interaction

p1 - : the first participant

p2 - : the second participant

expansionMethod - a CvTerm object.

Returns:

the new BinaryInteraction object

createBinaryInteractionEvidenceFrom

BinaryInteractionEvidence createBinaryInteractionEvidenceFrom(InteractionEvidence interaction,
                                                              ParticipantEvidence p1,
                                                              ParticipantEvidence p2,
                                                              CvTerm expansionMethod)

Create a new BinaryInteractionEvidence object from an InteractionEvidence parent and two participants evidences

Parameters:

interaction - : the original interaction

p1 - : the first participant

p2 - : the second participant

expansionMethod - : the expansion method

Returns:

the new BinaryInteractionEvidence object

createModelledBinaryInteractionFrom

ModelledBinaryInteraction createModelledBinaryInteractionFrom(ModelledInteraction interaction,
                                                              ModelledParticipant p1,
                                                              ModelledParticipant p2,
                                                              CvTerm expansionMethod)

Create a new ModelledBinaryInteraction object from a ModelledInteraction parent and two modelled participants

Parameters:

interaction - : the original interaction

p1 - : the first participant

p2 - : the second participant

expansionMethod - : the expansion method

Returns:

the new ModelledBinaryInteraction object

createSelfBinaryInteractionFrom

BinaryInteraction createSelfBinaryInteractionFrom(Interaction interaction)

Create a binary interaction representing a self interaction

Parameters:

interaction - : the original interaction

Returns:

the resulting self binary interaction

createSelfBinaryInteractionEvidenceFrom

BinaryInteractionEvidence createSelfBinaryInteractionEvidenceFrom(InteractionEvidence interaction)

Creates a BinaryInteractionEvidence representing a self interaction

Parameters:

interaction - : the original interaction

Returns:

the resulting self binary interaction

createSelfModelledBinaryInteractionFrom

ModelledBinaryInteraction createSelfModelledBinaryInteractionFrom(ModelledInteraction interaction)

Creates a ModelledInteraction representing a self interaction

Parameters:

interaction - : the original interaction

Returns:

the resulting self binary interaction

createBinaryInteractionWrapperFrom

BinaryInteraction createBinaryInteractionWrapperFrom(Interaction interaction)

Creates a BinaryInteraction that wraps the given interaction

Parameters:

interaction - : the original interaction

Returns:

the resulting binary interaction wrapper

createBinaryInteractionEvidenceWrapperFrom

BinaryInteractionEvidence createBinaryInteractionEvidenceWrapperFrom(InteractionEvidence interaction)

Creates a BinaryInteractionEvidence that wraps the given interaction

Parameters:

interaction - : the original interaction

Returns:

the resulting binary interaction wrapper

createModelledBinaryInteractionWrapperFrom

ModelledBinaryInteraction createModelledBinaryInteractionWrapperFrom(ModelledInteraction interaction)

Creates a ModelledBinaryInteraction that wraps the given interaction

Parameters:

interaction - : the original interaction

Returns:

the resulting binary interaction wrapper

instantiateNewBinaryInteraction

BinaryInteraction instantiateNewBinaryInteraction()

Instantiate a new BinaryInteraction

Returns:

the binary interaction instance

instantiateNewBinaryInteractionEvidence

BinaryInteractionEvidence instantiateNewBinaryInteractionEvidence()

Instantiate a new BinaryInteraction evidence

Returns:

the binary interaction instance

instantiateNewModelledBinaryInteraction

ModelledBinaryInteraction instantiateNewModelledBinaryInteraction()

Instantiate a new modelled binary interaction

Returns:

the binary interaction instance

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright © 2021. All rights reserved.


text:
const KeepOrMulliganPrompt = require('../../../../server/game/gamesteps/setup/keepormulliganprompt.js');

describe('the KeepOrMulliganPrompt', function() {
    beforeEach(function() {
        this.gameSpy = jasmine.createSpyObj('game', ['addMessage', 'raiseEvent']);
        this.playerSpy = jasmine.createSpyObj('player', ['keep', 'mulligan']);
        this.prompt = new KeepOrMulliganPrompt(this.gameSpy);
    });

    describe('the onMenuCommand() function', function() {
        describe('when the arg is keep', function() {
            beforeEach(function() {
                this.prompt.onMenuCommand(this.playerSpy, 'keep');
            });

            it('should call keep on the player', function() {
                expect(this.playerSpy.keep).toHaveBeenCalled();
                expect(this.playerSpy.mulligan).not.toHaveBeenCalled();
            });

            it('should raise the onPlayerKeepHandOrMerged event', function() {
                expect(this.gameSpy.raiseEvent).toHaveBeenCalledWith('onPlayerKeepHandOrMulligan', jasmine.objectContaining({ player: this.playerSpy, choice: 'keep' }));
            });
        });

        describe('when the arg is mulligan', function() {
            beforeEach(function() {
                this.prompt.onMenuCommand(this.playerSpy, 'mulligan');
            });

            it('should call mulligan on the player', function() {
                expect(this.playerSpy.keep).not.toHaveBeenCalled();
                expect(this.playerSpy.mulligan).toHaveBeenCalled();
            });

            it('should raise the onPlayerKeepHandOrMerged event', function() {
                expect(this.gameSpy.raiseEvent).toHaveBeenCalledWith('onPlayerKeepHandOrMulligan', jasmine.objectContaining({ player: this.playerSpy, choice: 'mulligan' }));
            });
        });
    });
});


text:
package main

import (
	"flag"
	"fmt"
	"io/ioutil"
	"math/rand"
	"os"
	"os/signal"
	"path/filepath"
	"syscall"
	"time"
	"stripe-ctf.com/sqlcluster/log"
	"stripe-ctf.com/sqlcluster/server"
)

func main() {
	var verbose bool
	var listen, join, directory string

	flag.BoolVar(&verbose, "v", false, "Enable debug output")
	flag.StringVar(&listen, "l", "127.0.0.1:4000", "Socket to listen on (Unix or TCP)")
	flag.StringVar(&join, "join", "", "Cluster to join")
	flag.StringVar(&directory, "d", "", "Storage directory")

	dir := filepath.Dir(os.Args[0])
	base := "./" + filepath.Base(os.Args[0])
	flag.Usage = func() {
		fmt.Fprintf(os.Stderr, `Usage: %s [options]

SQLCluster is a highly-available SQL store. It accepts commands over
HTTP, and returns the output of commands together with a
SequenceNumber which indicates the ordering in which requests are
being applied. (SequenceNumber is useful for validation, and can
otherwise be ignored.)

Run a cluster as follows:

  cd %s
  %s -d /tmp/sqlcluster/node0 &
  %s -d /tmp/sqlcluster/node1 -l 127.0.0.1:4001 --join 127.0.0.1:4000 &
  %s -d /tmp/sqlcluster/node2 -l 127.0.0.1:4002 --join 127.0.0.1:4000

You can then issue queries using your favorite HTTP client.

  curl 127.0.0.1:4000/sql -d 'CREATE TABLE hello (world int)'
  curl 127.0.0.1:4000/sql -d 'INSERT INTO hello (world) VALUES (1), (2)'
  curl 127.0.0.1:4000/sql -d 'SELECT * FROM hello'

This should return the following sequence of outputs:
  - SequenceNumber: 0

  - SequenceNumber: 1

  - SequenceNumber: 2
    1
    2

By default, SQLCluster will listen on a TCP port. However, if you
specify a listen address that begins with a / or ., that will be
interpeted as Unix path for SQLCluster to listen on. (Note that
Octopus runs using Unix sockets only, but it will probably be more
convient for you to develop using TCP.)

OPTIONS:
`, os.Args[0], dir, base, base, base)
		flag.PrintDefaults()
	}

	flag.Parse()

	if flag.NArg() != 0 {
		flag.Usage()
		os.Exit(1)
	}

	log.SetVerbose(verbose)

	rand.Seed(time.Now().UnixNano())

	if directory == "" {
		var err error
		directory, err = ioutil.TempDir("/tmp", "node")
		if err != nil {
			log.Fatalf("Could not create temporary base directory: %s", err)
		}
		defer os.RemoveAll(directory)

		log.Printf("Storing state in tmpdir %s", directory)
	} else {
		if err := os.MkdirAll(directory, os.ModeDir|0755); err != nil {
			log.Fatalf("Error while creating storage directory: %s", err)
		}
	}

	log.Printf("Changing directory to %s", directory)
	if err := os.Chdir(directory); err != nil {
		log.Fatalf("Error while changing to storage directory: %s", err)
	}
	// Make sure we don't leave stranded sqlclusters lying around
	go func() {
		for {
			time.Sleep(2 * time.Second)
			if os.Getppid() == 1 {
				log.Fatal("Parent process exited; terminating")
			}
		}
	}()

	// Start the server
	go func() {
		s, err := server.New(directory, listen)
		if err != nil {
			log.Fatal(err)
		}

		if err := s.ListenAndServe(join); err != nil {
			log.Fatal(err)
		}
	}()

	// Exit cleanly so we can remove the tmpdir
	sigchan := make(chan os.Signal)
	signal.Notify(sigchan, syscall.SIGINT, syscall.SIGTERM)
	<-sigchan
}


text:
from __future__ import print_function
from yambopy     import *
import argparse

print('This script breaks the symmetries of a given nscf run and')
print('prepares the rt-folder for the RT simulations')
print('Any previous "database" folder will be erased')
print('arg1: folder with nscf data')
print('arg2: folder for RT simulation')
print('arg3: prefix')
print('arg4: symmetry')
print('Example: python break-symm.py -i nscf -o rt-100 -p si -s 100')

parser = argparse.ArgumentParser(description='Map of a double-grid')
parser.add_argument('-i' ,'--input'    , help='Folder with nscf data')
parser.add_argument('-o' ,'--output'   , help='Folder for RT simulation')
parser.add_argument('-p' ,'--prefix'   ,help='Prefix of nscf calculation')
parser.add_argument('-s' ,'--symmetry' ,help='Choice symmetry: 100 010 110')
args = parser.parse_args()

print('Folder of nscf data     ===>>>  ' ,args.input)
print('Folder of RT simulation ===>>>  ' ,args.output)
print('Prefix                  ===>>>  ' ,args.prefix)
print('Symmetry                ===>>>  ' ,args.symmetry)

nscf_folder = args.input
rt_folder   = args.output
prefix      = args.prefix
symm        = args.symmetry

# Check rt_folder
if os.path.isdir(rt_folder):
    print('Real-time folder already exists')
    raise SystemExit
# Generation of the database folder
if os.path.isdir('database'):
    os.system('rm -rf database')
os.system('cd %s/%s.save ; p2y -O ../../database' % (nscf_folder, prefix))
os.system('cd database; yambo')

# Breaking of symmetries

if symm   == '100':
    breaking_symmetries([1,0,0], [0,0,0], rt_folder)
elif symm == '010':
    breaking_symmetries([0,1,0], [0,0,0], rt_folder)
elif symm == '110':
    breaking_symmetries([1,0,0], [0,1,0], rt_folder)


text:
<?php

namespace AppBundle\Entity;

use Application\Sonata\MediaBundle\Entity\Media;
use Doctrine\ORM\Mapping as ORM;

/**
 * Traveller
 *
 * @ORM\Table(name="travellers")
 * @ORM\Entity
 */
class Traveller
{
    const GENDER_M = 'm';
    const GENDER_W = 'w';
    const TYPE_ADULT = 'adult';
    const TYPE_CHILD = 'child';

    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="full_name", type="string", length=255)
     */
    private $fullName;

    /**
     * @var string
     *
     * @ORM\Column(name="email", type="string", length=255, nullable=true)
     */
    private $email;

    /**
     * @var string
     *
     * @ORM\Column(name="phone", type="string", length=64, nullable=true)
     */
    private $phone;

    /**
     * @var string
     *
     * @ORM\Column(name="age", type="string", length=64, nullable=true)
     */
    private $age;

    /**
     * @var string
     *
     * @ORM\Column(name="gender", type="string", length=32)
     */
    private $gender;

    /**
     * @var boolean
     *
     * @ORM\Column(name="children", type="boolean")
     */
    private $children;

    /**
     * @var integer
     *
     * @ORM\Column(name="child_number", type="smallint", nullable=true)
     */
    private $childNumber;

    /**
     * @var integer
     *
     * @ORM\Column(name="child_min_age", type="smallint", nullable=true)
     */
    private $childMinAge;

    /**
     * @var boolean
     *
     * @ORM\Column(name="opposite_gender_living", type="boolean")
     */
    private $oppositeGenderLiving;

    /**
     * @var boolean
     *
     * @ORM\Column(name="living_with_parents", type="boolean")
     */
    private $livingWithParents;

    /**
     * @var string
     *
     * @ORM\Column(name="type", type="string", length=32)
     */
    private $type;

    /**
     * @var integer
     * @ORM\Column(name="place_number", type="smallint", nullable=true)
     */
    private $placeNumber;

    /**
     * @var Media
     * @ORM\OneToOne(targetEntity="Application\Sonata\MediaBundle\Entity\Media", cascade={"persist", "remove"})
     * @ORM\JoinColumn(name="photo_id")
     */
    private $photo;

    /**
     * @var string
     */
    private $photoPublicUrl;

    /**
     * @var boolean
     *
     * @ORM\Column(name="initiator", type="boolean")
     */
    private $initiator;

    public function __construct()
    {
        $this->oppositeGenderLiving = true;
        $this->children = false;
        $this->livingWithParents = false;
        $this->initiator = true;
        $this->childNumber = 0;
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set fullName
     *
     * @param string $fullName
     * @return Traveller
     */
    public function setFullName($fullName)
    {
        $this->fullName = $fullName;

        return $this;
    }

    /**
     * Get fullName
     *
     * @return string
     */
    public function getFullName()
    {
        return $this->fullName;
    }

    /**
     * Set email
     *
     * @param string $email
     * @return Traveller
     */
    public function setEmail($email)
    {
        $this->email = $email;

        return $this;
    }

    /**
     * Get email
     *
     * @return string
     */
    public function getEmail()
    {
        return $this->email;
    }

    /**
     * Set phone
     *
     * @param string $phone
     * @return Traveller
     */
    public function setPhone($phone)
    {
        $this->phone = $phone;

        return $this;
    }

    /**
     * Get phone
     *
     * @return string
     */
    public function getPhone()
    {
        return $this->phone;
    }

    /**
     * Set age
     *
     * @param string $age
     * @return Traveller
     */
    public function setAge($age)
    {
        $this->age = $age;

        return $this;
    }

    /**
     * Get age
     *
     * @return string
     */
    public function getAge()
    {
        return $this->age;
    }

    /**
     * Set gender
     *
     * @param string $gender
     * @return Traveller
     */
    public function setGender($gender)
    {
        $this->gender = $gender;

        return $this;
    }

    /**
     * Get gender
     *
     * @return string
     */
    public function getGender()
    {
        return $this->gender;
    }

    /**
     * Set children
     *
     * @param boolean $children
     * @return Traveller
     */
    public function setChildren($children)
    {
        $this->children = $children;

        return $this;
    }

    /**
     * Get children
     *
     * @return boolean
     */
    public function hasChildren()
    {
        return $this->children;
    }

    /**
     * Set childNumber
     *
     * @param integer $childNumber
     * @return Traveller
     */
    public function setChildNumber($childNumber)
    {
        $this->childNumber = $childNumber;

        return $this;
    }

    /**
     * Get childNumber
     *
     * @return integer
     */
    public function getChildNumber()
    {
        return $this->childNumber;
    }

    /**
     * Set childMinAge
     *
     * @param integer $childMinAge
     * @return Traveller
     */
    public function setChildMinAge($childMinAge)
    {
        $this->childMinAge = $childMinAge;

        return $this;
    }

    /**
     * Get childMinAge
     *
     * @return integer
     */
    public function getChildMinAge()
    {
        return $this->childMinAge;
    }

    /**
     * Set oppositeGenderLiving
     *
     * @param boolean $oppositeGenderLiving
     * @return Traveller
     */
    public function setOppositeGenderLiving($oppositeGenderLiving)
    {
        $this->oppositeGenderLiving = $oppositeGenderLiving;

        return $this;
    }

    /**
     * Get oppositeGenderLiving
     *
     * @return boolean
     */
    public function getOppositeGenderLiving()
    {
        return $this->oppositeGenderLiving;
    }

    /**
     * Set livingWithParents
     *
     * @param boolean $livingWithParents
     * @return Traveller
     */
    public function setLivingWithParents($livingWithParents)
    {
        $this->livingWithParents = $livingWithParents;

        return $this;
    }

    /**
     * Get livingWithParents
     *
     * @return boolean
     */
    public function getLivingWithParents()
    {
        return $this->livingWithParents;
    }

    /**
     * Set type
     *
     * @param string $type
     * @return Traveller
     */
    public function setType($type)
    {
        $this->type = $type;

        return $this;
    }

    /**
     * Get type
     *
     * @return string
     */
    public function getType()
    {
        return $this->type;
    }

    /**
     * @return Media
     */
    public function getPhoto()
    {
        return $this->photo;
    }

    /**
     * @param Media $photo
     */
    public function setPhoto($photo)
    {
        $this->photo = $photo;
    }

    /**
     * @return int
     */
    public function getPlaceNumber()
    {
        return $this->placeNumber;
    }

    /**
     * @param int $placeNumber
     */
    public function setPlaceNumber($placeNumber)
    {
        $this->placeNumber = $placeNumber;
    }

    /**
     * @param $photoPublicUrl
     */
    public function setPhotoPublicUrl($photoPublicUrl)
    {
        $this->photoPublicUrl = $photoPublicUrl;
    }

    /**
     * @return string
     */
    public function getPhotoPublicUrl()
    {
        return $this->photoPublicUrl;
    }

    public function __toString()
    {
        return $this->getFullName();
    }

    /**
     * @return boolean
     */
    public function isInitiator()
    {
        return $this->initiator;
    }

    /**
     * @param boolean $initiator
     */
    public function setInitiator($initiator)
    {
        $this->initiator = $initiator;
    }
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Bull. Sci. Nat. Géol. 25:320. 1831

#### Original name
null

### Remarks
null


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>调用XPath显示XML文档</title>

    <meta name="author" content="Lisong Wang">

    <link href="/assets/themes/twitter/css/1.4.0/bootstrap.css" rel="stylesheet">
    <link href="/assets/themes/twitter/css/style.css?body=1" rel="stylesheet" type="text/css" media="all">

          虎克的博客

Archive

Categories

Pages

Tags

调用XPath显示XML文档 Supporting tagline

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Xml;

using System.Xml.Schema;

public partial class ShowXpath : System.Web.UI.Page

{

    /// <summary>

    /// Handles the Load event of the Page control.

    /// </summary>

    /// <param name="sender">The source of the event.</param>

    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>

    protected void Page_Load(object sender, EventArgs e)

    {

        if (!IsPostBack)

        {

            ddlExpressions.Items.Add("//book/title");

            ddlExpressions.Items.Add("//book/[@genre='novel']/title");

            ddlExpressions.Items.Add("//book/author/first-name");

            ddlExpressions.Items.Add("//book/[@genre='philosophy']/title");

            ddlExpressions.Items.Add("//book/price");

            ddlExpressions.Items.Add("//book[3]/title");

            ddlExpressions.SelectedIndex = 0;

            UpdateDisplay();

        }

    }

    /// <summary>

    /// Handles the SelectedIndexChanged event of the ddlExpressions control.

    /// </summary>

    /// <param name="sender">The source of the event.</param>

    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>

    protected void ddlExpressions_SelectedIndexChanged(object sender, EventArgs e)

    {

        UpdateDisplay();

    }

    /// <summary>

    /// Updates the display.

    /// </summary>

    void UpdateDisplay()

    {

        lstOutput.Items.Clear();

        string xmlFilePath = Request.PhysicalApplicationPath + @"App_Data\Books.xml";

        XmlDocument doc = new XmlDocument();

        doc.Load(xmlFilePath);

        XmlNodeList nodeList = doc.DocumentElement.SelectNodes(ddlExpressions.SelectedItem.Text);

        foreach (XmlNode child in nodeList)

        {

            lstOutput.Items.Add("Node name: " + child.Name);

            lstOutput.Items.Add("Node value: " + child.FirstChild.Value);

        }

    }

}

← Previous

Archive

Next →

Please enable JavaScript to view the comments powered by Disqus.
blog comments powered by Disqus

Published

26 March 2009

© Lisong Wang 2012
          with help from Jekyll Bootstrap
          and Twitter Bootstrap


text:
package joshie.maritech.tile;

import joshie.maritech.extensions.modules.ExtensionFactory;
import net.minecraft.item.ItemStack;

public class TileRotorTitanium extends TileRotor {
    @Override
    protected double getTier() {
        return 5D;
    }

    @Override
    protected int getMaxDamage() {
        return 5760000;
    }

    @Override
    public ItemStack getDrop() {
        ItemStack stack = new ItemStack(ExtensionFactory.turbineTitanium);
        stack.setItemDamage((int) Math.floor(damage / 200));
        return stack;
    }
}