text:
import {Attribute, ChangeDetectorRef, ElementRef, Host, InjectFlags, Optional, Renderer2, Self, SkipSelf, TemplateRef, ViewContainerRef, defineInjectable} from '@angular/core';
import {RenderFlags} from '@angular/core/src/render3/interfaces/definition';

import {defineComponent} from '../../src/render3/definition';
import {bloomAdd, bloomFindPossibleInjector, getOrCreateNodeInjector, injectAttribute} from '../../src/render3/di';
import {NgOnChangesFeature, PublicFeature, defineDirective, directiveInject, injectChangeDetectorRef, injectElementRef, injectRenderer2, injectTemplateRef, injectViewContainerRef} from '../../src/render3/index';
import {bind, container, containerRefreshEnd, containerRefreshStart, createNodeAtIndex, createLViewData, createTView, element, elementEnd, elementStart, embeddedViewEnd, embeddedViewStart, enterView, interpolation2, leaveView, projection, projectionDef, reference, template, text, textBinding, loadDirective, elementContainerStart, elementContainerEnd} from '../../src/render3/instructions';
import {LInjector} from '../../src/render3/interfaces/injector';
import {isProceduralRenderer} from '../../src/render3/interfaces/renderer';
import {AttributeMarker, TNodeType} from '../../src/render3/interfaces/node';

import {LViewFlags} from '../../src/render3/interfaces/view';
import {ViewRef} from '../../src/render3/view_ref';

import {getRendererFactory2} from './imported_renderer2';
import {ComponentFixture, createComponent, createDirective, renderComponent, toHtml} from './render_util';

describe('di', () => {
  describe('no dependencies', () => {
    it('should create directive with no deps', () => {
      class Directive {
        value: string = 'Created';
        static ngDirectiveDef = defineDirective({
          type: Directive,
          selectors: [['', 'dir', '']],
          factory: () => new Directive,
          exportAs: 'dir'
        });
      }

      /**
 {{ dir.value }}
 */
      const App = createComponent('app', function(rf: RenderFlags, ctx: any) {
        if (rf & RenderFlags.Create) {
          elementStart(0, 'div', ['dir', ''], ['dir', 'dir']);
          { text(2); }
          elementEnd();
        }
        if (rf & RenderFlags.Update) {
          const tmp = reference(1) as any;
          textBinding(2, bind(tmp.value));
        }
      }, 3, 1, [Directive]);

      const fixture = new ComponentFixture(App);
      expect(fixture.html).toEqual('
Created
');
    });
  });

  describe('directive injection', () => {
    let log: string[] = [];

    class DirB {
      value = 'DirB';
      constructor() { log.push(this.value); }

      static ngDirectiveDef = defineDirective({
        selectors: [['', 'dirB', '']],
        type: DirB,
        factory: () => new DirB(),
        features: [PublicFeature]
      });
    }

    beforeEach(() => log = []);

    it('should create directive with intra view dependencies', () => {
      class DirA {
        value: string = 'DirA';
        static ngDirectiveDef = defineDirective({
          type: DirA,
          selectors: [['', 'dirA', '']],
          factory: () => new DirA(),
          features: [PublicFeature]
        });
      }

      class DirC {
        value: string;
        constructor(a: DirA, b: DirB) { this.value = a.value + b.value; }
        static ngDirectiveDef = defineDirective({
          type: DirC,
          selectors: [['', 'dirC', '']],
          factory: () => new DirC(directiveInject(DirA), directiveInject(DirB)),
          exportAs: 'dirC'
        });
      }

      /**
       *

       *   {{ dir.value }}
       *

       */
      const App = createComponent('app', function(rf: RenderFlags, ctx: any) {
        if (rf & RenderFlags.Create) {
          elementStart(0, 'div', ['dirA', '']);
          {
            elementStart(1, 'span', ['dirB', '', 'dirC', ''], ['dir', 'dirC']);
            { text(3); }
            elementEnd();
          }
          elementEnd();
        }
        if (rf & RenderFlags.Update) {
          const tmp = reference(2) as any;
          textBinding(3, bind(tmp.value));
        }
      }, 4, 1, [DirA, DirB, DirC]);

      const fixture = new ComponentFixture(App);
      expect(fixture.html).toEqual('
DirADirB
');
    });

    it('should instantiate injected directives in dependency order', () => {
      class DirA {
        constructor(dir: DirB) { log.push(`DirA (dep: ${dir.value})`); }

        static ngDirectiveDef = defineDirective({
          selectors: [['', 'dirA', '']],
          type: DirA,
          factory: () => new DirA(directiveInject(DirB)),
        });
      }

      /**

 */
      const App = createComponent('app', function(rf: RenderFlags, ctx: any) {
        if (rf & RenderFlags.Create) {
          element(0, 'div', ['dirA', '', 'dirB', '']);
        }
      }, 1, 0, [DirA, DirB]);

      new ComponentFixture(App);
      expect(log).toEqual(['DirB', 'DirA (dep: DirB)']);
    });

    it('should fallback to the module injector', () => {
      class DirA {
        constructor(dir: DirB) { log.push(`DirA (dep: ${dir.value})`); }

        static ngDirectiveDef = defineDirective({
          selectors: [['', 'dirA', '']],
          type: DirA,
          factory: () => new DirA(directiveInject(DirB)),
        });
      }

      // `<div dirB></div><div dirA></div>`
      // - dirB is know to the node injectors (it uses the diPublic feature)
      // - then when dirA tries to inject dirB, it will check the node injector first tree
      // - if not found, it will check the module injector tree
      const App = createComponent('app', function(rf: RenderFlags, ctx: any) {
        if (rf & RenderFlags.Create) {
          element(0, 'div', ['dirB', '']);
          element(1, 'div', ['dirA', '']);
        }
      }, 2, 0, [DirA, DirB]);

      const fakeModuleInjector: any = {
        get: function(token: any) {
          const value = token === DirB ? 'module' : 'fail';
          return {value: value};
        }
      };

      new ComponentFixture(App, {injector: fakeModuleInjector});
      expect(log).toEqual(['DirB', 'DirA (dep: module)']);
    });

    it('should instantiate injected directives before components', () => {
      class Comp {
        constructor(dir: DirB) { log.push(`Comp (dep: ${dir.value})`); }

        static ngComponentDef = defineComponent({
          selectors: [['comp']],
          type: Comp,
          consts: 0,
          vars: 0,
          factory: () => new Comp(directiveInject(DirB)),
          template: (ctx: any, fm: boolean) => {}
        });
      }

      /** <comp dirB></comp> */
      const App = createComponent('app', function(rf: RenderFlags, ctx: any) {
        if (rf & RenderFlags.Create) {
          element(0, 'comp', ['dirB', '']);
        }
      }, 1, 0, [Comp, DirB]);

      new ComponentFixture(App);
      expect(log).toEqual(['DirB', 'Comp (dep: DirB)']);
    });

    it('should inject directives in the correct order in a for loop', () => {
      class DirA {
        constructor(dir: DirB) { log.push(`DirA (dep: ${dir.value})`); }

        static ngDirectiveDef = defineDirective({
          selectors: [['', 'dirA', '']],
          type: DirA,
          factory: () => new DirA(directiveInject(DirB))
        });
      }

      /**
       * % for(let i = 0; i < 3; i++) {
       *

       * % }
       */
      const App = createComponent('app', function(rf: RenderFlags, ctx: any) {
        if (rf & RenderFlags.Create) {
          container(0);
        }
        if (rf & RenderFlags.Update) {
          containerRefreshStart(0);
          {
            for (let i = 0; i < 3; i++) {
              if (embeddedViewStart(0, 1, 0)) {
                element(0, 'div', ['dirA', '', 'dirB', '']);
              }
              embeddedViewEnd();
            }
          }
          containerRefreshEnd();
        }
      }, 1, 0, [DirA, DirB]);

      new ComponentFixture(App);
      expect(log).toEqual(
          ['DirB', 'DirA (dep: DirB)', 'DirB', 'DirA (dep: DirB)', 'DirB', 'DirA (dep: DirB)']);
    });

    it('should instantiate directives with multiple out-of-order dependencies', () => {
      class DirA {
        value = 'DirA';
        constructor() { log.push(this.value); }

        static ngDirectiveDef = defineDirective({
          selectors: [['', 'dirA', '']],
          type: DirA,
          factory: () => new DirA(),
          features: [PublicFeature]
        });
      }

      class DirB {
        constructor(dirA: DirA, dirC: DirC) {
          log.push(`DirB (deps: ${dirA.value} and ${dirC.value})`);
        }

        static ngDirectiveDef = defineDirective({
          selectors: [['', 'dirB', '']],
          type: DirB,
          factory: () => new DirB(directiveInject(DirA), directiveInject(DirC))
        });
      }

      class DirC {
        value = 'DirC';
        constructor() { log.push(this.value); }

        static ngDirectiveDef = defineDirective({
          selectors: [['', 'dirC', '']],
          type: DirC,
          factory: () => new DirC(),
          features: [PublicFeature]
        });
      }

      /**

 */
      const App = createComponent('app', function(rf: RenderFlags, ctx: any) {
        if (rf & RenderFlags.Create) {
          element(0, 'div', ['dirA', '', 'dirB', '', 'dirC', '']);
        }
      }, 1, 0, [DirA, DirB, DirC]);

      new ComponentFixture(App);
      expect(log).toEqual(['DirA', 'DirC', 'DirB (deps: DirA and DirC)']);
    });

    it('should instantiate in the correct order for complex case', () => {
      class Comp {
        constructor(dir: DirD) { log.push(`Comp (dep: ${dir.value})`); }

        static ngComponentDef = defineComponent({
          selectors: [['comp']],
          type: Comp,
          consts: 0,
          vars: 0,
          factory: () => new Comp(directiveInject(DirD)),
          template: (ctx: any, fm: boolean) => {}
        });
      }

      class DirA {
        value = 'DirA';
        constructor(dir: DirC) { log.push(`DirA (dep: ${dir.value})`); }

        static ngDirectiveDef = defineDirective({
          selectors: [['', 'dirA', '']],
          type: DirA,
          factory: () => new DirA(directiveInject(DirC)),
          features: [PublicFeature]
        });
      }

      class DirC {
        value = 'DirC';
        constructor(dir: DirB) { log.push(`DirC (dep: ${dir.value})`); }

        static ngDirectiveDef = defineDirective({
          selectors: [['', 'dirC', '']],
          type: DirC,
          factory: () => new DirC(directiveInject(DirB)),
          features: [PublicFeature]
        });
      }

      class DirD {
        value = 'DirD';
        constructor(dir: DirA) { log.push(`DirD (dep: ${dir.value})`); }

        static ngDirectiveDef = defineDirective({
          selectors: [['', 'dirD', '']],
          type: DirD,
          factory: () => new DirD(directiveInject(DirA)),
          features: [PublicFeature]
        });
      }

      /** <comp dirA dirB dirC dirD></comp> */
      const App = createComponent('app', function(rf: RenderFlags, ctx: any) {
        if (rf & RenderFlags.Create) {
          element(0, 'comp', ['dirA', '', 'dirB', '', 'dirC', '', 'dirD', '']);
        }
      }, 1, 0, [Comp, DirA, DirB, DirC, DirD]);

      new ComponentFixture(App);
      expect(log).toEqual(
          ['DirB', 'DirC (dep: DirB)', 'DirA (dep: DirC)', 'DirD (dep: DirA)', 'Comp (dep: DirD)']);
    });

    it('should instantiate in correct order with mixed parent and peer dependencies', () => {
      class DirA {
        constructor(dirB: DirB, app: App) {
          log.push(`DirA (deps: ${dirB.value} and ${app.value})`);
        }

        static ngDirectiveDef = defineDirective({
          selectors: [['', 'dirA', '']],
          type: DirA,
          factory: () => new DirA(directiveInject(DirB), directiveInject(App)),
        });
      }

      class App {
        value = 'App';

        static ngComponentDef = defineComponent({
          selectors: [['app']],
          type: App,
          factory: () => new App(),
          consts: 1,
          vars: 0,
          /**

 */
          template: (rf: RenderFlags, ctx: any) => {
            if (rf & RenderFlags.Create) {
              element(0, 'div', ['dirA', '', 'dirB', '', 'dirC', 'dirC']);
            }
          },
          directives: [DirA, DirB],
          features: [PublicFeature],
        });
      }

      new ComponentFixture(App);
      expect(log).toEqual(['DirB', 'DirA (deps: DirB and App)']);
    });

    it('should not use a parent when peer dep is available', () => {
      let count = 1;

      class DirA {
        constructor(dirB: DirB) { log.push(`DirA (dep: DirB - ${dirB.count})`); }

        static ngDirectiveDef = defineDirective({
          selectors: [['', 'dirA', '']],
          type: DirA,
          factory: () => new DirA(directiveInject(DirB)),
        });
      }

      class DirB {
        count: number;

        constructor() {
          log.push(`DirB`);
          this.count = count++;
        }

        static ngDirectiveDef = defineDirective({
          selectors: [['', 'dirB', '']],
          type: DirB,
          factory: () => new DirB(),
          features: [PublicFeature],
        });
      }

      /**

 */
      const Parent = createComponent('parent', function(rf: RenderFlags, ctx: any) {
        if (rf & RenderFlags.Create) {
          element(0, 'div', ['dirA', '', 'dirB', '']);
        }
      }, 1, 0, [DirA, DirB]);

      /** <parent dirB></parent> */
      const App = createComponent('app', function(rf: RenderFlags, ctx: any) {
        if (rf & RenderFlags.Create) {
          element(0, 'parent', ['dirB', '']);
        }
      }, 1, 0, [Parent, DirB]);

      new ComponentFixture(App);
      expect(log).toEqual(['DirB', 'DirB', 'DirA (dep: DirB - 2)']);
    });

    it('should create instance even when no injector present', () => {
      class MyService {
        value = 'MyService';
        static ngInjectableDef =
            defineInjectable({providedIn: 'root', factory: () => new MyService()});
      }

      class MyComponent {
        constructor(public myService: MyService) {}
        static ngComponentDef = defineComponent({
          type: MyComponent,
          selectors: [['my-component']],
          consts: 1,
          vars: 1,
          factory: () => new MyComponent(directiveInject(MyService)),
          template: function(rf: RenderFlags, ctx: MyComponent) {
            if (rf & RenderFlags.Create) {
              text(0);
            }
            if (rf & RenderFlags.Update) {
              textBinding(0, bind(ctx.myService.value));
            }
          }
        });
      }

      const fixture = new ComponentFixture(MyComponent);
      fixture.update();
      expect(fixture.html).toEqual('MyService');
    });

    it('should throw if directive is not found anywhere', () => {
      class Dir {
        constructor(siblingDir: OtherDir) {}

        static ngDirectiveDef = defineDirective({
          selectors: [['', 'dir', '']],
          type: Dir,
          factory: () => new Dir(directiveInject(OtherDir)),
          features: [PublicFeature]
        });
      }

      class OtherDir {
        static ngDirectiveDef = defineDirective({
          selectors: [['', 'other', '']],
          type: OtherDir,
          factory: () => new OtherDir(),
          features: [PublicFeature]
        });
      }

      /**

 */
      const App = createComponent('app', function(rf: RenderFlags, ctx: any) {
        if (rf & RenderFlags.Create) {
          element(0, 'div', ['dir', '']);
        }
      }, 1, 0, [Dir, OtherDir]);

      expect(() => new ComponentFixture(App)).toThrowError(/Injector: NOT_FOUND \[OtherDir\]/);
    });

    it('should throw if directive is not found in ancestor tree', () => {
      class Dir {
        constructor(siblingDir: OtherDir) {}

        static ngDirectiveDef = defineDirective({
          selectors: [['', 'dir', '']],
          type: Dir,
          factory: () => new Dir(directiveInject(OtherDir)),
          features: [PublicFeature]
        });
      }

      class OtherDir {
        static ngDirectiveDef = defineDirective({
          selectors: [['', 'other', '']],
          type: OtherDir,
          factory: () => new OtherDir(),
          features: [PublicFeature]
        });
      }

      /**
       *

       *

       */
      const App = createComponent('app', function(rf: RenderFlags, ctx: any) {
        if (rf & RenderFlags.Create) {
          element(0, 'div', ['other', '']);
          element(1, 'div', ['dir', '']);
        }
      }, 2, 0, [Dir, OtherDir]);

      expect(() => new ComponentFixture(App)).toThrowError(/Injector: NOT_FOUND \[OtherDir\]/);
    });

    it('should throw if directives try to inject each other', () => {
      class DirA {
        constructor(dir: DirB) {}

        static ngDirectiveDef = defineDirective({
          selectors: [['', 'dirA', '']],
          type: DirA,
          factory: () => new DirA(directiveInject(DirB)),
          features: [PublicFeature]
        });
      }

      class DirB {
        constructor(dir: DirA) {}

        static ngDirectiveDef = defineDirective({
          selectors: [['', 'dirB', '']],
          type: DirB,
          factory: () => new DirB(directiveInject(DirA)),
          features: [PublicFeature]
        });
      }

      /**

 */
      const App = createComponent('app', function(rf: RenderFlags, ctx: any) {
        if (rf & RenderFlags.Create) {
          element(0, 'div', ['dirA', '', 'dirB', '']);
        }
      }, 1, 0, [DirA, DirB]);

      expect(() => new ComponentFixture(App)).toThrowError(/Cannot instantiate cyclic dependency!/);
    });

    it('should throw if directive tries to inject itself', () => {
      class Dir {
        constructor(dir: Dir) {}

        static ngDirectiveDef = defineDirective({
          selectors: [['', 'dir', '']],
          type: Dir,
          factory: () => new Dir(directiveInject(Dir)),
          features: [PublicFeature]
        });
      }

      /**

 */
      const App = createComponent('app', function(rf: RenderFlags, ctx: any) {
        if (rf & RenderFlags.Create) {
          element(0, 'div', ['dir', '']);
        }
      }, 1, 0, [Dir]);

      expect(() => new ComponentFixture(App)).toThrowError(/Cannot instantiate cyclic dependency!/);
    });

    describe('flags', () => {

      class DirB {
        // TODO(issue/24571): remove '!'.
        value !: string;

        static ngDirectiveDef = defineDirective({
          type: DirB,
          selectors: [['', 'dirB', '']],
          factory: () => new DirB(),
          inputs: {value: 'dirB'},
          features: [PublicFeature]
        });
      }

      it('should not throw if dependency is @Optional', () => {
        let dirA: DirA;

        class DirA {
          constructor(@Optional() public dirB: DirB|null) {}

          static ngDirectiveDef = defineDirective({
            type: DirA,
            selectors: [['', 'dirA', '']],
            factory: () => dirA = new DirA(directiveInject(DirB, InjectFlags.Optional))
          });
        }

        /**

 */
        const App = createComponent('app', function(rf: RenderFlags, ctx: any) {
          if (rf & RenderFlags.Create) {
            element(0, 'div', ['dirA', '']);
          }
        }, 1, 0, [DirA, DirB]);

        expect(() => {
          new ComponentFixture(App);
          expect(dirA !.dirB).toEqual(null);
        }).not.toThrow();
      });

      it('should not throw if dependency is @Optional but defined elsewhere', () => {
        let dirA: DirA;

        class DirA {
          constructor(@Optional() public dirB: DirB|null) {}

          static ngDirectiveDef = defineDirective({
            type: DirA,
            selectors: [['', 'dirA', '']],
            factory: () => dirA = new DirA(directiveInject(DirB, InjectFlags.Optional))
          });
        }

        /**
         *

         *

         */
        const App = createComponent('app', function(rf: RenderFlags, ctx: any) {
          if (rf & RenderFlags.Create) {
            element(0, 'div', ['dirB', '']);
            element(1, 'div', ['dirA', '']);
          }
        }, 2, 0, [DirA, DirB]);

        expect(() => {
          new ComponentFixture(App);
          expect(dirA !.dirB).toEqual(null);
        }).not.toThrow();
      });

      it('should skip the current node with @SkipSelf', () => {
        let dirA: DirA;

        class DirA {
          constructor(@SkipSelf() public dirB: DirB) {}

          static ngDirectiveDef = defineDirective({
            type: DirA,
            selectors: [['', 'dirA', '']],
            factory: () => dirA = new DirA(directiveInject(DirB, InjectFlags.SkipSelf))
          });
        }

        /**

 */
        const Comp = createComponent('comp', function(rf: RenderFlags, ctx: any) {
          if (rf & RenderFlags.Create) {
            element(0, 'div', ['dirA', '', 'dirB', 'self']);
          }
        }, 1, 0, [DirA, DirB]);

        /* <comp dirB="parent"></comp> */
        const App = createComponent('app', function(rf: RenderFlags, ctx: any) {
          if (rf & RenderFlags.Create) {
            element(0, 'comp', ['dirB', 'parent']);
          }
        }, 1, 0, [Comp, DirB]);

        new ComponentFixture(App);
        expect(dirA !.dirB.value).toEqual('parent');
      });

      it('should check only the current node with @Self', () => {
        let dirA: DirA;

        class DirA {
          constructor(@Self() public dirB: DirB) {}

          static ngDirectiveDef = defineDirective({
            type: DirA,
            selectors: [['', 'dirA', '']],
            factory: () => dirA = new DirA(directiveInject(DirB, InjectFlags.Self))
          });
        }

        /**
         *

         *

         *

         */
        const App = createComponent('app', function(rf: RenderFlags, ctx: any) {
          if (rf & RenderFlags.Create) {
            elementStart(0, 'div', ['dirB', '']);
            element(1, 'div', ['dirA', '']);
            elementEnd();
          }
        }, 2, 0, [DirA, DirB]);

        expect(() => { new ComponentFixture(App); }).toThrowError(/Injector: NOT_FOUND \[DirB\]/);
      });

      it('should check only the current node with @Self even with false positive', () => {
        let dirA: DirA;

        class DirA {
          constructor(@Self() public dirB: DirB) {}

          static ngDirectiveDef = defineDirective({
            type: DirA,
            selectors: [['', 'dirA', '']],
            factory: () => dirA = new DirA(directiveInject(DirB, InjectFlags.Self))
          });
        }

        const DirC = createDirective('dirC');

        /**
         *

         *

         *

         */
        const App = createComponent('app', function(rf: RenderFlags, ctx: any) {
          if (rf & RenderFlags.Create) {
            elementStart(0, 'div', ['dirB', '']);
            element(1, 'div', ['dirA', '', 'dirC', '']);
            elementEnd();
          }
        }, 2, 0, [DirA, DirB, DirC]);

        expect(() => {
          (DirA as any)['__NG_ELEMENT_ID__'] = 1;
          (DirC as any)['__NG_ELEMENT_ID__'] = 257;
          new ComponentFixture(App);
        }).toThrowError(/Injector: NOT_FOUND \[DirB\]/);
      });

      it('should not pass component boundary with @Host', () => {
        let dirA: DirA;

        class DirA {
          constructor(@Host() public dirB: DirB) {}

          static ngDirectiveDef = defineDirective({
            type: DirA,
            selectors: [['', 'dirA', '']],
            factory: () => dirA = new DirA(directiveInject(DirB, InjectFlags.Host))
          });
        }

        /**

 */
        const Comp = createComponent('comp', function(rf: RenderFlags, ctx: any) {
          if (rf & RenderFlags.Create) {
            element(0, 'div', ['dirA', '']);
          }
        }, 1, 0, [DirA, DirB]);

        /* <comp dirB></comp> */
        const App = createComponent('app', function(rf: RenderFlags, ctx: any) {
          if (rf & RenderFlags.Create) {
            element(0, 'comp', ['dirB', '']);
          }
        }, 1, 0, [Comp, DirB]);

        expect(() => { new ComponentFixture(App); }).toThrowError(/Injector: NOT_FOUND \[DirB\]/);

      });

    });

  });

  describe('ElementRef', () => {
    it('should create directive with ElementRef dependencies', () => {
      class Directive {
        value: string;
        constructor(public elementRef: ElementRef) {
          this.value = (elementRef.constructor as any).name;
        }
        static ngDirectiveDef = defineDirective({
          type: Directive,
          selectors: [['', 'dir', '']],
          factory: () => new Directive(injectElementRef()),
          features: [PublicFeature],
          exportAs: 'dir'
        });
      }

      class DirectiveSameInstance {
        value: boolean;
        constructor(elementRef: ElementRef, directive: Directive) {
          this.value = (elementRef === directive.elementRef) && elementRef instanceof ElementRef;
        }
        static ngDirectiveDef = defineDirective({
          type: DirectiveSameInstance,
          selectors: [['', 'dirSame', '']],
          factory: () => new DirectiveSameInstance(injectElementRef(), directiveInject(Directive)),
          exportAs: 'dirSame'
        });
      }

      /**
       *

       *   {{ dir.value }} - {{ dirSame.value }}
       *

       */
      const App = createComponent('app', function(rf: RenderFlags, ctx: any) {
        if (rf & RenderFlags.Create) {
          elementStart(0, 'div', ['dir', '', 'dirSame', ''], ['dirSame', 'dirSame', 'dir', 'dir']);
          { text(3); }
          elementEnd();
        }

        if (rf & RenderFlags.Update) {
          const tmp1 = reference(1) as any;
          const tmp2 = reference(2) as any;
          textBinding(3, interpolation2('', tmp2.value, '-', tmp1.value, ''));
        }
      }, 4, 2, [Directive, DirectiveSameInstance]);

      const fixture = new ComponentFixture(App);
      expect(fixture.html).toEqual('
ElementRef-true
');
    });
  });

  describe('TemplateRef', () => {
    it('should create directive with TemplateRef dependencies', () => {
      class Directive {
        value: string;
        constructor(public templateRef: TemplateRef<any>) {
          this.value = (templateRef.constructor as any).name;
        }
        static ngDirectiveDef = defineDirective({
          type: Directive,
          selectors: [['', 'dir', '']],
          factory: () => new Directive(injectTemplateRef()),
          features: [PublicFeature],
          exportAs: 'dir'
        });
      }

      class DirectiveSameInstance {
        value: boolean;
        constructor(templateRef: TemplateRef<any>, directive: Directive) {
          this.value = templateRef === directive.templateRef;
        }
        static ngDirectiveDef = defineDirective({
          type: DirectiveSameInstance,
          selectors: [['', 'dirSame', '']],
          factory: () => new DirectiveSameInstance(injectTemplateRef(), directiveInject(Directive)),
          exportAs: 'dirSame'
        });
      }

      /**
       * <ng-template dir dirSame #dir="dir" #dirSame="dirSame">
       *   {{ dir.value }} - {{ dirSame.value }}
       * </ng-template>
       */
      const App = createComponent('app', function(rf: RenderFlags, ctx: any) {
        if (rf & RenderFlags.Create) {
          template(0, function() {
          }, 0, 0, undefined, ['dir', '', 'dirSame', ''], ['dir', 'dir', 'dirSame', 'dirSame']);
          text(3);
        }
        if (rf & RenderFlags.Update) {
          const tmp1 = reference(1) as any;
          const tmp2 = reference(2) as any;
          textBinding(3, interpolation2('', tmp1.value, '-', tmp2.value, ''));
        }
      }, 4, 2, [Directive, DirectiveSameInstance]);

      const fixture = new ComponentFixture(App);
      expect(fixture.html).toEqual('TemplateRef-true');
    });
  });

  describe('ViewContainerRef', () => {
    it('should create directive with ViewContainerRef dependencies', () => {
      class Directive {
        value: string;
        constructor(public viewContainerRef: ViewContainerRef) {
          this.value = (viewContainerRef.constructor as any).name;
        }
        static ngDirectiveDef = defineDirective({
          type: Directive,
          selectors: [['', 'dir', '']],
          factory: () => new Directive(injectViewContainerRef()),
          features: [PublicFeature],
          exportAs: 'dir'
        });
      }

      class DirectiveSameInstance {
        value: boolean;
        constructor(viewContainerRef: ViewContainerRef, directive: Directive) {
          this.value = viewContainerRef === directive.viewContainerRef;
        }
        static ngDirectiveDef = defineDirective({
          type: DirectiveSameInstance,
          selectors: [['', 'dirSame', '']],
          factory:
              () => new DirectiveSameInstance(injectViewContainerRef(), directiveInject(Directive)),
          exportAs: 'dirSame'
        });
      }

      /**
       *

       *   {{ dir.value }} - {{ dirSame.value }}
       *

       */
      const App = createComponent('app', function(rf: RenderFlags, ctx: any) {
        if (rf & RenderFlags.Create) {
          elementStart(0, 'div', ['dir', '', 'dirSame', ''], ['dir', 'dir', 'dirSame', 'dirSame']);
          { text(3); }
          elementEnd();
        }
        if (rf & RenderFlags.Update) {
          const tmp1 = reference(1) as any;
          const tmp2 = reference(2) as any;
          textBinding(3, interpolation2('', tmp1.value, '-', tmp2.value, ''));
        }
      }, 4, 2, [Directive, DirectiveSameInstance]);

      const fixture = new ComponentFixture(App);
      expect(fixture.html).toEqual('
ViewContainerRef-true
');
    });
  });

  describe('ChangeDetectorRef', () => {
    let dir: Directive;
    let dirSameInstance: DirectiveSameInstance;
    let comp: MyComp;

    class MyComp {
      constructor(public cdr: ChangeDetectorRef) {}

      static ngComponentDef = defineComponent({
        type: MyComp,
        selectors: [['my-comp']],
        factory: () => comp = new MyComp(injectChangeDetectorRef()),
        consts: 1,
        vars: 0,
        template: function(rf: RenderFlags, ctx: MyComp) {
          if (rf & RenderFlags.Create) {
            projectionDef();
            projection(0);
          }
        }
      });
    }

    class Directive {
      value: string;

      constructor(public cdr: ChangeDetectorRef) { this.value = (cdr.constructor as any).name; }

      static ngDirectiveDef = defineDirective({
        type: Directive,
        selectors: [['', 'dir', '']],
        factory: () => dir = new Directive(injectChangeDetectorRef()),
        features: [PublicFeature],
        exportAs: 'dir'
      });
    }

    class DirectiveSameInstance {
      constructor(public cdr: ChangeDetectorRef) {}

      static ngDirectiveDef = defineDirective({
        type: DirectiveSameInstance,
        selectors: [['', 'dirSame', '']],
        factory: () => dirSameInstance = new DirectiveSameInstance(injectChangeDetectorRef())
      });
    }

    class IfDirective {
      /* @Input */
      myIf = true;

      constructor(public template: TemplateRef<any>, public vcr: ViewContainerRef) {}

      ngOnChanges() {
        if (this.myIf) {
          this.vcr.createEmbeddedView(this.template);
        }
      }

      static ngDirectiveDef = defineDirective({
        type: IfDirective,
        selectors: [['', 'myIf', '']],
        factory: () => new IfDirective(injectTemplateRef(), injectViewContainerRef()),
        inputs: {myIf: 'myIf'},
        features: [PublicFeature, NgOnChangesFeature]
      });
    }

    const directives = [MyComp, Directive, DirectiveSameInstance, IfDirective];

    it('should inject current component ChangeDetectorRef into directives on components', () => {
      /** <my-comp dir dirSameInstance #dir="dir"></my-comp> {{ dir.value }} */
      const MyApp = createComponent('my-app', function(rf: RenderFlags, ctx: any) {
        if (rf & RenderFlags.Create) {
          element(0, 'my-comp', ['dir', '', 'dirSame', ''], ['dir', 'dir']);
          text(2);
        }
        if (rf & RenderFlags.Update) {
          const tmp = reference(1) as any;
          textBinding(2, bind(tmp.value));
        }
      }, 3, 1, directives);

      const app = renderComponent(MyApp);
      // ChangeDetectorRef is the token, ViewRef has historically been the constructor
      expect(toHtml(app)).toEqual('<my-comp dir="" dirsame=""></my-comp>ViewRef');
      expect((comp !.cdr as ViewRef<MyComp>).context).toBe(comp);

      expect(dir !.cdr).toBe(comp !.cdr);
      expect(dir !.cdr).toBe(dirSameInstance !.cdr);
    });

    it('should inject host component ChangeDetectorRef into directives on elements', () => {

      class MyApp {
        constructor(public cdr: ChangeDetectorRef) {}

        static ngComponentDef = defineComponent({
          type: MyApp,
          selectors: [['my-app']],
          consts: 3,
          vars: 1,
          factory: () => new MyApp(injectChangeDetectorRef()),
          /**
 {{ dir.value }}
 */
          template: function(rf: RenderFlags, ctx: any) {
            if (rf & RenderFlags.Create) {
              elementStart(0, 'div', ['dir', '', 'dirSame', ''], ['dir', 'dir']);
              { text(2); }
              elementEnd();
            }
            if (rf & RenderFlags.Update) {
              const tmp = reference(1) as any;
              textBinding(2, bind(tmp.value));
            }
          },
          directives: directives
        });
      }

      const app = renderComponent(MyApp);
      expect(toHtml(app)).toEqual('
ViewRef
');
      expect((app !.cdr as ViewRef<MyApp>).context).toBe(app);

      expect(dir !.cdr).toBe(app.cdr);
      expect(dir !.cdr).toBe(dirSameInstance !.cdr);
    });

    it('should inject host component ChangeDetectorRef into directives in ContentChildren', () => {
      class MyApp {
        constructor(public cdr: ChangeDetectorRef) {}

        static ngComponentDef = defineComponent({
          type: MyApp,
          selectors: [['my-app']],
          consts: 4,
          vars: 1,
          factory: () => new MyApp(injectChangeDetectorRef()),
          /**
           * <my-comp>
           *

           * </my-comp>
           * {{ dir.value }}
           */
          template: function(rf: RenderFlags, ctx: any) {
            if (rf & RenderFlags.Create) {
              elementStart(0, 'my-comp');
              { element(1, 'div', ['dir', '', 'dirSame', ''], ['dir', 'dir']); }
              elementEnd();
              text(3);
            }
            if (rf & RenderFlags.Update) {
              const tmp = reference(2) as any;
              textBinding(3, bind(tmp.value));
            }
          },
          directives: directives
        });
      }

      const app = renderComponent(MyApp);
      expect(toHtml(app)).toEqual('<my-comp>

</my-comp>ViewRef');
      expect((app !.cdr as ViewRef<MyApp>).context).toBe(app);

      expect(dir !.cdr).toBe(app !.cdr);
      expect(dir !.cdr).toBe(dirSameInstance !.cdr);
    });

    it('should inject host component ChangeDetectorRef into directives in embedded views', () => {

      class MyApp {
        showing = true;

        constructor(public cdr: ChangeDetectorRef) {}

        static ngComponentDef = defineComponent({
          type: MyApp,
          selectors: [['my-app']],
          factory: () => new MyApp(injectChangeDetectorRef()),
          consts: 1,
          vars: 0,
          /**
           * % if (showing) {
           *
 {{ dir.value }}

           * % }
           */
          template: function(rf: RenderFlags, ctx: MyApp) {
            if (rf & RenderFlags.Create) {
              container(0);
            }
            if (rf & RenderFlags.Update) {
              containerRefreshStart(0);
              {
                if (ctx.showing) {
                  let rf1 = embeddedViewStart(0, 3, 1);
                  if (rf1 & RenderFlags.Create) {
                    elementStart(0, 'div', ['dir', '', 'dirSame', ''], ['dir', 'dir']);
                    { text(2); }
                    elementEnd();
                  }
                  if (rf1 & RenderFlags.Update) {
                    const tmp = reference(1) as any;
                    textBinding(2, bind(tmp.value));
                  }
                }
                embeddedViewEnd();
              }
              containerRefreshEnd();
            }
          },
          directives: directives
        });
      }

      const app = renderComponent(MyApp);
      expect(toHtml(app)).toEqual('
ViewRef
');
      expect((app !.cdr as ViewRef<MyApp>).context).toBe(app);

      expect(dir !.cdr).toBe(app.cdr);
      expect(dir !.cdr).toBe(dirSameInstance !.cdr);
    });

    it('should inject host component ChangeDetectorRef into directives on containers', () => {
      function C1(rf1: RenderFlags, ctx1: any) {
        if (rf1 & RenderFlags.Create) {
          elementStart(0, 'div', ['dir', '', 'dirSame', ''], ['dir', 'dir']);
          { text(2); }
          elementEnd();
        }
        if (rf1 & RenderFlags.Update) {
          const tmp = reference(1) as any;
          textBinding(2, bind(tmp.value));
        }
      }

      class MyApp {
        showing = true;

        constructor(public cdr: ChangeDetectorRef) {}

        static ngComponentDef = defineComponent({
          type: MyApp,
          selectors: [['my-app']],
          factory: () => new MyApp(injectChangeDetectorRef()),
          consts: 1,
          vars: 0,
          /**
 {{ dir.value }}
 */
          template: function(rf: RenderFlags, ctx: MyApp) {
            if (rf & RenderFlags.Create) {
              template(0, C1, 3, 1, null, ['myIf', 'showing']);
            }
          },
          directives: directives
        });
      }

      const app = renderComponent(MyApp);
      expect(toHtml(app)).toEqual('
ViewRef
');
      expect((app !.cdr as ViewRef<MyApp>).context).toBe(app);

      expect(dir !.cdr).toBe(app.cdr);
      expect(dir !.cdr).toBe(dirSameInstance !.cdr);
    });
  });

  describe('Renderer2', () => {
    let comp: MyComp;

    class MyComp {
      constructor(public renderer: Renderer2) {}

      static ngComponentDef = defineComponent({
        type: MyComp,
        selectors: [['my-comp']],
        factory: () => comp = new MyComp(injectRenderer2()),
        consts: 1,
        vars: 0,
        template: function(rf: RenderFlags, ctx: MyComp) {
          if (rf & RenderFlags.Create) {
            text(0, 'Foo');
          }
        }
      });
    }

    it('should inject the Renderer2 used by the application', () => {
      const rendererFactory = getRendererFactory2(document);
      new ComponentFixture(MyComp, {rendererFactory: rendererFactory});
      expect(isProceduralRenderer(comp.renderer)).toBeTruthy();
    });

    it('should throw when injecting Renderer2 but the application is using Renderer3',
       () => { expect(() => new ComponentFixture(MyComp)).toThrow(); });
  });

  describe('@Attribute', () => {

    class MyDirective {
      exists = 'wrong' as string | undefined;
      myDirective = 'wrong' as string | undefined;
      constructor(
          @Attribute('exist') existAttrValue: string|undefined,
          @Attribute('myDirective') myDirectiveAttrValue: string|undefined) {
        this.exists = existAttrValue;
        this.myDirective = myDirectiveAttrValue;
      }

      static ngDirectiveDef = defineDirective({
        type: MyDirective,
        selectors: [['', 'myDirective', '']],
        factory: () => new MyDirective(injectAttribute('exist'), injectAttribute('myDirective'))
      });
    }

    it('should inject attribute', () => {
      let exist = 'wrong' as string | undefined;
      let nonExist = 'wrong' as string | undefined;

      const MyApp = createComponent('my-app', function(rf: RenderFlags, ctx: any) {
        if (rf & RenderFlags.Create) {
          elementStart(0, 'div', ['exist', 'existValue', 'other', 'ignore']);
          exist = injectAttribute('exist');
          nonExist = injectAttribute('nonExist');
        }
      }, 1);

      new ComponentFixture(MyApp);
      expect(exist).toEqual('existValue');
      expect(nonExist).toEqual(undefined);
    });

    // https://stackblitz.com/edit/angular-scawyi?file=src%2Fapp%2Fapp.component.ts
    it('should inject attributes on <ng-template>', () => {
      let myDirectiveInstance: MyDirective;

      /* <ng-template myDirective="initial" exist="existValue" other="ignore"></ng-template>*/
      const MyApp = createComponent('my-app', function(rf: RenderFlags, ctx: any) {
        if (rf & RenderFlags.Create) {
          template(
              0, null, 0, 0, null,
              ['myDirective', 'initial', 'exist', 'existValue', 'other', 'ignore']);
        }
        if (rf & RenderFlags.Update) {
          myDirectiveInstance = loadDirective(0);
        }
      }, 1, 0, [MyDirective]);

      new ComponentFixture(MyApp);
      expect(myDirectiveInstance !.exists).toEqual('existValue');
      expect(myDirectiveInstance !.myDirective).toEqual('initial');
    });

    // https://stackblitz.com/edit/angular-scawyi?file=src%2Fapp%2Fapp.component.ts
    it('should inject attributes on <ng-container>', () => {
      let myDirectiveInstance: MyDirective;

      /* <ng-container myDirective="initial" exist="existValue" other="ignore"></ng-container>*/
      const MyApp = createComponent('my-app', function(rf: RenderFlags, ctx: any) {
        if (rf & RenderFlags.Create) {
          elementContainerStart(
              0, ['myDirective', 'initial', 'exist', 'existValue', 'other', 'ignore']);
          elementContainerEnd();
        }
        if (rf & RenderFlags.Update) {
          myDirectiveInstance = loadDirective(0);
        }
      }, 1, 0, [MyDirective]);

      new ComponentFixture(MyApp);
      expect(myDirectiveInstance !.exists).toEqual('existValue');
      expect(myDirectiveInstance !.myDirective).toEqual('initial');
    });

    // https://stackblitz.com/edit/angular-8ytqkp?file=src%2Fapp%2Fapp.component.ts
    it('should not inject attributes representing bindings and outputs', () => {
      let exist = 'wrong' as string | undefined;
      let nonExist = 'wrong' as string | undefined;

      const MyApp = createComponent('my-app', function(rf: RenderFlags, ctx: any) {
        if (rf & RenderFlags.Create) {
          elementStart(0, 'div', ['exist', 'existValue', AttributeMarker.SelectOnly, 'nonExist']);
          exist = injectAttribute('exist');
          nonExist = injectAttribute('nonExist');
        }
      }, 1);

      new ComponentFixture(MyApp);
      expect(exist).toEqual('existValue');
      expect(nonExist).toEqual(undefined);
    });

    it('should not accidentally inject attributes representing bindings and outputs', () => {
      let exist = 'wrong' as string | undefined;
      let nonExist = 'wrong' as string | undefined;

      const MyApp = createComponent('my-app', function(rf: RenderFlags, ctx: any) {
        if (rf & RenderFlags.Create) {
          elementStart(0, 'div', [
            'exist', 'existValue', AttributeMarker.SelectOnly, 'binding1', 'nonExist', 'binding2'
          ]);
          exist = injectAttribute('exist');
          nonExist = injectAttribute('nonExist');
        }
      }, 1);

      new ComponentFixture(MyApp);
      expect(exist).toEqual('existValue');
      expect(nonExist).toEqual(undefined);
    });
  });

  describe('inject', () => {
    describe('bloom filter', () => {
      let di: LInjector;
      beforeEach(() => {
        di = {} as any;
        di.bf0 = 0;
        di.bf1 = 0;
        di.bf2 = 0;
        di.bf3 = 0;
        di.bf4 = 0;
        di.bf5 = 0;
        di.bf6 = 0;
        di.bf7 = 0;
        di.bf3 = 0;
        di.cbf0 = 0;
        di.cbf1 = 0;
        di.cbf2 = 0;
        di.cbf3 = 0;
        di.cbf4 = 0;
        di.cbf5 = 0;
        di.cbf6 = 0;
        di.cbf7 = 0;
      });

      function bloomState() {
        return [di.bf7, di.bf6, di.bf5, di.bf4, di.bf3, di.bf2, di.bf1, di.bf0];
      }

      it('should add values', () => {
        bloomAdd(di, { __NG_ELEMENT_ID__: 0 } as any);
        expect(bloomState()).toEqual([0, 0, 0, 0, 0, 0, 0, 1]);
        bloomAdd(di, { __NG_ELEMENT_ID__: 32 + 1 } as any);
        expect(bloomState()).toEqual([0, 0, 0, 0, 0, 0, 2, 1]);
        bloomAdd(di, { __NG_ELEMENT_ID__: 64 + 2 } as any);
        expect(bloomState()).toEqual([0, 0, 0, 0, 0, 4, 2, 1]);
        bloomAdd(di, { __NG_ELEMENT_ID__: 96 + 3 } as any);
        expect(bloomState()).toEqual([0, 0, 0, 0, 8, 4, 2, 1]);
        bloomAdd(di, { __NG_ELEMENT_ID__: 128 + 4 } as any);
        expect(bloomState()).toEqual([0, 0, 0, 16, 8, 4, 2, 1]);
        bloomAdd(di, { __NG_ELEMENT_ID__: 160 + 5 } as any);
        expect(bloomState()).toEqual([0, 0, 32, 16, 8, 4, 2, 1]);
        bloomAdd(di, { __NG_ELEMENT_ID__: 192 + 6 } as any);
        expect(bloomState()).toEqual([0, 64, 32, 16, 8, 4, 2, 1]);
        bloomAdd(di, { __NG_ELEMENT_ID__: 224 + 7 } as any);
        expect(bloomState()).toEqual([128, 64, 32, 16, 8, 4, 2, 1]);
      });

      it('should query values', () => {
        bloomAdd(di, { __NG_ELEMENT_ID__: 0 } as any);
        bloomAdd(di, { __NG_ELEMENT_ID__: 32 } as any);
        bloomAdd(di, { __NG_ELEMENT_ID__: 64 } as any);
        bloomAdd(di, { __NG_ELEMENT_ID__: 96 } as any);
        bloomAdd(di, { __NG_ELEMENT_ID__: 127 } as any);
        bloomAdd(di, { __NG_ELEMENT_ID__: 161 } as any);
        bloomAdd(di, { __NG_ELEMENT_ID__: 188 } as any);
        bloomAdd(di, { __NG_ELEMENT_ID__: 223 } as any);
        bloomAdd(di, { __NG_ELEMENT_ID__: 255 } as any);

        expect(bloomFindPossibleInjector(di, 0, InjectFlags.Default)).toEqual(di);
        expect(bloomFindPossibleInjector(di, 1, InjectFlags.Default)).toEqual(null);
        expect(bloomFindPossibleInjector(di, 32, InjectFlags.Default)).toEqual(di);
        expect(bloomFindPossibleInjector(di, 64, InjectFlags.Default)).toEqual(di);
        expect(bloomFindPossibleInjector(di, 96, InjectFlags.Default)).toEqual(di);
        expect(bloomFindPossibleInjector(di, 127, InjectFlags.Default)).toEqual(di);
        expect(bloomFindPossibleInjector(di, 161, InjectFlags.Default)).toEqual(di);
        expect(bloomFindPossibleInjector(di, 188, InjectFlags.Default)).toEqual(di);
        expect(bloomFindPossibleInjector(di, 223, InjectFlags.Default)).toEqual(di);
        expect(bloomFindPossibleInjector(di, 255, InjectFlags.Default)).toEqual(di);
      });
    });

    it('should inject from parent view', () => {
      const ParentDirective = createDirective('parentDir');

      class ChildDirective {
        value: string;
        constructor(public parent: any) { this.value = (parent.constructor as any).name; }
        static ngDirectiveDef = defineDirective({
          type: ChildDirective,
          selectors: [['', 'childDir', '']],
          factory: () => new ChildDirective(directiveInject(ParentDirective)),
          features: [PublicFeature],
          exportAs: 'childDir'
        });
      }

      class Child2Directive {
        value: boolean;
        constructor(parent: any, child: ChildDirective) { this.value = parent === child.parent; }
        static ngDirectiveDef = defineDirective({
          selectors: [['', 'child2Dir', '']],
          type: Child2Directive,
          factory: () => new Child2Directive(
                       directiveInject(ParentDirective), directiveInject(ChildDirective)),
          exportAs: 'child2Dir'
        });
      }

      /**
       *

       *
       *      {{ child1.value }} - {{ child2.value }}
       *
       *

       */
      const App = createComponent('app', function(rf: RenderFlags, ctx: any) {
        if (rf & RenderFlags.Create) {
          elementStart(0, 'div', ['parentDir', '']);
          { container(1); }
          elementEnd();
        }
        if (rf & RenderFlags.Update) {
          containerRefreshStart(1);
          {
            let rf1 = embeddedViewStart(0, 4, 2);
            if (rf1 & RenderFlags.Create) {
              elementStart(
                  0, 'span', ['childDir', '', 'child2Dir', ''],
                  ['child1', 'childDir', 'child2', 'child2Dir']);
              { text(3); }
              elementEnd();
            }
            if (rf & RenderFlags.Update) {
              const tmp1 = reference(1) as any;
              const tmp2 = reference(2) as any;
              textBinding(3, interpolation2('', tmp1.value, '-', tmp2.value, ''));
            }
            embeddedViewEnd();
          }
          containerRefreshEnd();
        }
      }, 2, 0, [ChildDirective, Child2Directive, ParentDirective]);

      const fixture = new ComponentFixture(App);
      expect(fixture.html)
          .toEqual('
Directive-true
');
    });

    it('should inject from module Injector', () => {

                                             });
  });

  describe('getOrCreateNodeInjector', () => {
    it('should handle initial undefined state', () => {
      const contentView = createLViewData(
          null !, createTView(-1, null, 1, 0, null, null, null), null, LViewFlags.CheckAlways);
      const oldView = enterView(contentView, null);
      try {
        const parentTNode = createNodeAtIndex(0, TNodeType.Element, null, null, null, null);
        // Simulate the situation where the previous parent is not initialized.
        // This happens on first bootstrap because we don't init existing values
        // so that we have smaller HelloWorld.
        (parentTNode as{parent: any}).parent = undefined;

        const injector: any = getOrCreateNodeInjector();  // TODO: Review use of `any` here (#19904)
        expect(injector).not.toBe(null);
      } finally {
        leaveView(oldView);
      }
    });
  });

});


text:
module.exports = function(sequelize, DataTypes) {

    // Creates post model with column post_id, author, topic, post_title, post_message
    var Thread = sequelize.define("Thread", {
        thread_id: {
            autoIncrement: true,
            type: DataTypes.INTEGER,
            primaryKey: true
        },
        thread_title: {
            type: DataTypes.STRING,
            allowNull: false,
            validate: {
                len: [1]
            },
        },
        topic_name: {
            type: DataTypes.STRING,
            allowNull: false,
        },
        createdAt: {
            type: DataTypes.DATE,
            defaultValue: sequelize.fn('now')
        },
        updatedAt: {
            type: DataTypes.DATE,
            defaultValue: sequelize.fn('now')
        }

    });
    // returns the model we just defined
    return Thread;
};

redpajama_set_name: RedPajamaGithub


text:
require 'gosu'

# A transperant overlay with instructions
class InstructionsOverlay
  def initialize(game_window)
    @x = 0
    @y = 0
    @z = 3
    @w = game_window.width
    @h = game_window.height
    init_drawing
  end

  def init_drawing
    @bg_color = Gosu::Color.new(250, 20, 20, 20)
    @font = Gosu::Font.new(60)
    @font_color = Gosu::Color.new(255, 240, 240, 240)
    @text = ['User the arrow keys to move',
             'You heal over time, if not in combat',
             'Kill all the orcs!'].reverse
  end

  def draw
    Gosu.draw_rect(@x, @y, @w, @h, @bg_color, @z)

    relative_offset = 0.5 # Centers the text relative to its x and y values
    scale = 1
    @text.each.with_index do |line, i|
      @font.draw_rel(line, @w / 2, @h / 2 + 60 - i * 60, @z,
                     relative_offset, relative_offset, scale, scale, @font_color)
    end
  end
end


text:
package com.google.security.zynamics.binnavi.API.debug;

import com.google.security.zynamics.binnavi.CUtilityFunctions;
import com.google.security.zynamics.binnavi.APIHelpers.ObjectFinders;
import com.google.security.zynamics.binnavi.debug.models.processmanager.ProcessManager;
import com.google.security.zynamics.binnavi.debug.models.processmanager.TargetProcessThread;
import com.google.security.zynamics.binnavi.debug.models.processmanager.interfaces.ProcessManagerListener;
import com.google.security.zynamics.binnavi.debug.models.targetinformation.DebuggerException;
import com.google.security.zynamics.zylib.general.ListenerProvider;
import com.google.security.zynamics.zylib.types.lists.FilledList;

import java.util.ArrayList;
import java.util.List;

// / Target process of the debugger.
/**
 * Represents a target process that is being debugged.
 */
public final class Process {
  /**
   * The wrapped internal process manager object.
   */
  private final ProcessManager processManager;

  /**
   * Simulated threads of the process.
   */
  private final List<Thread> threads = new ArrayList<>();

  /**
   * Simulated modules loaded into the address space of the process.
   */
  private final List<MemoryModule> modules = new ArrayList<>();

  /**
   * Simulated memory map of the project.
   */
  private MemoryMap memoryMap;

  /**
   * Simulated memory of the process.
   */
  private Memory memory;

  /**
   * Information about the target process.
   */
  private TargetInformation targetInformation;

  /**
   * Keeps the API process object synchronized with the internal process object.
   */
  private final InternalProcessListener listener = new InternalProcessListener();

  /**
   * Listeners that are notified about changes in the process.
   */
  private final ListenerProvider<IProcessListener> listeners = new ListenerProvider<>();

  // / @cond INTERNAL
  /**
   * Creates a new API process object.
   *
   * @param processManager The wrapped internal process object.
   */
  // / @endcond
  public Process(
      final com.google.security.zynamics.binnavi.debug.models.processmanager.ProcessManager processManager) {
    this.processManager = processManager;

    processManager.addListener(listener);

    memory = new Memory(processManager.getMemory());
    targetInformation = processManager.getTargetInformation() == null ? null
        : new TargetInformation(processManager.getTargetInformation());
    memoryMap = new MemoryMap(processManager.getMemoryMap());

    for (final TargetProcessThread thread : processManager.getThreads()) {
      threads.add(new Thread(thread));
    }

    for (final com.google.security.zynamics.binnavi.debug.models.processmanager.MemoryModule
        module : processManager.getModules()) {
      modules.add(new MemoryModule(module));
    }
  }

  // ! Adds a process listener.
  /**
   * Adds an object that is notified about changes in the process.
   *
   * @param listener The listener object that is notified about changes in the process.
   *
   * @throws IllegalArgumentException Thrown if the listener argument is null.
   * @throws IllegalStateException Thrown if the listener object is already listening on the
   *         process.
   */
  public void addListener(final IProcessListener listener) {
    listeners.addListener(listener);
  }

  // ! Returns the process memory.
  /**
   * Returns the simulated memory of target process. This memory object contains all the memory data
   * that was already sent from the debug client to com.google.security.zynamics.binnavi.
   *
   * @return The simulated memory of the target process.
   */
  public Memory getMemory() {
    return memory;
  }

  // ! Returns the process memory layout.
  /**
   * Returns the memory layout of the target process. The memory map object contains a list of all
   * allocated parts of the target process memory.
   *
   * @return The memory layout of the target process.
   */
  public MemoryMap getMemoryMap() {
    return memoryMap;
  }

  // ! Returns the loaded modules.
  /**
   * Returns the modules loaded into the address space of the process.
   *
   * @return The modules loaded into the address space of the process.
   */
  public List<MemoryModule> getModules() {
    return new ArrayList<MemoryModule>(modules);
  }

  // ! Returns information about the target process.
  /**
   * Returns the target information object of the target process.
   *
   * @return The target information object of the target process.
   */
  public TargetInformation getTargetInformation() {
    return targetInformation;
  }

  // ! Returns active threads in the target process.
  /**
   * Returns all threads that are active in the target process.
   *
   * @return List of threads of the target process.
   */
  public List<Thread> getThreads() {
    return new ArrayList<Thread>(threads);
  }

  // ! Removes a process listener.
  /**
   * Removes a listener object from the process.
   *
   * @param listener The listener object to remove from the process.
   *
   * @throws IllegalArgumentException Thrown if the listener argument is null.
   * @throws IllegalStateException Thrown if the listener object was not listening on the process.
   */
  public void removeListener(final IProcessListener listener) {
    listeners.removeListener(listener);
  }

  // ! Printable representation of the process.
  /**
   * Returns a string representation of the target process.
   *
   * @return A string representation of the target process.
   */
  @Override
  public String toString() {
    return String.format("Target Process");
  }

  /**
   * Keeps the API process object synchronized with the internal process object.
   */
  private class InternalProcessListener implements ProcessManagerListener {
    @Override
    public void addedModule(
        final com.google.security.zynamics.binnavi.debug.models.processmanager.MemoryModule module) {
      final MemoryModule newModule = new MemoryModule(module);

      modules.add(newModule);

      for (final IProcessListener listener : listeners) {
        try {
          listener.addedModule(Process.this, newModule);
        } catch (final Exception e) {
          CUtilityFunctions.logException(e);
        }
      }
    }

    @Override
    public void addedThread(final TargetProcessThread thread) {
      final Thread newThread = new Thread(thread);

      threads.add(newThread);

      for (final IProcessListener listener : listeners) {
        try {
          listener.addedThread(Process.this, newThread);
        } catch (final Exception e) {
          CUtilityFunctions.logException(e);
        }
      }
    }

    @Override
    public void attached() {
      for (final IProcessListener listener : listeners) {
        try {
          listener.attached(Process.this);
        } catch (final Exception e) {
          CUtilityFunctions.logException(e);
        }
      }
    }

    @Override
    public void changedActiveThread(final TargetProcessThread oldThread,
        final TargetProcessThread newThread) {
      // This should not be passed to the API
    }

    @Override
    public void changedMemoryMap() {
      memoryMap = new MemoryMap(processManager.getMemoryMap());

      for (final IProcessListener listener : listeners) {
        try {
          listener.changedMemoryMap(Process.this, memoryMap);
        } catch (final Exception e) {
          CUtilityFunctions.logException(e);
        }
      }
    }

    @Override
    public void changedTargetInformation(
        final com.google.security.zynamics.binnavi.debug.models.targetinformation.TargetInformation information) {
      for (final Thread thread : threads) {
        thread.dispose();
      }

      targetInformation = new TargetInformation(information);

      modules.clear();
      threads.clear();
      memoryMap = new MemoryMap(new com.google.security.zynamics.binnavi.debug.models.processmanager.MemoryMap(new ArrayList<com.google.security.zynamics.binnavi.debug.models.processmanager.MemorySection>()));
      memory = new Memory(new com.google.security.zynamics.zylib.general.memmanager.Memory());

      for (final IProcessListener listener : listeners) {
        try {
          listener.changedTargetInformation(Process.this);
        } catch (final Exception e) {
          CUtilityFunctions.logException(e);
        }
      }
    }

    @Override
    public void detached() {
      targetInformation = null;
      modules.clear();
      threads.clear();
      memoryMap = new MemoryMap(new com.google.security.zynamics.binnavi.debug.models.processmanager.MemoryMap(new FilledList<com.google.security.zynamics.binnavi.debug.models.processmanager.MemorySection>()));
      memory = new Memory(new com.google.security.zynamics.zylib.general.memmanager.Memory());

      for (final IProcessListener listener : listeners) {
        // ESCA-JAVA0166:
        try {
          listener.detached(Process.this);
        } catch (final Exception e) {
          CUtilityFunctions.logException(e);
        }
      }
    }

    @Override
    public void raisedException(final DebuggerException exception) {
      // TODO (timkornau): inform listeners about exception
    }

    @Override
    public void removedModule(
        final com.google.security.zynamics.binnavi.debug.models.processmanager.MemoryModule module) {
      final MemoryModule apiModule = ObjectFinders.getObject(module, modules);

      modules.remove(apiModule);

      for (final IProcessListener listener : listeners) {
        try {
          listener.removedModule(Process.this, apiModule);
        } catch (final Exception e) {
          CUtilityFunctions.logException(e);
        }
      }
    }

    @Override
    public void removedNonExistingModule(
        final com.google.security.zynamics.binnavi.debug.models.processmanager.MemoryModule module) {
      // We do not export this event to API listeners since it is mainly important for internal
      // protocol actions.
    }

    @Override
    public void removedThread(final TargetProcessThread thread) {
      final Thread apiThread = ObjectFinders.getObject(thread, threads);

      threads.remove(apiThread);

      for (final IProcessListener listener : listeners) {
        try {
          listener.removedThread(Process.this, apiThread);
        } catch (final Exception e) {
          CUtilityFunctions.logException(e);
        }
      }
    }
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<bean:beans xmlns="http://www.springframework.org/schema/batch"
    xmlns:bean="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jdbc="http://www.springframework.org/schema/jdbc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-2.5.xsd
    http://www.springframework.org/schema/batch
    http://www.springframework.org/schema/batch/spring-batch-2.2.xsd
    http://www.springframework.org/schema/jdbc
    http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd">
    <bean:import resource="classpath:ch06/job-context.xml"/>

    <jdbc:initialize-database data-source="dataSource">
		<jdbc:script location="classpath:/ch06/db/create-tables-mysql.sql" />
	</jdbc:initialize-database>

    <job id="hibernateReadJob">
        <step id="hibernateReadStep">
            <tasklet transaction-manager="transactionManager">
                <chunk reader="hibernateItemReader" processor="creditBillProcessor"
                    writer="creditItemWriter" commit-interval="2"></chunk>
            </tasklet>
        </step>
    </job>

    <!-- hibernate读取数据库 -->
    <bean:bean id="hibernateItemReader"
		class="org.springframework.batch.item.database.HibernateCursorItemReader" scope="step">
		<bean:property name="sessionFactory" ref="sessionFactory"/>
		<bean:property name="queryString" value="from CreditBill where id between :begin and :end "/>
		<bean:property name="parameterValues">
		    <bean:map>
				<bean:entry key="begin" value="#{jobParameters['begin']}" />
				<bean:entry key="end" value="#{jobParameters['end']}" />
			</bean:map>
		</bean:property>
	</bean:bean>

     <bean:bean id="sessionFactory"
		class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
		<bean:property name="dataSource" ref="dataSource"/>
		<bean:property name="configurationClass"
			value="org.hibernate.cfg.AnnotationConfiguration"/>
		<bean:property name="configLocation"
			value="classpath:/ch06/cfg/hibernate.cfg.xml"/>
		<bean:property name="hibernateProperties">
			<bean:value>
				hibernate.dialect=org.hibernate.dialect.MySQLDialect
				hibernate.show_sql=true
			</bean:value>
		</bean:property>
	</bean:bean>

    <bean:bean id="creditBillProcessor" scope="step"
        class="com.juxtapose.example.ch06.hibernate.CreditBillProcessor">
    </bean:bean>

    <bean:bean id="creditItemWriter"
        class="com.juxtapose.example.ch06.hibernate.DummyCreditItemWriter"/>

</bean:beans>


text:
package org.osgi.util.promise;

import java.util.Collection;
import java.util.Collections;

/**
 * Promise failure exception for a collection of failed Promises.
 *
 * @author $Id: 95546abe53fcca0c3daa3d2847a915fe94b9cef8 $
 */
public class FailedPromisesException extends RuntimeException {
	private static final long				serialVersionUID	= 1L;
	private final Collection<Promise<?>>	failed;

	/**
	 * Create a new FailedPromisesException with the specified Promises.
	 *
	 * @param failed A collection of Promises that have been resolved with a
	 *        failure. Must not be {@code null}, must not be empty and all of
	 *        the elements in the collection must not be {@code null}.
	 * @param cause The cause of this exception. This is typically the failure
	 *        of the first Promise in the specified collection.
	 */
	public FailedPromisesException(Collection<Promise<?>> failed, Throwable cause) {
		super(cause);
		this.failed = Collections.unmodifiableCollection(failed);
	}

	/**
	 * Returns the collection of Promises that have been resolved with a
	 * failure.
	 *
	 * @return The collection of Promises that have been resolved with a
	 *         failure. The returned collection is unmodifiable.
	 */
	public Collection<Promise<?>> getFailedPromises() {
		return failed;
	}
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width initial-scale=1" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge">

  <title>Survey Article Accepted To ACM Computing Surveys!</title>
  <meta name="description" content="Perpetually Under Construction...">
  <meta name="author" content="Brett Israelsen">
  <meta name="HandheldFriendly" content="True">
  <meta name="MobileOptimized" content="320">
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

  <meta name="twitter:card" content="summary">
  <meta name="twitter:title" content="Brett Israelsen">
  <meta name="twitter:description" content="Perpetually Under Construction...">

  <meta property="og:type" content="article">
  <meta property="og:title" content="Brett Israelsen">
  <meta property="og:description" content="Perpetually Under Construction...">

  <link rel="apple-touch-icon" sizes="57x57" href="/images/favicons/apple-touch-icon-57x57.png">
  <link rel="apple-touch-icon" sizes="60x60" href="/images/favicons/apple-touch-icon-60x60.png">
  <link rel="apple-touch-icon" sizes="72x72" href="/images/favicons/apple-touch-icon-72x72.png">
  <link rel="apple-touch-icon" sizes="76x76" href="/images/favicons/apple-touch-icon-76x76.png">
  <link rel="apple-touch-icon" sizes="114x114" href="/images/favicons/apple-touch-icon-114x114.png">
  <link rel="apple-touch-icon" sizes="120x120" href="/images/favicons/apple-touch-icon-120x120.png">
  <link rel="apple-touch-icon" sizes="144x144" href="/images/favicons/apple-touch-icon-144x144.png">
  <link rel="apple-touch-icon" sizes="152x152" href="/images/favicons/apple-touch-icon-152x152.png">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/favicons/apple-touch-icon-180x180.png">
  <link rel="icon" type="image/png" href="/images/favicons/favicon-32x32.png" sizes="32x32">
  <link rel="icon" type="image/png" href="/images/favicons/favicon-194x194.png" sizes="194x194">
  <link rel="icon" type="image/png" href="/images/favicons/favicon-96x96.png" sizes="96x96">
  <link rel="icon" type="image/png" href="/images/favicons/android-chrome-192x192.png" sizes="192x192">
  <link rel="icon" type="image/png" href="/images/favicons/favicon-16x16.png" sizes="16x16">
  <link rel="manifest" href="/images/favicons/manifest.json">
  <link rel="shortcut icon" href="/images/favicons/favicon.ico">
  <meta name="msapplication-TileColor" content="#ffc40d">
  <meta name="msapplication-TileImage" content="/images/favicons/mstile-144x144.png">
  <meta name="theme-color" content="#ffffff">

  <link rel="stylesheet" href="/css/main.css">
  <link rel="canonical" href="http://bisraelsen.github.io///2018/assurances/">
  <link rel="alternate" type="application/rss+xml" title="Brett Israelsen" href="/feed.xml">

Brett Israelsen

Perpetually Under Construction...

Bio/CV

Publications

Code

Blog

Contact

                  Twitter

                  LinkedIn

                  GitHub

                  Email

                RSS

      <time datetime="28 Aug 2018" class="post-meta__date date">28 Aug 2018</time> • on news publications

Survey Article Accepted To ACM Computing Surveys!

Nisar Ahmed and I have had our survey paper accepted to the ACM Computing Surveys journal. Take a few minutes to check it out.

Please enable JavaScript to view the comments powered by Disqus.

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

  © 2018 Brett Israelsen. All rights reserved.


text:
package com.perimeterx.api.blockhandler;

import com.perimeterx.models.PXContext;
import com.perimeterx.models.configuration.PXConfiguration;
import com.perimeterx.models.exceptions.PXException;

import javax.servlet.http.HttpServletResponseWrapper;

/**
 * BlockHandler is a common interface to be applied on block event
 * <p>
 * Created by Shikloshi on 03/07/2016.
 */
public interface BlockHandler {

    /**
     * Blocking handle will be called when pxVerify will return that user is not verified
     *
     * @param context         - requests context
     * @param responseWrapper - response wrapper
     * @throws PXException
     */
    void handleBlocking(PXContext context, PXConfiguration pxConfig, HttpServletResponseWrapper responseWrapper) throws PXException;

}


text:
<ly-slider [ngClass]="classes.slider" [value]="76"></ly-slider>
<ly-slider [ngClass]="classes.slider" [value]="[11, 50]" [color]="'primary'"></ly-slider>


text:
package br.com.cinema.consultas;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.TypedQuery;

import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

import br.com.cinema.model.Categoria;

public class ConsultaCategoria {

    private static EntityManagerFactory factory;

    private EntityManager manager;

    @BeforeClass
    public static void init() {
	factory = Persistence.createEntityManagerFactory("CinemaJsfPU");
    }

    @Before
    public void setUp() {
	this.manager = factory.createEntityManager();
    }

    @After
    public void tearDown() {
	this.manager.close();
    }

    @Test
    public void cache() {
	/*
	 * Utilizando o método "getReference" você fará um select buscando
	 * apenas o ID do objeto, aliviando o tráfego de dados ao banco de
	 * dados.
	 */

	TypedQuery<Categoria> query = this.manager.createQuery("select * from Categoria",
			Categoria.class);
	Categoria categoria = query.getSingleResult();

	System.out.println();
	System.out.println("Categoria Info: " + categoria.getCategoria_info());
	System.out.println("Catgoria Nome: " + categoria.getCategoria_nome());

    }

}


text:
<!DOCTYPE html>
<html>
 <!--
Copyright 2010 The Closure Library Authors. All Rights Reserved

Use of this source code is governed by the Apache License, Version 2.0.
See the COPYING file for details.
-->
 <!--
-->
 <head>
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta charset="UTF-8" />
  <title>
   Closure Unit Tests - goog.ui.ColorButton
  </title>
  <script type="text/javascript" src="../base.js">
  </script>
  <script type="text/javascript">
   goog.require('goog.ui.ColorButtonTest');
  </script>
 </head>
 <body>
  <div id="buttonDiv">
  </div>
 </body>
</html>


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

namespace OpenSim.Framework
{
    // ACL Class
    // Modelled after the structure of the Zend ACL Framework Library
    // with one key difference - the tree will search for all matching
    // permissions rather than just the first. Deny permissions will
    // override all others.

    #region ACL Core Class

    /// <summary>
    /// Access Control List Engine
    /// </summary>
    public class ACL
    {
        private Dictionary<string, Resource> Resources = new Dictionary<string, Resource>();
        private Dictionary<string, Role> Roles = new Dictionary<string, Role>();

        /// <summary>
        /// Adds a new role
        /// </summary>
        /// <param name="role"></param>
        /// <returns></returns>
        public ACL AddRole(Role role)
        {
            if (Roles.ContainsKey(role.Name))
                throw new AlreadyContainsRoleException(role);

            Roles.Add(role.Name, role);

            return this;
        }

        /// <summary>
        /// Adds a new resource
        /// </summary>
        /// <param name="resource"></param>
        /// <returns></returns>
        public ACL AddResource(Resource resource)
        {
            Resources.Add(resource.Name, resource);

            return this;
        }

        /// <summary>
        /// Permision for user/roll on a resource
        /// </summary>
        /// <param name="role"></param>
        /// <param name="resource"></param>
        /// <returns></returns>
        public Permission HasPermission(string role, string resource)
        {
            if (!Roles.ContainsKey(role))
                throw new KeyNotFoundException();

            if (!Resources.ContainsKey(resource))
                throw new KeyNotFoundException();

            return Roles[role].RequestPermission(resource);
        }

        public ACL GrantPermission(string role, string resource)
        {
            if (!Roles.ContainsKey(role))
                throw new KeyNotFoundException();

            if (!Resources.ContainsKey(resource))
                throw new KeyNotFoundException();

            Roles[role].GivePermission(resource, Permission.Allow);

            return this;
        }

        public ACL DenyPermission(string role, string resource)
        {
            if (!Roles.ContainsKey(role))
                throw new KeyNotFoundException();

            if (!Resources.ContainsKey(resource))
                throw new KeyNotFoundException();

            Roles[role].GivePermission(resource, Permission.Deny);

            return this;
        }

        public ACL ResetPermission(string role, string resource)
        {
            if (!Roles.ContainsKey(role))
                throw new KeyNotFoundException();

            if (!Resources.ContainsKey(resource))
                throw new KeyNotFoundException();

            Roles[role].GivePermission(resource, Permission.None);

            return this;
        }
    }

    #endregion

    #region Exceptions

    /// <summary>
    /// Thrown when an ACL attempts to add a duplicate role.
    /// </summary>
    public class AlreadyContainsRoleException : Exception
    {
        protected Role m_role;

        public AlreadyContainsRoleException(Role role)
        {
            m_role = role;
        }

        public Role ErrorRole
        {
            get { return m_role; }
        }

        public override string ToString()
        {
            return "This ACL already contains a role called '" + m_role.Name + "'.";
        }
    }

    #endregion

    #region Roles and Resources

    /// <summary>
    /// Does this Role have permission to access a specified Resource?
    /// </summary>
    public enum Permission
    {
        Deny,
        None,
        Allow
    } ;

    /// <summary>
    /// A role class, for use with Users or Groups
    /// </summary>
    public class Role
    {
        private string m_name;
        private Role[] m_parents;
        private Dictionary<string, Permission> m_resources = new Dictionary<string, Permission>();

        public Role(string name)
        {
            m_name = name;
            m_parents = null;
        }

        public Role(string name, Role[] parents)
        {
            m_name = name;
            m_parents = parents;
        }

        public string Name
        {
            get { return m_name; }
        }

        public Permission RequestPermission(string resource)
        {
            return RequestPermission(resource, Permission.None);
        }

        public Permission RequestPermission(string resource, Permission current)
        {
            // Deny permissions always override any others
            if (current == Permission.Deny)
                return current;

            Permission temp = Permission.None;

            // Pickup non-None permissions
            if (m_resources.ContainsKey(resource) && m_resources[resource] != Permission.None)
                temp = m_resources[resource];

            if (m_parents != null)
            {
                foreach (Role parent in m_parents)
                {
                    temp = parent.RequestPermission(resource, temp);
                }
            }

            return temp;
        }

        public void GivePermission(string resource, Permission perm)
        {
            m_resources[resource] = perm;
        }
    }

    public class Resource
    {
        private string m_name;

        public Resource(string name)
        {
            m_name = name;
        }

        public string Name
        {
            get { return m_name; }
        }
    }

    #endregion

    #region Tests

    /// <summary>
    /// ACL Test class
    /// </summary>
    internal class ACLTester
    {
        public ACLTester()
        {
            ACL acl = new ACL();

            Role Guests = new Role("Guests");
            acl.AddRole(Guests);

            Role[] parents = new Role[0];
            parents[0] = Guests;

            Role JoeGuest = new Role("JoeGuest", parents);
            acl.AddRole(JoeGuest);

            Resource CanBuild = new Resource("CanBuild");
            acl.AddResource(CanBuild);

            acl.GrantPermission("Guests", "CanBuild");

            acl.HasPermission("JoeGuest", "CanBuild");
        }
    }

    #endregion
}


text:
Compiling/running servxd unit tests
------------------------------------

servxd unit tests are in the `src/test/` directory; they
use the Boost::Test unit-testing framework.

To compile and run the tests:

	cd src
	make -f makefile.unix test_servx  # Replace makefile.unix if you're not on unix
	./test_servx   # Runs the unit tests

If all tests succeed the last line of output will be:
`*** No errors detected`

To add more tests, add `BOOST_AUTO_TEST_CASE` functions to the existing
.cpp files in the test/ directory or add new .cpp files that
implement new BOOST_AUTO_TEST_SUITE sections (the makefiles are
set up to add test/*.cpp to test_servx automatically).

Compiling/running Servx-Qt unit tests
---------------------------------------

Bitcoin-Qt unit tests are in the src/qt/test/ directory; they
use the Qt unit-testing framework.

To compile and run the tests:

	qmake bitcoin-qt.pro BITCOIN_QT_TEST=1
	make
	./servx-qt_test

To add more tests, add them to the `src/qt/test/` directory,
the `src/qt/test/test_main.cpp` file, and bitcoin-qt.pro.


text:
"""Create a ccache binary for mac hosts."""

import argparse
import common
import os
import subprocess
import utils

URL = "https://github.com/ccache/ccache/releases/download/v3.7.7/ccache-3.7.7.tar.gz"
VERSION = "ccache-3.7.7"

def create_asset(target_dir):
  # configure --prefix requires an absolute path.
  target_dir = os.path.abspath(target_dir)

  # Download and extract the source.
  with utils.tmp_dir():
    subprocess.check_call(["curl", "-L", "-o", VERSION + ".tar.gz",
                           "https://github.com/ccache/ccache/releases/download/v3.7.7/ccache-3.7.7.tar.gz"])
    subprocess.check_call(["tar", "-xzf", VERSION + ".tar.gz"])
    os.chdir(VERSION)

    subprocess.check_call(["./configure", "--disable-man", "--prefix=" + target_dir])
    subprocess.check_call(["make"])
    subprocess.check_call(["make" ,"install"])

def main():
  parser = argparse.ArgumentParser()
  parser.add_argument('--target_dir', '-t', required=True)
  args = parser.parse_args()
  create_asset(args.target_dir)

if __name__ == '__main__':
  main()


text:
using System.Collections.Generic;
namespace SuperMap.WinRT.REST
{
    ///
    /// 	<para>${REST_QueryByGeometryService_Tile}</para>
    /// 	<para>${REST_QueryByGeometryService_Description}</para>
    ///
    public class QueryByGeometryService : QueryService
    {
        /// ${REST_QueryByGeometryService_constructor_None_D}
        /// <overloads>${REST_QueryByGeometryService_constructor_overloads}</overloads>
        public QueryByGeometryService() { }

        /// ${REST_QueryByGeometryService_string_constructor}
        /// <param name="url">${REST_QueryByGeometryService_string_constructor_param_url}</param>
        public QueryByGeometryService(string url) : base(url) { }
        /// ${REST_Query_QueryByDistanceService_method_GetParameters_D}
        /// <param name="parameters">${REST_Query_QueryByDistanceService_method_GetParameters_parameters}</param>
        protected override Dictionary<string, string> GetParameters(QueryParameters parameters)
        {
            Dictionary<string, string> dictionary = new Dictionary<string, string>();

            dictionary.Add("queryMode", "\"SpatialQuery\"");
            dictionary.Add("queryParameters", QueryParameters.ToJson(parameters));
            dictionary.Add("geometry", ServerGeometry.ToJson(((QueryByGeometryParameters)parameters).Geometry.ToServerGeometry()));
            dictionary.Add("spatialQueryMode", string.Format("\"{0}\"", ((QueryByGeometryParameters)parameters).SpatialQueryMode));

            return dictionary;
        }
    }
}


text:
package main

import (
	"crypto/md5"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"io"
	"kara"
	"model"
	"net/http"
	"os"
	"os/exec"
	"sync"
	"time"

	"github.com/labstack/echo"
	"github.com/nareix/joy4/av"
	"github.com/nareix/joy4/av/avutil"
	"github.com/nareix/joy4/av/pktque"
	"github.com/nareix/joy4/av/pubsub"
	"github.com/nareix/joy4/format"
	"github.com/nareix/joy4/format/flv"
	"github.com/nareix/joy4/format/rtmp"
)

type avinfo struct {
	AID   string   `json:"aid"`
	Tags  []string `json:"tags"`
	Title string   `json:"title"`
}

//Channel is struct of the subpub queue
type Channel struct {
	que *pubsub.Queue
}

type writeFlusher struct {
	httpflusher http.Flusher
	io.Writer
}

//FrameDropper defines the drop frame
type FrameDropper struct {
	Interval     int
	n            int
	skipping     bool
	DelaySkip    time.Duration
	lasttime     time.Time
	lastpkttime  time.Duration
	delay        time.Duration
	SkipInterval int
}

//User user
type User struct {
	Username string `json:"username"`
	Password string `json:"password"`
}

var (
	cachepath = "./zealot/.avcache"
	videopath = "./static/video/"
)

func init() {
	format.RegisterAll()
}

func (w writeFlusher) Flush() error {
	w.httpflusher.Flush()
	return nil
}

//ModifyPacket implement the  ModifyPacket interface
func (fp *FrameDropper) ModifyPacket(pkt *av.Packet, streams []av.CodecData, videoidx int, audioidx int) (drop bool, err error) {
	if fp.DelaySkip != 0 && pkt.Idx == int8(videoidx) {
		now := time.Now()
		if !fp.lasttime.IsZero() {
			realdiff := now.Sub(fp.lasttime)
			pktdiff := pkt.Time - fp.lastpkttime
			fp.delay += realdiff - pktdiff
		}
		fp.lasttime = time.Now()
		fp.lastpkttime = pkt.Time

		if !fp.skipping {
			if fp.delay > fp.DelaySkip {
				fp.skipping = true
				fp.delay = 0
			}
		} else {
			if pkt.IsKeyFrame {
				fp.skipping = false
			}
		}
		if fp.skipping {
			drop = true
		}

		if fp.SkipInterval != 0 && pkt.IsKeyFrame {
			if fp.n == fp.SkipInterval {
				fp.n = 0
				fp.skipping = true
			}
			fp.n++
		}
	}

	if fp.Interval != 0 {
		if fp.n >= fp.Interval && pkt.Idx == int8(videoidx) && !pkt.IsKeyFrame {
			drop = true
			fp.n = 0
		}
		fp.n++
	}

	return
}

//forwardviaFFmpeg will forward the rtmp address to another address
//need ffmpeg plugin
func forwardviaFFmpeg(src string, dst string) {
	exec.Command("ffmpeg", "-re", "-i", src, "-acodec", "libfaac", "-ab", "128k", "-vcodec", "libx264", "-s", "640x360", "-b:v", "500k", "-preset", "medium", "-vprofile", "baseline", "-r", "25 ", "-f", "flv", dst)
}

func main() {
	//WS server
	h := kara.NewHub()
	go h.Run()
	//Live
	//RTMP server
	s := new(rtmp.Server)
	// fenix := new(rtmp.Server)
	// fenix.Addr =":1936"
	mutex := new(sync.RWMutex)
	channels := make(map[string]*Channel)
	// FenixChannels := make(map[string]*Channel)
	// FenixMutex := new(sync.RWMutex)
	//hanleplay
	s.HandlePlay = func(conn *rtmp.Conn) {
		mutex.RLock()
		ch := channels[conn.URL.Path]
		mutex.RUnlock()

		if ch != nil {
			cursor := ch.que.Latest()
			avutil.CopyFile(conn, cursor)
		}
	}
	//HandlePublish
	s.HandlePublish = func(conn *rtmp.Conn) {
		streams, _ := conn.Streams()

		mutex.Lock()
		ch := channels[conn.URL.Path]
		if ch != nil {
			ch = nil
		} else {
			ch = new(Channel)
			ch.que = pubsub.NewQueue()
			ch.que.WriteHeader(streams)
			channels[conn.URL.Path] = ch
		}
		mutex.Unlock()
		if ch == nil {
			return
		}
		defer ch.que.Close()
		avutil.CopyPackets(ch.que, conn)
		mutex.Lock()
		delete(channels, conn.URL.Path)
		mutex.Unlock()
		return
	}

	go s.ListenAndServe()

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		//fork
		forwardviaFFmpeg("rtmp://localhost/test", "rtmp://localhost/md")
		//fork
		forwardviaFFmpeg("rtmp://localhost/test", "rtmp://localhost/md2")
		mutex.RLock()
		ch := channels[r.URL.Path]
		mutex.RUnlock()

		if ch != nil {
			w.Header().Set("Content-Type", "video/x-flv")
			w.Header().Set("Transfer-Encoding", "chunked")
			w.Header().Set("Access-Control-Allow-Origin", "*")
			w.WriteHeader(200)
			flusher := w.(http.Flusher)
			flusher.Flush()

			muxer := flv.NewMuxerWriteFlusher(writeFlusher{httpflusher: flusher, Writer: w})
			cursor := ch.que.Latest()
			streams, err := cursor.Streams()
			if err != nil {
				panic(err)
			}

			query := r.URL.Query()
			if q := query.Get("delaygop"); q != "" {
				n := 0
				fmt.Sscanf(q, "%d", &n)
				cursor = ch.que.DelayedGopCount(n)
			} else if q := query.Get("delaytime"); q != "" {
				dur, _ := time.ParseDuration(q)
				cursor = ch.que.DelayedTime(dur)
			}

			filters := pktque.Filters{}

			if q := query.Get("waitkey"); q != "" {
				filters = append(filters, &pktque.WaitKeyFrame{})
			}

			filters = append(filters, &pktque.FixTime{StartFromZero: true, MakeIncrement: true})

			if q := query.Get("framedrop"); q != "" {
				n := 0
				fmt.Sscanf(q, "%d", &n)
				filters = append(filters, &FrameDropper{Interval: n})
			}

			if q := query.Get("delayskip"); q != "" {
				dur, _ := time.ParseDuration(q)
				skipper := &FrameDropper{DelaySkip: dur}
				if q := query.Get("skipinterval"); q != "" {
					n := 0
					fmt.Sscanf(q, "%d", &n)
					skipper.SkipInterval = n
				}
				filters = append(filters, skipper)
			}

			demuxer := &pktque.FilterDemuxer{
				Filter:  filters,
				Demuxer: cursor,
			}

			muxer.WriteHeader(streams)
			avutil.CopyPackets(muxer, demuxer)
			muxer.WriteTrailer()
			// avutil.CopyFile(muxer, cursor)

		} else {
			http.NotFound(w, r)
		}
	})

	go http.ListenAndServe(":8091", nil)

	go func() {
		commands := []string{"-re", "-i", "/Users/scnace/go/src/Project/shakuras/static/video/17459827-1.flv", "-vcodec", "libx264", "-acodec", "aac", "-f", "flv", "rtmp://localhost/fenix"}
		cm := exec.Command("ffmpeg", commands...)
		cm.Run()
	}()
	//API Gateway
	e := echo.New()

	e.Static("/", "static")
	e.Static("/watch/js", "static/js")
	e.Static("/watch/css", "static/css")
	e.Static("/watch/video", "static/video")

	e.File("/", "static/chat.html")

	e.File("/live", "static/live.html")
	e.File("/fenix", "static/fenix.html")
	e.GET("/video", func(c echo.Context) error {
		vid := c.QueryParam("vid")
		if vid == "" {
			return c.JSON(404, "no such source.")
		}
		video, err := os.Open(videopath + vid + ".flv")
		if err != nil {
			return c.JSON(404, "no such source.")
		}
		return c.Stream(200, "video/mp4", video)
	})

	e.GET("/ws", func(c echo.Context) error {
		kara.ServeWs(h, c.Response().Writer(), c.Request())
		return nil
	})

	e.GET("/videotags", func(c echo.Context) error {
		data, err := model.ChangeType(cachepath, model.Bucketname)
		if err != nil {
			return c.JSON(http.StatusInternalServerError, err)
		}
		tags := []string{}
		info := make(map[string][]string)
		err = json.Unmarshal([]byte(data), &info)
		if err != nil {
			return c.JSON(http.StatusInternalServerError, err)
		}
		for k := range info {
			tags = append(tags, k)
		}
		return c.JSON(http.StatusOK, tags)
	})

	e.GET("/getSeries", func(c echo.Context) error {
		tagName := c.QueryParam("tagname")

		data, err := model.ChangeType(cachepath, model.Bucketname)
		if err != nil {
			return c.JSON(http.StatusInternalServerError, err)
		}
		info := make(map[string][]string)
		err = json.Unmarshal([]byte(data), &info)
		if err != nil {
			return c.JSON(http.StatusInternalServerError, err)
		}
		if info[tagName] != nil {
			res := []map[string]interface{}{}
			for _, v := range info[tagName] {
				resinfo := make(map[string]interface{})
				json.Unmarshal([]byte(v), &resinfo)
				res = append(res, resinfo)
			}
			return c.JSON(http.StatusOK, res)
		}
		return c.JSON(http.StatusOK, "no this tag")
	})

	e.GET("/firstvideo", func(c echo.Context) error {
		data, err := model.GetFirstVID(cachepath)
		if err != nil {
			return c.JSON(http.StatusInternalServerError, err)
		}
		var firstvid string
		for k := range data {
			firstvid = k
		}
		video, err := os.Open(videopath + firstvid + ".flv")
		if err != nil {
			return c.JSON(http.StatusNotFound, "no such source.")
		}
		return c.Stream(http.StatusOK, "video/mp4", video)
	})

	e.PUT("/regist", func(c echo.Context) error {

		user := new(User)
		if err := c.Bind(user); err != nil {
			return c.JSON(http.StatusBadRequest, "bad request")
		}
		username := user.Username
		pwd := user.Password
		if username == "" || pwd == "" {
			return c.JSON(http.StatusBadRequest, "bad request")
		}
		uhash := md5hash(username)
		userInfo := struct {
			Username string `json:"username"`
			Password string `json:"password"`
		}{
			username,
			pwd,
		}
		userInfoJSON, err := json.Marshal(userInfo)
		if err != nil {
			c.JSON(http.StatusBadGateway, err.Error())
		}
		//check username if not exist
		model.DefaultCachePath = ".usercache"
		err = model.CreateBucket("userinfo")
		if err != nil {
			return c.JSON(http.StatusBadGateway, err.Error())
		}
		uinfo, db, err := model.SelectDB("userinfo", uhash)
		if err != nil {
			return c.JSON(http.StatusBadGateway, err.Error())
		}
		db.Close()
		if uinfo == nil {
			err = model.InsertDB("userinfo", uhash, string(userInfoJSON))
			if err != nil {
				return c.JSON(http.StatusBadGateway, err.Error())
			}
			return c.JSON(http.StatusOK, "success")
		}
		return c.JSON(http.StatusUnprocessableEntity, "duplicate username")
	})

	e.POST("/login", func(c echo.Context) error {
		user := new(User)
		if err := c.Bind(user); err != nil {
			return c.JSON(http.StatusBadRequest, "Bad Request")
		}
		username := user.Username
		password := user.Password
		if username == "" || password == "" {
			return c.JSON(http.StatusBadRequest, "Bad Request")
		}
		uhash := md5hash(username)
		model.DefaultCachePath = ".usercache"
		uinfo, _, err := model.SelectDB("userinfo", uhash)
		if err != nil {
			return c.JSON(http.StatusServiceUnavailable, err.Error())
		}
		// db.Close()
		realInfo := make(map[string]string)
		err = json.Unmarshal(uinfo, &realInfo)

		if err != nil {
			return c.JSON(http.StatusServiceUnavailable, err.Error())
		}
		realPassword := realInfo["password"]
		if password == realPassword {
			cookie := new(http.Cookie)
			cookie.Name = "username"
			cookie.Value = username
			cookie.Expires = time.Now().Add(time.Hour * 12)
			c.SetCookie(cookie)
			return c.JSON(http.StatusOK, "OK")
		}
		return c.JSON(http.StatusBadRequest, "password not correct")
	})
	// e.GET("/v", func(c echo.Context) error {
	// 	mutex.RLock()
	// 	ch := channels[c.Request().URL.Path]
	// 	mutex.RUnlock()
	// 	if ch != nil {
	// 		c.Response().Header().Set("Content-Type", "video/x-flv")
	// 		c.Response().Header().Set("Transfer-Encoding", "chunked")
	// 		c.Response().WriteHeader(http.StatusOK)
	// 		flusher := c.Response().Writer().(http.Flusher)
	// 		c.Response().Flush()
	// 		muxer := flv.NewMuxerWriteFlusher(writeFlusher{httpflusher: flusher, Writer: c.Response().Writer()})
	// 		cursor := ch.que.Latest()
	//
	// 		avutil.CopyFile(muxer, cursor)
	// 		return c.JSON(http.StatusOK, nil)
	// 	}
	// 	return c.JSON(http.StatusNotFound, nil)
	//
	// })

	e.Logger.Fatal(e.Start(":8090"))

}

func md5hash(rawstr string) string {
	hasher := md5.New()
	hasher.Write([]byte(rawstr))
	return hex.EncodeToString(hasher.Sum(nil))
}


text:
package org.sana.net.http.handler;

import com.google.gson.reflect.TypeToken;

import org.sana.clients.Client;
import org.sana.net.Response;

import java.lang.reflect.Type;
import java.util.Collection;

/**
 * Created by winkler.em@gmail.com, on 06/05/2017.
 */
public class ClientResponseHandler  extends ApiResponseHandler<Response<Collection<Client>>>{

    @Override
    public Type getType() {
        return new TypeToken<Response<Collection<Client>>>(){}.getType();
    }
}


text:
var app = sm("do_App");
var page = sm("do_Page");

var back = ui("do_ImageView_1");
back.on("touch",function(){
	app.closePage();
})

var barcode = ui("do_BarcodeView_1");

page.on("start",function(){
	barcode.start(function(data, e) {
		var result = JSON.stringify(data);
		deviceone.print(result,"扫描结果");
		app.openPage("source://do_BarcodeView/view/weixin/result/index0.ui", data, function(data, e) {

		})
	})
})