text:
"use strict";

const should = require("should");
const mockrequire = require("mock-require");
const sinon = require("sinon");

const {
  KuzzleError,
  NotFoundError,
  PluginImplementationError,
} = require("../../../index");
const Plugin = require("../../../lib/core/plugin/plugin");
const KuzzleMock = require("../../mocks/kuzzle.mock");
const {
  BaseController,
} = require("../../../lib/api/controllers/baseController");

describe("Plugin", () => {
  let kuzzle;
  let plugin;
  let application;
  let PluginsManager;
  let pluginsManager;

  const createPlugin = (name, app = false) => {
    const instance = {
      init: sinon.stub().resolves(),
      config: {},
    };

    return new Plugin(instance, { name, application: app });
  };
  const createApplication = (name) => createPlugin(name, true);

  beforeEach(() => {
    kuzzle = new KuzzleMock();

    plugin = createPlugin("test-plugin");
    application = createApplication("lambda-core");

    mockrequire.reRequire("../../../lib/core/plugin/pluginContext");
    mockrequire.reRequire("../../../lib/core/plugin/privilegedContext");
    PluginsManager = mockrequire.reRequire(
      "../../../lib/core/plugin/pluginsManager"
    );

    pluginsManager = new PluginsManager();
  });

  describe("#set application", () => {
    it("should adds the application to plugins", () => {
      pluginsManager.application = application;
      pluginsManager._plugins.set(plugin.name, plugin);

      should(pluginsManager._plugins.get(application.name)).be.eql(application);
      should(pluginsManager.application).be.eql(application);
    });

    it("should throws error if there is already application", () => {
      pluginsManager.application = application;

      should(() => {
        pluginsManager.application = application;
      }).throw();
    });

    it("should throws error if there is already plugins", () => {
      pluginsManager._plugins.set(plugin.name, plugin);

      should(() => {
        pluginsManager.application = application;
      }).throw();
    });
  });

  describe("#get plugins", () => {
    it("should returns plugins", () => {
      pluginsManager.application = application;
      pluginsManager._plugins.set(plugin.name, plugin);

      should(Array.from(pluginsManager.plugins.keys())).be.length(1);
      should(pluginsManager._plugins.get(plugin.name)).be.eql(plugin);
    });
  });

  describe("#getPluginsDescription", () => {
    it("should returns plugins descriptions", () => {
      const otherPlugin = createPlugin("other-plugin");
      otherPlugin.info = sinon.stub().returns("other-plugin");
      plugin.info = sinon.stub().returns("plugin");
      pluginsManager._plugins.set(plugin.name, plugin);
      pluginsManager._plugins.set(otherPlugin.name, otherPlugin);

      const description = pluginsManager.getPluginsDescription();

      should(description).match({
        "test-plugin": "plugin",
        "other-plugin": "other-plugin",
      });
    });
  });

  describe("#init", () => {
    beforeEach(() => {
      pluginsManager._initControllers = sinon.stub();
      pluginsManager._initApi = sinon.stub().resolves();
      pluginsManager._initAuthenticators = sinon.stub();
      pluginsManager._initStrategies = sinon.stub();
      pluginsManager._initHooks = sinon.stub();
      pluginsManager._initPipes = sinon.stub();
      pluginsManager.loadPlugins = sinon.stub().returns(new Map());
    });

    it("should only load core plugins in failsafe mode", async () => {
      const loggerPlugin = createPlugin("kuzzle-plugin-logger");
      const localPlugin = createPlugin("kuzzle-plugin-auth-passport-local");
      pluginsManager.loadPlugins.returns(
        new Map([
          [loggerPlugin.name, loggerPlugin],
          [localPlugin.name, localPlugin],
        ])
      );
      pluginsManager._plugins.set(plugin.name, plugin);
      pluginsManager.config.common.failsafeMode = true;

      await pluginsManager.init();

      should(pluginsManager.loadedPlugins).be.eql([
        "kuzzle-plugin-logger",
        "kuzzle-plugin-auth-passport-local",
      ]);
    });

    it("should loads plugins with existing plugins", async () => {
      const otherPlugin = createPlugin("other-plugin");
      pluginsManager.loadPlugins.returns(
        new Map([
          [otherPlugin.name, otherPlugin],
          [application.name, application],
        ])
      );
      pluginsManager._plugins.set(plugin.name, plugin);

      await pluginsManager.init("additional plugins");

      should(pluginsManager._plugins.get(plugin.name)).be.eql(plugin);
      should(pluginsManager._plugins.get(otherPlugin.name)).be.eql(otherPlugin);
      should(pluginsManager.loadedPlugins).be.eql([
        "other-plugin",
        "test-plugin",
      ]);
    });

    it("should registers handlers on hook events ", async () => {
      await pluginsManager.init();

      should(kuzzle.on).be.calledTwice();
      should(kuzzle.on.getCall(0).args[0]).be.eql("plugin:hook:loop-error");
      should(kuzzle.on.getCall(1).args[0]).be.eql("hook:onError");
    });

    it("should calls the application init function", async () => {
      application.init = sinon.stub();
      pluginsManager.application = application;

      await pluginsManager.init();

      should(pluginsManager.application.init).be.calledWith(application.name);
    });

    it("should calls each plugin instance init function", async () => {
      pluginsManager.application = application;
      pluginsManager._plugins.set(plugin.name, plugin);

      await pluginsManager.init();

      should(plugin.instance.init).be.calledWith(plugin.config, plugin.context);
      should(application.instance.init).be.calledWith(
        application.config,
        application.context
      );
      should(plugin.initCalled).be.true();
      should(application.initCalled).be.true();
    });

    it("should registers plugins features", async () => {
      pluginsManager.config.common = {
        pipeWarnTime: 42,
        initTimeout: 100,
      };
      application.instance.api = "api";
      application.instance.hooks = "hooks";
      application.instance.pipes = "pipe";
      plugin.instance.controllers = "controllers";
      plugin.instance.authenticators = "authenticators";
      plugin.instance.strategies = "strategies";
      pluginsManager.application = application;
      pluginsManager._plugins.set(plugin.name, plugin);

      await pluginsManager.init();

      should(pluginsManager._initApi).be.calledWith(application);
      should(pluginsManager._initHooks).be.calledWith(application);
      should(pluginsManager._initPipes).be.calledWith(application);
      should(pluginsManager._initControllers).be.calledWith(plugin);
      should(pluginsManager._initAuthenticators).be.calledWith(plugin);
      should(pluginsManager._initStrategies).be.calledWith(plugin);
    });

    it("should throws an error if a plugin init method take too long", () => {
      pluginsManager.config.common = {
        initTimeout: 10,
      };
      pluginsManager.application = application;
      application.instance.init = () =>
        new Promise((resolve) => setTimeout(resolve, 15));

      return should(pluginsManager.init()).be.rejected();
    });
  });

  describe("#_initApi", () => {
    beforeEach(() => {
      plugin.instance.api = {
        email: {
          actions: {
            send: {
              handler: sinon.stub().resolves(),
            },
            receive: {
              handler: sinon.stub().resolves(),
              http: [
                { verb: "get", path: "/path-from-root" },
                { verb: "post", path: "path-with-leading-underscore" },
              ],
            },
          },
        },
      };
    });

    it("should create a BaseController and add corresponding actions", async () => {
      await pluginsManager._initApi(plugin);

      const emailController = pluginsManager.controllers.get("email");
      should(emailController).be.instanceOf(BaseController);
      should(emailController.__actions).be.eql(new Set(["send", "receive"]));
      should(emailController.send).be.a.Function();
      should(emailController.receive).be.a.Function();
    });

    it("should add http routes and generate default routes", async () => {
      await pluginsManager._initApi(plugin);

      should(pluginsManager.routes).match([
        {
          // generated route
          action: "send",
          controller: "email",
          openapi: undefined,
          path: "/_/email/send",
          verb: "get",
        },
        {
          action: "receive",
          controller: "email",
          openapi: undefined,
          path: "/path-from-root",
          verb: "get",
        },
        {
          action: "receive",
          controller: "email",
          openapi: undefined,
          path: "/_/path-with-leading-underscore",
          verb: "post",
        },
      ]);
    });

    it("should register openapi when defined", async () => {
      const openapi = {
        description: "Example",
        responses: {
          200: {
            description: "OK",
            content: {
              "application/json": {
                schema: {
                  type: "string",
                },
              },
            },
          },
        },
      };

      // HTTP route level
      plugin.instance.api.email.actions.receive.http[0].openapi = openapi;

      await pluginsManager._initApi(plugin);

      should(pluginsManager.routes).match([
        {
          // generated route
          action: "send",
          controller: "email",
          openapi: undefined,
          path: "/_/email/send",
          verb: "get",
        },
        {
          action: "receive",
          controller: "email",
          openapi,
          path: "/path-from-root",
          verb: "get",
        },
        {
          action: "receive",
          controller: "email",
          openapi: undefined,
          path: "/_/path-with-leading-underscore",
          verb: "post",
        },
      ]);
    });

    it("should throw an error if the openAPI specification is invalid", () => {
      plugin.instance.api.email.actions.receive.http[0].openapi = {
        invalid: "specification",
      };

      should(pluginsManager._initApi(plugin)).be.rejectedWith({
        id: "plugin.controller.invalid_openapi_schema",
      });
    });

    it("should throw an error if the openAPI specification is not an object", () => {
      plugin.instance.api.email.actions.receive.http[0].openapi = true;

      should(pluginsManager._initApi(plugin)).be.rejectedWith({
        id: "plugin.assert.invalid_controller_definition",
      });
    });

    it("should throw an error if the controller definition is invalid", () => {
      plugin.instance.api = {
        email: {
          actions: {
            handelr: sinon.stub().resolves(),
          },
        },
      };

      should(pluginsManager._initApi(plugin)).be.rejectedWith({
        id: "plugin.assert.invalid_controller_definition",
      });
    });

    it("should throw an error when trying to override a native controller", () => {
      plugin.instance.api = {
        document: {
          actions: {
            handler: sinon.stub().resolves(),
          },
        },
      };

      should(pluginsManager._initApi(plugin)).be.rejectedWith({
        id: "plugin.assert.invalid_controller_definition",
      });
    });
  });

  describe("#_initControllers", () => {
    it("should attach controller actions with method name", () => {
      plugin.instance.controllers = {
        foo: {
          actionName: "functionName",
        },
      };

      plugin.instance.functionName = () => {};

      pluginsManager._initControllers(plugin);

      should(pluginsManager.controllers.get("test-plugin/foo")).be.instanceof(
        BaseController
      );
      should(
        pluginsManager.controllers.get("test-plugin/foo").actionName
      ).be.eql(plugin.instance.functionName.bind(plugin.instance));
    });

    it("should attach controller actions with function", () => {
      const action = sinon.spy();

      plugin.instance.controllers = {
        foo: {
          actionName: action,
        },
      };

      plugin.instance.functionName = () => {};

      pluginsManager._initControllers(plugin);

      should(pluginsManager.controllers.get("test-plugin/foo")).be.instanceof(
        BaseController
      );
      should(
        pluginsManager.controllers.get("test-plugin/foo").actionName
      ).be.eql(action);
    });

    it("should attach controller routes on kuzzle object", () => {
      plugin.instance.routes = [
        { verb: "get", url: "/bar/:name", controller: "foo", action: "bar" },
        { verb: "head", url: "/bar/:name", controller: "foo", action: "bar" },
        { verb: "post", url: "/bar", controller: "foo", action: "bar" },
        { verb: "put", url: "/bar", controller: "foo", action: "bar" },
        { verb: "delete", url: "/bar", controller: "foo", action: "bar" },
        { verb: "patch", url: "/bar", controller: "foo", action: "bar" },
      ];

      plugin.instance.controllers = {
        foo: {
          bar: "functionName",
        },
      };

      plugin.instance.functionName = () => {};

      pluginsManager._initControllers(plugin);

      should(pluginsManager.routes).be.an.Array().and.length(12);

      should(pluginsManager.routes[0].verb).be.equal("get");
      should(pluginsManager.routes[0].path).be.equal(
        "/_plugin/test-plugin/bar/:name"
      );
      should(pluginsManager.routes[0].controller).be.equal("test-plugin/foo");
      should(pluginsManager.routes[0].action).be.equal("bar");

      should(pluginsManager.routes[1].verb).be.equal("get");
      should(pluginsManager.routes[1].path).be.equal("/_/bar/:name");
      should(pluginsManager.routes[1].controller).be.equal("test-plugin/foo");
      should(pluginsManager.routes[1].action).be.equal("bar");

      should(pluginsManager.routes[2].verb).be.equal("head");
      should(pluginsManager.routes[2].path).be.equal(
        "/_plugin/test-plugin/bar/:name"
      );
      should(pluginsManager.routes[2].controller).be.equal("test-plugin/foo");
      should(pluginsManager.routes[2].action).be.equal("bar");

      should(pluginsManager.routes[3].verb).be.equal("head");
      should(pluginsManager.routes[3].path).be.equal("/_/bar/:name");
      should(pluginsManager.routes[3].controller).be.equal("test-plugin/foo");
      should(pluginsManager.routes[3].action).be.equal("bar");

      should(pluginsManager.routes[4].verb).be.equal("post");
      should(pluginsManager.routes[4].path).be.equal(
        "/_plugin/test-plugin/bar"
      );
      should(pluginsManager.routes[4].controller).be.equal("test-plugin/foo");
      should(pluginsManager.routes[4].action).be.equal("bar");

      should(pluginsManager.routes[5].verb).be.equal("post");
      should(pluginsManager.routes[5].path).be.equal("/_/bar");
      should(pluginsManager.routes[5].controller).be.equal("test-plugin/foo");
      should(pluginsManager.routes[5].action).be.equal("bar");

      should(pluginsManager.routes[6].verb).be.equal("put");
      should(pluginsManager.routes[6].path).be.equal(
        "/_plugin/test-plugin/bar"
      );
      should(pluginsManager.routes[6].controller).be.equal("test-plugin/foo");
      should(pluginsManager.routes[6].action).be.equal("bar");

      should(pluginsManager.routes[7].verb).be.equal("put");
      should(pluginsManager.routes[7].path).be.equal("/_/bar");
      should(pluginsManager.routes[7].controller).be.equal("test-plugin/foo");
      should(pluginsManager.routes[7].action).be.equal("bar");

      should(pluginsManager.routes[8].verb).be.equal("delete");
      should(pluginsManager.routes[8].path).be.equal(
        "/_plugin/test-plugin/bar"
      );
      should(pluginsManager.routes[8].controller).be.equal("test-plugin/foo");
      should(pluginsManager.routes[8].action).be.equal("bar");

      should(pluginsManager.routes[9].verb).be.equal("delete");
      should(pluginsManager.routes[9].path).be.equal("/_/bar");
      should(pluginsManager.routes[9].controller).be.equal("test-plugin/foo");
      should(pluginsManager.routes[9].action).be.equal("bar");

      should(pluginsManager.routes[10].verb).be.equal("patch");
      should(pluginsManager.routes[10].path).be.equal(
        "/_plugin/test-plugin/bar"
      );
      should(pluginsManager.routes[10].controller).be.equal("test-plugin/foo");
      should(pluginsManager.routes[10].action).be.equal("bar");

      should(pluginsManager.routes[11].verb).be.equal("patch");
      should(pluginsManager.routes[11].path).be.equal("/_/bar");
      should(pluginsManager.routes[11].controller).be.equal("test-plugin/foo");
      should(pluginsManager.routes[11].action).be.equal("bar");
    });

    it("should abort the plugin initialization if the controller object is incorrectly defined", () => {
      plugin.instance.controllers = {
        foo: "bar",
      };

      should(() => {
        pluginsManager._initControllers(plugin);
      }).throw();
    });

    it("should abort the plugin initialization if one of the controller action is not correctly defined", () => {
      plugin.instance.controllers = {
        foo: {
          actionName: [],
        },
      };

      should(() => {
        pluginsManager._initControllers(plugin);
      }).throw();
    });

    it("should abort the controller initialization if one of the controller action target does not exist", () => {
      plugin.instance.controllers = {
        foo: {
          actionName: "functionName",
          anotherActionName: "fou",
        },
      };

      plugin.instance.functionName = () => {};
      plugin.instance.foo = () => {};

      global.NODE_ENV = "development";

      should(() => pluginsManager._initControllers(plugin)).throw({
        id: "plugin.controller.invalid_action",
        message: /Did you mean "foo"/,
      });
    });

    it("should not add an invalid route to the API", () => {
      plugin.instance.controllers = {
        foo: {
          bar: "functionName",
        },
      };

      global.NODE_ENV = "development";

      plugin.instance.functionName = () => {};

      plugin.instance.routes = [
        { vert: "get", url: "/bar/:name", controller: "foo", action: "bar" },
      ];

      should(() => pluginsManager._initControllers(plugin)).throw({
        id: "plugin.controller.unexpected_route_property",
        message: /Did you mean "verb"/,
      });

      plugin.instance.routes = [
        { verb: "post", url: ["/bar"], controller: "foo", action: "bar" },
      ];

      should(() => pluginsManager._initControllers(plugin)).throw({
        id: "plugin.controller.invalid_route_property",
      });

      plugin.instance.routes = [
        { verb: "posk", url: "/bar", controller: "foo", action: "bar" },
      ];

      should(() => pluginsManager._initControllers(plugin)).throw({
        id: "plugin.controller.unsupported_verb",
        message: /Did you mean "post"/,
      });

      plugin.instance.routes = [
        { verb: "get", url: "/bar/:name", controller: "foo", action: "baz" },
      ];

      should(() => pluginsManager._initControllers(plugin)).throw({
        id: "plugin.controller.undefined_action",
        message: /Did you mean "bar"/,
      });

      plugin.instance.routes = [
        { verb: "get", url: "/bar/:name", controller: "fou", action: "bar" },
      ];

      should(() => pluginsManager._initControllers(plugin)).throw({
        id: "plugin.controller.undefined_controller",
        message: /Did you mean "foo"/,
      });

      plugin.instance.routes = [
        { verb: "get", url: "/bar/:name", controler: "foo", action: "bar" },
      ];

      should(() => {
        pluginsManager._initControllers(plugin);
      });
    });
  });

  describe("strategy management", () => {
    let pluginsManagerStrategy;

    beforeEach(() => {
      plugin._instance = {
        ...plugin.instance,
        afterRegisterFunction: sinon.stub(),
        createFunction: sinon.stub(),
        existsFunction: sinon.stub(),
        deleteFunction: sinon.stub(),
        getByIdFunction: sinon.stub(),
        getInfoFunction: sinon.stub(),
        updateFunction: sinon.stub(),
        validateFunction: sinon.stub(),
        verifyFunction: sinon.stub(),
      };

      plugin.instance.authenticators = {
        SomeStrategy: sinon.stub(),
      };

      plugin.instance.strategies = {
        someStrategy: {
          config: {
            authenticator: "SomeStrategy",
            strategyOptions: {
              someStrategy: "options",
            },
            authenticateOptions: {
              someAuthenticate: "options",
            },
            fields: ["aField", "anotherField"],
          },
          methods: {
            afterRegister: "afterRegisterFunction",
            create: "createFunction",
            delete: "deleteFunction",
            exists: "existsFunction",
            getById: "getByIdFunction",
            getInfo: "getInfoFunction",
            update: "updateFunction",
            validate: "validateFunction",
            verify: "verifyFunction",
          },
        },
      };

      pluginsManagerStrategy = {
        strategy: plugin.instance.strategies.someStrategy,
        methods: {
          exists: plugin.instance.existsFunction,
          create: plugin.instance.createFunction,
          update: plugin.instance.updateFunction,
          delete: plugin.instance.deleteFunction,
          getById: plugin.instance.getByIdFunction,
          getInfo: plugin.instance.getInfoFunction,
          validate: plugin.instance.validateFunction,
          afterRegister: plugin.instance.afterRegisterFunction,
        },
        owner: plugin.name,
      };

      pluginsManager.strategies.someStrategy = pluginsManagerStrategy;
      pluginsManager._plugins.set(plugin.name, plugin);
      sinon.resetHistory();
    });

    describe("#getStrategyFields", () => {
      it("should return fields from configuration", () => {
        should(pluginsManager.getStrategyFields("someStrategy")).be.deepEqual([
          "aField",
          "anotherField",
        ]);
      });
    });

    describe("#hasStrategyMethod", () => {
      it("should return true if a method exists", () => {
        should(
          pluginsManager.hasStrategyMethod("someStrategy", "exists")
        ).be.true();
      });

      it("should false true if a method does not exist", () => {
        should(
          pluginsManager.hasStrategyMethod("someStrategy", "notExists")
        ).be.false();
      });
    });

    describe("#getStrategyMethod", () => {
      it("should return a method", () => {
        should(
          pluginsManager.getStrategyMethod("someStrategy", "exists")
        ).be.a.Function();
      });
    });

    describe("#initAuthenticators", () => {
      it("should throw if the provided authenticators property is not an object", () => {
        [[], "foobar", 123, true].forEach((authenticators) => {
          plugin.instance.authenticators = authenticators;
          should(() => pluginsManager._initAuthenticators(plugin)).throw(
            PluginImplementationError,
            { id: "plugin.authenticators.not_an_object" }
          );
        });
      });

      it("should throw if one of the provided authenticators is not a constructor", () => {
        [() => {}, "foobar", true, 123].forEach((ctor) => {
          plugin.instance.authenticators.foo = ctor;
          should(() => pluginsManager._initAuthenticators(plugin)).throw(
            PluginImplementationError,
            { id: "plugin.authenticators.invalid_authenticator" }
          );
        });
      });
    });

    describe("#initStrategies", () => {
      let foo = { foo: "bar" };

      beforeEach(() => {
        pluginsManager.strategies = {};
        pluginsManager.authenticators[plugin.name] = {
          SomeStrategy: plugin.instance.authenticators.SomeStrategy,
        };
        pluginsManager._plugins.get(plugin.name).initCalled = true;
      });

      it("should add the strategy in strategies if it is well-formed", (done) => {
        plugin.instance.existsFunction = sinon.stub().returns(foo);
        plugin.instance.verifyFunction = sinon.stub().resolves({ kuid: "foo" });

        pluginsManager._initStrategies(plugin);

        should(pluginsManager.strategies.someStrategy.strategy).be.deepEqual(
          plugin.instance.strategies.someStrategy
        );
        should(
          pluginsManager.strategies.someStrategy.methods.afterRegister
        ).be.Function();
        should(plugin.instance.afterRegisterFunction).be.calledOnce();
        should(
          plugin.instance.afterRegisterFunction.firstCall.args[0]
        ).be.instanceOf(plugin.instance.authenticators.SomeStrategy);
        should(
          pluginsManager.strategies.someStrategy.methods.exists
        ).be.Function();
        should(
          pluginsManager.strategies.someStrategy.methods.create
        ).be.Function();
        should(
          pluginsManager.strategies.someStrategy.methods.update
        ).be.Function();
        should(
          pluginsManager.strategies.someStrategy.methods.delete
        ).be.Function();
        should(
          pluginsManager.strategies.someStrategy.methods.getById
        ).be.Function();
        should(
          pluginsManager.strategies.someStrategy.methods.getInfo
        ).be.Function();
        should(
          pluginsManager.strategies.someStrategy.methods.validate
        ).be.Function();
        should(plugin.instance.authenticators.SomeStrategy)
          .calledOnce()
          .calledWithNew();

        pluginsManager.strategies.someStrategy.methods
          .exists(foo)
          .then((result) => {
            should(result).be.deepEqual(foo);
            should(plugin.instance.existsFunction).be.calledOnce();

            const verifyAdapter =
              plugin.instance.authenticators.SomeStrategy.firstCall.args[1];
            verifyAdapter({}, (error) => done(error));
          });
      });

      it("should handle plugin names using uppercases", () => {
        // plugin names are stored lowercased
        pluginsManager._plugins.set(plugin.name, plugin);

        plugin.name = plugin.name.toUpperCase();

        pluginsManager.authenticators = {
          [plugin.name]: {
            SomeStrategy: plugin.instance.authenticators.SomeStrategy,
          },
        };

        plugin.instance.existsFunction = sinon.stub().returns(foo);
        plugin.instance.verifyFunction = sinon.stub().resolves({ kuid: "foo" });

        pluginsManager._initStrategies(plugin);
        should(pluginsManager.strategies.someStrategy.strategy).be.deepEqual(
          plugin.instance.strategies.someStrategy
        );
        should(plugin.instance.afterRegisterFunction).be.calledOnce();
      });

      it("method invocation should intercept a thrown error to transform it into PluginImplementationError", () => {
        plugin.instance.existsFunction = sinon
          .stub()
          .throws(new Error("some error"));

        pluginsManager._initStrategies(plugin);
        should(pluginsManager.strategies.someStrategy.strategy).be.deepEqual(
          plugin.instance.strategies.someStrategy
        );
        should(
          pluginsManager.strategies.someStrategy.methods.exists
        ).be.Function();
        should(
          pluginsManager.strategies.someStrategy.methods.create
        ).be.Function();
        should(
          pluginsManager.strategies.someStrategy.methods.update
        ).be.Function();
        should(
          pluginsManager.strategies.someStrategy.methods.delete
        ).be.Function();
        should(
          pluginsManager.strategies.someStrategy.methods.getInfo
        ).be.Function();
        should(
          pluginsManager.strategies.someStrategy.methods.validate
        ).be.Function();

        return should(
          pluginsManager.strategies.someStrategy.methods.exists(foo)
        ).be.rejectedWith(PluginImplementationError);
      });

      it("should throw if strategies is not a non-empty object", () => {
        const message =
          /\[test-plugin\] the exposed "strategies" plugin property must be a non-empty object/;

        [{}, [], null, undefined, "foobar", 123, true].forEach((strategies) => {
          plugin.instance.strategies = strategies;
          should(() => pluginsManager._initStrategies(plugin)).throw(
            PluginImplementationError,
            { message }
          );
        });
      });

      it("should throw if the provided strategy is not an object", () => {
        [[], null, undefined, "foobar", 123, true].forEach((strategy) => {
          plugin.instance.strategies.someStrategy = strategy;
          should(() => pluginsManager._initStrategies(plugin)).throw(
            PluginImplementationError,
            {
              id: "plugin.strategy.invalid_description",
            }
          );
        });
      });

      it("should throw if methods is not an object", () => {
        [[], null, undefined, "foobar", 123, true].forEach((methods) => {
          plugin.instance.strategies.someStrategy.methods = methods;
          should(() => pluginsManager._initStrategies(plugin)).throw(
            PluginImplementationError,
            { id: "plugin.strategy.invalid_methods" }
          );
        });
      });

      it("should throw if config is not an object", () => {
        [[], null, undefined, "foobar", 123, true].forEach((config) => {
          const message = new RegExp(
            `\\[test-plugin\\] Strategy someStrategy: expected a "config" property of type "object", got: ${config}`
          );
          plugin.instance.strategies.someStrategy.config = config;
          should(() => pluginsManager._initStrategies(plugin)).throw(
            PluginImplementationError,
            { message }
          );
        });
      });

      it("should throw if a required method is invalid", () => {
        [[], null, undefined, {}, 123, true].forEach((fn) => {
          plugin.instance.strategies.someStrategy.methods.exists = fn;
          should(() => pluginsManager._initStrategies(plugin)).throw(
            PluginImplementationError,
            {
              id: "plugin.strategy.invalid_method_type",
            }
          );
        });
      });

      it("should throw if a mandatory method is not exposed by the plugin object", () => {
        ["exists", "create", "update", "delete", "validate", "verify"].forEach(
          (methodName) => {
            const fnName = methodName + "Function";

            delete plugin.instance[fnName];

            should(() => pluginsManager._initStrategies(plugin)).throw(
              PluginImplementationError,
              {
                id: "plugin.strategy.missing_method_function",
              }
            );

            plugin.instance[fnName] = sinon.stub();
          }
        );
      });

      it("should throw if an optional method is specified but with an invalid value", () => {
        for (const methodName of ["getInfo", "getById", "afterRegister"]) {
          const clone = createPlugin(plugin.name);
          clone._instance = JSON.parse(JSON.stringify(plugin._instance));

          for (const value of [[], {}, 123, false]) {
            clone.instance.strategies.someStrategy.methods[methodName] = value;

            /* eslint-disable-next-line no-loop-func */
            should(() => pluginsManager._initStrategies(clone)).throw(
              PluginImplementationError,
              {
                id: "plugin.strategy.invalid_method_type",
              }
            );
          }
        }
      });

      it("should throw if an optional method is specified but does not point to a function", () => {
        ["getInfo", "getById", "afterRegister"].forEach((methodName) => {
          const fnName = methodName + "Function";

          delete plugin.instance[fnName];

          should(() => pluginsManager._initStrategies(plugin)).throw(
            PluginImplementationError,
            {
              id: "plugin.strategy.missing_method_function",
            }
          );

          plugin.instance[fnName] = sinon.stub();
        });
      });

      it("should throw if the strategy authenticator is invalid or missing", () => {
        [[], {}, 123, null, undefined, true].forEach((authenticator) => {
          plugin.instance.strategies.someStrategy.config.authenticator =
            authenticator;

          should(() => pluginsManager._initStrategies(plugin)).throw(
            PluginImplementationError,
            {
              id: "plugin.strategy.invalid_authenticator",
            }
          );
        });
      });

      it("should throw if the provided authenticator is not listed in this.authenticators", () => {
        plugin.instance.strategies.someStrategy.config.authenticator = "foobar";
        should(() => pluginsManager._initStrategies(plugin)).throw(
          PluginImplementationError,
          {
            id: "plugin.strategy.unknown_authenticator",
          }
        );
      });

      it('should throw if the "strategyOptions" config is invalid', () => {
        [[], "foobar", 123, false].forEach((opts) => {
          plugin.instance.strategies.someStrategy.config.strategyOptions = opts;

          should(() => pluginsManager._initStrategies(plugin)).throw(
            PluginImplementationError,
            {
              id: "plugin.strategy.invalid_option",
            }
          );
        });
      });

      it('should throw if the "authenticateOptions" config is invalid', () => {
        [[], "foobar", 123, false].forEach((opts) => {
          plugin.instance.strategies.someStrategy.config.authenticateOptions =
            opts;

          should(() => pluginsManager._initStrategies(plugin)).throw(
            PluginImplementationError,
            {
              id: "plugin.strategy.invalid_option",
            }
          );
        });
      });

      it('should throw if the "fields" config is invalid', () => {
        [{}, "foobar", 123, false].forEach((opts) => {
          plugin.instance.strategies.someStrategy.config.fields = opts;

          should(() => pluginsManager._initStrategies(plugin)).throw(
            PluginImplementationError,
            {
              id: "plugin.strategy.invalid_fields",
            }
          );
        });
      });

      it("should unregister a strategy first if already registered", () => {
        sinon.spy(pluginsManager, "unregisterStrategy");

        pluginsManager._initStrategies(plugin);

        should(pluginsManager.unregisterStrategy).not.be.called();

        pluginsManager._initStrategies(plugin);

        should(pluginsManager.unregisterStrategy)
          .calledOnce()
          .calledWith(plugin.name, "someStrategy");
      });
    });

    describe("#verifyAdapter", () => {
      let verifyAdapter;

      beforeEach(() => {
        pluginsManager.authenticators[plugin.name] = {
          SomeStrategy: plugin.instance.authenticators.SomeStrategy,
        };
        pluginsManager._plugins.get(plugin.name).initCalled = true;
        pluginsManager._initStrategies(plugin);
        verifyAdapter =
          plugin.instance.authenticators.SomeStrategy.firstCall.args[1];
      });

      it("should reject if the plugin returns a non-thenable value", (done) => {
        plugin.instance.verifyFunction.returns(null);
        verifyAdapter("foo", "bar", "baz", (err, res, msg) => {
          try {
            should(res).be.undefined();
            should(msg).be.undefined();
            should(err)
              .instanceOf(PluginImplementationError)
              .match({ id: "plugin.strategy.invalid_verify_return" });
            done();
          } catch (e) {
            done(e);
          }
        });
      });

      it("should reject if the plugin resolves to a non-false non-object value", (done) => {
        plugin.instance.verifyFunction.resolves(true);
        verifyAdapter("foo", "bar", (err, res, msg) => {
          try {
            should(res).be.undefined();
            should(msg).be.undefined();
            should(err)
              .instanceOf(PluginImplementationError)
              .match({
                message:
                  /\[test-plugin\] Strategy someStrategy: invalid authentication strategy result/,
              });
            done();
          } catch (e) {
            done(e);
          }
        });
      });

      it("should reject if the plugin resolves to a non-string kuid", (done) => {
        plugin.instance.verifyFunction.resolves({ kuid: 123 });
        verifyAdapter("foo", "bar", (err, res, msg) => {
          try {
            should(res).be.undefined();
            should(msg).be.undefined();
            should(err)
              .instanceOf(PluginImplementationError)
              .match({
                message:
                  /\[test-plugin\] Strategy someStrategy: invalid authentication kuid returned: expected a string, got a number/,
              });
            done();
          } catch (e) {
            done(e);
          }
        });
      });

      it('should resolve to "false" if the plugins refuse the provided credentials', (done) => {
        plugin.instance.verifyFunction.resolves(false);
        verifyAdapter((err, res, msg) => {
          try {
            should(res).be.false();
            should(msg).be.eql({ message: null });
            should(err).be.null();
            done();
          } catch (e) {
            done(e);
          }
        });
      });

      it("should provide a default message if the plugins rejects a login without one", (done) => {
        plugin.instance.verifyFunction.resolves({});
        verifyAdapter((err, res, msg) => {
          try {
            should(res).be.false();
            should(msg).be.eql({
              message: 'Unable to log in using the strategy "someStrategy"',
            });
            should(err).be.null();
            done();
          } catch (e) {
            done(e);
          }
        });
      });

      it("should relay the plugin  message if one is provided", (done) => {
        plugin.instance.verifyFunction.resolves({
          message: '"NONE SHALL PASS!" -The Black Knight',
        });
        verifyAdapter((err, res, msg) => {
          try {
            should(res).be.false();
            should(msg).be.eql({
              message: '"NONE SHALL PASS!" -The Black Knight',
            });
            should(err).be.null();
            done();
          } catch (e) {
            done(e);
          }
        });
      });

      it("should reject if the plugin returns an invalid kuid", (done) => {
        plugin.instance.verifyFunction.resolves({ kuid: "Waldo" });

        const error = new Error("foo");
        error.id = "security.user.not_found";

        kuzzle.ask.withArgs("core:security:user:get", "Waldo").rejects(error);

        verifyAdapter((err, res, msg) => {
          try {
            should(res).be.undefined();
            should(msg).be.undefined();
            should(err)
              .instanceOf(PluginImplementationError)
              .match({ id: "plugin.strategy.unknown_kuid" });
            done();
          } catch (e) {
            done(e);
          }
        });
      });
    });

    describe("#unregisterStrategy", () => {
      it("should remove a strategy using its provided name", () => {
        pluginsManager.unregisterStrategy(plugin.name, "someStrategy");
        should(pluginsManager.strategies).be.an.Object().and.be.empty();
        should(kuzzle.passport.unuse).calledWith("someStrategy");
      });

      it("should throw if the strategy does not exist", () => {
        should(() =>
          pluginsManager.unregisterStrategy(plugin.name, "foobar")
        ).throw(NotFoundError, { id: "plugin.strategy.strategy_not_found" });
      });

      it("should throw if not the owner of the strategy", () => {
        should(() =>
          pluginsManager.unregisterStrategy(
            "Frank William Abagnale Jr.",
            "someStrategy"
          )
        ).throw(PluginImplementationError, {
          id: "plugin.strategy.unauthorized_removal",
        });
      });
    });

    describe("#registerStrategy", () => {
      it("should add the strategy to strategies object if init method has not been called", () => {
        const strategy = {
          config: {
            authenticator: "SomeStrategy",
          },
          methods: {
            create: sinon.stub(),
            delete: sinon.stub(),
            exists: sinon.stub(),
            getById: sinon.stub(),
            getInfo: sinon.stub(),
            update: sinon.stub(),
            validate: sinon.stub(),
            verify: sinon.stub(),
          },
        };

        pluginsManager.registerStrategy(plugin.name, "foobar", strategy);

        should(plugin.instance.strategies.foobar).be.eql(strategy);
      });
    });
  });

  describe("#_initHooks", () => {
    let pluginMock;

    beforeEach(() => {
      pluginMock = sinon.mock(plugin.instance);
    });

    it("should attach event hook with method name", async () => {
      plugin.instance.hooks = {
        "foo:bar": "foo",
        "bar:foo": "bar",
      };

      plugin.instance.foo = () => {};
      plugin.instance.bar = () => {};

      pluginMock.expects("foo").once();
      pluginMock.expects("bar").never();

      await pluginsManager._initHooks(plugin);
      kuzzle.emit("foo:bar");
      pluginMock.verify();
    });

    it("should attach event hook with function", async () => {
      const bar = sinon.spy();
      const foo = sinon.spy();

      plugin.instance.hooks = {
        "foo:bar": bar,
        "bar:foo": foo,
      };

      await pluginsManager._initHooks(plugin);
      kuzzle.emit("foo:bar");

      should(bar).be.calledOnce();
      should(foo).not.be.called();
    });

    it("should attach multi-target hook with method name", async () => {
      plugin.instance.hooks = {
        "foo:bar": ["foo", "bar"],
        "bar:foo": ["baz"],
      };

      plugin.instance.foo = () => {};
      plugin.instance.bar = () => {};
      plugin.instance.baz = () => {};

      pluginMock.expects("foo").once();
      pluginMock.expects("bar").once();
      pluginMock.expects("baz").never();

      await pluginsManager._initHooks(plugin);

      kuzzle.emit("foo:bar");

      pluginMock.verify();
    });

    it("should attach multi-target hook with function", async () => {
      const bar = sinon.spy();
      const foo = sinon.spy();
      const baz = sinon.spy();

      plugin.instance.hooks = {
        "foo:bar": [foo, bar],
        "bar:foo": [baz],
      };

      await pluginsManager._initHooks(plugin);

      kuzzle.emit("foo:bar");

      should(bar).be.calledOnce();
      should(foo).be.calledOnce();
      should(baz).not.be.called();
    });

    it("should attach event hook with wildcard with method name", async () => {
      plugin.instance.hooks = {
        "foo:*": "foo",
        "bar:foo": "bar",
      };

      plugin.instance.foo = () => {};
      plugin.instance.bar = () => {};

      pluginMock.expects("foo").once();
      pluginMock.expects("bar").never();

      await pluginsManager._initHooks(plugin);

      kuzzle.emit("foo:bar");
      pluginMock.verify();
    });

    it("should throw if a hook target is not a function and not a method name", () => {
      plugin.instance.hooks = {
        "foo:bar": "fou",
      };

      plugin.instance.foo = () => {};

      global.NODE_ENV = "development";
      should(() => pluginsManager._initHooks(plugin)).throw({
        id: "plugin.assert.invalid_hook",
        message: /Did you mean "foo"/,
      });
    });
  });

  describe("#_initPipes", () => {
    let pluginMock;

    beforeEach(() => {
      pluginMock = sinon.mock(plugin.instance);
      kuzzle.pipe.restore();
      kuzzle.pluginsManager = pluginsManager;
    });

    it("should attach pipes bound to the plugin object using method names", async () => {
      plugin.instance.pipes = {
        "foo:bar": "foo",
        "bar:foo": "bar",
      };

      plugin.instance.foo = sinon.stub().callsFake(async function () {
        should(this).be.eql(plugin.instance);
      });
      plugin.instance.bar = sinon.stub();

      await pluginsManager._initPipes(plugin);
      await kuzzle.pipe("foo:bar");

      should(plugin.instance.foo).be.calledOnce();
      should(plugin.instance.bar).not.be.called();
    });

    it("should attach pipes event with a function", async () => {
      const bar = sinon.stub().resolves();
      const foo = sinon.stub().callsArgWith(1, null);

      plugin.instance.pipes = {
        "foo:bar": foo,
        "bar:foo": bar,
      };

      await pluginsManager._initPipes(plugin);
      await kuzzle.pipe("foo:bar");

      should(foo).be.calledOnce();
      should(bar).not.be.called();
    });

    it("should attach pipes event with wildcard with method name", async () => {
      plugin.instance.pipes = {
        "foo:*": "foo",
        "bar:foo": "bar",
      };

      plugin.instance.foo = sinon.stub().resolves();
      plugin.instance.bar = sinon.stub().callsArgWith(1, null);

      await pluginsManager._initPipes(plugin);
      await kuzzle.pipe("foo:bar");

      should(plugin.instance.foo).be.calledOnce();
      should(plugin.instance.bar).not.be.called();
    });

    it("should attach multi-target event to pipes with method name", async () => {
      plugin.instance.pipes = {
        "foo:bar": ["foo", "baz"],
        "bar:foo": ["bar"],
      };

      plugin.instance.foo = sinon.stub().callsFake(async function () {
        should(this).eql(plugin.instance);
      });
      plugin.instance.bar = sinon.stub().resolves();
      plugin.instance.baz = sinon.stub().callsFake(function (arg, cb) {
        should(this).eql(plugin.instance);
        cb(null);
      });

      await pluginsManager._initPipes(plugin);
      await kuzzle.pipe("foo:bar");

      should(plugin.instance.foo).be.calledOnce();
      should(plugin.instance.baz).be.calledOnce();
      should(plugin.instance.bar).not.be.called();
    });

    it("should attach multi-target event to pipes with function", async () => {
      const bar = sinon.stub().resolves();
      const foo = sinon.stub().resolves();
      const baz = sinon.stub().resolves();

      plugin.instance.pipes = {
        "foo:bar": [foo, baz],
        "bar:foo": [bar],
      };

      await pluginsManager._initPipes(plugin);
      await kuzzle.pipe("foo:bar");

      should(foo).be.calledOnce();
      should(baz).be.calledOnce();
      should(bar).not.be.called();
    });

    it("should throw if a pipe target is not a function and not a method name", () => {
      plugin.instance.pipes = {
        "foo:bar": "fou",
      };

      plugin.instance.foo = () => {};

      global.NODE_ENV = "development";
      should(() => pluginsManager._initPipes(plugin)).throw({
        id: "plugin.assert.invalid_pipe",
        message: /Did you mean "foo"/,
      });
    });

    it("should attach pipes event and reject if an attached function return an error", () => {
      plugin.instance.pipes = {
        "foo:bar": "foo",
      };

      plugin.instance.foo = sinon
        .stub()
        .callsArgWith(1, new KuzzleError("foobar"));

      pluginsManager._initPipes(plugin);

      return should(kuzzle.pipe("foo:bar")).be.rejectedWith(KuzzleError, {
        message: "foobar",
      });
    });

    it("should embed a non-KuzzleError error in a PluginImplementationError", async () => {
      plugin.instance.pipes = {
        "foo:bar": "foo",
      };

      plugin.instance.foo = () => {};

      pluginMock.expects("foo").once().callsArgWith(1, "foobar");
      pluginsManager._initPipes(plugin);

      return should(kuzzle.pipe("foo:bar")).be.rejectedWith(
        PluginImplementationError,
        { id: "plugin.runtime.unexpected_error" }
      );
    });

    it("should log a warning in case a pipe plugin exceeds the warning delay", async () => {
      const fooStub = sinon.stub().callsFake((ev, cb) => {
        setTimeout(() => cb(null), 15);
      });
      plugin.instance.pipes = {
        "foo:bar": fooStub,
      };

      plugin.config.pipeWarnTime = 10;

      await pluginsManager._initPipes(plugin);
      await kuzzle.pipe("foo:bar");

      should(fooStub).be.calledOnce();
      should(kuzzle.log.warn).calledWithMatch(
        /\[test-plugin\] pipe for event 'foo:bar' is slow \(\d+ms\)/
      );
    });

    it("should accept promises for pipes", async () => {
      plugin.instance.pipes = {
        "foo:bar": "foo",
      };

      plugin.instance.foo = sinon.stub().resolves("foobar");

      await pluginsManager._initPipes(plugin);
      const response = await kuzzle.pipe("foo:bar");

      should(plugin.instance.foo).be.calledOnce();
      should(response).eql("foobar");
    });
  });

  describe("#loadPlugin", () => {
    it("", () => {});
  });
});


text:
function DialogDocumentationController($scope, $mdDialog, DocumentationService, apiId) {
  'ngInject';

  var that = this;
  $scope.$watch('pageContentFile.content', function (data) {
    if (data) {
      that.selectPageType($scope.IMPORT);
    } else {
      that.selectPageType(null);
    }
  });

  $scope.pageContentFile = {content: '', name : ''};

  $scope.MARKDOWN_PAGE = 'MARKDOWN';
  $scope.RAML_PAGE = 'RAML';
  $scope.SWAGGER_PAGE = 'SWAGGER';
  $scope.IMPORT = 'IMPORT';
  $scope.pageTitle = null;

  this.hide = function(){
    $mdDialog.hide();
  };

  this.selectPageType = function(pageType) {
    this.selectedPageType = pageType;
  };

  function getPageType() {
    if ($scope.pageContentFile.name) {
      var fileExtension = $scope.pageContentFile.name.split('.').pop();
      switch (fileExtension) {
        case 'md':
          return $scope.MARKDOWN_PAGE;
        case 'raml':
          return $scope.RAML_PAGE;
        case 'json':
          return $scope.SWAGGER_PAGE;
        default :
          throw 'The document extension is not managed:' + fileExtension;
      }
    }
    return that.selectedPageType;
  }

  this.createPage = function() {
    var selectedPageType = getPageType();
    if (selectedPageType && $scope.pageTitle) {
      var newPage = {
        'name' : $scope.pageTitle.replace(/\s/g, '-').toLowerCase(),
        'type' : selectedPageType,
        'content' : $scope.pageContentFile.content
      };
      DocumentationService.createPage(apiId, newPage).then(function (page) {
        $mdDialog.hide(page);
      }).catch(function (error) {
        $scope.error = error;
      });
    }
  };
}

export default DialogDocumentationController;

redpajama_set_name: RedPajamaGithub


text:
Fiddler Bot UI
==============

UI for fiddler bot.

If you've never used Node or npm before, you'll need to install Node.
If you use homebrew, do:

```
brew install node
```

Otherwise, you can download and install from [here](http://nodejs.org/download/).

### Install npm dependencies
```
npm install
```

This runs through all dependencies listed in `package.json` and downloads them to a `node_modules` folder in your project directory.

### The `gulp` command
To run the version of gulp installed local to the project, in the root of your this project, you'd run

```
./node_modules/.bin/gulp
```

**WAT.** Why can't I just run `gulp`? Well, you could install gulp globally with `npm install -g gulp`, which will add the gulp script to your global bin folder, but it's always better to use the version that's specified in your project's package.json.  My solution to this is to simply alias `./node_modules/.bin/gulp` to `gulp`. Open up `~/.zshrc` or `~./bashrc` and add the following line:

```
alias gulp='node_modules/.bin/gulp'
```
Now, running `gulp` in the project directory will use the version specified and installed from the `package.json` file.

TODO
====

- Refactor html into partials/data
- Refactor css
- Add/refactor JavaScript from original
- Add remaining control items
- Update flat control theme


text:
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Owin;
using System;
using Microsoft.Owin.Security.Google;

namespace Tournamentz.Host
{
    using DAL.Entity;
    using Extensions;
    using Microsoft.Owin.Security.DataProtection;

    public partial class Startup
    {
        internal static IDataProtectionProvider DataProtectionProvider { get; private set; }

        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            DataProtectionProvider = app.GetDataProtectionProvider();

            // Enable the application to use a cookie to store information for the signed in user
            // and to use a cookie to temporarily store information about a user logging in with a third party login provider
            // Configure the sign in cookie
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Account/Login"),
                Provider = new CookieAuthenticationProvider
                {
                    OnValidateIdentity =
                        SecurityStampValidator
                            .OnValidateIdentity<DAL.Identity.ApplicationUserManager, ApplicationUser, Guid>(
                                validateInterval: TimeSpan.FromMinutes(30),
                                regenerateIdentityCallback: (manager, user) => user.GenerateUserIdentityAsync(manager),
                                getUserIdCallback: id => id.GetUserGuid())
                }
            });
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
            app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

            // Enables the application to remember the second login verification factor such as phone or email.
            // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
            // This is similar to the RememberMe option when you log in.
            app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

            // Uncomment the following lines to enable logging in with third party login providers
            app.UseMicrosoftAccountAuthentication(
                clientId: "000000004C18E248",
                clientSecret: "Kk34acS2g1TJB5wZm3kSk2LI-UzcmJDX");

            //app.UseTwitterAuthentication(
            //   consumerKey: "",
            //   consumerSecret: "");

            //app.UseFacebookAuthentication(
            //   appId: "",
            //   appSecret: "");

            app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            {
                ClientId = "697963680533-al1vl9dmp2klbndp5hsfn013tk85nqd7.apps.googleusercontent.com",
                ClientSecret = "a5z2rT66ksGX_GaunXQBGaX-"
            });
        }
    }
}


text:
'use strict';

var gulp = require('gulp'),
    watch = require('gulp-watch'),
    join = require('path').join,
    http = require('http'),
    connect = require('connect'),
    serveStatic = require('serve-static'),
    openResource = require('open'),
    Proxy = require('gulp-connect-proxy'),
    gconnect = require('gulp-connect')
;

var port = 5555;

// --------------
// Serve dev.

var staticPath = join(__dirname, '..', "/");

gulp.task('serve', [/*'build.dev'*/], function() {
  var app;

  watch('./app/**', function() {
    //gulp.start('build.dev');
  });

  app = connect().use( serveStatic(staticPath) );

  http.createServer(app).listen(port, function() {
    openResource('http://localhost:' + port);
  });
});

// A local web server for dev convenience
gulp.task("servep", function() {
	gconnect.server({
	  root: staticPath,
	  port: port,
          middleware: function (connect, opt) {
	      opt.route = '/proxy';
	      var proxy = new Proxy.https(opt);
	      return [proxy];
	  }
	});

  /*
  watch('./app/**', function() {
    gconnect.reload();
  });
  */

});


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

using Consumption.Tests.Helpers;
using Microsoft.Azure.Management.Consumption;
using Microsoft.Azure.Management.Consumption.Models;
using Microsoft.Azure.Management.Resources;
using Microsoft.Rest.ClientRuntime.Azure.TestFramework;
using System;
using System.Linq;
using System.Net;
using Xunit;

namespace Consumption.Tests.ScenarioTests
{
    public class BudgetTests : TestBase
    {
        protected const int NumberOfItems = 10;
        protected const string subscriptionId = "1caaa5a3-2b66-438e-8ab4-bce37d518c5d";
        protected const string budgetName = "NETSDKTestBudget30";
        protected const string resourceGroupName = "MyNewResourceGroup";

        [Fact]
        public void BudgetCreateOrUpdateTest()
        {
            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                var consumptionMgmtClient = ConsumptionTestUtilities.GetConsumptionManagementClient(
                    context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK });
                consumptionMgmtClient.SubscriptionId = subscriptionId;

                var timePeriod = new BudgetTimePeriod
                {
                    StartDate = new DateTime(2018, 2, 1),
                    EndDate = new DateTime(2018, 11, 1),
                };
                var budget = new Budget("Cost", 60, "Monthly", timePeriod);

                var budgetResponse = consumptionMgmtClient.Budgets.CreateOrUpdate(budgetName, budget);

                ValidateProperties(budgetResponse);

                Assert.Equal(budget.Amount, budgetResponse.Amount);
                Assert.Equal(budget.Category, budgetResponse.Category);
                Assert.Equal(budget.TimeGrain, budgetResponse.TimeGrain);
                Assert.Equal(budget.TimePeriod.StartDate, budgetResponse.TimePeriod.StartDate);
                Assert.Equal(budget.TimePeriod.EndDate, budgetResponse.TimePeriod.EndDate);
            }
        }

        [Fact]
        public void BudgetDeleteTest()
        {
            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                var consumptionMgmtClient = ConsumptionTestUtilities.GetConsumptionManagementClient(
                    context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK });
                consumptionMgmtClient.SubscriptionId = subscriptionId;

                consumptionMgmtClient.Budgets.Delete("NETSDKTestBudget");
            }
        }

        [Fact]
        public void BudgetGetTest()
        {
            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                var consumptionMgmtClient = ConsumptionTestUtilities.GetConsumptionManagementClient(
                    context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK });
                consumptionMgmtClient.SubscriptionId = subscriptionId;

                var budget = consumptionMgmtClient.Budgets.Get(budgetName);

                ValidateProperties(budget, true);
            }
        }

        [Fact]
        public void BudgetListTest()
        {
            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                var consumptionMgmtClient = ConsumptionTestUtilities.GetConsumptionManagementClient(
                    context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK });
                consumptionMgmtClient.SubscriptionId = subscriptionId;

                var budgets = consumptionMgmtClient.Budgets.List();

                Assert.NotNull(budgets);
                Assert.True(budgets.Any());
                foreach (var b in budgets)
                {
                    ValidateProperties(b, true);
                }
            }
        }

        [Fact]
        public void BudgetCreateOrUpdateByResourceGroupNameTest()
        {
            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                var consumptionMgmtClient = ConsumptionTestUtilities.GetConsumptionManagementClient(
                    context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK });
                consumptionMgmtClient.SubscriptionId = subscriptionId;

                var timePeriod = new BudgetTimePeriod
                {
                    StartDate = new DateTime(2018, 2, 1),
                    EndDate = new DateTime(2018, 11, 1),
                };

                var budget = new Budget("Cost", 60, "Monthly", timePeriod);

                var budgetResponse = consumptionMgmtClient.Budgets.CreateOrUpdateByResourceGroupName(resourceGroupName, budgetName, budget);

                ValidateProperties(budgetResponse);

                Assert.Equal(budget.Amount, budgetResponse.Amount);
                Assert.Equal(budget.Category, budgetResponse.Category);
                Assert.Equal(budget.TimeGrain, budgetResponse.TimeGrain);
                Assert.Equal(budget.TimePeriod.StartDate, budgetResponse.TimePeriod.StartDate);
                Assert.Equal(budget.TimePeriod.EndDate, budgetResponse.TimePeriod.EndDate);
            }
        }

        [Fact]
        public void BudgetDeleteByResourceGroupNameTest()
        {
            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                var consumptionMgmtClient = ConsumptionTestUtilities.GetConsumptionManagementClient(
                    context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK });
                consumptionMgmtClient.SubscriptionId = subscriptionId;

                consumptionMgmtClient.Budgets.DeleteByResourceGroupName(resourceGroupName, "NETSDKTestBudget");
            }
        }

        [Fact]
        public void BudgetGetByResourceGroupNameTest()
        {
            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                var consumptionMgmtClient = ConsumptionTestUtilities.GetConsumptionManagementClient(
                    context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK });
                consumptionMgmtClient.SubscriptionId = subscriptionId;

                var budget = consumptionMgmtClient.Budgets.GetByResourceGroupName(resourceGroupName, budgetName);

                ValidateProperties(budget, true);
            }
        }

        [Fact]
        public void BudgetListByResourceGroupNameTest()
        {
            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                var consumptionMgmtClient = ConsumptionTestUtilities.GetConsumptionManagementClient(
                    context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK });
                consumptionMgmtClient.SubscriptionId = subscriptionId;

                var budgets = consumptionMgmtClient.Budgets.ListByResourceGroupName(resourceGroupName);

                Assert.NotNull(budgets);
                Assert.True(budgets.Any());
                foreach (var b in budgets)
                {
                    ValidateProperties(b, true);
                }
            }
        }

        private static void ValidateProperties(Budget item, bool validateCurrentSpend = false)
        {
            Assert.NotNull(item);
            Assert.NotNull(item.Id);
            Assert.NotNull(item.Name);
            Assert.NotNull(item.Type);
            Assert.NotNull(item.Category);
            Assert.NotNull(item.ETag);
            Assert.NotNull(item.TimeGrain);
            Assert.NotNull(item.TimePeriod);
            if (validateCurrentSpend)
            {
                Assert.NotNull(item.CurrentSpend);
            }
        }
    }
}


text:
package com.ocdsoft.bacta.swg.shared.datatable;

import bacta.iff.Iff;
import com.google.common.base.Preconditions;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
import com.google.inject.Inject;
import com.ocdsoft.bacta.tre.TreeFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;

/**
 * Created by crush on 11/20/2015.
 */
public final class DataTableManager {
    private static final Logger logger = LoggerFactory.getLogger(DataTableManager.class);

    private final TreeFile treeFile;
    private final Map<String, DataTable> tables;
    private final Multimap<String, Consumer<DataTable>> reloadCallbacks;

    @Inject
    public DataTableManager(final TreeFile treeFile) {
        this.treeFile = treeFile;
        this.tables = new HashMap<>();
        this.reloadCallbacks = ArrayListMultimap.create();
    }

    public void close(final String table) {
        this.tables.remove(table);
    }

    public DataTable getTable(final String table) {
        return getTable(table, true);
    }

    public DataTable getTable(final String table, boolean openIfNotFound) {
        if (this.tables.containsKey(table))
            return this.tables.get(table);

        if (openIfNotFound) {
            final DataTable dataTable = open(table);

            if (dataTable == null) {
                Preconditions.checkArgument(true, "Could not find table [%s].", table);
                return null;
            }

            return dataTable;
        }

        return null;
    }

    public DataTable reload(final String table) {
        close(table);

        final DataTable dataTable = open(table);

        if (dataTable != null) {
            final Collection<Consumer<DataTable>> reloadCallbacks = this.reloadCallbacks.get(table);

            for (Consumer<DataTable> callback : reloadCallbacks)
                callback.accept(dataTable);
        }

        return dataTable;
    }

    public DataTable reloadIfOpen(final String table) {
        if (isOpen(table))
            return reload(table);
        else
            return null;
    }

    public void addReloadCallback(final String table, final Consumer<DataTable> callbackFunction) {
        this.reloadCallbacks.put(table, callbackFunction);
    }

    public boolean isOpen(final String table) {
        return this.tables.containsKey(table);
    }

    /**
     * If a DataTable is already loaded, then it will return that table. Otherwise, it will try to load the table
     * from the TreeFile. If the table does not exist, it will return null.
     *
     * @param table The path of the table to open.
     * @return The loaded DataTable.
     */
    private DataTable open(final String table) {
        DataTable dataTable = getTable(table, false);

        if (dataTable != null)
            return dataTable;

        if (!treeFile.exists(table)) {
            logger.warn(String.format("Could not find treefile table for open [%s].", table));
            return null;
        }

        final Iff iff = new Iff(table, treeFile.open(table));
        dataTable = new DataTable();
        dataTable.load(iff, this);

        this.tables.put(table, dataTable);

        return dataTable;
    }
}


text:
import * as types from '../types';

export const dismissAlert = () => (dispatch) => {
  return dispatch({type: types.REMOVE_ALERT});
};

export default { dismissAlert };


text:
namespace engine {

ArmorSystem::ArmorSystem()
    : mScene( Scene::Get() )
{
}

void ArmorSystem::Init()
{
}

void ArmorSystem::Update( double DeltaTime )
{
    for( ActorList_t::iterator it = mScene.GetActors().begin(), e = mScene.GetActors().end(); it != e; ++it )
    {
        Actor& actor = **it;
        Opt<IArmorComponent> armorC = actor.Get<IArmorComponent>();
        if ( !armorC.IsValid() )
        {
            continue;
        }
        Opt<IHealthComponent> healthC = actor.Get<IHealthComponent>();
        if ( !healthC.IsValid() || !healthC->IsAlive()
             || healthC->GetDamage() <= 0 )
        {
            continue;
        }
        int32_t damage = healthC->GetDamage();
        int32_t newArmor = armorC->GetCurrentArmor() - damage;
        healthC->ResetDamage();
        if ( newArmor < 0 )
        {
            healthC->TakeDamage( -1 * newArmor );
            newArmor = 0;
        }
        int32_t armorDiff = armorC->GetCurrentArmor() - newArmor;
        armorC->SetCurrentArmor( newArmor );
        Opt<IPositionComponent> positionC = actor.Get<IPositionComponent>();
        if( positionC.IsValid() )
        {
            core::DamageTakenEvent damageTakeEvent = core::DamageTakenEvent( positionC->GetX(), positionC->GetY() );
            damageTakeEvent.ActorGUID = actor.GetGUID();
            damageTakeEvent.Damage = armorDiff;
            damageTakeEvent.type = core::DamageTakenEvent::Armor;
            EventServer<core::DamageTakenEvent>::Get().SendEvent( damageTakeEvent );
        }
    }
}

} // namespace engine


text:
var rc = require('rc');
var fs = require('fs');
var path = require('path');
var hostCache = {};
var keyCache = {};

function getKey(host){
	var key, config = getConfig(), file = path.join(config.sshDir, 'id_rsa');

	// See if we've seen this exactly host before
	if(hostCache[host] && keyCache[hostCache[host]]){
		return keyCache[hostCache[host]];
	}

	// Check for special config for this host key file.
	for(key in config.hosts){
		if(new RegExp(key).test(host)){
			file = path.join(config.sshDir, config.hosts[key]);
		}
	}

	//Check to see if this file is in cache, if so cache it for this host.
	if(keyCache[file]){
		hostCache[host] = file;
		return keyCache[file];
	}

	// If missed caches, get the file and cache it.
	try{
		keyCache[file] = {
			privateKey: fs.readFileSync(file),
			keyName: path.basename(file)
		};
		hostCache[host] = file;
		return keyCache[hostCache[host]];
	}catch(e){
		return {};
	}
}

function cachePassphrase(host, passphrase){
	if(!hostCache[host] || !keyCache[hostCache[host]]){
		return {};
	}
	keyCache[hostCache[host]].passphrase = passphrase;
	return keyCache[hostCache[host]];
}

function getConfig() {
	return rc('mcdownload', {
		sshDir: path.join(
			(process.platform === 'win32') ? process.env.USERPROFILE : process.env.HOME,
			'.ssh'
		),
		hosts: {}
	});
}

function fileExists(file){
	try{
		fs.lstatSync(file);
		return true;
	}catch(e){
		return false;
	}
}

module.exports = getKey;
getKey.cachePassphrase = cachePassphrase;


text:
// Copyright (c) 2014 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.xwalk.core.internal;

import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * This class represents the preferences and could be set by callers.
 * It is not thread-safe and must be called on the UI thread.
 * Afterwards, the preference could be read from all threads and can impact
 * all XWalkViewInternal instances.
 */
@XWalkAPI(noInstance = true)
public class XWalkPreferencesInternal {
    static class PreferenceValue {
        static final int PREFERENCE_TYPE_BOOLEAN = 1;
        static final int PREFERENCE_TYPE_INTEGER = 2;
        static final int PREFERENCE_TYPE_STRING = 3;

        int mType;
        Object mValue;

        PreferenceValue(boolean value) {
            mType = PREFERENCE_TYPE_BOOLEAN;
            mValue = value;
        }

        PreferenceValue(int value) {
            mType = PREFERENCE_TYPE_INTEGER;
            mValue = value;
        }

        PreferenceValue(String value) {
            mType = PREFERENCE_TYPE_STRING;
            mValue = value;
        }

        int getType() {
            return mType;
        }

        boolean getBooleanValue() {
            if (mType != PREFERENCE_TYPE_BOOLEAN) return false;
            return (Boolean) mValue;
        }

        int getIntegerValue() {
            if (mType != PREFERENCE_TYPE_INTEGER) return -1;
            return (Integer) mValue;
        }

        String getStringValue() {
            if (mType != PREFERENCE_TYPE_STRING) return null;
            return (String) mValue;
        }
    }

    private static HashMap<String, PreferenceValue> sPrefMap = new HashMap<String, PreferenceValue>();
    // Here we use WeakReference to make sure the KeyValueChangeListener instance
    // can be GC-ed to avoid memory leaking issue.
    private static ArrayList<WeakReference<KeyValueChangeListener> > sListeners =
            new ArrayList<WeakReference<KeyValueChangeListener> >();
    private static ReferenceQueue<KeyValueChangeListener> sRefQueue =
            new ReferenceQueue<KeyValueChangeListener>();

    /**
     * The key string to enable/disable remote debugging.
     * @since 1.0
     */
    @XWalkAPI
    public static final String REMOTE_DEBUGGING = "remote-debugging";

    /**
     * The key string to enable/disable animatable XWalkViewInternal. Default value is
     * true.
     *
     * If this key is set to False, then SurfaceView will be created internally as the
     * rendering backend.
     * If this key is set to True, the XWalkViewInternal created by Crosswalk can be
     * transformed and animated. Internally, Crosswalk is alternatively using
     * TextureView as the backend of XWalkViewInternal.
     *
     *
     * TextureView is a kind of
     *
     * android.view.View that is different from
     *
     * SurfaceView. Unlike SurfaceView, it can be resized, transformed and
     * animated. Once this key is set to True, all XWalkViewInternal will use TextureView
     * as the rendering target instead of SurfaceView. The downside of TextureView
     * is, it would consume more graphics memory than SurfaceView and may have
     * 1~3 extra frames of latency to display updates.
     *
     * Note this key MUST be set before creating the first XWalkViewInternal, otherwise
     * a RuntimeException will be thrown.
     *
     * @since 2.0
     */
    @XWalkAPI
    public static final String ANIMATABLE_XWALK_VIEW = "animatable-xwalk-view";

    /**
     * The key string to allow/disallow javascript to open
     * window automatically.
     * @since 3.0
     */
    @XWalkAPI
    public static final String JAVASCRIPT_CAN_OPEN_WINDOW =
            "javascript-can-open-window";

    /**
     * The key string to allow/disallow having universal access
     * from file origin.
     * @since 3.0
     */
    @XWalkAPI
    public static final String ALLOW_UNIVERSAL_ACCESS_FROM_FILE =
            "allow-universal-access-from-file";

    /**
     * The key string to enable/disable multiple windows.
     * @since 3.0
     */
    @XWalkAPI
    public static final String SUPPORT_MULTIPLE_WINDOWS =
            "support-multiple-windows";

    /**
     * The key string to set xwalk profile name.
     * User data will be kept separated for different profiles.
     * Profile needs to be set before any XWalkView instance created.
     * @since 3.0
     */
    @XWalkAPI
    public static final String PROFILE_NAME = "profile-name";

    /**
     * The key string to enable/disable javascript.
     * TODO(wang16): Remove this after cordova removes its dependency.
     */
    static final String ENABLE_JAVASCRIPT = "enable-javascript";

    /**
     * The key string to enable/disable xwalk extensions.
     *
     */
    static final String ENABLE_EXTENSIONS = "enable-extensions";

    static {
        sPrefMap.put(REMOTE_DEBUGGING, new PreferenceValue(false));
        sPrefMap.put(ANIMATABLE_XWALK_VIEW, new PreferenceValue(true));
        sPrefMap.put(ENABLE_JAVASCRIPT, new PreferenceValue(true));
        sPrefMap.put(JAVASCRIPT_CAN_OPEN_WINDOW, new PreferenceValue(true));
        sPrefMap.put(
                ALLOW_UNIVERSAL_ACCESS_FROM_FILE, new PreferenceValue(false));
        sPrefMap.put(SUPPORT_MULTIPLE_WINDOWS, new PreferenceValue(false));
        sPrefMap.put(ENABLE_EXTENSIONS, new PreferenceValue(true));
        sPrefMap.put(PROFILE_NAME, new PreferenceValue("Default"));
    }

    /**
     * Set a boolean preference value into Crosswalk. An exception will be thrown if
     * the key for the preference is not valid.
     * @param key the string name of the key.
     * @param enabled true if setting it as enabled.
     * @since 1.0
     */
    @XWalkAPI
    public static synchronized void setValue(String key, boolean enabled) throws RuntimeException {
        checkKey(key);
        // If the listener list is not empty, we consider the preference is
        // loaded by Crosswalk and taken effect already.
        if (key == ANIMATABLE_XWALK_VIEW && !sListeners.isEmpty()) {
            throw new RuntimeException("Warning: the preference key " + key +
                    " can not be set if the preference is already loaded by Crosswalk");
        }
        if (sPrefMap.get(key).getBooleanValue() != enabled) {
            PreferenceValue v = new PreferenceValue(enabled);
            sPrefMap.put(key, v);
            onKeyValueChanged(key, v);
        }
    }

    /**
     * Set an integer preference value into Crosswalk. An exception will be thrown if
     * the key for the preference is not valid.
     * @param key the string name of the key.
     * @param value the integer value.
     * @since 3.0
     */
    @XWalkAPI
    public static synchronized void setValue(String key, int value) throws RuntimeException {
        checkKey(key);
        // If the listener list is not empty, we consider the preference is
        // loaded by Crosswalk and taken effect already.
        if (key == ANIMATABLE_XWALK_VIEW && !sListeners.isEmpty()) {
            throw new RuntimeException("Warning: the preference key " + key +
                    " can not be set if the preference is already loaded by Crosswalk");
        }
        if (sPrefMap.get(key).getIntegerValue() != value) {
            PreferenceValue v = new PreferenceValue(value);
            sPrefMap.put(key, v);
            onKeyValueChanged(key, v);
        }
    }

    /**
     * Set a string preference value into Crosswalk. An exception will be thrown if
     * the key for the preference is not valid.
     * @param key the string name of the key.
     * @param value the string value.
     * @since 3.0
     */
    @XWalkAPI
    public static synchronized void setValue(String key, String value) throws RuntimeException {
        checkKey(key);
        // If the listener list is not empty, we consider the preference is
        // loaded by Crosswalk and taken effect already.
        if (key == ANIMATABLE_XWALK_VIEW && !sListeners.isEmpty()) {
            throw new RuntimeException("Warning: the preference key " + key +
                    " can not be set if the preference is already loaded by Crosswalk");
        }
        if (value != null && !value.equals(sPrefMap.get(key).getStringValue())) {
            PreferenceValue v = new PreferenceValue(value);
            sPrefMap.put(key, v);
            onKeyValueChanged(key, v);
        }
    }

    /**
     * Get a boolean preference value from Crosswalk. An exception will be thrown if
     * the key for the preference is not valid.
     * @param key the string name of the key.
     * @return true if it's enabled.
     * @since 1.0
     * @deprecated
     */
    @XWalkAPI
    public static synchronized boolean getValue(String key) throws RuntimeException {
        checkKey(key);
        return sPrefMap.get(key).getBooleanValue();
    }

    /**
     * Get a boolean preference value from Crosswalk. An exception will be thrown if
     * the key for the preference is not valid.
     * @param key the string name of the key.
     * @return true if it's enabled.
     * @since 3.0
     */
    @XWalkAPI
    public static synchronized boolean getBooleanValue(String key) throws RuntimeException {
        checkKey(key);
        return sPrefMap.get(key).getBooleanValue();
    }

    /**
     * Get a int preference value from Crosswalk. An exception will be thrown if
     * the key for the preference is not valid.
     * @param key the string name of the key.
     * @return the integer value.
     * @since 3.0
     */
    @XWalkAPI
    public static synchronized int getIntegerValue(String key) throws RuntimeException {
        checkKey(key);
        return sPrefMap.get(key).getIntegerValue();
    }

    /**
     * Get a string preference value from Crosswalk. An exception will be thrown if
     * the key for the preference is not valid.
     * @param key the string name of the key.
     * @return the string value.
     * @since 3.0
     */
    @XWalkAPI
    public static synchronized String getStringValue(String key) throws RuntimeException {
        checkKey(key);
        return sPrefMap.get(key).getStringValue();
    }

    static synchronized void load(KeyValueChangeListener listener) {
        // Load current settings for initialization of a listener implementor.
        for (Map.Entry<String, PreferenceValue> entry : sPrefMap.entrySet()) {
            listener.onKeyValueChanged(entry.getKey(), entry.getValue());
        }

        registerListener(listener);
    }

    static synchronized void unload(KeyValueChangeListener listener) {
        unregisterListener(listener);
    }

    // Listen to value changes.
    interface KeyValueChangeListener {
        public void onKeyValueChanged(String key, PreferenceValue value);
    }

    private static synchronized void registerListener(KeyValueChangeListener listener) {
        removeEnqueuedReference();
        WeakReference<KeyValueChangeListener> weakListener =
                new WeakReference<KeyValueChangeListener>(listener, sRefQueue);
        sListeners.add(weakListener);
    }

    private static synchronized void unregisterListener(KeyValueChangeListener listener) {
        removeEnqueuedReference();
        for (WeakReference<KeyValueChangeListener> weakListener : sListeners) {
            if (weakListener.get() == listener) {
                sListeners.remove(weakListener);
                break;
            }
        }
    }

    private static void onKeyValueChanged(String key, PreferenceValue value) {
        for (WeakReference<KeyValueChangeListener> weakListener : sListeners) {
            KeyValueChangeListener listener = weakListener.get();
            if (listener != null) listener.onKeyValueChanged(key, value);
        }
    }

    private static void checkKey(String key) throws RuntimeException {
        removeEnqueuedReference();
        if (!sPrefMap.containsKey(key)) {
            throw new RuntimeException("Warning: the preference key " + key +
                    " is not supported by Crosswalk.");
        }
    }

    /**
     * Internal method to keep track of weak references and remove the enqueued
     * references from listener list by polling the reference queue.
     */
    @SuppressWarnings("unchecked")
    private static void removeEnqueuedReference() {
        WeakReference<KeyValueChangeListener> toRemove;
        while ((toRemove = (WeakReference<KeyValueChangeListener>) sRefQueue.poll()) != null) {
            sListeners.remove(toRemove);
        }
    }
}


text:
package com.cloud.agent.api.storage;

import com.cloud.agent.api.Command;

public abstract class ssCommand extends Command {
    private String secUrl;

	public ssCommand() {
	}

    protected ssCommand(ssCommand that) {
        this.secUrl = that.secUrl;
    }
	public ssCommand(String secUrl) {
	    this.secUrl = secUrl;
    }

	@Override
    public boolean executeInSequence() {
        return true;
    }

    public String getSecUrl() {
        return secUrl;
    }

    public void setSecUrl(String secUrl) {
        this.secUrl = secUrl;
    }

}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;

namespace Iamport.RestApi.Extensions
{
    /// <summary>
    /// Enum에 관련된 확장 메서드
    /// </summary>
    public static class EnumExtensions
    {
        /// <summary>
        /// 주어진 enum 값에 선언된 EnumMemberAttribute의 Value를 반환합니다.
        /// EnumMemberAttribute가 없을 경우 enum 값을 ToString()하여 반환합니다.
        /// </summary>
        /// <param name="enumeration">enum 값</param>
        /// <returns>EnumMemberAttribute로 정의한 Value.</returns>
        public static string GetMemberValue(this Enum enumeration)
        {
            return enumeration.GetType().GetTypeInfo()
                .DeclaredMembers
                .FirstOrDefault(m => m.Name == enumeration.ToString())
                ?.GetCustomAttribute<EnumMemberAttribute>()
                ?.Value
                ?? enumeration.ToString();
        }

        /// <summary>
        /// 주어진 enum 값에 선언된 DisplayAttribute의 Name을 반환합니다.
        /// DisplayAttribute가 없을 경우 enum 값을 ToString()하여 반환합니다.
        /// </summary>
        /// <param name="enumeration">enum 값</param>
        /// <returns>DisplayAttribute로 정의한 Value.</returns>
        public static string GetDisplayName(this Enum enumeration)
        {
            return enumeration.GetType().GetTypeInfo()
                .DeclaredMembers
                .FirstOrDefault(m => m.Name == enumeration.ToString())
                ?.GetCustomAttribute<DisplayAttribute>()
                ?.Name
                ?? enumeration.ToString();
        }

        /// <summary>
        /// 주어진 타입의 Enum에 설정된 EnumMemberAttribute의 Value에 대한 Enum값의 맵을 반환합니다.
        /// EnumMemberAttribute가 없을 경우 해당 Enum을 ToString()한 값으로 매핑합니다.
        /// </summary>
        /// <typeparam name="TEnum">Enum 타입</typeparam>
        /// <returns>MemberValue에 대한 Enum값의 맵</returns>
        public static IReadOnlyDictionary<string, TEnum> GetMemberValueEnumMap<TEnum>()
        {
            var type = typeof(TEnum);
            return type.GetFields()
                .Where(m => m.IsLiteral && !m.IsSpecialName)
                .Select(m => new { MemberValue = m.GetCustomAttribute<EnumMemberAttribute>()?.Value ?? m.Name, Member = m })
                .ToDictionary(m => m.MemberValue, m => (TEnum)Enum.Parse(type, m.Member.Name));
        }
    }
}


text:
mkdir -p $PREFIX/bin
mkdir -p $PREFIX/lib/QueryFuse

cat <<EOF >$PREFIX/bin/QF_wrapper
#!/bin/env bash
SCRIPT_DIR=\$( cd "\$( dirname "\${BASH_SOURCE[0]}" )" && pwd )
QF_DIR=\$( cd \$SCRIPT_DIR/../lib/QueryFuse && pwd )
python \$QF_DIR/QF_multi_query_wrapper.py \$@
EOF
chmod +x $PREFIX/bin/QF_wrapper
cp ./QueryFuse_v1/* $PREFIX/lib/QueryFuse/


text:
/*******************************************************************************
  System Initialization File

  File Name:
    system_init.c

  Summary:
    This file contains source code necessary to initialize the system.

  Description:
    This file contains source code necessary to initialize the system.  It
    implements the "SYS_Initialize" function, defines the configuration bits,
    and allocates any necessary global system resources, such as the
    sysObj structure that contains the object handles to all the MPLAB Harmony
    module objects in the system.
 *******************************************************************************/

// DOM-IGNORE-BEGIN
/*******************************************************************************
Copyright (c) 2013-2015 released Microchip Technology Inc.  All rights reserved.

Microchip licenses to you the right to use, modify, copy and distribute
Software only when embedded on a Microchip microcontroller or digital signal
controller that is integrated into your product or third party product
(pursuant to the sublicense terms in the accompanying license agreement).

You should refer to the license agreement accompanying this Software for
additional information regarding your rights and obligations.

SOFTWARE AND DOCUMENTATION ARE PROVIDED AS IS WITHOUT WARRANTY OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF
MERCHANTABILITY, TITLE, NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE.
IN NO EVENT SHALL MICROCHIP OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER
CONTRACT, NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR
OTHER LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE OR
CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT OF
SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
 *******************************************************************************/
// DOM-IGNORE-END

// *****************************************************************************
// *****************************************************************************
// Section: Included Files
// *****************************************************************************
// *****************************************************************************

#include "system_config.h"
#include "system_definitions.h"

// ****************************************************************************
// ****************************************************************************
// Section: Configuration Bits
// ****************************************************************************
// ****************************************************************************
// <editor-fold defaultstate="collapsed" desc="Configuration Bits">

/*** DEVCFG0 ***/

#pragma config DEBUG =      OFF
#pragma config ICESEL =     ICS_PGx2
#pragma config PWP =        OFF
#pragma config BWP =        OFF
#pragma config CP =         OFF

/*** DEVCFG1 ***/

#pragma config FNOSC =      PRIPLL
#pragma config FSOSCEN =    OFF
#pragma config IESO =       ON
#pragma config POSCMOD =    XT
#pragma config OSCIOFNC =   OFF
#pragma config FPBDIV =     DIV_1
#pragma config FCKSM =      CSDCMD
#pragma config WDTPS =      PS1048576
#pragma config FWDTEN =     ON

/*** DEVCFG2 ***/

#pragma config FPLLIDIV =   DIV_2
#pragma config FPLLMUL =    MUL_20
#pragma config FPLLODIV =   DIV_1
#pragma config UPLLIDIV =   DIV_12
#pragma config UPLLEN =     OFF

/*** DEVCFG3 ***/

#pragma config USERID =     0xffff
#pragma config FSRSSEL =    PRIORITY_7
#pragma config FMIIEN =     ON
#pragma config FETHIO =     ON
#pragma config FCANIO =     ON
#pragma config FUSBIDIO =   ON
#pragma config FVBUSONIO =  ON
// </editor-fold>

// *****************************************************************************
// *****************************************************************************
// Section: Library/Stack Initialization Data
// *****************************************************************************
// *****************************************************************************

// *****************************************************************************
// *****************************************************************************
// Section: Driver Initialization Data
// *****************************************************************************
// *****************************************************************************

//<editor-fold defaultstate="collapsed" desc="DRV_USART Initialization Data">

const DRV_USART_INIT drvUsart0InitData =
{
    .moduleInit.value = DRV_USART_POWER_STATE_IDX0,
    .usartID = DRV_USART_PERIPHERAL_ID_IDX0,
    .mode = DRV_USART_OPER_MODE_IDX0,
    .modeData.AddressedModeInit.address = DRV_USART_OPER_MODE_DATA_IDX0,
    .flags = DRV_USART_INIT_FLAGS_IDX0,
    .brgClock = DRV_USART_BRG_CLOCK_IDX0,
    .lineControl = DRV_USART_LINE_CNTRL_IDX0,
    .baud = DRV_USART_BAUD_RATE_IDX0,
    .handshake = DRV_USART_HANDSHAKE_MODE_IDX0,
    .interruptTransmit = DRV_USART_XMIT_INT_SRC_IDX0,
    .interruptReceive = DRV_USART_RCV_INT_SRC_IDX0,
    .queueSizeTransmit = DRV_USART_XMIT_QUEUE_SIZE_IDX0,
    .queueSizeReceive = DRV_USART_RCV_QUEUE_SIZE_IDX0,
};

// </editor-fold>

// *****************************************************************************
// *****************************************************************************
// Section: System Data
// *****************************************************************************
// *****************************************************************************

/* Structure to hold the object handles for the modules in the system. */
SYSTEM_OBJECTS sysObj;

// *****************************************************************************
// *****************************************************************************
// Section: Module Initialization Data
// *****************************************************************************
// *****************************************************************************

/*******************************************************************************
  Device Control System Service Initialization Data

  <editor-fold defaultstate="collapsed"
  desc="Device Control System Service Initialization Data">
*/

const SYS_DEVCON_INIT sysDevconInit =
{
    .moduleInit = {0},
};

// </editor-fold>

// *****************************************************************************
// *****************************************************************************
// Section: Static Initialization Functions
// *****************************************************************************
// *****************************************************************************

// *****************************************************************************
// *****************************************************************************
// Section: System Initialization
// *****************************************************************************
// *****************************************************************************

/*******************************************************************************
  Function:
    void SYS_Initialize ( SYS_INIT_DATA *data )

  Summary:
    Initializes the board, services, drivers, application and other modules.

  Remarks:
    See prototype in system/common/sys_module.h.
 */

void SYS_Initialize ( void* data )
{
    /* Core Processor Initialization */
    SYS_CLK_Initialize( NULL );
    sysObj.sysDevcon = SYS_DEVCON_Initialize(SYS_DEVCON_INDEX_0, (SYS_MODULE_INIT*)&sysDevconInit);
    SYS_DEVCON_PerformanceConfig(SYS_CLK_SystemFrequencyGet());
    SYS_DEVCON_JTAGDisable();
    SYS_PORTS_Initialize();

    /* Initialize Drivers */
    /* Initialize ADC */
    DRV_ADC_Initialize();
    sysObj.drvUsart0 = DRV_USART_Initialize(DRV_USART_INDEX_0, (SYS_MODULE_INIT *)&drvUsart0InitData);
    SYS_INT_VectorPrioritySet(INT_VECTOR_UART1, INT_PRIORITY_LEVEL1);
    SYS_INT_VectorSubprioritySet(INT_VECTOR_UART1, INT_SUBPRIORITY_LEVEL0);

    /* Initialize System Services */
    SYS_INT_Initialize();

    /* Initialize Middleware */

    /* Initialize the Application */
    USART_Initialize();
    CONTROL_Initialize();
    OLED_Initialize();
    ROVER_Initialize();
    SENSOR_Initialize();
}

/*******************************************************************************
 End of File
*/


text:
<?xml version="1.0" encoding="utf-8" ?>
<software>
    <metadata>
        <name>eZ Comments LS</name>
        <version>5.2.0</version>
        <copyright>Copyright (C) 1999-2013 eZ Systems AS</copyright>
        <license>GNU General Public License v2.0</license>
        <info_url>http://projects.ez.no/ezcomments</info_url>

         <software>
            <uses>
                <name>reCAPTCHA PHP Library</name>
                <license></license>
                <copyright>Copyright (c) 2007-2012 reCAPTCHA -- http://www.google.com/recaptcha</copyright>
                <version>1.11</version>
            </uses>
        </software>

    </metadata>

    <dependencies>
        <uses>
            <extension name="ezjscore" />
        </uses>
        <extends>
            <extension name="ezwebin" />
        </extends>
    </dependencies>
</software>


text:
require 'spec_helper'

describe UsersController do

  describe "GET 'show'" do
    before :each do
      @user = create :user
    end

    it "should be successful" do
      get :show, username: @user
      response.should be_success
    end

    it "should find the right user" do
      get :show, username: @user
      assigns(:user).should == @user
    end
  end

end