text:
"use strict";
var __extends = (this && this.__extends) || (function () {
    var extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
Object.defineProperty(exports, "__esModule", { value: true });
var chai = require("chai");
var Index_1 = require("../src/Index");
var expect = chai.expect;
describe('Registration via attributes', function () {
    var sut;
    beforeEach(function () {
        sut = new Index_1.Container();
    });
    it('should return a new instance when resolving a transient entry', function () {
        // Arrange
        var instanceCount = 0;
        var Foo = (function () {
            function Foo() {
                ++instanceCount;
            }
            Foo = __decorate([
                Index_1.InstancePerDependency(),
                __metadata("design:paramtypes", [])
            ], Foo);
            return Foo;
        }());
        sut.register(Foo);
        // Act
        var instance = sut.resolve(Foo);
        // Assert
        expect(instance instanceof Foo).to.equal(true, "instance should be a Foo but was " + typeof instance);
        expect(instanceCount).to.equal(1);
    });
    it('should construct a new instance for each resolution of a transient entry', function () {
        // Arrange
        var instanceCount = 0;
        var Foo = (function () {
            function Foo() {
                ++instanceCount;
            }
            Foo = __decorate([
                Index_1.InstancePerDependency(),
                __metadata("design:paramtypes", [])
            ], Foo);
            return Foo;
        }());
        // Act
        sut.register(Foo);
        var instanceA = sut.resolve(Foo);
        var instanceB = sut.resolve(Foo);
        // Assert
        expect(instanceA instanceof Foo).to.be.true;
        expect(instanceB instanceof Foo).to.be.true;
        expect(instanceCount).to.equal(2);
        expect(instanceA).to.not.equal(instanceB);
    });
    it('should resolve implementation registered for service when resolving', function () {
        // Arrange
        var IAnimal = (function () {
            function IAnimal() {
            }
            return IAnimal;
        }());
        var Dog = (function () {
            function Dog() {
            }
            Dog = __decorate([
                Index_1.InstancePerDependency(IAnimal)
            ], Dog);
            return Dog;
        }());
        sut.register(IAnimal);
        sut.register(Dog);
        // Arrange
        var instance = sut.resolve(IAnimal);
        // Assert
        expect(instance instanceof Dog).to.be.true;
    });
    it('should allow transient implementations to register as multiple services', function () {
        // Arrange
        var IAnimal = (function () {
            function IAnimal() {
            }
            return IAnimal;
        }());
        var IPet = (function () {
            function IPet() {
            }
            return IPet;
        }());
        var Dog = (function () {
            function Dog() {
            }
            Dog = __decorate([
                Index_1.InstancePerDependency(IAnimal, IPet)
            ], Dog);
            return Dog;
        }());
        sut.register(IAnimal);
        sut.register(IPet);
        sut.register(Dog);
        // Arrange
        var instanceA = sut.resolve(IAnimal);
        var instanceB = sut.resolve(IPet);
        // Assert
        expect(instanceA instanceof Dog).to.be.true;
        expect(instanceB instanceof Dog).to.be.true;
    });
    it('should only construct one instance of a singleton entry', function () {
        // Arrange
        var instanceCount = 0;
        var Foo = (function () {
            function Foo() {
                ++instanceCount;
            }
            Foo = __decorate([
                Index_1.SingleInstance(),
                __metadata("design:paramtypes", [])
            ], Foo);
            return Foo;
        }());
        sut.register(Foo);
        // Act
        var instanceA = sut.resolve(Foo);
        var instanceB = sut.resolve(Foo);
        // Assert
        expect(instanceA instanceof Foo).to.be.true;
        expect(instanceB instanceof Foo).to.be.true;
        expect(instanceCount).to.equal(1);
        expect(instanceA).to.equal(instanceB);
    });
    it('should allow singleton implementations to register as multiple services', function () {
        // Arrange
        var IAnimal = (function () {
            function IAnimal() {
            }
            return IAnimal;
        }());
        var IPet = (function () {
            function IPet() {
            }
            return IPet;
        }());
        var Dog = (function () {
            function Dog() {
            }
            Dog = __decorate([
                Index_1.SingleInstance(IAnimal, IPet)
            ], Dog);
            return Dog;
        }());
        sut.register(IAnimal);
        sut.register(IPet);
        sut.register(Dog);
        // Arrange
        var instanceA = sut.resolve(IAnimal);
        var instanceB = sut.resolve(IPet);
        // Assert
        expect(instanceA instanceof Dog).to.be.true;
        expect(instanceB instanceof Dog).to.be.true;
        expect(instanceA).to.equal(instanceB);
    });
    it('should resolve parameters when resolving an instance', function () {
        // Arrange
        var Bar = (function () {
            function Bar() {
            }
            Bar = __decorate([
                Index_1.InstancePerDependency()
            ], Bar);
            return Bar;
        }());
        var Foo = (function () {
            function Foo(bar) {
                this.bar = bar;
            }
            Foo = __decorate([
                Index_1.InstancePerDependency(),
                __metadata("design:paramtypes", [Bar])
            ], Foo);
            return Foo;
        }());
        sut.register(Bar);
        sut.register(Foo);
        // Act
        var instance = sut.resolve(Foo);
        // Assert
        expect(instance instanceof Foo).to.be.true;
        expect(instance.bar instanceof Bar).to.be.true;
    });
    it('should respect parameters lifetimes when resolving an instance', function () {
        // Arrange
        var barInstanceCount = 0;
        var bazInstanceCount = 0;
        var Bar = (function () {
            function Bar() {
                ++barInstanceCount;
            }
            Bar = __decorate([
                Index_1.SingleInstance(),
                __metadata("design:paramtypes", [])
            ], Bar);
            return Bar;
        }());
        var Baz = (function () {
            function Baz() {
                ++bazInstanceCount;
            }
            Baz = __decorate([
                Index_1.InstancePerDependency(),
                __metadata("design:paramtypes", [])
            ], Baz);
            return Baz;
        }());
        var Foo = (function () {
            function Foo(bar, baz) {
                this.bar = bar;
                this.baz = baz;
            }
            Foo = __decorate([
                Index_1.InstancePerDependency(),
                __metadata("design:paramtypes", [Bar, Baz])
            ], Foo);
            return Foo;
        }());
        sut.register(Foo);
        sut.register(Bar);
        sut.register(Baz);
        // Act
        sut.resolve(Foo);
        sut.resolve(Foo);
        // Assert
        expect(barInstanceCount).to.equal(1);
        expect(bazInstanceCount).to.equal(2);
    });
    it('should resolve registered instances rather than constructing new instances', function () {
        // Arrange
        var instanceCount = 0;
        var Foo = (function () {
            function Foo() {
                ++instanceCount;
            }
            Foo = __decorate([
                Index_1.InstancePerDependency(),
                __metadata("design:paramtypes", [])
            ], Foo);
            return Foo;
        }());
        var instanceA = new Foo();
        sut.register(Foo).resetResolutionStrategy().providedInstance(instanceA);
        // Act
        var instanceB = sut.resolve(Foo);
        // Assert
        expect(instanceB instanceof Foo).to.be.true;
        expect(instanceCount).to.equal(1);
        expect(instanceA).to.equal(instanceB);
    });
    it('should resolve an empty array when there are no registrations for a service injected as an array', function () {
        // Arrange
        var IAnimal = (function () {
            function IAnimal() {
            }
            return IAnimal;
        }());
        var Zoo = (function () {
            function Zoo(animals) {
                this.animals = animals;
            }
            Zoo = __decorate([
                Index_1.InstancePerDependency(),
                __param(0, Index_1.ArrayOf(IAnimal)),
                __metadata("design:paramtypes", [Array])
            ], Zoo);
            return Zoo;
        }());
        sut.register(IAnimal);
        sut.register(Zoo);
        // Act
        var instance = sut.resolve(Zoo);
        // Assert
        expect(instance.animals.length).to.equal(0);
    });
    it('should resolve all registrations for a service when resolving an array', function () {
        // Arrange
        var IAnimal = (function () {
            function IAnimal() {
            }
            return IAnimal;
        }());
        var Dog = (function () {
            function Dog() {
            }
            Dog = __decorate([
                Index_1.InstancePerDependency(IAnimal)
            ], Dog);
            return Dog;
        }());
        var Cat = (function () {
            function Cat() {
            }
            Cat = __decorate([
                Index_1.InstancePerDependency(IAnimal)
            ], Cat);
            return Cat;
        }());
        var Zoo = (function () {
            function Zoo(animals) {
                this.animals = animals;
            }
            Zoo = __decorate([
                Index_1.InstancePerDependency(),
                __param(0, Index_1.ArrayOf(IAnimal)),
                __metadata("design:paramtypes", [Array])
            ], Zoo);
            return Zoo;
        }());
        sut.register(IAnimal);
        sut.register(Dog);
        sut.register(Cat);
        sut.register(Zoo);
        // Act
        var instance = sut.resolve(Zoo);
        // Assert
        expect(instance.animals.length).to.equal(2);
        expect(instance.animals[0] instanceof Dog).to.be.true;
        expect(instance.animals[1] instanceof Cat).to.be.true;
    });
    it('should respect lifetime registrations when resolving arrays', function () {
        // Arrange
        var dogInstanceCount = 0;
        var IAnimal = (function () {
            function IAnimal() {
            }
            return IAnimal;
        }());
        var Dog = (function () {
            function Dog() {
                ++dogInstanceCount;
            }
            Dog = __decorate([
                Index_1.SingleInstance(IAnimal),
                __metadata("design:paramtypes", [])
            ], Dog);
            return Dog;
        }());
        var Cat = (function () {
            function Cat() {
            }
            Cat = __decorate([
                Index_1.InstancePerDependency(IAnimal)
            ], Cat);
            return Cat;
        }());
        var Zoo = (function () {
            function Zoo(animals) {
                this.animals = animals;
            }
            Zoo = __decorate([
                Index_1.InstancePerDependency(),
                __param(0, Index_1.ArrayOf(IAnimal)),
                __metadata("design:paramtypes", [Array])
            ], Zoo);
            return Zoo;
        }());
        sut.register(IAnimal);
        sut.register(Dog);
        sut.register(Cat);
        sut.register(Zoo);
        // Act
        sut.resolve(Zoo);
        sut.resolve(Zoo);
        // Assert
        expect(dogInstanceCount).to.equal(1);
    });
    it('should inject factories where the factory attribute is used', function () {
        // Arrange
        var Foo = (function () {
            function Foo() {
            }
            Foo = __decorate([
                Index_1.InstancePerDependency()
            ], Foo);
            return Foo;
        }());
        var Bar = (function () {
            function Bar(factory) {
                this.a = factory();
                this.b = factory();
            }
            Bar = __decorate([
                Index_1.InstancePerDependency(),
                __param(0, Index_1.Factory(Foo)),
                __metadata("design:paramtypes", [Function])
            ], Bar);
            return Bar;
        }());
        sut.register(Foo);
        sut.register(Bar);
        // Act
        var instance = sut.resolve(Bar);
        // Assert
        expect(instance.a instanceof Foo).to.be.true;
        expect(instance.b instanceof Foo).to.be.true;
        expect(instance.a === instance.b).to.be.false;
    });
    it('should respect the lifetime registrations when resolving through factories', function () {
        // Arrange
        var instanceCount = 0;
        var Foo = (function () {
            function Foo() {
                ++instanceCount;
            }
            Foo = __decorate([
                Index_1.SingleInstance(),
                __metadata("design:paramtypes", [])
            ], Foo);
            return Foo;
        }());
        var Bar = (function () {
            function Bar(factory) {
                this.a = factory();
                this.b = factory();
            }
            Bar = __decorate([
                Index_1.InstancePerDependency(),
                __param(0, Index_1.Factory(Foo)),
                __metadata("design:paramtypes", [Function])
            ], Bar);
            return Bar;
        }());
        sut.register(Foo);
        sut.register(Bar);
        // Act
        sut.resolve(Bar);
        // Assert
        expect(instanceCount).to.equal(1);
    });
    it('should respect per scope container registrations when resolving through factories', function () {
        // Arrange
        var instanceCount = 0;
        var MyScope = 'MyScope';
        var Leaf = (function () {
            function Leaf() {
                ++instanceCount;
            }
            Leaf = __decorate([
                Index_1.InstancePerScope(MyScope),
                __metadata("design:paramtypes", [])
            ], Leaf);
            return Leaf;
        }());
        var Lv1 = (function () {
            function Lv1(a, b) {
                this.a = a;
                this.b = b;
            }
            Lv1 = __decorate([
                Index_1.InstancePerDependency(),
                __metadata("design:paramtypes", [Leaf, Leaf])
            ], Lv1);
            return Lv1;
        }());
        var Lv2 = (function () {
            function Lv2(lv1Factory, lv1FactoryScoped) {
                this.lv1Factory = lv1Factory;
                this.lv1FactoryScoped = lv1FactoryScoped;
                this.a = lv1Factory();
                this.b = lv1Factory();
                this.c = lv1FactoryScoped();
            }
            Lv2 = __decorate([
                Index_1.InstancePerDependency(),
                __param(0, Index_1.Factory(Lv1)),
                __param(1, Index_1.ScopedFactory(MyScope, Lv1)),
                __metadata("design:paramtypes", [Function, Function])
            ], Lv2);
            return Lv2;
        }());
        var Root = (function () {
            function Root(factory) {
                this.a = factory();
                this.b = factory();
            }
            Root = __decorate([
                Index_1.InstancePerDependency(),
                __param(0, Index_1.ScopedFactory(MyScope, Lv2)),
                __metadata("design:paramtypes", [Function])
            ], Root);
            return Root;
        }());
        sut.register(Leaf);
        sut.register(Lv1);
        sut.register(Lv2);
        sut.register(Root);
        // Act
        sut.resolve(Root);
        // Assert
        expect(instanceCount).to.equal(4);
        // Details:
        // a->a->a: instance #1
        // a->a->b: instance #1
        // a->b->a: instance #1
        // a->b->b: instance #1
        // a->c->a: instance #2
        // a->c->b: instance #2
        // b->a->a: instance #3
        // b->a->b: instance #3
        // b->b->a: instance #3
        // b->b->b: instance #3
        // b->c->a: instance #4
        // b->c->b: instance #4
    });
    it('should respect per scope container registrations when resolving units of work', function () {
        // Arrange
        var instanceCount = 0;
        var MyScope = 'MyScope';
        var Leaf = (function () {
            function Leaf() {
                ++instanceCount;
            }
            Leaf = __decorate([
                Index_1.InstancePerScope(MyScope),
                __metadata("design:paramtypes", [])
            ], Leaf);
            return Leaf;
        }());
        var Lv1 = (function () {
            function Lv1(a, b) {
                this.a = a;
                this.b = b;
            }
            Lv1 = __decorate([
                Index_1.InstancePerDependency(),
                __metadata("design:paramtypes", [Leaf, Leaf])
            ], Lv1);
            return Lv1;
        }());
        var Lv2 = (function () {
            function Lv2(lv1Factory, lv1FactoryScoped) {
                this.lv1Factory = lv1Factory;
                this.lv1FactoryScoped = lv1FactoryScoped;
                this.a = lv1Factory().value;
                this.b = lv1Factory().value;
                this.c = lv1FactoryScoped().value;
            }
            Lv2 = __decorate([
                Index_1.InstancePerDependency(),
                __param(0, Index_1.UnitOfWork(Lv1)),
                __param(1, Index_1.ScopedUnitOfWork(MyScope, Lv1)),
                __metadata("design:paramtypes", [Function, Function])
            ], Lv2);
            return Lv2;
        }());
        var Root = (function () {
            function Root(factory) {
                this.a = factory().value;
                this.b = factory().value;
            }
            Root = __decorate([
                Index_1.InstancePerDependency(),
                __param(0, Index_1.ScopedUnitOfWork(MyScope, Lv2)),
                __metadata("design:paramtypes", [Function])
            ], Root);
            return Root;
        }());
        sut.register(Leaf);
        sut.register(Lv1);
        sut.register(Lv2);
        sut.register(Root);
        // Act
        sut.resolve(Root);
        // Assert
        expect(instanceCount).to.equal(4);
        // Details:
        // a->a->a: instance #1
        // a->a->b: instance #1
        // a->b->a: instance #1
        // a->b->b: instance #1
        // a->c->a: instance #2
        // a->c->b: instance #2
        // b->a->a: instance #3
        // b->a->b: instance #3
        // b->b->a: instance #3
        // b->b->b: instance #3
        // b->c->a: instance #4
        // b->c->b: instance #4
    });
    it('should resolve descendants with arguments provided to factories', function () {
        // Arrange
        var Color = (function () {
            function Color() {
            }
            Color.Red = new Color();
            Color.Green = new Color();
            return Color;
        }());
        var Knee = (function () {
            function Knee(color) {
                this.color = color;
            }
            Knee = __decorate([
                Index_1.InstancePerDependency(),
                __metadata("design:paramtypes", [Color])
            ], Knee);
            return Knee;
        }());
        var Leg = (function () {
            function Leg(knee) {
                this.knee = knee;
            }
            Leg = __decorate([
                Index_1.InstancePerDependency(),
                __metadata("design:paramtypes", [Knee])
            ], Leg);
            return Leg;
        }());
        var Robot = (function () {
            function Robot(factory) {
                this.left = factory(Color.Red);
                this.right = factory(Color.Green);
            }
            Robot = __decorate([
                Index_1.InstancePerDependency(),
                __param(0, Index_1.Factory(Color, Leg)),
                __metadata("design:paramtypes", [Function])
            ], Robot);
            return Robot;
        }());
        sut.register(Knee);
        sut.register(Leg);
        sut.register(Robot);
        // Act
        var instance = sut.resolve(Robot);
        // Assert
        expect(instance.left.knee.color).to.equal(Color.Red);
        expect(instance.right.knee.color).to.equal(Color.Green);
        expect(instance.left.knee.color).to.not.equal(instance.right.knee.color);
    });
    it('should override existing registrations when factory is provided with a parameter', function () {
        // Arrange
        var Param = (function () {
            function Param() {
            }
            Param = __decorate([
                Index_1.InstancePerDependency()
            ], Param);
            return Param;
        }());
        var Config = (function () {
            function Config() {
            }
            Config = __decorate([
                Index_1.InstancePerDependency()
            ], Config);
            return Config;
        }());
        var App = (function () {
            function App(factory) {
                this.config = factory(new Param());
            }
            App = __decorate([
                Index_1.InstancePerDependency(),
                __param(0, Index_1.Factory(Param, Config)),
                __metadata("design:paramtypes", [Function])
            ], App);
            return App;
        }());
        sut.register(Param); // Param exists as a transient in the global scope
        sut.register(Config);
        sut.register(App); // But it is also provided via a factory here
        // Act + Assert (no throw)
        sut.resolve(App);
    });
    it('should dispose of transient resources when the container is disposed', function () {
        // Arrange
        var disposeCount = 0;
        var Foo = (function () {
            function Foo() {
            }
            Foo.prototype.dispose = function () {
                ++disposeCount;
            };
            Foo = __decorate([
                Index_1.InstancePerDependency(),
                Index_1.Disposable()
            ], Foo);
            return Foo;
        }());
        sut.register(Foo);
        sut.resolve(Foo);
        sut.resolve(Foo);
        // Act
        sut.dispose();
        // Assert
        expect(disposeCount).to.equal(2);
    });
    it('should dispose of singleton resources when the container is disposed', function () {
        // Arrange
        var disposeCount = 0;
        var Foo = (function () {
            function Foo() {
            }
            Foo.prototype.dispose = function () {
                ++disposeCount;
            };
            Foo = __decorate([
                Index_1.SingleInstance(),
                Index_1.Disposable()
            ], Foo);
            return Foo;
        }());
        sut.register(Foo);
        sut.resolve(Foo);
        sut.resolve(Foo);
        // Act
        sut.dispose();
        // Assert
        expect(disposeCount).to.equal(1);
    });
    it('should dispose of resources created through factories when the container is disposed', function () {
        // Arrange
        var disposeCount = 0;
        var Foo = (function () {
            function Foo() {
            }
            Foo.prototype.dispose = function () {
                ++disposeCount;
            };
            Foo = __decorate([
                Index_1.InstancePerDependency(),
                Index_1.Disposable()
            ], Foo);
            return Foo;
        }());
        var FooFactory = (function () {
            function FooFactory(factory) {
                this.factory = factory;
            }
            FooFactory.prototype.create = function () {
                return this.factory();
            };
            FooFactory = __decorate([
                Index_1.InstancePerDependency(),
                __param(0, Index_1.Factory(Foo)),
                __metadata("design:paramtypes", [Function])
            ], FooFactory);
            return FooFactory;
        }());
        sut.register(Foo);
        sut.register(FooFactory);
        var factoryInstance = sut.resolve(FooFactory);
        factoryInstance.create();
        factoryInstance.create();
        // Act
        sut.dispose();
        // Assert
        expect(disposeCount).to.equal(2);
    });
    it('should dispose of transitively owned resources when a unit of work is disposed', function () {
        // Arrange
        var disposeCount = 0;
        var OwnedResource = (function () {
            function OwnedResource() {
            }
            OwnedResource.prototype.dispose = function () {
                ++disposeCount;
            };
            OwnedResource = __decorate([
                Index_1.InstancePerDependency(),
                Index_1.Disposable()
            ], OwnedResource);
            return OwnedResource;
        }());
        var MyWorkManager = (function () {
            function MyWorkManager(workFactory) {
                this.unitOfWork = workFactory();
            }
            MyWorkManager = __decorate([
                Index_1.InstancePerDependency(),
                __param(0, Index_1.UnitOfWork(OwnedResource)),
                __metadata("design:paramtypes", [Function])
            ], MyWorkManager);
            return MyWorkManager;
        }());
        sut.register(OwnedResource);
        sut.register(MyWorkManager);
        var instance = sut.resolve(MyWorkManager);
        // Act
        instance.unitOfWork.dispose();
        // Assert
        expect(disposeCount).to.equal(1);
    });
    it('should not dispose of non-owned resources, e.g., singletons, when a unit of work is disposed', function () {
        // Arrange
        var disposeCount = 0;
        var NotOwnedResource = (function () {
            function NotOwnedResource() {
            }
            NotOwnedResource.prototype.dispose = function () {
                ++disposeCount;
            };
            NotOwnedResource = __decorate([
                Index_1.SingleInstance(),
                Index_1.Disposable()
            ], NotOwnedResource);
            return NotOwnedResource;
        }());
        var MyWorkManager = (function () {
            function MyWorkManager(workFactory) {
                this.unitOfWork = workFactory();
            }
            MyWorkManager = __decorate([
                Index_1.InstancePerDependency(),
                __param(0, Index_1.UnitOfWork(NotOwnedResource)),
                __metadata("design:paramtypes", [Function])
            ], MyWorkManager);
            return MyWorkManager;
        }());
        sut.register(NotOwnedResource);
        sut.register(MyWorkManager);
        var instance = sut.resolve(MyWorkManager);
        // Act
        instance.unitOfWork.dispose();
        // Assert
        expect(disposeCount).to.equal(0);
    });
    it('should dispose of nested child containers when an ancestor is disposed', function () {
        // Arrange
        var disposeCount = 0;
        var OwnedResource = (function () {
            function OwnedResource() {
            }
            OwnedResource.prototype.dispose = function () {
                ++disposeCount;
            };
            OwnedResource = __decorate([
                Index_1.InstancePerDependency(),
                Index_1.Disposable()
            ], OwnedResource);
            return OwnedResource;
        }());
        var MyWorkManager = (function () {
            function MyWorkManager(workFactory) {
                this.unitOfWork = workFactory();
            }
            MyWorkManager = __decorate([
                Index_1.InstancePerDependency(),
                __param(0, Index_1.UnitOfWork(OwnedResource)),
                __metadata("design:paramtypes", [Function])
            ], MyWorkManager);
            return MyWorkManager;
        }());
        var MyOuterWorkManager = (function () {
            function MyOuterWorkManager(workFactory) {
                this.unitOfWork = workFactory();
            }
            MyOuterWorkManager = __decorate([
                Index_1.InstancePerDependency(),
                __param(0, Index_1.UnitOfWork(MyWorkManager)),
                __metadata("design:paramtypes", [Function])
            ], MyOuterWorkManager);
            return MyOuterWorkManager;
        }());
        sut.register(OwnedResource);
        sut.register(MyWorkManager);
        sut.register(MyOuterWorkManager);
        var instance = sut.resolve(MyOuterWorkManager);
        // Act
        instance.unitOfWork.dispose();
        // Assert
        expect(disposeCount).to.equal(1);
    });
    it('should resolve descendants with arguments passed to unit of work factory', function () {
        // Arrange
        var Color = (function () {
            function Color() {
            }
            Color.Blue = new Color();
            return Color;
        }());
        var OwnedResource = (function () {
            function OwnedResource(color) {
                this.color = color;
            }
            OwnedResource = __decorate([
                Index_1.InstancePerDependency(),
                __metadata("design:paramtypes", [Color])
            ], OwnedResource);
            return OwnedResource;
        }());
        var MyWorkManager = (function () {
            function MyWorkManager(workFactory) {
                this.unitOfWork = workFactory(Color.Blue);
            }
            MyWorkManager = __decorate([
                Index_1.InstancePerDependency(),
                __param(0, Index_1.UnitOfWork(Color, OwnedResource)),
                __metadata("design:paramtypes", [Function])
            ], MyWorkManager);
            return MyWorkManager;
        }());
        sut.register(OwnedResource);
        sut.register(MyWorkManager);
        // Act
        var instance = sut.resolve(MyWorkManager);
        // Assert
        expect(instance.unitOfWork.value.color).to.equal(Color.Blue);
    });
    it('should be possible to determine whether an object is registered via an annotation or not', function () {
        // Arrange
        var Foo = (function () {
            function Foo() {
            }
            Foo = __decorate([
                Index_1.SingleInstance()
            ], Foo);
            return Foo;
        }());
        var Bar = (function () {
            function Bar() {
            }
            Bar = __decorate([
                Index_1.InstancePerDependency()
            ], Bar);
            return Bar;
        }());
        var Baz = (function () {
            function Baz() {
            }
            return Baz;
        }());
        // Act
        var isFooAnnotated = Index_1.hasRegistrationAnnotation(Foo);
        var isBarAnnotated = Index_1.hasRegistrationAnnotation(Bar);
        var isBazAnnotated = Index_1.hasRegistrationAnnotation(Baz);
        // Assert
        expect(isFooAnnotated).to.be.true;
        expect(isBarAnnotated).to.be.true;
        expect(isBazAnnotated).to.be.false;
    });
    it('should be possible to register a type in multiple containers', function () {
        // Arrange
        var otherSut = new Index_1.Container();
        var Foo = (function () {
            function Foo() {
            }
            Foo = __decorate([
                Index_1.InstancePerDependency()
            ], Foo);
            return Foo;
        }());
        // Act
        sut.register(Foo);
        otherSut.register(Foo);
        // Assert
        expect(sut.resolve(Foo)).is.instanceof(Foo);
        expect(otherSut.resolve(Foo)).is.instanceof(Foo);
    });
    it('should ignore base class registrations', function () {
        // Arrange
        var Super = (function () {
            function Super() {
            }
            Super = __decorate([
                Index_1.InstancePerDependency()
            ], Super);
            return Super;
        }());
        var Foo = (function (_super) {
            __extends(Foo, _super);
            function Foo() {
                return _super !== null && _super.apply(this, arguments) || this;
            }
            Foo = __decorate([
                Index_1.SingleInstance()
            ], Foo);
            return Foo;
        }(Super));
        // Act
        sut.register(Super);
        sut.register(Foo);
        // Assert
        expect(sut.resolve(Foo)).equals(sut.resolve(Foo));
    });
    it('should allow registering a singleton of a base type and itself', function () {
        // Arrange
        var Super = (function () {
            function Super() {
            }
            Super.prototype.test = function () { return 1; };
            return Super;
        }());
        var Service = (function () {
            function Service() {
            }
            Service_1 = Service;
            Service.prototype.test = function () { return 2; };
            Service = Service_1 = __decorate([
                Index_1.SingleInstance(Super, Service_1) // NOTE: Registration as self here is not necessary. It will cause a warning.
            ], Service);
            return Service;
            var Service_1;
        }());
        var ConsumerA = (function () {
            function ConsumerA(service) {
                this.service = service;
            }
            ConsumerA.prototype.test = function () { return this.service.test(); };
            ConsumerA = __decorate([
                Index_1.InstancePerDependency(),
                __metadata("design:paramtypes", [Service])
            ], ConsumerA);
            return ConsumerA;
        }());
        var ConsumerB = (function () {
            function ConsumerB(service) {
                this.service = service;
            }
            ConsumerB.prototype.test = function () { return this.service.test(); };
            ConsumerB = __decorate([
                Index_1.InstancePerDependency(),
                __metadata("design:paramtypes", [Super])
            ], ConsumerB);
            return ConsumerB;
        }());
        sut.register(Service);
        sut.register(ConsumerA);
        sut.register(ConsumerB);
        // Act
        var a = sut.resolve(ConsumerA);
        var b = sut.resolve(ConsumerB);
        // Assert
        expect(a.test()).equals(2);
        expect(b.test()).equals(2);
    });
    it('should allow resolution as self when registered as a base type', function () {
        // Arrange
        var Super = (function () {
            function Super() {
            }
            Super.prototype.test = function () { return 1; };
            return Super;
        }());
        var Service = (function () {
            function Service() {
            }
            Service.prototype.test = function () { return 2; };
            Service = __decorate([
                Index_1.SingleInstance(Super)
            ], Service);
            return Service;
        }());
        var Consumer = (function () {
            function Consumer(factory) {
                this.factory = factory;
            }
            Consumer.prototype.test = function () {
                var instance = this.factory();
                return instance.test();
            };
            Consumer = __decorate([
                Index_1.InstancePerDependency(),
                __param(0, Index_1.Factory(Service)),
                __metadata("design:paramtypes", [Function])
            ], Consumer);
            return Consumer;
        }());
        // Act
        sut.register(Service);
        sut.register(Consumer);
        var consumer = sut.resolve(Consumer);
        var result = consumer.test();
        // Assert
        expect(result).equals(2);
    });
    it('should allow the user to override the parameter type using ParamOf', function () {
        // Arrange
        var Service = (function () {
            function Service() {
            }
            Service = __decorate([
                Index_1.InstancePerDependency()
            ], Service);
            return Service;
        }());
        var Consumer = (function () {
            function Consumer(service) {
                this.service = service;
            }
            Consumer = __decorate([
                Index_1.InstancePerDependency(),
                __param(0, Index_1.ParamOf(Service)),
                __metadata("design:paramtypes", [Object])
            ], Consumer);
            return Consumer;
        }());
        // Act
        sut.register(Service);
        sut.register(Consumer);
        var consumer = sut.resolve(Consumer);
        // Assert
        expect(consumer.service instanceof Service).to.be.true;
    });
    it('should allow registration after extends has been called in generated code', function () {
        // Context:
        //   When a class extends another in TypeScript the static enumerable properties are copied
        //   from the super type to the sub type. As we store metadata on the constructor functions
        //   this can cause issues when registering classes that are defined and extended in another
        //   module.
        // Arrange
        var Service = (function () {
            function Service() {
            }
            return Service;
        }());
        function moduleA(container) {
            var ServiceImplA = (function (_super) {
                __extends(ServiceImplA, _super);
                function ServiceImplA() {
                    var _this = _super !== null && _super.apply(this, arguments) || this;
                    _this.name = 'a';
                    return _this;
                }
                ServiceImplA = __decorate([
                    Index_1.SingleInstance(Service)
                ], ServiceImplA);
                return ServiceImplA;
            }(Service));
            container.register(ServiceImplA);
        }
        function moduleB(container) {
            var ServiceImplB = (function (_super) {
                __extends(ServiceImplB, _super);
                function ServiceImplB() {
                    var _this = _super !== null && _super.apply(this, arguments) || this;
                    _this.name = 'b';
                    return _this;
                }
                ServiceImplB = __decorate([
                    Index_1.SingleInstance(Service)
                ], ServiceImplB);
                return ServiceImplB;
            }(Service));
            container.register(ServiceImplB);
        }
        // Act
        sut.register(Service);
        moduleA(sut);
        moduleB(sut);
        var impls = sut.resolveManyAbstract(Service);
        // Assert
        var names = impls.map(function (impl) { return impl.name; });
        expect(names).to.deep.equal(['a', 'b']);
    });
});


text:
#pragma once

#define DELEGATE_IUNK_INTERFACE(objectClass, dualClass) \
	STDMETHODIMP_(ULONG) objectClass::X##dualClass::AddRef() \
		{ \
		METHOD_PROLOGUE(objectClass, dualClass) \
		return pThis->ExternalAddRef(); \
		} \
	STDMETHODIMP_(ULONG) objectClass::X##dualClass::Release() \
		{ \
		METHOD_PROLOGUE(objectClass, dualClass) \
		return pThis->ExternalRelease(); \
		} \
	STDMETHODIMP objectClass::X##dualClass::QueryInterface( \
		REFIID iid, LPVOID* ppvObj) \
		{ \
		METHOD_PROLOGUE(objectClass, dualClass) \
		return pThis->ExternalQueryInterface(&iid, ppvObj); \
		}

/*
* die idee an sich ist aus meiner sicht nicht so schlecht denn so koennte man auch den <company>/<product> speziellen pfad abhandeln.
* machen wir z.b. mit dem Meta auch so
*   ::SetEnvironmentVariable(_T("cticlientlocalappdata"), theServerSettings.GetCtiClientApplicationLocalDirectory().c_str());
*   ::SetEnvironmentVariable(_T("cticlientappdata"), theServerSettings.GetCtiClientApplicationRoamingDirectory().c_str());
*
* - die ansicht: voellig auf absolute FileNamen zu verzichten und alles relativ zu addressieren,
*   koennen wir getrost "ad acta" legen denn: es KANN NICHT in ein %ProgramFiles(x86)% verzeichnis geschrieben werden
*
* - andererseits gibt es inzwischen vermehrt produkte (spotify, chrome) die sich explizit lokal/per user installieren
* mal ein "per user" .msi bauen und einen pfad unter %appdata% installieren
*/
#define TOKEN_RESPONSE_USER_ENV_FMT	_T("%%appdata%%\\client_secret_%s.TokenResponse-user")
#define CLIENT_SECRET_ENV_FMT		_T("%%appdata%%\\client_secret_%s.json")

// CoAuthServiceCall command target
// diese klasse ist die MFC Version der ATL klasse (CCallbackoAuthImpl < T >)
class CoAuthServiceCall : public CCmdTarget
{
	friend class CoAuthRenewTokenAsync;

public:
	enum _state { InitialRequest, RetryOnce, Finish };

	CoAuthServiceCall();
	virtual void OnFinalRelease();

	HRESULT Init(LPCTSTR szMethod, LPCTSTR szUrl);
	enum _state GetState() { return m_eState; }
	HRESULT Dispose();

	// oAuthLib::IRenewCallback
	BEGIN_INTERFACE_PART(RenewCallback, oAuthLib::IRenewCallback)
		STDMETHOD(raw_Continue)();
		STDMETHOD(raw_Terminate)();
	END_INTERFACE_PART(RenewCallback)
	DECLARE_INTERFACE_MAP()

protected:
	DECLARE_DYNCREATE(CoAuthServiceCall)
	DECLARE_MESSAGE_MAP()

	DECLARE_DISPATCH_MAP()
	void ReadyStateChange();

protected:
	MSXML2::IXMLHTTPRequestPtr m_spRequest;
	CoAuthRenewTokenAsync* m_pRenewTokenAsync;

	virtual HRESULT GetTokenServer(oAuthLib::IAuthorize**) { return E_NOTIMPL; }
#ifdef AUTHORIZATION_SERVER_SUPPORT_JSON
	virtual void onSucceeded(web::json::value& result) { }
#else
	virtual void onSucceeded() { }
#endif
	virtual void onFailed() {
		TRACE2("  HTTP Status: 0x%d, %ls\n", m_spRequest->status, (BSTR)m_spRequest->statusText);
	}

	enum _state m_eState;
	_bstr_t m_bstrMethod;
	_bstr_t m_bstrUrl;

	// wir MUESSEN uns das zuletzt benutzte "access_token" merken
	// wir entscheiden zum ZEITPUNKT wo dieser request mit einem 401 zurueckkommt ob:
	// a.) wir die ersten sind die erkennen das ein Exchange noetig ist (und den Exchange triggern)
	// b.) aktuell bereits ein Exchange am laufen ist aber noch nicht beendet wurde. (wir wiederholen mit dem neuen token sobald es vorliegt)
	// c.) das access/refresh-token bereits aktualisiert wurde. (und wir direkt wiederholen koennen)
	CComBSTR m_bstrAccessToken;
};

redpajama_set_name: RedPajamaGithub


text:
from app import db

class Asset(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), index=True)
    bytes = db.Column(db.Integer)
    batch_id = db.Column(db.Integer, db.ForeignKey('batch.id'))

    def __repr__(self):
        return '<Asset %r>' % (self.name)

class Batches(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64))
    date = db.Column(db.DateTime)

    def __repr__(self):
        return '<Batch %r>' % (self.name)


text:
Posts

About

Colophon

RSS

Google+


text:
<?php

namespace vektah\parser_combinator\language\php\annotation;

use vektah\parser_combinator\Input;
use vektah\parser_combinator\Result;
use vektah\parser_combinator\combinator\Choice;
use vektah\parser_combinator\combinator\Many;
use vektah\parser_combinator\combinator\OptionalChoice;
use vektah\parser_combinator\combinator\Sequence;
use vektah\parser_combinator\formatter\Closure;
use vektah\parser_combinator\formatter\ClosureWithResult;
use vektah\parser_combinator\formatter\Ignore;
use vektah\parser_combinator\language\Grammar;
use vektah\parser_combinator\parser\PositiveMatch;
use vektah\parser_combinator\parser\RegexParser;
use vektah\parser_combinator\parser\RepSep;
use vektah\parser_combinator\parser\WhitespaceParser;
use vektah\parser_combinator\parser\literal\FloatLiteral;
use vektah\parser_combinator\parser\literal\IntLiteral;
use vektah\parser_combinator\parser\literal\StringLiteral;

class PhpAnnotationParser extends Grammar
{
    public function __construct() {
        $this->ws = new Ignore(new Many(new WhitespaceParser(1), '(/\*\*|\*/|\*)'));
        $this->ident = '[a-zA-Z_][a-zA-Z0-9_]*';
        $this->string = new StringLiteral();
        $this->float = new FloatLiteral();
        $this->int = new IntLiteral();

        $this->const = new ClosureWithResult(
            new Sequence(
                $this->ident,
                new OptionalChoice(
                    new Sequence(
                        '::',
                        $this->ident
                    )
                )
            ),
            function(Result $result, Input $input) {
                $data = $result->data;
                $line = $input->getLine($result->offset);

                if ($data[1]) {
                    return new ConstLookup($data[1][1], $data[0], $line);
                }

                return new ConstLookup($data[0], null, $line);
            }
        );

        $this->type = new Choice(
            $this->string,
            $this->float,
            $this->int,
            $this->const,
            new RegexParser('true', 'i'),
            new RegexParser('false', 'i'),
            new RegexParser('null', 'i')
        );

        $this->arguments = new Closure(
            new RepSep(
                new Sequence(
                    $this->ws,
                    new OptionalChoice(new Sequence(
                        $this->ident,
                        $this->ws,
                        '=',
                        $this->ws
                    )),
                    $this->type,
                    $this->ws
                )
            ),
            function($data) {
                $arguments = [];

                foreach ($data as $datum) {
                    if ($datum[0]) {
                        $arguments[$datum[0][0]] = $datum[1];
                    } else {
                        $arguments['value'] = $datum[1];
                    }
                }

                return $arguments;
            }
        );

        $this->array = new Closure(new Sequence(
            new Ignore('{'),
            new RepSep(new Sequence(
                $this->ws,
                new OptionalChoice(new Sequence(
                    $this->string,
                    $this->ws,
                    '=',
                    $this->ws
                )),
                $this->type,
                $this->ws
            )),
            new Ignore('}')
        ), function($data) {
            $result = [];
            foreach ($data[0] as $datum) {
                if ($datum[0]) {
                    $result[$datum[0][0]] = $datum[1];
                } else {
                    $result[] = $datum[1];
                }
            }

            return $result;
        });

        $this->type->append($this->array);

        $this->doctrine_annotation = new ClosureWithResult(new Sequence(
            new Ignore('@'),
            $this->ident,
            $this->ws,
            new OptionalChoice(new Sequence(
                new Ignore('('),
                PositiveMatch::instance(),
                $this->arguments,
                new Ignore(')')
            ))
        ), function(Result $result, Input $input) {
            $data = $result->data;
            $arguments = $data[1][0] ? $data[1][0] : [];
            return new DoctrineAnnotation($data[0], $arguments, $input->getLine($result->offset));
        });

        $this->type->append($this->doctrine_annotation);

        $this->non_doctrine_annotations = new ClosureWithResult(
            new Sequence('@', '[a-z][a-zA-Z0-9_\[\]]*', $this->ws, new RegexParser('[^@]*', 'ms')),
            function (Result $result, Input $input) {
                $value = str_replace('*/', '', $result->data[2]);
                $value = str_replace('*', '', $value);
                return new NonDoctrineAnnotation($result->data[1], trim($value), $input->getLine($result->offset));
            }
        );

        $this->comment = '[^@].*';

        $this->root = new Closure(
            new Sequence(
                $this->ws,
                new Many(
                    new Sequence(
                        new Choice(
                            $this->non_doctrine_annotations,
                            $this->doctrine_annotation,
                            $this->comment
                        ),
                        $this->ws
                    )
                )
            ),
            function($data) {
                return array_map(function($value) {
                    return $value[0];
                }, $data[0]);
            }
        );
    }
}


text:
import Key from 'input/keyboard/Key.js';

export default function DELETE () {

    return Key(46, 'DELETE');

}


text:
from openerp.tests.common import TransactionCase
from openerp.exceptions import ValidationError

class GlobalTestOpenAcademySession(TransactionCase):
    '''
    This create global test to sessions
    '''

    # Seudo-constructor method
    def setUp(self):
        super(GlobalTestOpenAcademySession, self).setUp()
        self.session = self.env['openacademy.session']
        self.partner_vauxoo = self.env.ref('base.res_partner_23')
        self.course = self.env.ref('openacademy.course1')
        self.partner_attende = self.env.ref('base.res_partner_5')
    # Generic methods
    # Test methods

    def test_10_instructor_is_attende(self):
        '''
        Check that raise of 'A session's instructor can't be an attendee'
        '''
        with self.assertRaisesRegexp(
                ValidationError,
                "A session's instructor can't be an attendee"
                ):
            self.session.create({
                'name': 'Session test 1',
                'seats': 1,
                'instructor_id': self.partner_vauxoo.id,
                'attendee_ids': [(6, 0, [self.partner_vauxoo.id])],
                'course_id': self.course.id,
            })

    def test_20_wkf_done(self):
        '''
        Check that the workflow work fine!
        '''
        session_test = self.session.create({
            'name': 'Session test 1',
            'seats': 2,
            'instructor_id': self.partner_vauxoo.id,
            'attendee_ids': [(6, 0, [self.partner_attende.id])],
            'course_id': self.course.id,
            })
        # Check initial state
        self.assertEqual(session_test.state, 'draft',
                         'Initial state should be in "draft"')

        # Change next state and check it
        session_test.signal_workflow('button_confirm')
        self.assertEqual(session_test.state, 'confirmed',
                         "Signal confirm don't work fine!")

        # Change next state and check it
        session_test.signal_workflow('button_done')
        self.assertEqual(session_test.state, 'done',
                         "Signal done don't work fine!")
        # self.env.cr.commit()  # Just to test the data
        # generated by the test. Please don't use!


text:
/**
   @file
   @ingroup pgm
   @brief opengm extensions
*/

#ifndef PGMLINK_PGM_H
#define PGMLINK_PGM_H

#include <vector>

#include <pgmlink/ext_opengm/loss_hamming.hxx>
#include <opengm/graphicalmodel/graphicalmodel.hxx>
#include <pgmlink/ext_opengm/loglinearmodel.hxx>
#include <opengm/inference/inference.hxx>
#include <opengm/functions/explicit_function.hxx>
#include <pgmlink/ext_opengm/decorator_weighted.hxx>
#include <pgmlink/ext_opengm/indicator_function.hxx>
#include <opengm/operations/adder.hxx>
#include <opengm/utilities/metaprogramming.hxx>

#include "pgmlink/hypotheses.h"
#include "pgmlink/graph.h"
#include "pgmlink/util.h"

namespace pgmlink {
  namespace pgm {
    using boost::shared_ptr;

    //typedef opengm::GraphicalModel<double, opengm::Adder> OpengmModel;
    typedef opengm::ExplicitFunction<double> ExplicitFunction;
    typedef opengm::FunctionDecoratorWeighted< opengm::IndicatorFunction<double> > FeatureFunction;
    typedef opengm::HammingFunction<double> LossFunction;
    typedef opengm::LoglinearModel<double,
      opengm::meta::TypeList<ExplicitFunction,
      opengm::meta::TypeList<FeatureFunction,
      opengm::meta::TypeList<LossFunction, opengm::meta::ListEnd > > > > OpengmModel;

    template <typename OGM_FUNCTION>
      class OpengmFactor {
    public:
      typedef OGM_FUNCTION FunctionType;

      OpengmFactor( const FunctionType&, const std::vector<size_t>& ogm_var_indices );
      template <typename ITER>
	OpengmFactor( const FunctionType&, ITER first_ogm_idx, ITER last_ogm_idx );

      typename FunctionType::ValueType get_value( std::vector<size_t> coords ) const;
      template <typename OGM_GRAPHICAL_MODEL>
	void add_to( OGM_GRAPHICAL_MODEL& ) const;

      FunctionType& function() { return ogmfunction_; }
      const FunctionType& function() const { return ogmfunction_; }
      const std::vector<size_t>& var_indices() const { return vi_; }
      const std::vector<size_t>& var_order() const { return order_; }

    protected:
      FunctionType ogmfunction_;
      std::vector<size_t> vi_;
      std::vector<size_t> order_;
    };

    template <typename VALUE>
      class OpengmExplicitFactor : public OpengmFactor<opengm::ExplicitFunction<VALUE> > {
    public:
      typedef typename OpengmFactor<opengm::ExplicitFunction<VALUE> >::FunctionType FunctionType;

      OpengmExplicitFactor( const std::vector<size_t>& ogm_var_indices, VALUE init=0, size_t states_per_var=2 );
      template <typename ITER>
	OpengmExplicitFactor( ITER first_ogm_idx, ITER last_ogm_idx, VALUE init=0, size_t states_per_var=2 );

      void set_value( std::vector<size_t> coords, VALUE v);

    private:
      void init_( VALUE init, size_t states_per_var );
    };

    template <typename VALUE>
      class OpengmWeightedFeature
      : public OpengmFactor< opengm::FunctionDecoratorWeighted< opengm::IndicatorFunction<VALUE> > >
    {
    public:
      typedef typename opengm::FunctionDecoratorWeighted< opengm::IndicatorFunction<VALUE> > FunctionType;

      template<class IT1, class IT2>
	OpengmWeightedFeature(const std::vector<size_t>& ogm_var_indices,
			      IT1 shapeBegin, IT1 shapeEnd,
			      IT2 indicate,
			      VALUE indicate_value = 1.,
			      VALUE weight = 1.,
			      VALUE default_value = 0);

      template <typename OGM_LOGLINEARMODEL>
	void add_as_feature_to( OGM_LOGLINEARMODEL&, typename OGM_LOGLINEARMODEL::IndexType weight_index ) const;

      void weight( VALUE w );
      VALUE weight() const;

      void indicate_value( VALUE v );
      VALUE indicate_value() const;

      void default_value( VALUE v );
      VALUE default_value() const;
    };

    /**
       @brief Accessing entries of a Factor/Function that was already added to a graphical model.

       Manages a pointer to an element of an array-like opengm function (usually opengm::ExplicitFunction).
       Validity of the pointer is ensured by owning a smart pointer to the full model.

       Use this class to modify factor elements of an already instantiated opengm graphical model.
    */
    class FactorEntry {
    public:
    FactorEntry() : entry_(NULL) {}
    FactorEntry( shared_ptr<OpengmModel> m, /**< has to be valid */
		 OpengmModel::ValueType* entry /**< has to point into the opengm model to ensure the same lifetime */
		 ) :
      m_(m), entry_(entry) {}

      void set( OpengmModel::ValueType );
      OpengmModel::ValueType get() const;

      shared_ptr<OpengmModel> model() const { return m_; }

    private:
      shared_ptr<OpengmModel> m_;
      OpengmModel::ValueType* entry_;
    };

/******************/
/* Implementation */
/******************/

////
//// class OpengmFactor
////
 template <typename OGM_FUNCTION>
   OpengmFactor<OGM_FUNCTION>::OpengmFactor( const FunctionType& f, const std::vector<size_t>& ogm_var_indices )
   : ogmfunction_(f), vi_(ogm_var_indices) {
  // store sorted order of indices
  indexsorter::sort_indices( vi_.begin(), vi_.end(), order_ );
}

 template <typename OGM_FUNCTION>
   template< typename ITER >
   OpengmFactor<OGM_FUNCTION>::OpengmFactor( const FunctionType& f, ITER first_ogm_idx, ITER last_ogm_idx )
   : ogmfunction_(f), vi_(first_ogm_idx, last_ogm_idx) {
  // store sorted order of indices
  indexsorter::sort_indices( vi_.begin(), vi_.end(), order_ );
 }

 template <typename OGM_FUNCTION>
   typename OpengmFactor<OGM_FUNCTION>::FunctionType::ValueType OpengmFactor<OGM_FUNCTION>::get_value( std::vector<size_t> coords ) const {
   if( coords.size() != vi_.size() ) {
     throw std::invalid_argument("OpengmFactor::get_value(): coordinate dimension differs from factor dimension");
   }
   indexsorter::reorder( coords, order_ );
   return ogmfunction_(coords.begin());
 }

 template <typename OGM_FUNCTION>
   template <typename OGM_GRAPHICAL_MODEL>
   void OpengmFactor<OGM_FUNCTION>::add_to( OGM_GRAPHICAL_MODEL& m ) const {
   std::vector<size_t> sorted_vi(vi_);
   std::sort(sorted_vi.begin(), sorted_vi.end());
   // opengm expects a monotonic increasing sequence
   if(!(m.isValidIndexSequence(sorted_vi.begin(), sorted_vi.end()))) {
     throw std::runtime_error("OpengmExplicitFactor::add_to(): invalid index sequence");
   }

   typename OGM_GRAPHICAL_MODEL::FunctionIdentifier id=m.addFunction( ogmfunction_ );
   m.addFactor(id, sorted_vi.begin(), sorted_vi.end());
 }

////
//// class OpengmExplicitFactor
////
 template <typename VALUE>
   OpengmExplicitFactor<VALUE>::OpengmExplicitFactor( const std::vector<size_t>& ogm_var_indices, VALUE init, size_t states_per_var )
   : OpengmFactor<opengm::ExplicitFunction<VALUE> >(opengm::ExplicitFunction<VALUE>(), ogm_var_indices) {
  init_( init, states_per_var );
}
 template <typename VALUE>
   template< typename ITER >
   OpengmExplicitFactor<VALUE>::OpengmExplicitFactor( ITER first_ogm_idx, ITER last_ogm_idx, VALUE init, size_t states_per_var )
   : OpengmFactor<opengm::ExplicitFunction<VALUE> >(opengm::ExplicitFunction<VALUE>(),first_ogm_idx, last_ogm_idx) {
  init_( init, states_per_var );
 }

 template <typename VALUE>
   void OpengmExplicitFactor<VALUE>::set_value( std::vector<size_t> coords, VALUE v) {
   if( coords.size() != this->vi_.size() ) {
     throw std::invalid_argument("OpengmExplicitFactor::set_value(): coordinate dimension differs from factor dimension");
   }
   typename opengm::ExplicitFunction<VALUE>::iterator element( this->ogmfunction_ );
   size_t index;

   indexsorter::reorder( coords, this->order_ );
   this->ogmfunction_.coordinatesToIndex(coords.begin(), index);
   element[index] = v;
 }

 template <typename VALUE>
   void OpengmExplicitFactor<VALUE>::init_( VALUE init, size_t states_per_var ) {
   std::vector<size_t> shape( this->vi_.size(), states_per_var );
   this->ogmfunction_ = opengm::ExplicitFunction<VALUE>( shape.begin(), shape.end(), init );
 }

////
//// class OpengmWeightedFeature
////
template<class VALUE>
  template<class IT1, class IT2>
  OpengmWeightedFeature<VALUE>::OpengmWeightedFeature(
			  const std::vector<size_t>& ogm_var_indices,
		          IT1 shapeBegin, IT1 shapeEnd,
			  IT2 indicate,
			  VALUE indicate_value,
			  VALUE weight,
			  VALUE default_value)
  : OpengmFactor<FunctionType >(FunctionType(new opengm::IndicatorFunction<VALUE>( shapeBegin,
										   shapeEnd,
										   indicate,
										   indicate_value,
										   default_value),
					     weight)
				, ogm_var_indices) {
   // replace function with a sorted variant
   std::vector<size_t> sorted_shape( shapeBegin, shapeEnd );
   indexsorter::reorder( sorted_shape, this->order_ );
   std::vector<size_t> sorted_indicate( this->ogmfunction_.innerFunction()->indicate() );
   indexsorter::reorder( sorted_indicate, this->order_ );

   this->ogmfunction_ = FunctionType(new opengm::IndicatorFunction<VALUE>( sorted_shape.begin(),
									   sorted_shape.end(),
									   sorted_indicate.begin(),
									   indicate_value,
									   default_value),
				     weight);
 }

template<class VALUE>
  template <typename OGM_LOGLINEARMODEL>
  void OpengmWeightedFeature<VALUE>::add_as_feature_to( OGM_LOGLINEARMODEL& m, typename OGM_LOGLINEARMODEL::IndexType weight_index ) const {
  std::vector<size_t> sorted_vi(this->vi_);
  std::sort(sorted_vi.begin(), sorted_vi.end());
  // opengm expects a monotonic increasing sequence
  if(!(m.isValidIndexSequence(sorted_vi.begin(), sorted_vi.end()))) {
    throw std::runtime_error("OpengmExplicitFactor::add_to(): invalid index sequence");
  }

  typename OGM_LOGLINEARMODEL::FunctionIdentifier id=m.addFeature( this->ogmfunction_, weight_index );
  m.addFactor(id, sorted_vi.begin(), sorted_vi.end());
 }

template<class VALUE>
  void OpengmWeightedFeature<VALUE>::weight( VALUE w ) {
  this->ogmfunction_.weight(w);
 }

template<class VALUE>
  VALUE OpengmWeightedFeature<VALUE>::weight() const {
  return this->ogmfunction_.weight();
 }

template<class VALUE>
  void OpengmWeightedFeature<VALUE>::indicate_value( VALUE v ) {
  this->ogmfunction_.innerFunction()->indicate_value(v);
 }

template<class VALUE>
  VALUE OpengmWeightedFeature<VALUE>::indicate_value() const {
  return this->ogmfunction_.innerFunction()->indicate_value();
 }

template<class VALUE>
  void OpengmWeightedFeature<VALUE>::default_value( VALUE v ) {
  this->ogmfunction_.innerFunction()->default_value(v);
 }

template<class VALUE>
  VALUE OpengmWeightedFeature<VALUE>::default_value() const {
  return this->ogmfunction_.innerFunction()->default_value();
 }

} /* namespace pgm */
} /* namespace pgmlink */

#endif /* PGMLINK_PGM_H */


text:
"""
Loading modules from a string representing the class name
or a short name that matches the dictionary item defined
in this module
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import importlib
import os

import tensorflow as tf

from niftynet.utilities.util_common import \
    damerau_levenshtein_distance as edit_distance

# pylint: disable=too-few-public-methods
SUPPORTED_APP = {
    'net_regress':
        'niftynet.application.regression_application.RegressionApplication',
    'net_segment':
        'niftynet.application.segmentation_application.SegmentationApplication',
    'net_autoencoder':
        'niftynet.application.autoencoder_application.AutoencoderApplication',
    'net_gan':
        'niftynet.application.gan_application.GANApplication',
    'net_classify':
        'niftynet.application.classification_application.'
        'ClassificationApplication',
}

SUPPORTED_NETWORK = {
    # GAN
    'simulator_gan':
        'niftynet.network.simulator_gan.SimulatorGAN',
    'simple_gan':
        'niftynet.network.simple_gan.SimpleGAN',

    # Segmentation
    "highres3dnet":
        'niftynet.network.highres3dnet.HighRes3DNet',
    "highres3dnet_small":
        'niftynet.network.highres3dnet_small.HighRes3DNetSmall',
    "highres3dnet_large":
        'niftynet.network.highres3dnet_large.HighRes3DNetLarge',
    "toynet":
        'niftynet.network.toynet.ToyNet',
    "unet":
        'niftynet.network.unet.UNet3D',
    "nonewnet":
        'niftynet.network.no_new_net.UNet3D',
    "vnet":
        'niftynet.network.vnet.VNet',
    "dense_vnet":
        'niftynet.network.dense_vnet.DenseVNet',
    "deepmedic":
        'niftynet.network.deepmedic.DeepMedic',
    "scalenet":
        'niftynet.network.scalenet.ScaleNet',
    "holisticnet":
        'niftynet.network.holistic_net.HolisticNet',
    "unet_2d":
        'niftynet.network.unet_2d.UNet2D',

    # classification
    "resnet": 'niftynet.network.resnet.ResNet',
    "se_resnet": 'niftynet.network.se_resnet.SE_ResNet',

    # autoencoder
    "vae": 'niftynet.network.vae.VAE'
}

SUPPORTED_LOSS_GAN = {
    'CrossEntropy': 'niftynet.layer.loss_gan.cross_entropy',
}

SUPPORTED_LOSS_SEGMENTATION = {
    "CrossEntropy":
        'niftynet.layer.loss_segmentation.cross_entropy',
    "CrossEntropy_Dense":
        'niftynet.layer.loss_segmentation.cross_entropy_dense',
    "Dice":
        'niftynet.layer.loss_segmentation.dice',
    "Dice_NS":
        'niftynet.layer.loss_segmentation.dice_nosquare',
    "Dice_Dense":
        'niftynet.layer.loss_segmentation.dice_dense',
    "Dice_Dense_NS":
        'niftynet.layer.loss_segmentation.dice_dense_nosquare',
    "Tversky":
        'niftynet.layer.loss_segmentation.tversky',
    "GDSC":
        'niftynet.layer.loss_segmentation.generalised_dice_loss',
    "DicePlusXEnt":
        'niftynet.layer.loss_segmentation.dice_plus_xent_loss',
    "WGDL":
        'niftynet.layer.loss_segmentation.generalised_wasserstein_dice_loss',
    "SensSpec":
        'niftynet.layer.loss_segmentation.sensitivity_specificity_loss',
    "VolEnforcement":
        'niftynet.layer.loss_segmentation.volume_enforcement',
    # "L1Loss":
    #     'niftynet.layer.loss_segmentation.l1_loss',
    # "L2Loss":
    #     'niftynet.layer.loss_segmentation.l2_loss',
    # "Huber":
    #     'niftynet.layer.loss_segmentation.huber_loss'
}

SUPPORTED_LOSS_REGRESSION = {
    "L1Loss":
        'niftynet.layer.loss_regression.l1_loss',
    "L2Loss":
        'niftynet.layer.loss_regression.l2_loss',
    "RMSE":
        'niftynet.layer.loss_regression.rmse_loss',
    "MAE":
        'niftynet.layer.loss_regression.mae_loss',
    "Huber":
        'niftynet.layer.loss_regression.huber_loss',
    "SmoothL1":
        'niftynet.layer.loss_regression.smooth_l1_loss',
    "Cosine":
        'niftynet.layer.loss_regression.cosine_loss'
}

SUPPORTED_LOSS_CLASSIFICATION = {
    "CrossEntropy":
        'niftynet.layer.loss_classification.cross_entropy',
}

SUPPORTED_LOSS_CLASSIFICATION_MULTI = {
    "ConfusionMatrix":
        'niftynet.layer.loss_classification_multi.loss_confusion_matrix',
    "Variability":
        'niftynet.layer.loss_classification_multi.loss_variability',
    "Consistency":
        'niftynet.layer.loss_classification_multi.rmse_consistency'
}

SUPPORTED_LOSS_AUTOENCODER = {
    "VariationalLowerBound":
        'niftynet.layer.loss_autoencoder.variational_lower_bound',
}

SUPPORTED_OPTIMIZERS = {
    'adam': 'niftynet.engine.application_optimiser.Adam',
    'gradientdescent': 'niftynet.engine.application_optimiser.GradientDescent',
    'momentum': 'niftynet.engine.application_optimiser.Momentum',
    'nesterov': 'niftynet.engine.application_optimiser.NesterovMomentum',

    'adagrad': 'niftynet.engine.application_optimiser.Adagrad',
    'rmsprop': 'niftynet.engine.application_optimiser.RMSProp',
}

SUPPORTED_INITIALIZATIONS = {
    'constant': 'niftynet.engine.application_initializer.Constant',
    'zeros': 'niftynet.engine.application_initializer.Zeros',
    'ones': 'niftynet.engine.application_initializer.Ones',
    'uniform_scaling':
        'niftynet.engine.application_initializer.UniformUnitScaling',
    'orthogonal': 'niftynet.engine.application_initializer.Orthogonal',
    'variance_scaling':
        'niftynet.engine.application_initializer.VarianceScaling',
    'glorot_normal':
        'niftynet.engine.application_initializer.GlorotNormal',
    'glorot_uniform':
        'niftynet.engine.application_initializer.GlorotUniform',
    'he_normal': 'niftynet.engine.application_initializer.HeNormal',
    'he_uniform': 'niftynet.engine.application_initializer.HeUniform'
}

SUPPORTED_EVALUATIONS = {
    'dice': 'niftynet.evaluation.segmentation_evaluations.dice',
    'jaccard': 'niftynet.evaluation.segmentation_evaluations.jaccard',
    'Dice': 'niftynet.evaluation.segmentation_evaluations.dice',
    'Jaccard': 'niftynet.evaluation.segmentation_evaluations.jaccard',
    'n_pos_ref': 'niftynet.evaluation.segmentation_evaluations.n_pos_ref',
    'n_neg_ref': 'niftynet.evaluation.segmentation_evaluations.n_neg_ref',
    'n_pos_seg': 'niftynet.evaluation.segmentation_evaluations.n_pos_seg',
    'n_neg_seg': 'niftynet.evaluation.segmentation_evaluations.n_neg_seg',
    'fp': 'niftynet.evaluation.segmentation_evaluations.fp',
    'fn': 'niftynet.evaluation.segmentation_evaluations.fn',
    'tp': 'niftynet.evaluation.segmentation_evaluations.tp',
    'tn': 'niftynet.evaluation.segmentation_evaluations.tn',
    'n_intersection': 'niftynet.evaluation.segmentation_evaluations'
                      '.n_intersection',
    'n_union': 'niftynet.evaluation.segmentation_evaluations.n_union',
    'specificity': 'niftynet.evaluation.segmentation_evaluations.specificity',
    'sensitivity': 'niftynet.evaluation.segmentation_evaluations.sensitivity',
    'accuracy': 'niftynet.evaluation.segmentation_evaluations.accuracy',
    'false_positive_rate': 'niftynet.evaluation.segmentation_evaluations'
                           '.false_positive_rate',
    'positive_predictive_values': 'niftynet.evaluation.segmentation_evaluations'
                                  '.positive_predictive_values',
    'negative_predictive_values': 'niftynet.evaluation.segmentation_evaluations'
                                  '.negative_predictive_values',
    'intersection_over_union': 'niftynet.evaluation.segmentation_evaluations'
                               '.intersection_over_union',
    'informedness': 'niftynet.evaluation.segmentation_evaluations.informedness',
    'markedness': 'niftynet.evaluation.segmentation_evaluations.markedness',
    'vol_diff': 'niftynet.evaluation.segmentation_evaluations.vol_diff',
    'average_distance': 'niftynet.evaluation.segmentation_evaluations'
                        '.average_distance',
    'hausdorff_distance': 'niftynet.evaluation.segmentation_evaluations'
                          '.hausdorff_distance',
    'hausdorff95_distance': 'niftynet.evaluation.segmentation_evaluations'
                            '.hausdorff95_distance',
    'com_ref': 'niftynet.contrib.evaluation.segmentation_evaluations.com_ref',
    'mse': 'niftynet.evaluation.regression_evaluations.mse',
    'rmse': 'niftynet.evaluation.regression_evaluations.rmse',
    'mae': 'niftynet.evaluation.regression_evaluations.mae',
    # 'r2': 'niftynet.contrib.evaluation.regression_evaluations.r2',
    'classification_accuracy': 'niftynet.evaluation.classification_evaluations'
                               '.accuracy',
    'roc_auc': 'niftynet.contrib.evaluation.classification_evaluations.roc_auc',
    'roc': 'niftynet.contrib.evaluation.classification_evaluations.roc',
}

SUPPORTED_EVENT_HANDLERS = {
    'model_restorer':
        'niftynet.engine.handler_model.ModelRestorer',
    'model_saver':
        'niftynet.engine.handler_model.ModelSaver',
    'sampler_threading':
        'niftynet.engine.handler_sampler.SamplerThreading',
    'apply_gradients':
        'niftynet.engine.handler_gradient.ApplyGradients',
    'output_interpreter':
        'niftynet.engine.handler_network_output.OutputInterpreter',
    'console_logger':
        'niftynet.engine.handler_console.ConsoleLogger',
    'tensorboard_logger':
        'niftynet.engine.handler_tensorboard.TensorBoardLogger',
    'performance_logger':
        'niftynet.engine.handler_performance.PerformanceLogger',
    'early_stopper':
        'niftynet.engine.handler_early_stopping.EarlyStopper',
}

SUPPORTED_ITERATION_GENERATORS = {
    'iteration_generator':
        'niftynet.engine.application_iteration.IterationMessageGenerator'
}

def select_module(module_name, type_str, lookup_table=None):
    """
    This function first tries to find the absolute module name
    by matching the static dictionary items, if not found, it
    tries to import the module by splitting the input ``module_name``
    as module name and class name to be imported.

    :param module_name: string that matches the keys defined in lookup_table
        or an absolute class name: module.name.ClassName
    :param type_str: type of the module (used for better error display)
    :param lookup_table: defines a set of shorthands for absolute class name
    """
    lookup_table = lookup_table or {}
    module_name = '{}'.format(module_name)
    is_external = True
    if module_name in lookup_table:
        module_name = lookup_table[module_name]
        is_external = False
    module_str, class_name = None, None
    try:
        module_str, class_name = module_name.rsplit('.', 1)
        the_module = importlib.import_module(module_str)
        the_class = getattr(the_module, class_name)
        if is_external:
            # print location of external module
            tf.logging.info('Import [%s] from %s.',
                            class_name, os.path.abspath(the_module.__file__))
        return the_class
    except (AttributeError, ValueError, ImportError) as not_imported:
        tf.logging.fatal(repr(not_imported))
        if '.' not in module_name:
            err = 'Could not import {}: ' \
                  'Incorrect module name "{}"; ' \
                  'expected "module.object".'.format(type_str, module_name)
        else:
            err = '{}: Could not import object' \
                  '"{}" from "{}"'.format(type_str, class_name, module_str)
        tf.logging.fatal(err)

        if not lookup_table:
            # no further guess
            raise ValueError(err)

        dists = dict(
            (k, edit_distance(k, module_name)) for k in list(lookup_table))
        closest = min(dists, key=dists.get)
        if dists[closest] <= 3:
            err = 'Could not import {2}: By "{0}", ' \
                  'did you mean "{1}"?\n "{0}" is ' \
                  'not a valid option. '.format(module_name, closest, type_str)
            tf.logging.fatal(err)
        raise ValueError(err)

class ModuleFactory(object):
    """
    General interface for importing a class by its name.
    """
    SUPPORTED = None
    type_str = 'object'

    @classmethod
    def create(cls, name):
        """
        import a class by name
        """
        return select_module(name, cls.type_str, cls.SUPPORTED)

class ApplicationNetFactory(ModuleFactory):
    """
    Import a network from ``niftynet.network`` or from user specified string
    """
    SUPPORTED = SUPPORTED_NETWORK
    type_str = 'network'

class ApplicationFactory(ModuleFactory):
    """
    Import an application from ``niftynet.application`` or
    from user specified string
    """
    SUPPORTED = SUPPORTED_APP
    type_str = 'application'

class LossGANFactory(ModuleFactory):
    """
    Import a GAN loss function from ``niftynet.layer`` or
    from user specified string
    """
    SUPPORTED = SUPPORTED_LOSS_GAN
    type_str = 'GAN loss'

class LossSegmentationFactory(ModuleFactory):
    """
    Import a segmentation loss function from ``niftynet.layer`` or
    from user specified string
    """
    SUPPORTED = SUPPORTED_LOSS_SEGMENTATION
    type_str = 'segmentation loss'

class LossRegressionFactory(ModuleFactory):
    """
    Import a regression loss function from ``niftynet.layer`` or
    from user specified string
    """
    SUPPORTED = SUPPORTED_LOSS_REGRESSION
    type_str = 'regression loss'

class LossClassificationFactory(ModuleFactory):
    """
    Import a classification loss function from niftynet.layer or
    from user specified string
    """
    SUPPORTED = SUPPORTED_LOSS_CLASSIFICATION
    type_str = 'classification loss'

class LossClassificationMultiFactory(ModuleFactory):
    """
    Import a classification loss function from niftynet.layer or
    from user specified string
    """
    SUPPORTED = SUPPORTED_LOSS_CLASSIFICATION_MULTI
    type_str = 'classification multi loss'

class LossAutoencoderFactory(ModuleFactory):
    """
    Import an autoencoder loss function from ``niftynet.layer`` or
    from user specified string
    """
    SUPPORTED = SUPPORTED_LOSS_AUTOENCODER
    type_str = 'autoencoder loss'

class OptimiserFactory(ModuleFactory):
    """
    Import an optimiser from ``niftynet.engine.application_optimiser`` or
    from user specified string
    """
    SUPPORTED = SUPPORTED_OPTIMIZERS
    type_str = 'optimizer'

class InitializerFactory(ModuleFactory):
    """
    Import an initializer from ``niftynet.engine.application_initializer`` or
    from user specified string
    """
    SUPPORTED = SUPPORTED_INITIALIZATIONS
    type_str = 'initializer'

    @staticmethod
    def get_initializer(name, args=None):
        """
        wrapper for getting the initializer.

        :param name:
        :param args: optional parameters for the initializer
        :return:
        """
        init_class = InitializerFactory.create(name)
        if args is None:
            args = {}
        return init_class.get_instance(args)

class EvaluationFactory(ModuleFactory):
    """
    Import an optimiser from niftynet.engine.application_optimiser or
    from user specified string
    """
    SUPPORTED = SUPPORTED_EVALUATIONS
    type_str = 'evaluation'

class EventHandlerFactory(ModuleFactory):
    """
    Import an event handler such as niftynet.engine.handler_console
    """
    SUPPORTED = SUPPORTED_EVENT_HANDLERS
    type_str = 'event handler'

class IteratorFactory(ModuleFactory):
    """
    Import an iterative message generator for the main engine loop
    """
    SUPPORTED = SUPPORTED_ITERATION_GENERATORS
    type_str = 'engine iterator'


text:
"""
This module contains a collection of models that implement a simple function:
:func:`~revscoring.Model.score`.  Currently, all models are
a subclass of :class:`revscoring.scoring.models.Learned`
which means that they also implement
:meth:`~revscoring.scoring.models.Learned.train` and
:meth:`~revscoring.scoring.models.Learned.cross_validate`.

Gradient Boosting
+++++++++++++++++
.. automodule:: revscoring.scoring.models.gradient_boosting

Naive Bayes
+++++++++++
.. automodule:: revscoring.scoring.models.naive_bayes

Linear Regression
+++++++++++++++++
.. automodule:: revscoring.scoring.models.linear

Support Vector
++++++++++++++
.. automodule:: revscoring.scoring.models.svc

Random Forest
+++++++++++++
.. automodule:: revscoring.scoring.models.random_forest

Abstract classes
++++++++++++++++
.. automodule:: revscoring.scoring.models.model

SciKit Learn-based models
+++++++++++++++++++++++++
.. automodule:: revscoring.scoring.models.sklearn

"""
from .gradient_boosting import GradientBoosting
from .linear import LogisticRegression
from .model import Classifier, Learned, open_file
from .naive_bayes import BernoulliNB, GaussianNB, MultinomialNB, NaiveBayes
from .random_forest import RandomForest
from .svc import RBFSVC, SVC, LinearSVC

__all__ = [
    Learned, Classifier, open_file,
    SVC, LinearSVC, RBFSVC, NaiveBayes, GaussianNB, MultinomialNB, BernoulliNB,
    RandomForest, GradientBoosting, LogisticRegression
]


text:
          <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Wipe Hours  This will set your hours to 0 for the specified date

          <form class="form-horizontal" role="form" id="wipeHoursDate">

			Date

				<input type="text" class="form-control" id="wipeHoursDatePicker" name="wipeHoursDatePicker">

			Comment

				<textarea id="wipeHoursComment" name="wipeHoursComment" cols="5" class="boxsizingBorder width100" placeholder="What is the reason for wiping the hours?"></textarea>

	</form>

          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
          <button id="wipeHoursButton" type="button" class="btn btn-primary">Wipe Hours</button>


text:
package quickforms.controller;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import quickforms.dao.Database;

/**
 *
 * @author achamney
 */
@WebServlet(name = "PutFile", urlPatterns = {"/putFile"})
public class PutFile extends HttpServlet {

    /**
     * Handles the HTTP
     * POST method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
       System.out.println("Saving Fact");
       //response.setContentType("text/html;charset=UTF-8");
       HashMap<String,String> parameters = new HashMap<String,String>();
       Database db = null;
       String json = null;
       String folder = "C:/images/";
       folder = request.getParameter("folder");
       System.out.println(folder);
       PrintWriter out = response.getWriter();
        try{

            List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
            for(FileItem item : items)
            {
                 if (item.isFormField()) {
                    if(item.getFieldName().equals("folder"))
                    {
                        folder = item.getString();
                    }
                }
            }
            for(FileItem item : items)
            {
                if (!item.isFormField()) {
                    saveFile(item,folder);
                    out.write(item.getName());
                }

            }
        }
        catch(Exception e)
        {
            out.write(e.toString());
        }
       out.close();
    }

    private void saveFile(FileItem item, String folderStr) throws IOException {
        // Process form file field (input type="file").
        String fieldname = item.getFieldName();
        String filename = FilenameUtils.getName(item.getName());

        File imgFolder = new File(folderStr);
        if(!imgFolder.exists()) imgFolder.mkdir();

        if(!filename.equals(""))
        {
            InputStream filecontent = item.getInputStream();

            if(filename.contains(".zip"))
            {
                //ByteArrayOutputStream out = new ByteArrayOutputStream();
                String foldername = folderStr+filename.substring(0, filename.length()-4);
                File folder = new File(foldername);
                if(!folder.exists()){
                        folder.mkdir();
                }
                unZipZipFileToLocation(filecontent,folder);
            }
            else
            {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                int thisByte=filecontent.read();
                while(thisByte != -1)
                {
                    baos.write(thisByte);
                    thisByte=filecontent.read();
                }
                File output2 = new File(folderStr+filename);
                FileOutputStream fout = new FileOutputStream(output2);
                fout.write(baos.toByteArray());
                fout.close();
            }
        }
        // ... (do your job here)
    }
     public void unZipZipFileToLocation(InputStream flInStr, File targetDir)
          throws IOException{

    try{
      ZipInputStream zis = new ZipInputStream(flInStr);
      try{
        ZipEntry entry = null;
        while((entry = zis.getNextEntry()) != null){
          String name = entry.getName();
          File newFile = new File(targetDir, name);
          if (entry.isDirectory() && ! newFile.exists() ){
            newFile.mkdirs();
          }
          else if (! entry.isDirectory() ){
            if (newFile.exists()){
              newFile.delete();
            }
            File parentDir = newFile.getParentFile();
            if (! parentDir.exists()){
              parentDir.mkdirs();
            }
            FileOutputStream stmOut = new FileOutputStream(newFile);
            try{
              simpleInputStreamToOutputStream(zis, stmOut);
            }
            finally{
              stmOut.close();
            }
          }
        }//end while.
      }
      finally{
        zis.close();
      }
    }
    finally{
      flInStr.close();
    }
  }

  private void simpleInputStreamToOutputStream(InputStream stmIn, OutputStream stmOut)
          throws IOException{

      IOUtils.copy(stmIn, stmOut);
//    byte[] buffer = null;
//    int iBufferSize = 8096;
//    buffer = new byte[iBufferSize];
//
//    boolean bKeepStreaming = true;
//    while (bKeepStreaming){
//      int iBytes = stmIn.read(buffer);
//      if (iBytes == -1){
//        bKeepStreaming = false;
//      }
//      else{
//        stmOut.write(buffer, 0, iBytes);
//      }//end else some bytes returned.
//    }//end while
  }

}


text:
{template '_header'}

<link rel="stylesheet" href="../addons/ewei_shopv2/plugin/exchange/static/css/common.css?v=201610091000">
<link href="../addons/ewei_shopv2/plugin/diypage/static/css/foxui.diy.css?v=201610091000"rel="stylesheet"type="text/css"/>

        {loop $diypage['items'] $diyitem}
            {template 'diypage/template/tpl_'.$diyitem['id']}
        {/loop}

恭喜!兑换成功!

确定

很遗憾!兑换码已失效!

知道了

    <input type="hidden" name="url" value="{php echo mobileUrl('exchange',array(),1);}" id="url">

{template '_footer'}


text:
using Genji.Models.Abstract;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;

namespace Genji.Models.Workers
{
    public class HttpRecorder : IHttpRecorder
    {
        public bool RecordingIncoming { get; set; }
        public string log { get; set; }
        private string cache { get; set; }
        public HttpRecorder(string logpath = null, bool recordIncoming = false)
        {
            RecordingIncoming = recordIncoming;
            var now = DateTime.Now;
            log = $"{logpath}Genji-Server-Log-{now.ToString("MM-dd-yy")}.txt";
        }
        public string ToTimeString(DateTime t)
        {
            return t.TimeOfDay.ToString();
        }
        public void Record(HttpContext context)
        {
            if (context.Response.ResponseCode == 200)
            {
                Console.ForegroundColor = ConsoleColor.White;
            }
            else
            {
                Console.ForegroundColor = ConsoleColor.Yellow;
            }
            PrintAndWrite($"{ToTimeString(DateTime.Now)} [{context.Response.ResponseCode}] HTTP {context.Request.Method}: {context.Request.PathWithArguments}");
        }
        public void Print(string content)
        {
            Console.ForegroundColor = ConsoleColor.Yellow;
            PrintAndWrite($"{ToTimeString(DateTime.Now)} [???] HTTP ???: {content}");
        }
        public void Warn(string content)
        {
            Console.ForegroundColor = ConsoleColor.Red;
            PrintAndWrite($"{ToTimeString(DateTime.Now)} [???] HTTP ???: {content}");
        }
        public void RecordException(Exception e)
        {
            Console.ForegroundColor = ConsoleColor.Red;
            PrintAndWrite($"{ToTimeString(DateTime.Now)} [???] HTTP ???: Genji server crashed because of {e.ToString()}: " + e.Message);
            PrintAndWrite(e.StackTrace);
        }

        public void RecordIncoming()
        {
            if (RecordingIncoming)
            {
                Console.ForegroundColor = ConsoleColor.Green;
                PrintAndWrite($"{ToTimeString(DateTime.Now)} [???] HTTP Incoming....");
            }
        }

        public void PrintAndWrite(string text)
        {
            Console.WriteLine(text);
            if (!string.IsNullOrEmpty(log))
            {
                cache += text + "\r\n";
                if (cache.Length > 10000)
                {
                    File.AppendAllText(log, cache);
                    cache = string.Empty;
                }
            }
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<com.twinone.locker.lock.PasswordView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:numlock="http://schemas.android.com/apk/res-auto"
    android:id="@+id/passwordView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:padding="0dp"
    numlock:cols="3"
    numlock:horizontalSpacing="7dp"
    numlock:maxHScale="1.2"
    numlock:maxVScale="1.2"
    numlock:maxWidth="400dp"
    numlock:rows="4"
    numlock:verticalSpacing="7dp" >

    <Button
        android:id="@+id/numlock_b1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="0px"
        android:gravity="center"
        android:padding="0px"
        android:text="@string/num1"
        android:textSize="@dimen/locker_button_text_size"
        android:textStyle="bold" />

    <Button
        android:id="@+id/numlock_b2"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="0px"
        android:gravity="center"
        android:padding="0px"
        android:text="@string/num2"
        android:textSize="@dimen/locker_button_text_size"
        android:textStyle="bold" />

    <Button
        android:id="@+id/numlock_b3"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:padding="0px"
        android:text="@string/num3"
        android:textSize="@dimen/locker_button_text_size"
        android:textStyle="bold" />

    <Button
        android:id="@+id/numlock_b4"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:padding="0px"
        android:text="@string/num4"
        android:textSize="@dimen/locker_button_text_size"
        android:textStyle="bold" />

    <Button
        android:id="@+id/numlock_b5"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:padding="0px"
        android:text="@string/num5"
        android:textSize="@dimen/locker_button_text_size"
        android:textStyle="bold" />

    <Button
        android:id="@+id/numlock_b6"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:padding="0px"
        android:text="@string/num6"
        android:textSize="@dimen/locker_button_text_size"
        android:textStyle="bold" />

    <Button
        android:id="@+id/numlock_b7"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:padding="0px"
        android:text="@string/num7"
        android:textSize="@dimen/locker_button_text_size"
        android:textStyle="bold" />

    <Button
        android:id="@+id/numlock_b8"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:padding="0px"
        android:text="@string/num8"
        android:textSize="@dimen/locker_button_text_size"
        android:textStyle="bold" />

    <Button
        android:id="@+id/numlock_b9"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:padding="0px"
        android:text="@string/num9"
        android:textSize="@dimen/locker_button_text_size"
        android:textStyle="bold" />

    <ImageButton
        android:id="@+id/numlock_bLeft"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:padding="0px" />

    <Button
        android:id="@+id/numlock_b0"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:padding="0px"
        android:text="@string/num0"
        android:textSize="@dimen/locker_button_text_size"
        android:textStyle="bold" />

    <ImageButton
        android:id="@+id/numlock_bRight"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:padding="0px" />

</com.twinone.locker.lock.PasswordView>


text:
<?xml version="1.0" encoding="UTF-8"?>
<actions>
        <action>
            <actionName>run</actionName>
            <packagings>
                <packaging>jar</packaging>
            </packagings>
            <goals>
                <goal>process-classes</goal>
                <goal>org.codehaus.mojo:exec-maven-plugin:1.2.1:exec</goal>
            </goals>
            <properties>
                <exec.args>-classpath %classpath uk.nominet.dnsjnio.demo.DemoClient</exec.args>
                <exec.executable>java</exec.executable>
                <exec.workingdir>target/classes</exec.workingdir>
            </properties>
        </action>
        <action>
            <actionName>debug</actionName>
            <packagings>
                <packaging>jar</packaging>
            </packagings>
            <goals>
                <goal>process-classes</goal>
                <goal>org.codehaus.mojo:exec-maven-plugin:1.2.1:exec</goal>
            </goals>
            <properties>
                <exec.args>-Xdebug -Xrunjdwp:transport=dt_socket,server=n,address=${jpda.address} -classpath %classpath uk.nominet.dnsjnio.demo.DemoClient</exec.args>
                <exec.executable>java</exec.executable>
                <jpda.listen>true</jpda.listen>
                <exec.workingdir>target/classes</exec.workingdir>
            </properties>
        </action>
        <action>
            <actionName>profile</actionName>
            <packagings>
                <packaging>jar</packaging>
            </packagings>
            <goals>
                <goal>process-classes</goal>
                <goal>org.codehaus.mojo:exec-maven-plugin:1.2.1:exec</goal>
            </goals>
            <properties>
                <exec.args>-classpath %classpath uk.nominet.dnsjnio.demo.DemoClient</exec.args>
                <exec.executable>java</exec.executable>
                <exec.workingdir>target/classes</exec.workingdir>
            </properties>
        </action>
    </actions>


text:
package wroblicky.andrew.euterpe.charts;

public enum TimeScope {
	ALL_TIME, WITHIN_RANGE;
}