text:
import {Compiler, Component, Directive, ErrorHandler, Inject, Injectable, InjectionToken, Injector, Input, ModuleWithProviders, NgModule, Optional, Pipe, Type, ViewChild, ɵsetClassMetadata as setClassMetadata, ɵɵdefineComponent as defineComponent, ɵɵdefineInjector as defineInjector, ɵɵdefineNgModule as defineNgModule, ɵɵsetNgModuleScope as setNgModuleScope, ɵɵtext as text} from '@angular/core';
import {TestBed, getTestBed} from '@angular/core/testing/src/test_bed';
import {By} from '@angular/platform-browser';
import {expect} from '@angular/platform-browser/testing/src/matchers';
import {onlyInIvy} from '@angular/private/testing';

const NAME = new InjectionToken<string>('name');

@Injectable({providedIn: 'root'})
class SimpleService {
  static ngOnDestroyCalls: number = 0;
  id: number = 1;
  ngOnDestroy() { SimpleService.ngOnDestroyCalls++; }
}

// -- module: HWModule
@Component({
  selector: 'hello-world',
  template: '<greeting-cmp></greeting-cmp>',
})
export class HelloWorld {
}

// -- module: Greeting
@Component({
  selector: 'greeting-cmp',
  template: 'Hello {{ name }}',
})
export class GreetingCmp {
  name: string;

  constructor(
      @Inject(NAME) @Optional() name: string,
      @Inject(SimpleService) @Optional() service: SimpleService) {
    this.name = name || 'nobody!';
  }
}

@Component({
  selector: 'cmp-with-providers',
  template: '<hello-world></hello-world>',
  providers: [
    SimpleService,  //
    {provide: NAME, useValue: `from Component`}
  ]
})
class CmpWithProviders {
}

@NgModule({
  declarations: [GreetingCmp],
  exports: [GreetingCmp],
})
export class GreetingModule {
}

@Component({selector: 'simple-cmp', template: 'simple'})
export class SimpleCmp {
}

@Component({selector: 'with-refs-cmp', template: '

'})
export class WithRefsCmp {
}

@Component({selector: 'inherited-cmp', template: 'inherited'})
export class InheritedCmp extends SimpleCmp {
}

@Directive({selector: '[hostBindingDir]', host: {'[id]': 'id'}})
export class HostBindingDir {
  id = 'one';
}

@Component({
  selector: 'component-with-prop-bindings',
  template: `

  `
})
export class ComponentWithPropBindings {
  title = 'some title';
  label = 'some label';
}

@Component({
  selector: 'simple-app',
  template: `
    <simple-cmp></simple-cmp> - <inherited-cmp></inherited-cmp>
  `
})
export class SimpleApp {
}

@Component({selector: 'inline-template', template: '
Hello
'})
export class ComponentWithInlineTemplate {
}

@NgModule({
  declarations: [
    HelloWorld, SimpleCmp, WithRefsCmp, InheritedCmp, SimpleApp, ComponentWithPropBindings,
    HostBindingDir, CmpWithProviders
  ],
  imports: [GreetingModule],
  providers: [
    {provide: NAME, useValue: 'World!'},
  ]
})
export class HelloWorldModule {
}

describe('TestBed', () => {
  beforeEach(() => {
    getTestBed().resetTestingModule();
    TestBed.configureTestingModule({imports: [HelloWorldModule]});
  });

  it('should compile and render a component', () => {
    const hello = TestBed.createComponent(HelloWorld);
    hello.detectChanges();

    expect(hello.nativeElement).toHaveText('Hello World!');
  });

  it('should give access to the component instance', () => {
    const hello = TestBed.createComponent(HelloWorld);
    hello.detectChanges();

    expect(hello.componentInstance).toBeAnInstanceOf(HelloWorld);
  });

  it('should give the ability to query by css', () => {
    const hello = TestBed.createComponent(HelloWorld);
    hello.detectChanges();

    const greetingByCss = hello.debugElement.query(By.css('greeting-cmp'));
    expect(greetingByCss.nativeElement).toHaveText('Hello World!');
    expect(greetingByCss.componentInstance).toBeAnInstanceOf(GreetingCmp);
  });

  it('should give the ability to trigger the change detection', () => {
    const hello = TestBed.createComponent(HelloWorld);

    hello.detectChanges();
    const greetingByCss = hello.debugElement.query(By.css('greeting-cmp'));
    expect(greetingByCss.nativeElement).toHaveText('Hello World!');

    greetingByCss.componentInstance.name = 'TestBed!';
    hello.detectChanges();
    expect(greetingByCss.nativeElement).toHaveText('Hello TestBed!');
  });

  it('should give the ability to access property bindings on a node', () => {
    const fixture = TestBed.createComponent(ComponentWithPropBindings);
    fixture.detectChanges();

    const divElement = fixture.debugElement.query(By.css('div'));
    expect(divElement.properties.id).toEqual('one');
    expect(divElement.properties.title).toEqual('some title');
  });

  it('should give the ability to access interpolated properties on a node', () => {
    const fixture = TestBed.createComponent(ComponentWithPropBindings);
    fixture.detectChanges();

    const paragraphEl = fixture.debugElement.query(By.css('p'));
    expect(paragraphEl.properties.title).toEqual('( some label - some title )');
    expect(paragraphEl.properties.id).toEqual('[ some label ] [ some title ]');
  });

  it('should give access to the node injector', () => {
    const fixture = TestBed.createComponent(HelloWorld);
    fixture.detectChanges();
    const injector = fixture.debugElement.query(By.css('greeting-cmp')).injector;

    // from the node injector
    const greetingCmp = injector.get(GreetingCmp);
    expect(greetingCmp.constructor).toBe(GreetingCmp);

    // from the node injector (inherited from a parent node)
    const helloWorldCmp = injector.get(HelloWorld);
    expect(fixture.componentInstance).toBe(helloWorldCmp);

    const nameInjected = injector.get(NAME);
    expect(nameInjected).toEqual('World!');
  });

  it('should give access to the node injector for root node', () => {
    const hello = TestBed.createComponent(HelloWorld);
    hello.detectChanges();
    const injector = hello.debugElement.injector;

    // from the node injector
    const helloInjected = injector.get(HelloWorld);
    expect(helloInjected).toBe(hello.componentInstance);

    // from the module injector
    const nameInjected = injector.get(NAME);
    expect(nameInjected).toEqual('World!');
  });

  it('should give access to local refs on a node', () => {
    const withRefsCmp = TestBed.createComponent(WithRefsCmp);
    const firstDivDebugEl = withRefsCmp.debugElement.query(By.css('div'));
    // assert that a native element is referenced by a local ref
    expect(firstDivDebugEl.references.firstDiv.tagName.toLowerCase()).toBe('div');
  });

  it('should give the ability to query by directive', () => {
    const hello = TestBed.createComponent(HelloWorld);
    hello.detectChanges();

    const greetingByDirective = hello.debugElement.query(By.directive(GreetingCmp));
    expect(greetingByDirective.componentInstance).toBeAnInstanceOf(GreetingCmp);
  });

  it('allow to override a template', () => {
    // use original template when there is no override
    let hello = TestBed.createComponent(HelloWorld);
    hello.detectChanges();
    expect(hello.nativeElement).toHaveText('Hello World!');

    // override the template
    getTestBed().resetTestingModule();
    TestBed.configureTestingModule({imports: [HelloWorldModule]});
    TestBed.overrideComponent(GreetingCmp, {set: {template: `Bonjour {{ name }}`}});
    hello = TestBed.createComponent(HelloWorld);
    hello.detectChanges();
    expect(hello.nativeElement).toHaveText('Bonjour World!');

    // restore the original template by calling `.resetTestingModule()`
    getTestBed().resetTestingModule();
    TestBed.configureTestingModule({imports: [HelloWorldModule]});
    hello = TestBed.createComponent(HelloWorld);
    hello.detectChanges();
    expect(hello.nativeElement).toHaveText('Hello World!');
  });

  it('allow to override a provider', () => {
    TestBed.overrideProvider(NAME, {useValue: 'injected World!'});
    const hello = TestBed.createComponent(HelloWorld);
    hello.detectChanges();
    expect(hello.nativeElement).toHaveText('Hello injected World!');
  });

  it('uses the most recent provider override', () => {
    TestBed.overrideProvider(NAME, {useValue: 'injected World!'});
    TestBed.overrideProvider(NAME, {useValue: 'injected World a second time!'});
    const hello = TestBed.createComponent(HelloWorld);
    hello.detectChanges();
    expect(hello.nativeElement).toHaveText('Hello injected World a second time!');
  });

  it('overrides a providers in an array', () => {
    TestBed.configureTestingModule({
      imports: [HelloWorldModule],
      providers: [
        [{provide: NAME, useValue: 'injected World!'}],
      ]
    });
    TestBed.overrideProvider(NAME, {useValue: 'injected World a second time!'});
    const hello = TestBed.createComponent(HelloWorld);
    hello.detectChanges();
    expect(hello.nativeElement).toHaveText('Hello injected World a second time!');
  });

  it('should not call ngOnDestroy for a service that was overridden', () => {
    SimpleService.ngOnDestroyCalls = 0;

    TestBed.overrideProvider(SimpleService, {useValue: {id: 2, ngOnDestroy: () => {}}});
    const fixture = TestBed.createComponent(CmpWithProviders);
    fixture.detectChanges();

    const service = TestBed.inject(SimpleService);
    expect(service.id).toBe(2);

    fixture.destroy();

    // verify that original `ngOnDestroy` was not called
    expect(SimpleService.ngOnDestroyCalls).toBe(0);
  });

  describe('module overrides using TestBed.overrideModule', () => {
    @Component({
      selector: 'test-cmp',
      template: '...',
    })
    class TestComponent {
      testField = 'default';
    }

    @NgModule({
      declarations: [TestComponent],
      exports: [TestComponent],
    })
    class TestModule {
    }

    @Component({
      selector: 'app-root',
      template: `<test-cmp #testCmpCtrl></test-cmp>`,
    })
    class AppComponent {
      @ViewChild('testCmpCtrl', {static: true}) testCmpCtrl !: TestComponent;
    }

    @NgModule({
      declarations: [AppComponent],
      imports: [TestModule],
    })
    class AppModule {
    }
    @Component({
      selector: 'test-cmp',
      template: '...',
    })
    class MockTestComponent {
      testField = 'overwritten';
    }

    it('should allow declarations override', () => {
      TestBed.configureTestingModule({
        imports: [AppModule],
      });
      // replace TestComponent with MockTestComponent
      TestBed.overrideModule(TestModule, {
        remove: {declarations: [TestComponent], exports: [TestComponent]},
        add: {declarations: [MockTestComponent], exports: [MockTestComponent]}
      });
      const fixture = TestBed.createComponent(AppComponent);
      const app = fixture.componentInstance;
      expect(app.testCmpCtrl.testField).toBe('overwritten');
    });
  });

  describe('multi providers', () => {
    const multiToken = new InjectionToken<string[]>('multiToken');
    const singleToken = new InjectionToken<string>('singleToken');
    @NgModule({providers: [{provide: multiToken, useValue: 'valueFromModule', multi: true}]})
    class MyModule {
    }

    @NgModule({
      providers: [
        {provide: singleToken, useValue: 't1'},
        {provide: multiToken, useValue: 'valueFromModule2', multi: true},
        {provide: multiToken, useValue: 'secondValueFromModule2', multi: true}
      ]
    })
    class MyModule2 {
    }

    beforeEach(() => {
      TestBed.configureTestingModule({
        imports: [MyModule, MyModule2],
      });
    });

    it('is preserved when other provider is overridden', () => {
      TestBed.overrideProvider(singleToken, {useValue: ''});
      const value = TestBed.inject(multiToken);
      expect(value.length).toEqual(3);
    });

    it('overridden with an array', () => {
      const overrideValue = ['override'];
      TestBed.overrideProvider(multiToken, { useValue: overrideValue, multi: true } as any);

      const value = TestBed.inject(multiToken);
      expect(value.length).toEqual(overrideValue.length);
      expect(value).toEqual(overrideValue);
    });

    it('overridden with a non-array', () => {
      // This is actually invalid because multi providers return arrays. We have this here so we can
      // ensure Ivy behaves the same as VE does currently.
      const overrideValue = 'override';
      TestBed.overrideProvider(multiToken, { useValue: overrideValue, multi: true } as any);

      const value = TestBed.inject(multiToken);
      expect(value.length).toEqual(overrideValue.length);
      expect(value).toEqual(overrideValue as {} as string[]);
    });
  });

  describe('overrides providers in ModuleWithProviders', () => {
    const TOKEN = new InjectionToken<string[]>('token');
    @NgModule()
    class MyMod {
      static multi = false;

      static forRoot() {
        return {
          ngModule: MyMod,
          providers: [{provide: TOKEN, multi: MyMod.multi, useValue: 'forRootValue'}]
        };
      }
    }

    beforeEach(() => MyMod.multi = true);

    it('when provider is a "regular" provider', () => {
      MyMod.multi = false;
      @NgModule({imports: [MyMod.forRoot()]})
      class MyMod2 {
      }
      TestBed.configureTestingModule({imports: [MyMod2]});
      TestBed.overrideProvider(TOKEN, {useValue: ['override']});
      expect(TestBed.inject(TOKEN)).toEqual(['override']);
    });

    it('when provider is multi', () => {
      @NgModule({imports: [MyMod.forRoot()]})
      class MyMod2 {
      }
      TestBed.configureTestingModule({imports: [MyMod2]});
      TestBed.overrideProvider(TOKEN, {useValue: ['override']});
      expect(TestBed.inject(TOKEN)).toEqual(['override']);
    });

    it('restores the original value', () => {
      @NgModule({imports: [MyMod.forRoot()]})
      class MyMod2 {
      }
      TestBed.configureTestingModule({imports: [MyMod2]});
      TestBed.overrideProvider(TOKEN, {useValue: ['override']});
      expect(TestBed.inject(TOKEN)).toEqual(['override']);

      TestBed.resetTestingModule();
      TestBed.configureTestingModule({imports: [MyMod2]});
      expect(TestBed.inject(TOKEN)).toEqual(['forRootValue']);
    });
  });

  it('should allow overriding a provider defined via ModuleWithProviders (using TestBed.overrideProvider)',
     () => {
       const serviceOverride = {
         get() { return 'override'; },
       };

       @Injectable({providedIn: 'root'})
       class MyService {
         get() { return 'original'; }
       }

       @NgModule({})
       class MyModule {
         static forRoot(): ModuleWithProviders<MyModule> {
           return {
             ngModule: MyModule,
             providers: [MyService],
           };
         }
       }
       TestBed.overrideProvider(MyService, {useValue: serviceOverride});
       TestBed.configureTestingModule({
         imports: [MyModule.forRoot()],
       });

       const service = TestBed.inject(MyService);
       expect(service.get()).toEqual('override');
     });

  it('should allow overriding a provider defined via ModuleWithProviders (using TestBed.configureTestingModule)',
     () => {
       const serviceOverride = {
         get() { return 'override'; },
       };

       @Injectable({providedIn: 'root'})
       class MyService {
         get() { return 'original'; }
       }

       @NgModule({})
       class MyModule {
         static forRoot(): ModuleWithProviders<MyModule> {
           return {
             ngModule: MyModule,
             providers: [MyService],
           };
         }
       }
       TestBed.configureTestingModule({
         imports: [MyModule.forRoot()],
         providers: [{provide: MyService, useValue: serviceOverride}],
       });

       const service = TestBed.inject(MyService);
       expect(service.get()).toEqual('override');
     });

  it('overrides injectable that is using providedIn: AModule', () => {
    @NgModule()
    class ServiceModule {
    }
    @Injectable({providedIn: ServiceModule})
    class Service {
    }

    const fake = 'fake';
    TestBed.overrideProvider(Service, {useValue: fake});
    // Create an injector whose source is the ServiceModule, not DynamicTestModule.
    const ngModuleFactory = TestBed.inject(Compiler).compileModuleSync(ServiceModule);
    const injector = ngModuleFactory.create(TestBed.inject(Injector)).injector;

    const service = injector.get(Service);
    expect(service).toBe(fake);
  });

  it('allow to override multi provider', () => {
    const MY_TOKEN = new InjectionToken('MyProvider');
    class MyProvider {}

    @Component({selector: 'my-comp', template: ``})
    class MyComp {
      constructor(@Inject(MY_TOKEN) public myProviders: MyProvider[]) {}
    }

    TestBed.configureTestingModule({
      declarations: [MyComp],
      providers: [{provide: MY_TOKEN, useValue: {value: 'old provider'}, multi: true}]
    });

    const multiOverride = {useValue: [{value: 'new provider'}], multi: true};
    TestBed.overrideProvider(MY_TOKEN, multiOverride as any);

    const fixture = TestBed.createComponent(MyComp);
    expect(fixture.componentInstance.myProviders).toEqual([{value: 'new provider'}]);
  });

  it('should resolve components that are extended by other components', () => {
    // SimpleApp uses SimpleCmp in its template, which is extended by InheritedCmp
    const simpleApp = TestBed.createComponent(SimpleApp);
    simpleApp.detectChanges();
    expect(simpleApp.nativeElement).toHaveText('simple - inherited');
  });

  it('should not trigger change detection for ComponentA while calling TestBed.createComponent for ComponentB',
     () => {
       const log: string[] = [];
       @Component({
         selector: 'comp-a',
         template: '...',
       })
       class CompA {
         @Input() inputA: string = '';
         ngOnInit() { log.push('CompA:ngOnInit', this.inputA); }
       }

       @Component({
         selector: 'comp-b',
         template: '...',
       })
       class CompB {
         @Input() inputB: string = '';
         ngOnInit() { log.push('CompB:ngOnInit', this.inputB); }
       }

       TestBed.configureTestingModule({declarations: [CompA, CompB]});

       log.length = 0;
       const appA = TestBed.createComponent(CompA);
       appA.componentInstance.inputA = 'a';
       appA.autoDetectChanges();
       expect(log).toEqual(['CompA:ngOnInit', 'a']);

       log.length = 0;
       const appB = TestBed.createComponent(CompB);
       appB.componentInstance.inputB = 'b';
       appB.autoDetectChanges();
       expect(log).toEqual(['CompB:ngOnInit', 'b']);
     });

  it('should resolve components without async resources synchronously', (done) => {
    TestBed
        .configureTestingModule({
          declarations: [ComponentWithInlineTemplate],
        })
        .compileComponents()
        .then(done)
        .catch(error => {
          // This should not throw any errors. If an error is thrown, the test will fail.
          // Specifically use `catch` here to mark the test as done and *then* throw the error
          // so that the test isn't treated as a timeout.
          done();
          throw error;
        });

    // Intentionally call `createComponent` before `compileComponents` is resolved. We want this to
    // work for components that don't have any async resources (templateUrl, styleUrls).
    TestBed.createComponent(ComponentWithInlineTemplate);
  });

  it('should be able to override the ErrorHandler via an import', () => {
    class CustomErrorHandler {}

    @NgModule({providers: [{provide: ErrorHandler, useClass: CustomErrorHandler}]})
    class ProvidesErrorHandler {
    }

    getTestBed().resetTestingModule();
    TestBed.configureTestingModule({imports: [ProvidesErrorHandler, HelloWorldModule]});

    expect(TestBed.inject(ErrorHandler)).toEqual(jasmine.any(CustomErrorHandler));

  });

  it('should throw errors in CD', () => {
    @Component({selector: 'my-comp', template: ''})
    class MyComp {
      name !: {hello: string};

      ngOnInit() {
        // this should throw because this.name is undefined
        this.name.hello = 'hello';
      }
    }

    TestBed.configureTestingModule({declarations: [MyComp]});

    expect(() => {
      const fixture = TestBed.createComponent(MyComp);
      fixture.detectChanges();
    }).toThrowError();
  });

  // TODO(FW-1245): properly fix issue where errors in listeners aren't thrown and don't cause
  // tests to fail. This is an issue in both View Engine and Ivy, and may require a breaking
  // change to completely fix (since simple re-throwing breaks handlers in ngrx, etc).
  xit('should throw errors in listeners', () => {

    @Component({selector: 'my-comp', template: '<button (click)="onClick()">Click me</button>'})
    class MyComp {
      name !: {hello: string};

      onClick() {
        // this should throw because this.name is undefined
        this.name.hello = 'hello';
      }
    }

    TestBed.configureTestingModule({declarations: [MyComp]});
    const fixture = TestBed.createComponent(MyComp);
    fixture.detectChanges();

    expect(() => {
      const button = fixture.nativeElement.querySelector('button');
      button.click();
    }).toThrowError();
  });

  onlyInIvy('TestBed new feature to allow declaration and import of component')
      .it('should allow both the declaration and import of a component into the testing module',
          () => {
            // This test validates that a component (Outer) which is both declared and imported
            // (via its module) in the testing module behaves correctly. That is:
            //
            // 1) the component should be compiled in the scope of its original module.
            //
            // This condition is tested by having the component (Outer) use another component
            // (Inner) within its template. Thus, if it's compiled in the correct scope then the
            // text 'Inner' from the template of (Inner) should appear in the result.
            //
            // 2) the component should be available in the TestingModule scope.
            //
            // This condition is tested by attempting to use the component (Outer) inside a test
            // fixture component (Fixture) which is declared in the testing module only.

            @Component({
              selector: 'inner',
              template: 'Inner',
            })
            class Inner {
            }

            @Component({
              selector: 'outer',
              template: '<inner></inner>',
            })
            class Outer {
            }

            @NgModule({
              declarations: [Inner, Outer],
            })
            class Module {
            }

            @Component({
              template: '<outer></outer>',
              selector: 'fixture',
            })
            class Fixture {
            }

            TestBed.configureTestingModule({
              declarations: [Outer, Fixture],
              imports: [Module],
            });

            const fixture = TestBed.createComponent(Fixture);
            // The Outer component should have its template stamped out, and that template should
            // include a correct instance of the Inner component with the 'Inner' text from its
            // template.
            expect(fixture.nativeElement.innerHTML).toEqual('<outer><inner>Inner</inner></outer>');
          });

  onlyInIvy('Ivy-specific errors').describe('checking types before compiling them', () => {
    @Directive({
      selector: 'my-dir',
    })
    class MyDir {
    }

    @NgModule()
    class MyModule {
    }

    // [decorator, type, overrideFn]
    const cases: [string, Type<any>, string][] = [
      ['Component', MyDir, 'overrideComponent'],
      ['NgModule', MyDir, 'overrideModule'],
      ['Pipe', MyModule, 'overridePipe'],
      ['Directive', MyModule, 'overrideDirective'],
    ];
    cases.forEach(([decorator, type, overrideFn]) => {
      it(`should throw an error in case invalid type is used in ${overrideFn} function`, () => {
        TestBed.configureTestingModule({declarations: [MyDir]});
        expect(() => {
          (TestBed as any)[overrideFn](type, {});
          TestBed.createComponent(type);
        }).toThrowError(new RegExp(`class doesn't have @${decorator} decorator`, 'g'));
      });
    });
  });

  onlyInIvy('TestBed should handle AOT pre-compiled Components')
      .describe('AOT pre-compiled components', () => {
        /**
         * Function returns a class that represents AOT-compiled version of the following Component:
         *
         * @Component({
         *  selector: 'comp',
         *  templateUrl: './template.ng.html',
         *  styleUrls: ['./style.css']
         * })
         * class ComponentClass {}
         *
         * This is needed to closer match the behavior of AOT pre-compiled components (compiled
         * outside of TestBed) without changing TestBed state and/or Component metadata to compile
         * them via TestBed with external resources.
         */
        const getAOTCompiledComponent = () => {
          class ComponentClass {
            static ɵfac = () => new ComponentClass();
            static ɵcmp = defineComponent({
              type: ComponentClass,
              selectors: [['comp']],
              decls: 1,
              vars: 0,
              template: (rf: any, ctx: any) => {
                if (rf & 1) {
                  text(0, 'Some template');
                }
              },
              styles: ['body { margin: 0; }']
            });
          }
          setClassMetadata(
              ComponentClass, [{
                type: Component,
                args: [{
                  selector: 'comp',
                  templateUrl: './template.ng.html',
                  styleUrls: ['./style.css'],
                }]
              }],
              null, null);
          return ComponentClass;
        };

        it('should have an ability to override template', () => {
          const SomeComponent = getAOTCompiledComponent();
          TestBed.configureTestingModule({declarations: [SomeComponent]});
          TestBed.overrideTemplateUsingTestingModule(SomeComponent, 'Template override');
          const fixture = TestBed.createComponent(SomeComponent);
          expect(fixture.nativeElement.innerHTML).toBe('Template override');
        });

        it('should have an ability to override template with empty string', () => {
          const SomeComponent = getAOTCompiledComponent();
          TestBed.configureTestingModule({declarations: [SomeComponent]});
          TestBed.overrideTemplateUsingTestingModule(SomeComponent, '');
          const fixture = TestBed.createComponent(SomeComponent);
          expect(fixture.nativeElement.innerHTML).toBe('');
        });

        it('should allow component in both in declarations and imports', () => {
          const SomeComponent = getAOTCompiledComponent();

          // This is an AOT compiled module which declares (but does not export) SomeComponent.
          class ModuleClass {
            static ɵmod = defineNgModule({
              type: ModuleClass,
              declarations: [SomeComponent],
            });
          }

          @Component({
            template: '<comp></comp>',

            selector: 'fixture',
          })
          class TestFixture {
          }

          TestBed.configureTestingModule({
            // Here, SomeComponent is both declared, and then the module which declares it is
            // also imported. This used to be a duplicate declaration error, but is now interpreted
            // to mean:
            // 1) Compile (or reuse) SomeComponent in the context of its original NgModule
            // 2) Make SomeComponent available in the scope of the testing module, even if it wasn't
            //    originally exported from its NgModule.
            //
            // This allows TestFixture to use SomeComponent, which is asserted below.
            declarations: [SomeComponent, TestFixture],
            imports: [ModuleClass],
          });
          const fixture = TestBed.createComponent(TestFixture);
          // The regex avoids any issues with styling attributes.
          expect(fixture.nativeElement.innerHTML).toMatch(/<comp[^>]*>Some template<\/comp>/);
        });
      });

  onlyInIvy('patched ng defs should be removed after resetting TestingModule')
      .describe('resetting ng defs', () => {
        it('should restore ng defs to their initial states', () => {
          @Pipe({name: 'somePipe', pure: true})
          class SomePipe {
            transform(value: string): string { return `transformed ${value}`; }
          }

          @Directive({selector: 'someDirective'})
          class SomeDirective {
            someProp = 'hello';
          }

          @Component({selector: 'comp', template: 'someText'})
          class SomeComponent {
          }

          @NgModule({declarations: [SomeComponent]})
          class SomeModule {
          }

          TestBed.configureTestingModule({imports: [SomeModule]});

          // adding Pipe and Directive via metadata override
          TestBed.overrideModule(
              SomeModule, {set: {declarations: [SomeComponent, SomePipe, SomeDirective]}});
          TestBed.overrideComponent(
              SomeComponent,
              {set: {template: `<span someDirective>{{'hello' | somePipe}}</span>`}});
          TestBed.createComponent(SomeComponent);

          const defBeforeReset = (SomeComponent as any).ɵcmp;
          expect(defBeforeReset.pipeDefs().length).toEqual(1);
          expect(defBeforeReset.directiveDefs().length).toEqual(2);  // directive + component

          TestBed.resetTestingModule();

          const defAfterReset = (SomeComponent as any).ɵcmp;
          expect(defAfterReset.pipeDefs).toBe(null);
          expect(defAfterReset.directiveDefs).toBe(null);
        });

        it('should cleanup ng defs for classes with no ng annotations (in case of inheritance)',
           () => {
             @Component({selector: 'someDirective', template: '...'})
             class SomeComponent {
             }

             class ComponentWithNoAnnotations extends SomeComponent {}

             @Directive({selector: 'some-directive'})
             class SomeDirective {
             }

             class DirectiveWithNoAnnotations extends SomeDirective {}

             @Pipe({name: 'some-pipe'})
             class SomePipe {
             }

             class PipeWithNoAnnotations extends SomePipe {}

             TestBed.configureTestingModule({
               declarations: [
                 ComponentWithNoAnnotations, DirectiveWithNoAnnotations, PipeWithNoAnnotations
               ]
             });
             TestBed.createComponent(ComponentWithNoAnnotations);

             expect(ComponentWithNoAnnotations.hasOwnProperty('ɵcmp')).toBeTruthy();
             expect(SomeComponent.hasOwnProperty('ɵcmp')).toBeTruthy();

             expect(DirectiveWithNoAnnotations.hasOwnProperty('ɵdir')).toBeTruthy();
             expect(SomeDirective.hasOwnProperty('ɵdir')).toBeTruthy();

             expect(PipeWithNoAnnotations.hasOwnProperty('ɵpipe')).toBeTruthy();
             expect(SomePipe.hasOwnProperty('ɵpipe')).toBeTruthy();

             TestBed.resetTestingModule();

             // ng defs should be removed from classes with no annotations
             expect(ComponentWithNoAnnotations.hasOwnProperty('ɵcmp')).toBeFalsy();
             expect(DirectiveWithNoAnnotations.hasOwnProperty('ɵdir')).toBeFalsy();
             expect(PipeWithNoAnnotations.hasOwnProperty('ɵpipe')).toBeFalsy();

             // ng defs should be preserved on super types
             expect(SomeComponent.hasOwnProperty('ɵcmp')).toBeTruthy();
             expect(SomeDirective.hasOwnProperty('ɵdir')).toBeTruthy();
             expect(SomePipe.hasOwnProperty('ɵpipe')).toBeTruthy();
           });

        it('should clean up overridden providers for modules that are imported more than once',
           () => {

             @Injectable()
             class Token {
               name: string = 'real';
             }

             @NgModule({
               providers: [Token],
             })
             class Module {
             }

             TestBed.configureTestingModule({imports: [Module, Module]});
             TestBed.overrideProvider(Token, {useValue: {name: 'fake'}});

             expect(TestBed.inject(Token).name).toEqual('fake');

             TestBed.resetTestingModule();

             // The providers for the module should have been restored to the original array, with
             // no trace of the overridden providers.
             expect((Module as any).ɵinj.providers).toEqual([Token]);
           });

        it('should clean up overridden providers on components whose modules are compiled more than once',
           async() => {
             @Injectable()
             class SomeInjectable {
               id: string|undefined;
             }

             @Component({providers: [SomeInjectable]})
             class ComponentWithProvider {
               constructor(readonly injectable: SomeInjectable) {}
             }

             @NgModule({declarations: [ComponentWithProvider]})
             class MyModule {
             }

             TestBed.configureTestingModule({imports: [MyModule]});
             const originalResolver = (ComponentWithProvider as any).ɵcmp.providersResolver;
             TestBed.overrideProvider(SomeInjectable, {useValue: {id: 'fake'}});

             const compiler = TestBed.inject(Compiler);
             await compiler.compileModuleAsync(MyModule);
             compiler.compileModuleSync(MyModule);

             TestBed.resetTestingModule();
             expect((ComponentWithProvider as any).ɵcmp.providersResolver)
                 .toEqual(originalResolver);
           });
      });

  onlyInIvy('VE injects undefined when provider does not have useValue or useFactory')
      .describe('overrides provider', () => {
        it('with empty provider object', () => {
          @Injectable()
          class Service {
          }
          TestBed.overrideProvider(Service, {});
          // Should be able to get a Service instance because it has no dependencies that can't be
          // resolved
          expect(TestBed.inject(Service)).toBeDefined();
        });
      });

  onlyInIvy('uses Ivy-specific compiler output')
      .it('should handle provider overrides when module imports are provided as a function', () => {
        class InjectedString {
          value?: string;
        }

        @Component({template: '{{injectedString.value}}'})
        class AppComponent {
          constructor(public injectedString: InjectedString) {}
        }

        @NgModule({})
        class DependencyModule {
        }

        // We need to write the compiler output manually here,
        // because it depends on code generated by ngcc.
        class TestingModule {
          static ɵmod = defineNgModule({type: TestingModule});
          static ɵinj =
              defineInjector({factory: () => new TestingModule(), imports: [DependencyModule]});
        }
        setNgModuleScope(TestingModule, {imports: () => [DependencyModule]});

        TestBed
            .configureTestingModule({
              imports: [TestingModule],
              declarations: [AppComponent],
              providers: [{provide: InjectedString, useValue: {value: 'initial'}}],
            })
            .compileComponents();

        TestBed.overrideProvider(InjectedString, {useValue: {value: 'changed'}})
            .compileComponents();

        const fixture = TestBed.createComponent(AppComponent);
        fixture.detectChanges();
        expect(fixture !.nativeElement.textContent).toContain('changed');
      });
});


text:
import matplotlib, pkgutil, itertools
from pymc import examples

matplotlib.use('Agg', warn=False)

def get_examples():
    prefix = examples.__name__ + "."
    for _, example, _ in pkgutil.iter_modules(examples.__path__):
        yield check_example, prefix + example

def check_example(example_name):
    example = __import__(example_name, fromlist='dummy')
    if hasattr(example, 'run'):
        example.run("short")

def test_examples0():
    for t in itertools.islice(get_examples(), 0, 10):
        yield t

def test_examples1():
    for t in itertools.islice(get_examples(), 10, 20):
        yield t

def test_examples2():
    for t in itertools.islice(get_examples(), 20, None):
        yield t

redpajama_set_name: RedPajamaGithub


text:
package ru.job4j.parser;

import org.junit.Test;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;

import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;

/**
 * DateParserTest.
 * @author Ivan Belyaev
 * @since 17.12.2019
 * @version 1.0
 */
public class DateParserTest {
    /**
     * Test for the DateParser class.
     */
    @Test
    public void whenParseDateThenGetTheSameDate() {
        LocalDateTime methodReturns = new DateParser().parseDate("14 дек 19, 20:14");
        assertThat(methodReturns, is(LocalDateTime.of(2019, 12, 14, 20, 14)));
        methodReturns = new DateParser().parseDate("сегодня, 14:32");
        assertThat(methodReturns, is(LocalDateTime.of(LocalDate.now(), LocalTime.of(14, 32))));
        methodReturns = new DateParser().parseDate("вчера, 14:32");
        assertThat(methodReturns, is(LocalDateTime.of(LocalDate.now().minusDays(1), LocalTime.of(14, 32))));
    }
}


text:
#include "modsecurity/rules_exceptions.h"

#include <string>

#include "src/utils/string.h"
#include "src/variables/variable.h"

namespace modsecurity {

RulesExceptions::RulesExceptions() {
}

RulesExceptions::~RulesExceptions() {
}

bool RulesExceptions::loadUpdateActionById(double id,
    std::unique_ptr<std::vector<std::unique_ptr<actions::Action> > > actions,
    std::string *error) {

    for (auto &a : *actions) {
        if (a->action_kind == actions::Action::ConfigurationKind) {
            std::cout << "General failure, action: " << a->m_name;
            std::cout << " has not expected to be used with UpdateActionByID.";
            std::cout << std::endl;
        } else if (a->action_kind
            == actions::Action::RunTimeBeforeMatchAttemptKind) {
            m_action_pre_update_target_by_id.emplace(std::pair<double,
                std::unique_ptr<actions::Action>>(id , std::move(a)));
        } else if (a->action_kind == actions::Action::RunTimeOnlyIfMatchKind) {
            m_action_pos_update_target_by_id.emplace(std::pair<double,
                std::unique_ptr<actions::Action>>(id , std::move(a)));
        } else {
            std::cout << "General failure, action: " << a->m_name;
            std::cout << " has an unknown type." << std::endl;
        }
    }

    return true;
}

bool RulesExceptions::loadRemoveRuleByMsg(const std::string &msg,
    std::string *error) {
    m_remove_rule_by_msg.push_back(msg);

    return true;
}

bool RulesExceptions::loadRemoveRuleByTag(const std::string &msg,
    std::string *error) {
    m_remove_rule_by_tag.push_back(msg);

    return true;
}

bool RulesExceptions::loadUpdateTargetByMsg(const std::string &msg,
    std::unique_ptr<std::vector<std::unique_ptr<variables::Variable> > > var,
    std::string *error) {
    for (auto &i : *var) {
        m_variable_update_target_by_msg.emplace(
            std::pair<std::shared_ptr<std::string>,
            std::unique_ptr<variables::Variable>>(
                std::make_shared<std::string>(msg),
                std::move(i)));
    }

    return true;
}

bool RulesExceptions::loadUpdateTargetByTag(const std::string &tag,
    std::unique_ptr<std::vector<std::unique_ptr<variables::Variable> > > var,
    std::string *error) {

    for (auto &i : *var) {
        m_variable_update_target_by_tag.emplace(
            std::pair<std::shared_ptr<std::string>,
                std::unique_ptr<variables::Variable>>(
                    std::make_shared<std::string>(tag),
                    std::move(i)));
    }

    return true;
}

bool RulesExceptions::loadUpdateTargetById(double id,
    std::unique_ptr<std::vector<std::unique_ptr<variables::Variable> > > var,
    std::string *error) {

    for (auto &i : *var) {
        m_variable_update_target_by_id.emplace(
            std::pair<double,
                std::unique_ptr<variables::Variable>>(id,
                std::move(i)));
    }

    return true;
}

bool RulesExceptions::load(const std::string &a, std::string *error) {
    bool added = false;
    std::vector<std::string> toRemove = utils::string::ssplit(a, ' ');
    for (std::string &r : toRemove) {
        std::string b = modsecurity::utils::string::parserSanitizer(r);
        if (b.size() == 0) {
            continue;
        }

        size_t dash = b.find('-');
        if (dash != std::string::npos) {
            std::string n1s = std::string(b, 0, dash);
            std::string n2s = std::string(b, dash + 1, b.size() - (dash + 1));
            int n1n = 0;
            int n2n = 0;
            try {
                n1n = std::stoi(n1s);
                added = true;
            } catch (...) {
                error->assign("Not a number: " + n1s);
                return false;
            }
            try {
                n2n = std::stoi(n2s);
                added = true;
            } catch (...) {
                error->assign("Not a number: " + n2s);
                return false;
            }

            if (n1s > n2s) {
                error->assign("Invalid range: " + b);
                return false;
            }
            addRange(n1n, n2n);
            added = true;
        } else {
            try {
                int num = std::stoi(b);
                addNumber(num);
                added = true;
            } catch (...) {
                error->assign("Not a number or range: " + b);
                return false;
            }
        }
    }

    if (added) {
        return true;
    }

    error->assign("Not a number or range: " + a);
    return false;
}

bool RulesExceptions::addNumber(int a) {
    m_numbers.push_back(a);
    return true;
}

bool RulesExceptions::addRange(int a, int b) {
    m_ranges.push_back(std::make_pair(a, b));
    return true;
}

bool RulesExceptions::contains(int a) {
    for (int z : m_numbers) {
        if (a == z) {
            return true;
        }
    }

    for (auto z : m_ranges) {
        if (z.first <= a && z.second >= a) {
            return true;
        }
    }

    return false;
}

bool RulesExceptions::merge(RulesExceptions *from) {
    for (int a : from->m_numbers) {
        bool ret = addNumber(a);
        if (ret == false) {
            return ret;
        }
    }
    for (auto b : from->m_ranges) {
        bool ret = addRange(b.first, b.second);
        if (ret == false) {
            return ret;
        }
    }

    for (auto &p : from->m_variable_update_target_by_tag) {
        m_variable_update_target_by_tag.emplace(
            std::pair<std::shared_ptr<std::string>,
            std::shared_ptr<variables::Variable>>(p.first,
                p.second));
    }

    for (auto &p : from->m_variable_update_target_by_msg) {
        m_variable_update_target_by_msg.emplace(
            std::pair<std::shared_ptr<std::string>,
            std::shared_ptr<variables::Variable>>(p.first,
                p.second));
    }

    for (auto &p : from->m_variable_update_target_by_id) {
        m_variable_update_target_by_id.emplace(
            std::pair<double,
                std::shared_ptr<variables::Variable>>(p.first,
                    p.second));
    }

    for (auto &p : from->m_action_pos_update_target_by_id) {
        m_action_pos_update_target_by_id.emplace(
            std::pair<double,
                std::shared_ptr<actions::Action>>(p.first,
                    p.second));
    }

    for (auto &p : from->m_action_pre_update_target_by_id) {
        m_action_pre_update_target_by_id.emplace(
            std::pair<double,
                std::shared_ptr<actions::Action>>(p.first,
                    p.second));
    }

    for (auto &p : from->m_remove_rule_by_msg) {
        m_remove_rule_by_msg.push_back(p);
    }

    for (auto &p : from->m_remove_rule_by_tag) {
        m_remove_rule_by_tag.push_back(p);
    }

    return true;
}

}  // namespace modsecurity


text:
#include <signal.h>
#include "sig.h"
#include "hassgact.h"

void sig_catch(sig,f)
int sig;
void (*f)();
{
#ifdef HASSIGACTION
  struct sigaction sa;
  sa.sa_handler = f;
  sa.sa_flags = 0;
  sigemptyset(&sa.sa_mask);
  sigaction(sig,&sa,(struct sigaction *) 0);
#else
  signal(sig,f); /* won't work under System V, even nowadays---dorks */
#endif
}


text:
import sequelize from '../../sequelize';
import File from './File';

function sync(...args) {
  return sequelize.sync(...args);
}
export default { sync };
export { File };


text:
package build

import (
	"context"

	"knative.dev/pkg/injection"

	"k8s.io/client-go/tools/cache"
	serviceaccountinformers "knative.dev/pkg/client/injection/kube/informers/core/v1/serviceaccount"
	"knative.dev/pkg/configmap"
	"knative.dev/pkg/controller"

	"github.com/google/knative-gcp/pkg/apis/configs/gcpauth"
	v1 "github.com/google/knative-gcp/pkg/apis/events/v1"
	cloudbuildsourceinformers "github.com/google/knative-gcp/pkg/client/injection/informers/events/v1/cloudbuildsource"
	pullsubscriptioninformers "github.com/google/knative-gcp/pkg/client/injection/informers/intevents/v1/pullsubscription"
	cloudbuildsourcereconciler "github.com/google/knative-gcp/pkg/client/injection/reconciler/events/v1/cloudbuildsource"
	"github.com/google/knative-gcp/pkg/pubsub/adapter/converters"
	"github.com/google/knative-gcp/pkg/reconciler"
	"github.com/google/knative-gcp/pkg/reconciler/identity"
	"github.com/google/knative-gcp/pkg/reconciler/identity/iam"
	"github.com/google/knative-gcp/pkg/reconciler/intevents"
)

const (
	// reconcilerName is the name of the reconciler
	reconcilerName = "CloudBuildSource"

	// controllerAgentName is the string used by this controller to identify
	// itself when creating events.
	controllerAgentName = "cloud-run-events-build-source-controller"

	// receiveAdapterName is the string used as name for the receive adapter pod.
	receiveAdapterName = "cloudbuildsource.events.cloud.google.com"
)

type Constructor injection.ControllerConstructor

// NewConstructor creates a constructor to make a CloudBuildSource controller.
func NewConstructor(ipm iam.IAMPolicyManager, gcpas *gcpauth.StoreSingleton) Constructor {
	return func(ctx context.Context, cmw configmap.Watcher) *controller.Impl {
		return newController(ctx, cmw, ipm, gcpas.Store(ctx, cmw))
	}
}

func newController(
	ctx context.Context,
	cmw configmap.Watcher,
	ipm iam.IAMPolicyManager,
	gcpas *gcpauth.Store,
) *controller.Impl {
	pullsubscriptionInformer := pullsubscriptioninformers.Get(ctx)
	cloudbuildsourceInformer := cloudbuildsourceinformers.Get(ctx)
	serviceAccountInformer := serviceaccountinformers.Get(ctx)

	r := &Reconciler{
		PubSubBase: intevents.NewPubSubBase(ctx,
			&intevents.PubSubBaseArgs{
				ControllerAgentName: controllerAgentName,
				ReceiveAdapterName:  receiveAdapterName,
				ReceiveAdapterType:  string(converters.CloudBuild),
				ConfigWatcher:       cmw,
			}),
		Identity:             identity.NewIdentity(ctx, ipm, gcpas),
		buildLister:          cloudbuildsourceInformer.Lister(),
		serviceAccountLister: serviceAccountInformer.Lister(),
	}
	impl := cloudbuildsourcereconciler.NewImpl(ctx, r)

	r.Logger.Info("Setting up event handlers")
	cloudbuildsourceInformer.Informer().AddEventHandlerWithResyncPeriod(
		controller.HandleAll(impl.Enqueue), reconciler.DefaultResyncPeriod)

	pullsubscriptionInformer.Informer().AddEventHandler(cache.FilteringResourceEventHandler{
		FilterFunc: controller.FilterControllerGK(v1.Kind("CloudBuildSource")),
		Handler:    controller.HandleAll(impl.EnqueueControllerOf),
	})

	serviceAccountInformer.Informer().AddEventHandler(cache.FilteringResourceEventHandler{
		FilterFunc: controller.FilterControllerGK(v1.Kind("CloudBuildSource")),
		Handler:    controller.HandleAll(impl.EnqueueControllerOf),
	})

	return impl
}


text:
package org.cloudfoundry.client.v2.spaces;

import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import org.cloudfoundry.client.v2.PaginatedResponse;
import org.cloudfoundry.client.v2.securitygroups.SecurityGroupResource;
import org.immutables.value.Value;

/**
 * The response payload for the List all Security Groups for the Space operation
 */
@JsonDeserialize
@Value.Immutable
abstract class _ListSpaceSecurityGroupsResponse extends PaginatedResponse<SecurityGroupResource> {

}


text:
<?php
require_once("header.php");
?>

<?php echo l10n("cart_title", "Orders") ?>

				<select onchange="location.href=$(this).val()">
					<option value="orders.php?status=inbox"><?php echo l10n('cart_inbox', 'Inbox') ?></option>
					<option value="orders.php?status=evaded"><?php echo l10n('cart_evaded', 'Evaded') ?></option>
					<option value="orders.php?status=waiting"><?php echo l10n('cart_waiting', 'Waiting') ?></option>
					<option value="availability.php" selected><?php echo l10n('cart_availability', 'Availability') ?></option>
					<option value="orders-charts.php"><?php echo l10n('cart_order_charts', 'Charts') ?></option>
				</select>

				<?php echo l10n('cart_inbox', 'Inbox') ?>
				<?php echo l10n('cart_evaded', 'Evaded') ?>
				<?php echo l10n('cart_waiting', 'Waiting') ?>
				<?php echo l10n('cart_availability', 'Availability') ?>
				<?php echo l10n('cart_order_charts', 'Charts') ?>

<?php
if (isset($imSettings['ecommerce']) && isset($imSettings['ecommerce']['database'])) { // Global check
	$dbconf = getDbData($imSettings['ecommerce']['database']['id']);
	$prefix = $imSettings['ecommerce']['database']['table'];
	$pagination_length = 15;
	$pagination_start = (isset($_GET['page']) ? $_GET['page'] * $pagination_length : 0);
	$ecommerce = new ImCart();
	// Clean the temp files
	$ecommerce->deleteTemporaryFiles("../");
	if ($ecommerce->setDatabaseConnection($dbconf['host'], $dbconf['user'], $dbconf['password'], $dbconf['database'], $prefix)) { // ecommerce connection

		/*
		|-----------------------------
		|	Show the  table
		|-----------------------------
		 */
		$results = $ecommerce->getDynamicProductsAvailabilityTable(0, 0);
		if (count($results)): // Available data
			foreach ($results as $category => $data): ?>

<?php echo $category; ?>

				<?php for ($i = 0; $i < count($data); $i++): ?>

	<div class="store-product-card-image" data-bg-image="<?php echo $data[$i]['image'] ?>">

<?php echo $data[$i]['name']; ?>

		<span class="availability <?php echo $data[$i]['status'] ?>">
		<?php echo l10n("cart_quantity", "Quantity:") . " " . $data[$i]['availableQuantity'] ?>

<?php	endfor; ?>
<?php 		endforeach; ?>

	<?php else: // Else available data ?>

			<?php echo l10n('search_empty', 'Empty results') ?>

	<?php endif; // End available data ?>
<?php
	} else { // End connection check
		echo "DB Connection error";
	}
} // End Global check
?>

<?php require_once("footer.php"); ?>


text:
<!doctype html>

	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<title>KeyValuePair | Yet Another Collection Approach</title>
	<meta name="description" content="">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<link rel="stylesheet" href="../assets/css/main.css">

						Search
						<input id="tsd-search-field" type="text" />

Preparing search index...

The search index is not available

					Yet Another Collection Approach

						Options

								All

Public

Public/Protected

All

							<input type="checkbox" id="tsd-filter-inherited" checked />
							Inherited
							<input type="checkbox" id="tsd-filter-externals" checked />
							Externals
							<input type="checkbox" id="tsd-filter-only-exported" />
							Only exported

					Menu

					Globals

					"KeyValuePair"

					KeyValuePair

Class KeyValuePair<K, V>

The class represents a key-value pair

Type parameters

K

V

Hierarchy

						KeyValuePair

Index

Constructors

constructor

Properties

_key

_value

Accessors

key

value

Constructors

constructor

new <wbr>Key<wbr>Value<wbr>Pair(key: K, value: V): KeyValuePair

Defined in KeyValuePair.ts:20

Default constructor with parameters

Parameters

key: K

Key

value: V

Value

Returns KeyValuePair

Properties

Private _key

_key: K

Defined in KeyValuePair.ts:5

Private _value

_value: V

Defined in KeyValuePair.ts:6

Accessors

key

get key(): K

Defined in KeyValuePair.ts:11

Gets the key

Returns K

value

get value(): V

Defined in KeyValuePair.ts:18

Gets the value

Returns V

						Globals

						"<wbr>Comparer"

						"<wbr>Dictionary"

						"<wbr>Iterator<wbr>Item"

						"<wbr>Key<wbr>Value<wbr>Pair"

						"<wbr>List"

						"<wbr>Sorted<wbr>Dictionary"

						"<wbr>Sorter"

						"interfaces/IComparer"

						"interfaces/IFor<wbr>Each<wbr>Interface<wbr>Dictionary"

						"interfaces/IFor<wbr>Each<wbr>Interface<wbr>List"

						"interfaces/IList"

						"interfaces/ISort<wbr>Interface"

						"interfaces/ISorter"

						Key<wbr>Value<wbr>Pair

								constructor

								_key

								_value

								key

								value

Legend

Module

Object literal

Variable

Function

Function with type parameter

Index signature

Type alias

Type alias with type parameter

Enumeration

Enumeration member

Property

Method

Interface

Interface with type parameter

Constructor

Property

Method

Index signature

Class

Class with type parameter

Constructor

Property

Method

Accessor

Index signature

Inherited constructor

Inherited property

Inherited method

Inherited accessor

Protected property

Protected method

Protected accessor

Private property

Private method

Private accessor

Static property

Static method

Generated using TypeDoc


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<OfficeApp xmlns="http://schemas.microsoft.com/office/appforoffice/1.1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="MailApp">
  <Id>4c3307d0-8efe-4f74-8aae-2a10ad05ede9</Id>
  <Version>1.0.0.0</Version>
  <ProviderName>MikeO</ProviderName>
  <DefaultLocale>en-US</DefaultLocale>
  <DisplayName DefaultValue="CRM Integration"/>
  <Description DefaultValue="CRM Integration"/>
  <!--<HighResolutionIconUrl DefaultValue="https://localhost/"/>-->
  <SupportUrl DefaultValue="http://localhost/"/>
  <Hosts>
    <Host Name="Mailbox"/>
  </Hosts>
  <Requirements>
    <Sets>
      <Set Name="MailBox" MinVersion="1.1"/>
    </Sets>
  </Requirements>
  <FormSettings>
    <Form xsi:type="ItemRead">
      <DesktopSettings>
        <SourceLocation DefaultValue="https://outlookcrm.azurewebsites.net/appread/home/home.html"/>
        <RequestedHeight>250</RequestedHeight>
      </DesktopSettings>
    </Form>
    <Form xsi:type="ItemEdit">
      <DesktopSettings>
        <SourceLocation DefaultValue="https://outlookcrm.azurewebsites.net/appcompose/home/home.html"/>
      </DesktopSettings>
    </Form>
  </FormSettings>
  <Permissions>ReadWriteItem</Permissions>
  <Rule xsi:type="RuleCollection" Mode="Or">
    <Rule xsi:type="ItemIs" ItemType="Message" FormType="Read"/>
    <Rule xsi:type="ItemIs" ItemType="Message" FormType="Edit"/>
    <Rule xsi:type="ItemIs" ItemType="Appointment" FormType="Read"/>
    <Rule xsi:type="ItemIs" ItemType="Appointment" FormType="Edit"/>
  </Rule>
  <DisableEntityHighlighting>false</DisableEntityHighlighting>
</OfficeApp>


text:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta http-equiv="Cache-Control"
	content="no-store, no-cache, must-revalidate, post-check=0, pre-check=0" />
<meta http-equiv="Connection" content="Close" />
<script type="text/javascript">
	function stringToHex(str) {
		var val = "";
		for (var i = 0; i < str.length; i++) {
			if (val == "")
				val = str.charCodeAt(i).toString(16);
			else
				val += str.charCodeAt(i).toString(16);
		}
		return val;
	}

	function YunSuoAutoJump() {
		var width = screen.width;
		var height = screen.height;
		var screendate = width + "," + height;
		var curlocation = window.location.href;
		if (-1 == curlocation.indexOf("security_verify_")) {
			document.cookie = "srcurl=" + stringToHex(window.location.href)
					+ ";path=/;";
		}
		self.location = "/detail/detail?type=63&id=CN201110050597.7&security_verify_data="
				+ stringToHex(screendate);
	}
</script>
<script>
	setTimeout("YunSuoAutoJump()", 50);
</script>
</head>
<!--2017-07-03 14:45:18-->
</html>


text:
package br.com.tt;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@SpringBootApplication
@Controller
public class CursoJavaWebApplication {

	public static void main(String[] args) {
		SpringApplication.run(CursoJavaWebApplication.class, args);
	}

	@GetMapping
	String index() {
		return "index";
	}

}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

		<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
		<title>All Classes</title>
		<link rel="stylesheet" type="text/css" href="stylesheet.css" title="style" />

All Classes

				TrapFactoryTest


text:
/* Contributed by Nicola Pero - Thu Mar  8 16:27:46 CET 2001 */
#include <objc/objc.h>
#include <objc/objc-api.h>
#include <objc/Object.h>

/* Test that by using -> we can access ivars of other objects of the same
   class */

@interface TestClass : Object
{
  int value;
}
- (int) value;
- (int) setValue: (int)number;
- (void) takeValueFrom: (TestClass *)object;
@end

@implementation TestClass : Object
{
  int value;
}
- (int) value
{
  return value;
}
- (int) setValue: (int)number
{
  value = number;
}
- (void) takeValueFrom: (TestClass *)object
{
  value = object->value;
}
@end

int main (void)
{
  TestClass *a;
  TestClass *b;

  a = [TestClass new];
  [a setValue: 10];

  b = [TestClass new];
  [b setValue: -10];

  [b takeValueFrom: a];

  if ([b value] != [a value])
    {
      abort ();
    }

  return 0;
}


text:
package com.blockwithme.meta.annotations;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Tells the annotation reader to "instantiate" a Class object, or
 * class-name-as-string, to an actual class instance.
 *
 * Currently, no constructor parameter is supported, and the class must have a
 * public default constructor.
 *
 * @author monster
 */
@Target(value = ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Instantiate {
    // NOP
}


text:
Editar Cuestionario

<mat-divider class="lineaDivisoria"></mat-divider>

          Titulo:
          <input style="background-color: transparent" type="text" name="nombre" requiered [(ngModel)]="titulo">

            Descripción:
            <input style="background-color: transparent; width: 450px;" type="text" name="descripcion"  requiered [(ngModel)]="descripcion">

      <button type="button"  class="btn Aceptar" (click)= "ModificarCuestionario()"> Aceptar Cambios
          check   </button>

      <button type="button" style="width: auto;" class="btn Agregar btn-block" (click) = "AbrirDialogoAgregarPreguntas()">  Añadir/Eliminar Preguntas
        post_add </button>

  <form style="width: 70%" *ngIf="preguntasCuestionarioSeleccionado;else Aviso_no_preguntas">
      <mat-form-field>
        <input matInput (keyup)="applyFilter($event.target.value)" placeholder="Filtro para buscar pregunta...">
        search
      </mat-form-field>

      <ng-container matColumnDef="tituloPregunta">
         Titulo
         {{pregunta.Titulo}}
      </ng-container>

      <ng-container matColumnDef="preguntaPregunta">
         Pregunta
         {{pregunta.Pregunta}}
      </ng-container>

      <ng-container matColumnDef="tematicaPregunta">
         Tematica
         {{pregunta.Tematica}}
      </ng-container>

  </form>

      <ng-template  #Aviso_no_preguntas>
Todavía no hay preguntas en este cuestionario.
</ng-template>

  <button type="button" class="btn Back" (click)="goBack()">Volver </button>


text:
package co.phoenixlab.hearthstone.hearthcapturelib.packets;

import co.phoenixlab.hearthstone.hearthcapturelib.GameEnums;
import co.phoenixlab.hearthstone.hearthcapturelib.packets.encoding.FieldNumber;
import co.phoenixlab.hearthstone.hearthcapturelib.packets.encoding.FieldType;

/**
 * Unknown packet. From Hearthy.
 *
 * @author Vincent Zhang
 */
public class Packet004PreCast extends CapturePacket {

    @FieldNumber(1)
    @FieldType(GameEnums.DataType.INT)
    private int entity;

    public Packet004PreCast() {
        super();
    }

    public int getEntity() {
        return entity;
    }
}


text:
Ciao {TO_USERNAME},

Di seguito è riportato un e-mail inviata da {FROM_USERNAME} tramite il tuo account su {SITENAME}. Se questo messaggio è spam, contiene commenti offensivi o altri trovi di offensivo, si prega di contattare il webmaster del consiglio di amministrazione al seguente indirizzo:

{BOARD_EMAIL}

Includere questa e-mail completo (in particolare le intestazioni). Siete pregati di notare che l'indirizzo di risposta a questa e-mail è stato impostato {FROM_USERNAME}.

Messaggio inviato a voi di seguito
~~~~~~~~~~~~~~~~~~~~~~~~~~~

{MESSAGE}


text:
package com.gufengxiachen.designpattern.Creational.factorymethod;

public class RTFDocument implements IDocument{

	public RTFDocument() {
        System.out.println("建立RTF文件");
    }

	public void close() {
		// TODO Auto-generated method stub
		System.out.println("关闭文件");
	}

	public void open() {
		// TODO Auto-generated method stub
		System.out.println("开启文件");
	}

	public void save() {
		// TODO Auto-generated method stub
		System.out.println("存储文件");
	}

}


text:
from wsgi import app

from flask import render_template, redirect, url_for, request, Response

#Para leer el archivo que subo
from werkzeug import secure_filename
#Para pasar el archivo a dataframe
from pandas import read_csv

from scipy import stats
#from estadistica import file_path, r_analisis

import os

#Path absoluto. Le agrego wsgi por que el runserver.py esta un directorio arriba.
path = os.getcwd() + '/wsgi/'

@app.route('/')
def home():
  return render_template('home.html')

@app.route('/contacto')
def contacto():
  return render_template('contacto.html')

@app.route("/get_file")
def get_file():
    f = open(path + 'data/datos3.csv', 'r')
    generator = f.readlines()

    return Response(generator,
                       mimetype="text/csv",
                       headers={"Content-Disposition":
                                    "attachment;filename=datos.csv"})

@app.route('/ejemplo')
def ejemplo():
  df_anio = read_csv(path + 'data/df_anio')
  df_meses = read_csv(path + 'data/df_meses')
  histo_breaks = read_csv(path + 'data/histo_breaks')
  histo_counts = read_csv(path + 'data/histo_counts')

  shape = df_anio['shape_year'][1]
  scale = df_anio['scale_year'][1]
  distribution = stats.exponweib(1, shape, loc = 0, scale = scale)

  y = distribution.pdf(histo_counts['mids'])

  data = []
  for i in range(8):
    data.append(df_meses[[i]].values.tolist())
  data.append(histo_breaks[[0]].values.tolist())
  for i in range(3):
    data.append(histo_counts[[i]].values.tolist())
  data.append(y.tolist())

  return render_template('analisis.html', data = data)

@app.route('/analisis', methods = ['GET', 'POST'])
def analisis():

  if request.method == 'POST':
  	# Get the FileStorage instance from request
    file = request.files['file']
    #Analisis estadistico
    new_path = file_path(file, path)
    df_anio, df_meses, histo_breaks, histo_counts = r_analisis(new_path)

    shape = df_anio['shape_year'][1]
    scale = df_anio['scale_year'][1]
    distribution = stats.exponweib(1, shape, loc = 0, scale = scale)

    y = distribution.pdf(histo_counts['mids'])

    data = []
    for i in range(8):
        data.append(df_meses[[i]].values.tolist())
    data.append(histo_breaks[[0]].values.tolist())
    for i in range(3):
        data.append(histo_counts[[i]].values.tolist())
    data.append(y.tolist())

    # Render template with file info
    return render_template('analisis.html', data = data)

  return render_template('upload.html')


text:
namespace Chamber.Domain.Interfaces
{
    public interface IModelAttribute
    {
        string Name { get; }
    }
}


text:
__author__ = 'rublog'

import logging
import requests
import os
import time
import random
from tqdm import tqdm
from fake_useragent import UserAgent

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
logger.addHandler(ch)
fh = logging.FileHandler('pdf.log')
fh.setLevel(logging.DEBUG)
fh.setFormatter(formatter)
logger.addHandler(fh)

def main():
    with open('pdf.txt', 'r') as f_pic, open('bad_pdf.log', 'w') as log:
        logger.debug("open files ok")
        lines = f_pic.readlines()
        split1 = ':80/'
        bas_dir = os.path.dirname(os.path.abspath("__file__"))
        logger.debug(bas_dir)
        for line in tqdm(lines):
            line.strip('\n\r')
            if split1 in line:
                str_name = line.split(':80/')[-1]
            else:
                str_name = line.split('0.org/')[-1]
            file_name = '/img1/' + str_name.strip()
            file_name = bas_dir + file_name
            (file_path, temp_file_name) = os.path.split(file_name)
            ua = UserAgent()
            headers = {'user-agent': ua.random,
                       'Host': 'web.archive.org',
                       'Proxy-Connection': 'keep-alive',
                       'Pragma': 'no-cache',
                       'Cache-Control': 'no-cache',
                       'Upgrade-Insecure-Requests': '1',
                       'DNT': '1',
                       'Accept': "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
                       'Accept-Encoding': "gzip, deflate",
                       'Accept-Language': "zh-CN,zh;q=0.9"
                       }
            logger.debug(file_name)
            if os.path.isfile(file_name):
                print("文件存在")
                pass
            else:
                mkdir(file_path)
                s = requests.Session()
                s.headers.update(headers)
                logger.debug(line)
                r = s.get(line, timeout=15)
                print(r.status_code)
                # print(type(r.status_code))
                if int(r.status_code) != 200:
                    log.write(line + '# status_code' + str(r.status_code) + '\n')
                else:
                    # print(r.headers['content-length'])
                    print(r.headers['X-Archive-Orig-content-length'])
                    if int(r.headers['content-length' if ('content-length' in r.headers) else 'X-Archive-Orig-content-length']) < 30:
                        log.write(line + '#请求文件太小' + '\n')
                    else:
                        with open(file_name, 'wb') as f:
                            for chunk in r.iter_content(chunk_size=1024):
                                if chunk:
                                    f.write(chunk)
                            print(file_name + "写入完毕")
                time.sleep(random.randint(2, 10))

def mkdir(path):
    if not os.path.isdir(path):
        mkdir(os.path.split(path)[0])
    else:
        return
    os.mkdir(path)

if __name__ == "__main__":
    main()


text:
package org.helianto.task.domain;

import javax.persistence.Table;
import javax.persistence.UniqueConstraint;

/**
 * Base line.
 *
 * @author mauriciofernandesdecastro
 */
@javax.persistence.Entity
@Table(name="task_baseline",
uniqueConstraints = {@UniqueConstraint(columnNames={"reportFolderId", "sequence"})}
)
public class ReportBaseLine
	extends AbstractReportFolderAggregate
{

	private static final long serialVersionUID = 1L;

	private Integer sequence;

    /**
     * Default Constructor.
     */
    public ReportBaseLine() {
		super();
	}

    /**
     * Key Constructor.
     *
     * @param reportFolder
     * @param sequence
     *
     */
	public ReportBaseLine(ReportFolder reportFolder, Integer sequence) {
		super();
		setReportFolder(reportFolder);
		setSequence(sequence);
	}

	/**
	 * Fields Constructor.
	 *
	 * @param id
	 * @param version
	 * @param reportFolder
	 * @param sequence
	 *
	 */
	public ReportBaseLine(int id, ReportFolder reportFolder, Integer sequence) {
		this(reportFolder, sequence);
		setId(id);
	}

	public ReportBaseLine setReportBaseLine(ReportBaseLine baseLine) {
		setReportFolder(baseLine.getReportFolder());
		setSequence(baseLine.getSequence());
		return this;
	}

	public Integer getSequence() {
		return sequence;
	}
	public void setSequence(Integer sequence) {
		this.sequence = sequence;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result
				+ ((getReportFolder() == null) ? 0 : getReportFolder().hashCode());
		result = prime * result
				+ ((sequence == null) ? 0 : sequence.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		ReportBaseLine other = (ReportBaseLine) obj;
		if (getReportFolder() == null) {
			if (other.getReportFolder() != null)
				return false;
		} else if (!getReportFolder().equals(other.getReportFolder()))
			return false;
		if (sequence == null) {
			if (other.sequence != null)
				return false;
		} else if (!sequence.equals(other.sequence))
			return false;
		return true;
	}

	@Override
	public String toString() {
		return "ReportBaseLine [reportFolder=" + getReportFolder() + ", sequence=" + sequence
				+ "]";
	}

}


text: <?=$this->SECTIONS->VIEWFORM->DATA->body;?>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using ConversionHelper;
using BEPUphysics.BroadPhaseEntries.MobileCollidables;
using BEPUphysics.Entities.Prefabs;
using BEPUphysics;
using BEPUphysics.CollisionShapes;
using BEPUutilities;
using Microsoft.Xna.Framework.Input;
using BEPUphysics.BroadPhaseEntries;
using Microsoft.Xna.Framework.Graphics;
using BEPUphysicsDrawer.Models;
using BEPUphysics.EntityStateManagement;
using BEPUphysics.PositionUpdating;
using BEPUphysics.NarrowPhaseSystems.Pairs;
using Particles;

namespace Trashdroids
{
    public class Missile : RenderableModel
    {
        private Capsule _collider;
        private Droid _owner;
        private Droid _target;

        private float _velocity = 20f;

        private static Nullable<Microsoft.Xna.Framework.Matrix> _defaultRootTransform = null;

        public override Microsoft.Xna.Framework.Matrix World
        {
            get
            {
                return MathConverter.Convert(_collider.WorldTransform);
            }
        }

        public Missile(TrashdroidsGame game, string model, string tag, Droid owner, Droid target, bool isLeft)
            : base(game, model)
        {
            _owner = owner;
            _target = target;

            BEPUutilities.Vector3[] vertices;
            int[] indices;

            if (_defaultRootTransform == null)
            {
                _defaultRootTransform = _model.Root.Transform;
            }
            _model.Root.Transform = (Microsoft.Xna.Framework.Matrix)_defaultRootTransform * Microsoft.Xna.Framework.Matrix.CreateScale(1 / 100f);

            ModelDataExtractor.GetVerticesAndIndicesFromModel(_model, out vertices, out indices);

            MotionState initialMotionState     = new MotionState();
            initialMotionState.LinearVelocity  = MathConverter.Convert(owner.World.Forward*_velocity);
            initialMotionState.Position        = MathConverter.Convert(owner.World.Translation + owner.World.Forward*2);
            initialMotionState.Position += MathConverter.Convert(owner.World.Up/2.35f);
            initialMotionState.Position += MathConverter.Convert((isLeft?owner.World.Left:owner.World.Right)/3f);

            initialMotionState.AngularVelocity = BEPUutilities.Vector3.Zero;
            initialMotionState.Orientation = MathConverter.Convert(Microsoft.Xna.Framework.Quaternion.Concatenate(
                    owner.Orientation,
                    Microsoft.Xna.Framework.Quaternion.CreateFromAxisAngle(owner.World.Left, (float)Math.PI / 2)
            ));

            _collider = new Capsule(initialMotionState, .75f, .05f, 1f);
            _collider.Tag = tag;
            _collider.CollisionInformation.Tag = tag;
            _collider.PositionUpdateMode = PositionUpdateMode.Continuous;

            _collider.AngularDamping = 0;
            _collider.LinearDamping = .8f;

            _collider.LinearMomentum = _collider.WorldTransform.Forward * 200;

            _collider.CollisionInformation.Events.InitialCollisionDetected += Events_InitialCollisionDetected;

            (game.Services.GetService(typeof(Space)) as Space).Add(_collider);
        }

        void Events_InitialCollisionDetected(EntityCollidable sender, Collidable other, CollidablePairHandler pair)
        {
            if (!(other.Tag.ToString().StartsWith("Missile")))
            {
                (_game.Services.GetService(typeof(Space)) as Space).Remove(_collider);
                _game.DetonateMissile(this);
            }
            if (other.Tag.ToString().StartsWith("Asteroid"))
            {
                if (TrashdroidsGame.ASTEROIDS_DESTRUCTABLE)
                {
                    _game.AsteroidExplode(other.Tag.ToString());
                }
            }
        }

        //Removes this model from simulation
        public void Destroy()
        {
            (_game.Services.GetService(typeof(Space)) as Space).Remove(_collider);
        }

        public void Update(GameTime gameTime)
        {
            if (_game.GameState == GameState.IN_GAME_MULTIPLAYER)
            {
                //Homing!
                BEPUutilities.Vector3 targetPos;

                if (_target != null)
                {
                    targetPos = MathConverter.Convert(
                        Microsoft.Xna.Framework.Vector3.Transform(_target.World.Translation - World.Translation, Microsoft.Xna.Framework.Matrix.Invert(MathConverter.Convert(_collider.OrientationMatrix))));
                }
                else
                {
                    targetPos = MathConverter.Convert(
                        Microsoft.Xna.Framework.Vector3.Transform(-World.Translation, Microsoft.Xna.Framework.Matrix.Invert(MathConverter.Convert(_collider.WorldTransform))));
                }

                _collider.AngularMomentum = BEPUutilities.Vector3.Zero;

                if (targetPos.X < 0)
                {
                    _collider.AngularMomentum -= MathConverter.Convert(this.World.Forward * _owner.HeatSeekingStrength);
                }
                else if (targetPos.X > 0)
                {
                    _collider.AngularMomentum += MathConverter.Convert(this.World.Forward * _owner.HeatSeekingStrength);
                }

                if (targetPos.Z < 0)
                {
                    _collider.AngularMomentum -= MathConverter.Convert(this.World.Right * _owner.HeatSeekingStrength);
                }
                else if (targetPos.Z > 0)
                {
                    _collider.AngularMomentum += MathConverter.Convert(this.World.Right * _owner.HeatSeekingStrength);
                }
            }

            _game.CreateMissileTrailEffect(World.Translation);
            _collider.LinearVelocity = MathConverter.Convert(this.World.Up * Math.Max(_velocity, _collider.LinearVelocity.Length()));
        }
    }
}


text:
// Copyright (c) 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
const ResourceLoader = {};
export default ResourceLoader;

let _lastStreamId = 0;

/** @type {!Object.<number, !Common.OutputStream>} */
const _boundStreams = {};

/**
 * @param {!Common.OutputStream} stream
 * @return {number}
 */
const _bindOutputStream = function(stream) {
  _boundStreams[++_lastStreamId] = stream;
  return _lastStreamId;
};

/**
 * @param {number} id
 */
const _discardOutputStream = function(id) {
  _boundStreams[id].close();
  delete _boundStreams[id];
};

/**
 * @param {number} id
 * @param {string} chunk
 */
export const streamWrite = function(id, chunk) {
  _boundStreams[id].write(chunk);
};

/**
 * @param {string} url
 * @param {?Object.<string, string>} headers
 * @param {function(number, !Object.<string, string>, string, number)} callback
 */
export function load(url, headers, callback) {
  const stream = new Common.StringOutputStream();
  loadAsStream(url, headers, stream, mycallback);

  /**
   * @param {number} statusCode
   * @param {!Object.<string, string>} headers
   * @param {number} netError
   */
  function mycallback(statusCode, headers, netError) {
    callback(statusCode, headers, stream.data(), netError);
  }
}

/**
 * @param {string} url
 * @param {?Object.<string, string>} headers
 * @param {!Common.OutputStream} stream
 * @param {function(number, !Object.<string, string>, number)=} callback
 */
export const loadAsStream = function(url, headers, stream, callback) {
  const streamId = _bindOutputStream(stream);
  const parsedURL = new Common.ParsedURL(url);
  if (parsedURL.isDataURL()) {
    loadXHR(url).then(dataURLDecodeSuccessful).catch(dataURLDecodeFailed);
    return;
  }

  const rawHeaders = [];
  if (headers) {
    for (const key in headers) {
      rawHeaders.push(key + ': ' + headers[key]);
    }
  }
  Host.InspectorFrontendHost.loadNetworkResource(url, rawHeaders.join('\r\n'), streamId, finishedCallback);

  /**
   * @param {!InspectorFrontendHostAPI.LoadNetworkResourceResult} response
   */
  function finishedCallback(response) {
    if (callback) {
      callback(response.statusCode, response.headers || {}, response.netError || 0);
    }
    _discardOutputStream(streamId);
  }

  /**
   * @param {string} text
   */
  function dataURLDecodeSuccessful(text) {
    streamWrite(streamId, text);
    finishedCallback(/** @type {!InspectorFrontendHostAPI.LoadNetworkResourceResult} */ ({statusCode: 200}));
  }

  function dataURLDecodeFailed() {
    finishedCallback(/** @type {!InspectorFrontendHostAPI.LoadNetworkResourceResult} */ ({statusCode: 404}));
  }
};

/* Legacy exported object */
self.Host = self.Host || {};

/* Legacy exported object */
Host = Host || {};

Host.ResourceLoader = ResourceLoader;

/**
 * @param {number} id
 * @param {string} chunk
 */
Host.ResourceLoader.streamWrite = streamWrite;

/**
 * @param {string} url
 * @param {?Object.<string, string>} headers
 * @param {function(number, !Object.<string, string>, string, number)} callback
 */
Host.ResourceLoader.load = load;

/**
 * @param {string} url
 * @param {?Object.<string, string>} headers
 * @param {!Common.OutputStream} stream
 * @param {function(number, !Object.<string, string>, number)=} callback
 */
Host.ResourceLoader.loadAsStream = loadAsStream;


text:
package org.broadleafcommerce.core.web.api.wrapper;

import java.io.Serializable;

import javax.servlet.http.HttpServletRequest;

/**
 * This interface is the super interface for all classes that will provide a JAXB wrapper
 * around classes.  Any class that will be exposed via JAXB annotations to the JAXRS API
 * may implement this as a convenience to provide a standard method to populate data objects.
 *
 * This is not a requirement as objects will not generally be passed using a reference to this
 * interface.
 * @param <T>
 */
public interface APIWrapper<T> extends Serializable {

    public void wrapDetails(T model, HttpServletRequest request);

    public void wrapSummary(T model, HttpServletRequest request);

}


text:
define('mp-01-web/tests/routes/votes.jshint', ['exports'], function (exports) {
  'use strict';

  QUnit.module('JSHint | routes/votes.js');
  QUnit.test('should pass jshint', function (assert) {
    assert.expect(1);
    assert.ok(true, 'routes/votes.js should pass jshint.');
  });
});


text:
package quickfix

import (
	"bytes"
	"fmt"
	"math"
	"time"

	"github.com/quickfixgo/quickfix/enum"
)

//Header is first section of a FIX Message
type Header struct{ FieldMap }

//in the message header, the first 3 tags in the message header must be 8,9,35
func headerFieldOrdering(i, j Tag) bool {
	var ordering = func(t Tag) uint32 {
		switch t {
		case tagBeginString:
			return 1
		case tagBodyLength:
			return 2
		case tagMsgType:
			return 3
		}

		return math.MaxUint32
	}

	orderi := ordering(i)
	orderj := ordering(j)

	switch {
	case orderi < orderj:
		return true
	case orderi > orderj:
		return false
	}

	return i < j
}

//Init initializes the Header instance
func (h *Header) Init() {
	h.initWithOrdering(headerFieldOrdering)
}

//Body is the primary application section of a FIX message
type Body struct{ FieldMap }

//Init initializes the FIX message
func (b *Body) Init() {
	b.init()
}

//Trailer is the last section of a FIX message
type Trailer struct{ FieldMap }

// In the trailer, CheckSum (tag 10) must be last
func trailerFieldOrdering(i, j Tag) bool {
	switch {
	case i == tagCheckSum:
		return false
	case j == tagCheckSum:
		return true
	}

	return i < j
}

//Init initializes the FIX message
func (t *Trailer) Init() {
	t.initWithOrdering(trailerFieldOrdering)
}

//Message is a FIX Message abstraction.
type Message struct {
	Header  Header
	Trailer Trailer
	Body    Body

	//ReceiveTime is the time that this message was read from the socket connection
	ReceiveTime time.Time

	rawMessage *bytes.Buffer

	//slice of Bytes corresponding to the message body
	bodyBytes []byte

	//field bytes as they appear in the raw message
	fields []TagValue

	//flag is true if this message should not be returned to pool after use
	keepMessage bool
}

//ToMessage returns the message itself
func (m *Message) ToMessage() *Message { return m }

//parseError is returned when bytes cannot be parsed as a FIX message.
type parseError struct {
	OrigError string
}

func (e parseError) Error() string { return fmt.Sprintf("error parsing message: %s", e.OrigError) }

//NewMessage returns a newly initialized Message instance
func NewMessage() *Message {
	m := new(Message)
	m.Header.Init()
	m.Body.Init()
	m.Trailer.Init()

	return m
}

//ParseMessage constructs a Message from a byte slice wrapping a FIX message.
func ParseMessage(msg *Message, rawMessage *bytes.Buffer) (err error) {
	msg.Header.Clear()
	msg.Body.Clear()
	msg.Trailer.Clear()
	msg.rawMessage = rawMessage

	rawBytes := rawMessage.Bytes()

	//allocate fields in one chunk
	fieldCount := 0
	for _, b := range rawBytes {
		if b == '\001' {
			fieldCount++
		}
	}

	if cap(msg.fields) < fieldCount {
		msg.fields = make([]TagValue, fieldCount)
	} else {
		msg.fields = msg.fields[0:fieldCount]
	}

	fieldIndex := 0

	//message must start with begin string, body length, msg type
	if rawBytes, err = extractSpecificField(&msg.fields[fieldIndex], tagBeginString, rawBytes); err != nil {
		return
	}

	msg.Header.add(msg.fields[fieldIndex : fieldIndex+1])
	fieldIndex++

	parsedFieldBytes := &msg.fields[fieldIndex]
	if rawBytes, err = extractSpecificField(parsedFieldBytes, tagBodyLength, rawBytes); err != nil {
		return
	}

	msg.Header.add(msg.fields[fieldIndex : fieldIndex+1])
	fieldIndex++

	parsedFieldBytes = &msg.fields[fieldIndex]
	if rawBytes, err = extractSpecificField(parsedFieldBytes, tagMsgType, rawBytes); err != nil {
		return
	}

	msg.Header.add(msg.fields[fieldIndex : fieldIndex+1])
	fieldIndex++

	trailerBytes := []byte{}
	foundBody := false
	for {
		parsedFieldBytes = &msg.fields[fieldIndex]
		rawBytes, err = extractField(parsedFieldBytes, rawBytes)
		if err != nil {
			return
		}

		switch {
		case parsedFieldBytes.tag.IsHeader():
			msg.Header.add(msg.fields[fieldIndex : fieldIndex+1])
		case parsedFieldBytes.tag.IsTrailer():
			msg.Trailer.add(msg.fields[fieldIndex : fieldIndex+1])
		default:
			foundBody = true
			trailerBytes = rawBytes
			msg.Body.add(msg.fields[fieldIndex : fieldIndex+1])
		}
		if parsedFieldBytes.tag == tagCheckSum {
			break
		}

		if !foundBody {
			msg.bodyBytes = rawBytes
		}

		fieldIndex++
	}

	//body length would only be larger than trailer if fields out of order
	if len(msg.bodyBytes) > len(trailerBytes) {
		msg.bodyBytes = msg.bodyBytes[:len(msg.bodyBytes)-len(trailerBytes)]
	}

	length := 0
	for _, field := range msg.fields {
		switch field.tag {
		case tagBeginString, tagBodyLength, tagCheckSum: //tags do not contribute to length
		default:
			length += field.length()
		}
	}

	bodyLength, err := msg.Header.GetInt(tagBodyLength)
	if err != nil {
		err = parseError{OrigError: err.Error()}
	} else if length != bodyLength {
		err = parseError{OrigError: fmt.Sprintf("Incorrect Message Length, expected %d, got %d", bodyLength, length)}
	}

	return
}

// MsgType returns MsgType (tag 35) field's value
func (m *Message) MsgType() (enum.MsgType, MessageRejectError) {
	s, err := m.Header.GetString(tagMsgType)
	if err != nil {
		return enum.MsgType(""), err
	}
	return enum.MsgType(s), nil
}

// IsMsgTypeOf returns true if the Header contains MsgType (tag 35) field and its value is the specified one.
func (m *Message) IsMsgTypeOf(msgType enum.MsgType) bool {
	if v, err := m.MsgType(); err == nil {
		return v == msgType
	}
	return false
}

//reverseRoute returns a message builder with routing header fields initialized as the reverse of this message.
func (m *Message) reverseRoute() *Message {
	reverseMsg := NewMessage()

	copy := func(src Tag, dest Tag) {
		var field FIXString
		if m.Header.GetField(src, &field) == nil {
			if len(field) != 0 {
				reverseMsg.Header.SetField(dest, field)
			}
		}
	}

	copy(tagSenderCompID, tagTargetCompID)
	copy(tagSenderSubID, tagTargetSubID)
	copy(tagSenderLocationID, tagTargetLocationID)

	copy(tagTargetCompID, tagSenderCompID)
	copy(tagTargetSubID, tagSenderSubID)
	copy(tagTargetLocationID, tagSenderLocationID)

	copy(tagOnBehalfOfCompID, tagDeliverToCompID)
	copy(tagOnBehalfOfSubID, tagDeliverToSubID)
	copy(tagDeliverToCompID, tagOnBehalfOfCompID)
	copy(tagDeliverToSubID, tagOnBehalfOfSubID)

	//tags added in 4.1
	var beginString FIXString
	if m.Header.GetField(tagBeginString, &beginString) == nil {
		if string(beginString) != enum.BeginStringFIX40 {
			copy(tagOnBehalfOfLocationID, tagDeliverToLocationID)
			copy(tagDeliverToLocationID, tagOnBehalfOfLocationID)
		}
	}

	return reverseMsg
}

func extractSpecificField(field *TagValue, expectedTag Tag, buffer []byte) (remBuffer []byte, err error) {
	remBuffer, err = extractField(field, buffer)
	switch {
	case err != nil:
		return
	case field.tag != expectedTag:
		err = parseError{OrigError: fmt.Sprintf("extractSpecificField: Fields out of order, expected %d, got %d", expectedTag, field.tag)}
		return
	}

	return
}

func extractField(parsedFieldBytes *TagValue, buffer []byte) (remBytes []byte, err error) {
	endIndex := bytes.IndexByte(buffer, '\001')
	if endIndex == -1 {
		err = parseError{OrigError: "extractField: No Trailing Delim in " + string(buffer)}
		remBytes = buffer
		return
	}

	err = parsedFieldBytes.parse(buffer[:endIndex+1])
	return buffer[(endIndex + 1):], err
}

func (m *Message) String() string {
	if m.rawMessage != nil {
		return m.rawMessage.String()
	}

	return string(m.build())
}

func formatCheckSum(value int) string {
	return fmt.Sprintf("%03d", value)
}

//Build constructs a []byte from a Message instance
func (m *Message) build() []byte {
	m.cook()

	var b bytes.Buffer
	m.Header.write(&b)
	m.Body.write(&b)
	m.Trailer.write(&b)
	return b.Bytes()
}

func (m *Message) cook() {
	bodyLength := m.Header.length() + m.Body.length() + m.Trailer.length()
	m.Header.SetInt(tagBodyLength, bodyLength)
	checkSum := (m.Header.total() + m.Body.total() + m.Trailer.total()) % 256
	m.Trailer.SetString(tagCheckSum, formatCheckSum(checkSum))
}


text:
var minDom = require('../../'),
    remove = minDom.remove,
    domify = minDom.domify;

describe('remove', function() {

  it('should remove element', function() {

    var node = domify('

');
    var child = node.childNodes[0];

    // when
    remove(child);

    expect(node.childNodes.length).to.eql(0);
    expect(child.parentNode).not.to.exist;
  });

});


text:
package de.chrlembeck.codegen.generator.lang;

import de.chrlembeck.codegen.generator.Environment;
import de.chrlembeck.codegen.grammar.CodeGenParser.ExpressionSignContext;

/**
 * Repräsentiert die unären numerischen Vorzeichenoperationen Plus und Minus.
 *
 * @author Christoph Lembeck
 */
public class SignExpression extends AbstractExpression<ExpressionSignContext> {

    /**
     * Mögliche Vorzeichen für die SignExpression.
     *
     * @author Christoph Lembeck
     */
    public enum Operator {

        /**
         * Positives Vorzeichen Plus.
         */
        PLUS,

        /**
         * Negatives Vorzeichen Minus.
         */
        MINUS
    }

    /**
     * Gewünschter Operator für die Vorzeichen-Operation (Plus oder Minus).
     */
    private Operator operator;

    /**
     * Ausdruck des Operanden, auf den die Vorzeichen-Operation angewandt werden soll.
     */
    private Expression expression;

    /**
     * Erzeugt eine neue SignExpression mit den übergebenen Werten.
     *
     * @param ctx
     *            Kontext, wie ihn der Parser beim Lesen der Template-Datei erzeugt hat.
     * @param expression
     *            Ausdruck für die Vorzeichen-Operation.
     * @param operator
     *            Gewünschter Operator für die Funktion (Plus oder Minus).
     */
    public SignExpression(final ExpressionSignContext ctx, final Operator operator, final Expression expression) {
        super(ctx);
        this.operator = operator;
        this.expression = expression;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public ObjectWithType<?> evaluate(final Object model, final Environment environment) {
        final ObjectWithType<?> exp = expression.evaluate(model, environment);
        final Number number = (Number) exp.getObject();
        Number result;
        if (operator == Operator.PLUS) {
            result = number;
        } else if (number instanceof Double) {
            result = Double.valueOf(-number.doubleValue());
        } else if (number instanceof Float) {
            result = Float.valueOf(-number.floatValue());
        } else if (number instanceof Long) {
            result = Long.valueOf(-number.longValue());
        } else if (number instanceof Integer) {
            result = Integer.valueOf(-number.intValue());
        } else {
            throw new RuntimeException("unkonwn type " + number.getClass().getName());
        }
        final Class<?> type = exp.getType();
        @SuppressWarnings({ "unchecked", "rawtypes" })
        final ObjectWithType<?> owt = new ObjectWithType(result, type);
        return owt;
    }
}


text:
SYNONYM

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

#### Published in
Minn. bot. Stud. 1(Bulletin 9): 660 (1896)

#### Original name
Chromosporium lateritium Cooke & Harkn., 1881

### Remarks
null


text: fw_depends play2 java


text:
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>BOOST_TEST_MAIN</title>
<link rel="stylesheet" href="../../../boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.76.1">
<link rel="home" href="../../../index.html" title="Boost.Test">
<link rel="up" href="../link_references.html" title="Build scenarios and behaviors">
<link rel="prev" href="../link_references.html" title="Build scenarios and behaviors">
<link rel="next" href="link_boost_test_module_macro.html" title="BOOST_TEST_MODULE">

Home
Libraries
People
FAQ
More

BOOST_TEST_MAIN

          When defined, this macro creates a stub for the test module initialization
          (the main entry part). This macro also expands properly into a main function in case the shared library
          variant of the Unit Test Framework is used.

Caution

            This macro should

                be defined before any inclusion directive to Unit Test
                Framework headers

                be defined exactly for one compilation unit of your test module

Tip

            The macro BOOST_TEST_MODULE should be
            preferred

Copyright © 2001-2016 Boost.Test contributors

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)


text:
package jack.rm.gui;

import java.awt.Component;

import javax.swing.JOptionPane;

public class Dialogs
{
  public static void showMessage(String title, String message, Component parent)
  {
    JOptionPane.showMessageDialog(parent, message, title, JOptionPane.INFORMATION_MESSAGE);
  }

  public static void showWarning(String title, String message, Component parent)
  {
    JOptionPane.showMessageDialog(parent, message, title, JOptionPane.WARNING_MESSAGE);
  }

  public static void showError(String title, String message, Component parent)
  {
    JOptionPane.showMessageDialog(parent, message, title, JOptionPane.ERROR_MESSAGE);
  }

  public static void showQuestion(String title, String message, Component parent, Runnable callback)
  {
    if (JOptionPane.showConfirmDialog(parent, message, title, JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
      callback.run();
  }
}