text:
package okhttp3.mock;

import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import okhttp3.*;
import okhttp3.mock.matchers.*;
import okio.Buffer;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.*;
import java.util.regex.Pattern;

import static okhttp3.mock.HttpCodes.HTTP_200_OK;
import static okhttp3.mock.HttpMethod.*;
import static okhttp3.mock.MediaTypes.MEDIATYPE_RAW_DATA;
import static okhttp3.mock.MediaTypes.MEDIATYPE_TEXT;
import static okhttp3.mock.matchers.MatcherHelper.*;

public class Rule {
    private final List<Matcher> matchers;
    private final RuleAnswer answer;
    private final long delay;
    private int times;

    private Rule(List<Matcher> matchers, RuleAnswer answer, int times, long delay) {
        this.matchers = matchers;
        this.answer = answer;
        this.times = times;
        this.delay = delay;
    }

    protected Response accept(Request request) {
        if (isConsumed()) {
            return null;
        }
        for (Matcher matcher : matchers) {

            if (!matcher.matches(request)) {
                return null;
            }
        }
        if (delay > 0) {
            try {
                Thread.sleep(delay);

            } catch (InterruptedException ignored) {
            }
        }
        if (times > 0 && times != Integer.MAX_VALUE) {
            times--;
        }
        return answer.respond(request)
                .protocol(Protocol.HTTP_1_1)
                .request(request)
                .message("Rule response " + this)
                .build();
    }

    public Map<Matcher, String> getFailReason(Request request) {
        Map<Matcher, String> reasons = new LinkedHashMap<>();
        for (Matcher matcher : matchers) {
            if (!matcher.matches(request)) {
                reasons.put(matcher, matcher.failReason(request));
            }
        }
        return reasons;
    }

    public boolean isConsumed() {
        return times == 0;
    }

    @Override
    public String toString() {
        return matchers.toString() + ", consumed=" + isConsumed();
    }

    public static class Builder {
        private final List<Matcher> matchers = new LinkedList<>();
        private int times = 1;
        private long delay = 0;
        private boolean negateNext;
        private boolean orNext;

        public Builder get() {
            method(GET);
            return this;
        }

        public Builder get(String url) {
            get();
            return url(url);
        }

        public Builder head() {
            method(HEAD);
            return this;
        }

        public Builder head(String url) {
            head();
            return url(url);
        }

        public Builder post() {
            method(POST);
            return this;
        }

        public Builder post(String url) {
            post();
            return url(url);
        }

        public Builder put() {
            method(PUT);
            return this;
        }

        public Builder put(String url) {
            put();
            return url(url);
        }

        public Builder delete() {
            method(DELETE);
            return this;
        }

        public Builder delete(String url) {
            delete();
            return url(url);
        }

        public Builder options() {
            method(OPTIONS);
            return this;
        }

        public Builder options(String url) {
            options();
            return url(url);
        }

        public Builder patch() {
            method(PATCH);
            return this;
        }

        public Builder patch(String url) {
            patch();
            return url(url);
        }

        public Builder method(@HttpMethod String method) {
            matches(new MethodMatcher(method));
            return this;
        }

        public Builder url(String url) {
            urlMatches(exact(url));
            return this;
        }

        public Builder urlStarts(String prefix) {
            urlMatches(prefix(prefix));
            return this;
        }

        public Builder urlEnds(String suffix) {
            urlMatches(suffix(suffix));
            return this;
        }

        public Builder urlMatches(Pattern pattern) {
            matches(new URLMatcher(pattern));
            return this;
        }

        public Builder path(String path) {
            pathMatches(exact(path));
            return this;
        }

        public Builder pathStarts(String prefix) {
            pathMatches(prefix(prefix));
            return this;
        }

        public Builder pathEnds(String suffix) {
            pathMatches(suffix(suffix));
            return this;
        }

        public Builder pathMatches(Pattern pattern) {
            matches(new PathMatcher(pattern));
            return this;
        }

        public Builder hasHeader(String header) {
            headerMatches(header, any());
            return this;
        }

        public Builder header(String header, String value) {
            headerMatches(header, exact(value));
            return this;
        }

        public Builder headerMatches(String header, Pattern pattern) {
            matches(new HeaderMatcher(header, pattern));
            return this;
        }

        public Builder paramMatches(String param, Pattern pattern) {
            matches(new QueryParamMatcher(param, pattern));
            return this;
        }

        public Builder hasParam(String param) {
            paramMatches(param, any());
            return this;
        }

        public Builder param(String param, String value) {
            paramMatches(param, exact(value));
            return this;
        }

        public Builder body(String value) {
            return body(value, null);
        }

        public Builder body(String value, Charset charset) {
            bodyMatches(exact(value), charset);
            return this;
        }

        public Builder bodyMatches(Pattern pattern) {
            return bodyMatches(pattern, null);
        }

        public Builder bodyMatches(Pattern pattern, Charset charset) {
            matches(new BodyMatcher(pattern, charset));
            return this;
        }

        public Builder not() {
            if (negateNext) {
                throw new IllegalStateException("'not()' can't be followed by another 'not()'");
            }
            negateNext = true;
            return this;
        }

        public Builder or() {
            if (orNext) {
                throw new IllegalStateException("'or()' can't be followed by another 'or()'");
            }
            orNext = true;
            return this;
        }

        public Builder matches(Matcher matcher) {
            if (negateNext) {
                negateNext = false;
                matcher = new NotMatcher(matcher);
            }
            if (orNext) {
                int count = matchers.size();
                if (count <= 0) {
                    throw new IllegalStateException("'or()' can't be the first matcher!");
                }

                orNext = false;
                Matcher prev = matchers.remove(count - 1);
                if (prev instanceof OrMatcher) {
                    ((OrMatcher) prev).add(matcher);
                    matcher = prev;

                } else {
                    matcher = new OrMatcher(prev, matcher);
                }
            }
            matchers.add(matcher);
            return this;
        }

        public Builder times(int times) {
            this.times = times;
            return this;
        }

        public Builder anyTimes() {
            this.times = Integer.MAX_VALUE;
            return this;
        }

        public Builder delay(long milliseconds) {
            this.delay = milliseconds;
            return this;
        }

        public Response.Builder respond(@NonNull String body) {
            return respond(body, MEDIATYPE_TEXT);
        }

        public Response.Builder respond(@NonNull String body, @NonNull MediaType mediaType) {
            return respond(ResponseBody.create(mediaType, body));
        }

        public Response.Builder respond(@NonNull byte[] body) {
            return respond(body, MEDIATYPE_RAW_DATA);
        }

        public Response.Builder respond(@NonNull byte[] body, @NonNull MediaType mediaType) {
            return respond(ResponseBody.create(mediaType, body));
        }

        public Response.Builder respond(@NonNull InputStream body) {
            return respond(-1, body);
        }

        public Response.Builder respond(@NonNull InputStream body, @NonNull MediaType mediaType) {
            return respond(-1, body, mediaType);
        }

        public Response.Builder respond(long contentLength, @NonNull InputStream body) {
            return respond(contentLength, body, MEDIATYPE_RAW_DATA);
        }

        public Response.Builder respond(long contentLength, @NonNull InputStream body, @NonNull MediaType mediaType) {
            try {
                return respond(ResponseBody.create(mediaType, contentLength, new Buffer().readFrom(body)));

            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        public Response.Builder respond(@HttpCode int code) {
            return respond(code, (ResponseBody) null);
        }

        public Response.Builder respond(@Nullable ResponseBody body) {
            return respond(HTTP_200_OK, body);
        }

        public Response.Builder respond(@HttpCode int code, @Nullable ResponseBody body) {
            FinalRuleBuilder builder = new FinalRuleBuilder();
            builder.code(code);
            builder.body(body != null ? body : ResponseBody.create(null, ""));
            onBuild(builder.buildRule());
            return builder;
        }

        public void answer(RuleAnswer answer) {
            onBuild(new Rule(Collections.unmodifiableList(matchers), answer, times, delay));
        }

        void onBuild(Rule rule) {
        }

        class FinalRuleBuilder extends Response.Builder implements RuleAnswer {
            private final boolean repeteable = times != 1;
            private ResponseBody repeteableBody;
            private byte repeteableBodyContent[];

            Rule buildRule() {
                if (negateNext) {
                    throw new IllegalStateException("Misted a predicate after 'not()'!");
                }
                if (orNext) {
                    throw new IllegalStateException("Misted a predicate after 'or()'!");
                }
                if (times < 1) {
                    throw new IllegalStateException("Time can't be less than 1!");
                }
                if (delay < 0) {
                    throw new IllegalStateException("Delay can't be less than 0!");
                }
                return new Rule(Collections.unmodifiableList(matchers), this, times, delay);
            }

            @Override
            public Response.Builder body(ResponseBody body) {
                if (repeteable) {
                    repeteableBody = body;
                    try {
                        repeteableBodyContent = body.bytes();

                    } catch (IOException e) {
                        throw new IllegalArgumentException("error preloading body for rule " + this, e);
                    }
                }
                return super.body(body);
            }

            @Override
            public Response.Builder respond(Request request) {
                if (repeteable) {
                    Buffer buffer = repeteableBody.source().buffer();
                    buffer.clear();
                    buffer.write(repeteableBodyContent);
                }
                return this;
            }

        }

    }

}


text:
package com.zxytech.designpatterns.gof.creationalpatterns.singletonpattern;

/**
 * Created by ryan on 2016/12/17.
 * 从 singleton 类获取唯一的对象。
 */
public class SingletonPatternDemo {
    public static void main(String[] args) {
        // 不合法的构造函数
        // 编译时错误:构造函SingleObject()是不可兼得
        // SingleObject object = new SingleObject();

        // 获取唯一可用的对象
        SingleObject object = SingleObject.getInstance();

        // 显示消息
        object.showMessage();

        // 单例模式的几种实现方式
        // 1、懒汉式,线程不安全
        SingletonLazy singletonLazy = SingletonLazy.getInstance();
        singletonLazy.showMessage();

        // 2、懒汉式,线程安全
        SingletonLazySync singletonLazySync = SingletonLazySync.getInstance();
        singletonLazySync.showMessage();

        // 3、饿汉式
        SingletonClassloader singletonClassloader = SingletonClassloader.getInstance();
        singletonClassloader.showMessage();

        // 4、双检锁/双重校验锁(DCL,即 double-checked locking)
        SingletonDCL singletonDCL = SingletonDCL.getInstance();
        singletonDCL.showMessage();

        // 5、登记式/静态内部类
        SingletonInside singletonInside = SingletonInside.getInstance();
        singletonInside.showMessage();

        // 6、枚举
        SingletonEnum singletonEnum = SingletonEnum.INSTANCE;
        singletonEnum.showMessage();
    }
}

redpajama_set_name: RedPajamaGithub


text:
'use strict';

const chai = require('chai');
const sinon = require('sinon');

const expect = chai.expect;
const Support = require('../support');
const { DataTypes, Sequelize } = require('@sequelize/core');
const _ = require('lodash');

const sequelize = Support.sequelize;

describe(Support.getTestDialectTeaser('Hooks'), () => {
  beforeEach(function () {
    this.Model = sequelize.define('m');
  });

  it('does not expose non-model hooks', function () {
    for (const badHook of ['beforeDefine', 'afterDefine', 'beforeConnect', 'afterConnect', 'beforeDisconnect', 'afterDisconnect', 'beforeInit', 'afterInit']) {
      expect(this.Model).to.not.have.property(badHook);
    }
  });

  describe('arguments', () => {
    it('hooks can modify passed arguments', async function () {
      this.Model.addHook('beforeCreate', options => {
        options.answer = 41;
      });

      const options = {};
      await this.Model.runHooks('beforeCreate', options);
      expect(options.answer).to.equal(41);
    });
  });

  describe('proxies', () => {
    beforeEach(() => {
      sinon.stub(sequelize, 'queryRaw').resolves([{
        _previousDataValues: {},
        dataValues: { id: 1, name: 'abc' },
      }]);
    });

    afterEach(() => {
      sequelize.queryRaw.restore();
    });

    describe('defined by options.hooks', () => {
      beforeEach(function () {
        this.beforeSaveHook = sinon.spy();
        this.afterSaveHook = sinon.spy();
        this.afterCreateHook = sinon.spy();

        this.Model = sequelize.define('m', {
          name: DataTypes.STRING,
        }, {
          hooks: {
            beforeSave: this.beforeSaveHook,
            afterSave: this.afterSaveHook,
            afterCreate: this.afterCreateHook,
          },
        });
      });

      it('calls beforeSave/afterSave', async function () {
        await this.Model.create({});
        expect(this.afterCreateHook).to.have.been.calledOnce;
        expect(this.beforeSaveHook).to.have.been.calledOnce;
        expect(this.afterSaveHook).to.have.been.calledOnce;
      });
    });

    describe('defined by addHook method', () => {
      beforeEach(function () {
        this.beforeSaveHook = sinon.spy();
        this.afterSaveHook = sinon.spy();

        this.Model = sequelize.define('m', {
          name: DataTypes.STRING,
        });

        this.Model.addHook('beforeSave', this.beforeSaveHook);
        this.Model.addHook('afterSave', this.afterSaveHook);
      });

      it('calls beforeSave/afterSave', async function () {
        await this.Model.create({});
        expect(this.beforeSaveHook).to.have.been.calledOnce;
        expect(this.afterSaveHook).to.have.been.calledOnce;
      });
    });

    describe('defined by hook method', () => {
      beforeEach(function () {
        this.beforeSaveHook = sinon.spy();
        this.afterSaveHook = sinon.spy();

        this.Model = sequelize.define('m', {
          name: DataTypes.STRING,
        });

        this.Model.addHook('beforeSave', this.beforeSaveHook);
        this.Model.addHook('afterSave', this.afterSaveHook);
      });

      it('calls beforeSave/afterSave', async function () {
        await this.Model.create({});
        expect(this.beforeSaveHook).to.have.been.calledOnce;
        expect(this.afterSaveHook).to.have.been.calledOnce;
      });
    });
  });

  describe('multiple hooks', () => {
    beforeEach(function () {
      this.hook1 = sinon.spy();
      this.hook2 = sinon.spy();
      this.hook3 = sinon.spy();
    });

    describe('runs all hooks on success', () => {
      afterEach(function () {
        expect(this.hook1).to.have.been.calledOnce;
        expect(this.hook2).to.have.been.calledOnce;
        expect(this.hook3).to.have.been.calledOnce;
      });

      it('using addHook', async function () {
        this.Model.addHook('beforeCreate', this.hook1);
        this.Model.addHook('beforeCreate', this.hook2);
        this.Model.addHook('beforeCreate', this.hook3);

        await this.Model.runHooks('beforeCreate');
      });

      it('using function', async function () {
        this.Model.beforeCreate(this.hook1);
        this.Model.beforeCreate(this.hook2);
        this.Model.beforeCreate(this.hook3);

        await this.Model.runHooks('beforeCreate');
      });

      it('using define', async function () {
        await sequelize.define('M', {}, {
          hooks: {
            beforeCreate: [this.hook1, this.hook2, this.hook3],
          },
        }).runHooks('beforeCreate');
      });

      it('using a mixture', async function () {
        const Model = sequelize.define('M', {}, {
          hooks: {
            beforeCreate: this.hook1,
          },
        });
        Model.beforeCreate(this.hook2);
        Model.addHook('beforeCreate', this.hook3);

        await Model.runHooks('beforeCreate');
      });
    });

    it('stops execution when a hook throws', async function () {
      this.Model.beforeCreate(() => {
        this.hook1();

        throw new Error('No!');
      });
      this.Model.beforeCreate(this.hook2);

      await expect(this.Model.runHooks('beforeCreate')).to.be.rejected;
      expect(this.hook1).to.have.been.calledOnce;
      expect(this.hook2).not.to.have.been.called;
    });

    it('stops execution when a hook rejects', async function () {
      this.Model.beforeCreate(async () => {
        this.hook1();

        throw new Error('No!');
      });
      this.Model.beforeCreate(this.hook2);

      await expect(this.Model.runHooks('beforeCreate')).to.be.rejected;
      expect(this.hook1).to.have.been.calledOnce;
      expect(this.hook2).not.to.have.been.called;
    });
  });

  describe('global hooks', () => {
    describe('using addHook', () => {

      it('invokes the global hook', async function () {
        const globalHook = sinon.spy();

        sequelize.addHook('beforeUpdate', globalHook);

        await this.Model.runHooks('beforeUpdate');
        expect(globalHook).to.have.been.calledOnce;
      });

      it('invokes the global hook, when the model also has a hook', async () => {
        const globalHookBefore = sinon.spy();
        const globalHookAfter = sinon.spy();
        const localHook = sinon.spy();

        sequelize.addHook('beforeUpdate', globalHookBefore);

        const Model = sequelize.define('m', {}, {
          hooks: {
            beforeUpdate: localHook,
          },
        });

        sequelize.addHook('beforeUpdate', globalHookAfter);

        await Model.runHooks('beforeUpdate');
        expect(globalHookBefore).to.have.been.calledOnce;
        expect(globalHookAfter).to.have.been.calledOnce;
        expect(localHook).to.have.been.calledOnce;

        expect(localHook).to.have.been.calledBefore(globalHookBefore);
        expect(localHook).to.have.been.calledBefore(globalHookAfter);
      });
    });

    describe('using define hooks', () => {
      beforeEach(function () {
        this.beforeCreate = sinon.spy();
        this.sequelize = Support.createSequelizeInstance({
          define: {
            hooks: {
              beforeCreate: this.beforeCreate,
            },
          },
        });
      });

      it('runs the global hook when no hook is passed', async function () {
        const Model = this.sequelize.define('M', {}, {
          hooks: {
            beforeUpdate: _.noop, // Just to make sure we can define other hooks without overwriting the global one
          },
        });

        await Model.runHooks('beforeCreate');
        expect(this.beforeCreate).to.have.been.calledOnce;
      });

      it('does not run the global hook when the model specifies its own hook', async function () {
        const localHook = sinon.spy();
        const Model = this.sequelize.define('M', {}, {
          hooks: {
            beforeCreate: localHook,
          },
        });

        await Model.runHooks('beforeCreate');
        expect(this.beforeCreate).not.to.have.been.called;
        expect(localHook).to.have.been.calledOnce;
      });
    });
  });

  describe('#removeHook', () => {
    it('should remove hook', async function () {
      const hook1 = sinon.spy();
      const hook2 = sinon.spy();

      this.Model.addHook('beforeCreate', 'myHook', hook1);
      this.Model.beforeCreate('myHook2', hook2);

      await this.Model.runHooks('beforeCreate');
      expect(hook1).to.have.been.calledOnce;
      expect(hook2).to.have.been.calledOnce;

      hook1.resetHistory();
      hook2.resetHistory();

      this.Model.removeHook('beforeCreate', 'myHook');
      this.Model.removeHook('beforeCreate', 'myHook2');

      await this.Model.runHooks('beforeCreate');
      expect(hook1).not.to.have.been.called;
      expect(hook2).not.to.have.been.called;
    });

    it('should not remove other hooks', async function () {
      const hook1 = sinon.spy();
      const hook2 = sinon.spy();
      const hook3 = sinon.spy();
      const hook4 = sinon.spy();

      this.Model.addHook('beforeCreate', hook1);
      this.Model.addHook('beforeCreate', 'myHook', hook2);
      this.Model.beforeCreate('myHook2', hook3);
      this.Model.beforeCreate(hook4);

      await this.Model.runHooks('beforeCreate');
      expect(hook1).to.have.been.calledOnce;
      expect(hook2).to.have.been.calledOnce;
      expect(hook3).to.have.been.calledOnce;
      expect(hook4).to.have.been.calledOnce;

      hook1.resetHistory();
      hook2.resetHistory();
      hook3.resetHistory();
      hook4.resetHistory();

      this.Model.removeHook('beforeCreate', 'myHook');

      await this.Model.runHooks('beforeCreate');
      expect(hook1).to.have.been.calledOnce;
      expect(hook2).not.to.have.been.called;
      expect(hook3).to.have.been.calledOnce;
      expect(hook4).to.have.been.calledOnce;
    });
  });

  describe('#addHook', () => {
    it('should add additional hook when previous exists', async function () {
      const hook1 = sinon.spy();
      const hook2 = sinon.spy();

      const Model = this.sequelize.define('Model', {}, {
        hooks: { beforeCreate: hook1 },
      });

      Model.addHook('beforeCreate', hook2);

      await Model.runHooks('beforeCreate');
      expect(hook1).to.have.been.calledOnce;
      expect(hook2).to.have.been.calledOnce;
    });
  });

  describe('promises', () => {
    it('can return a promise', async function () {
      this.Model.beforeBulkCreate(async () => {
        // This space intentionally left blank
      });

      await expect(this.Model.runHooks('beforeBulkCreate')).to.be.fulfilled;
    });

    it('can return undefined', async function () {
      this.Model.beforeBulkCreate(() => {
        // This space intentionally left blank
      });

      await expect(this.Model.runHooks('beforeBulkCreate')).to.be.fulfilled;
    });

    it('can return an error by rejecting', async function () {
      this.Model.beforeCreate(async () => {
        throw new Error('Forbidden');
      });

      await expect(this.Model.runHooks('beforeCreate')).to.be.rejectedWith('Forbidden');
    });

    it('can return an error by throwing', async function () {
      this.Model.beforeCreate(() => {
        throw new Error('Forbidden');
      });

      await expect(this.Model.runHooks('beforeCreate')).to.be.rejectedWith('Forbidden');
    });
  });

  describe('sync hooks', () => {
    beforeEach(function () {
      this.hook1 = sinon.spy();
      this.hook2 = sinon.spy();
      this.hook3 = sinon.spy();
      this.hook4 = sinon.spy();
    });

    it('runs all beforInit/afterInit hooks', function () {
      Sequelize.addHook('beforeInit', 'h1', this.hook1);
      Sequelize.addHook('beforeInit', 'h2', this.hook2);
      Sequelize.addHook('afterInit', 'h3', this.hook3);
      Sequelize.addHook('afterInit', 'h4', this.hook4);

      Support.createSequelizeInstance();

      expect(this.hook1).to.have.been.calledOnce;
      expect(this.hook2).to.have.been.calledOnce;
      expect(this.hook3).to.have.been.calledOnce;
      expect(this.hook4).to.have.been.calledOnce;

      // cleanup hooks on Sequelize
      Sequelize.removeHook('beforeInit', 'h1');
      Sequelize.removeHook('beforeInit', 'h2');
      Sequelize.removeHook('afterInit', 'h3');
      Sequelize.removeHook('afterInit', 'h4');

      Support.createSequelizeInstance();

      // check if hooks were removed
      expect(this.hook1).to.have.been.calledOnce;
      expect(this.hook2).to.have.been.calledOnce;
      expect(this.hook3).to.have.been.calledOnce;
      expect(this.hook4).to.have.been.calledOnce;
    });

    it('runs all beforDefine/afterDefine hooks', function () {
      const sequelize = Support.createSequelizeInstance();
      sequelize.addHook('beforeDefine', this.hook1);
      sequelize.addHook('beforeDefine', this.hook2);
      sequelize.addHook('afterDefine', this.hook3);
      sequelize.addHook('afterDefine', this.hook4);
      sequelize.define('Test', {});
      expect(this.hook1).to.have.been.calledOnce;
      expect(this.hook2).to.have.been.calledOnce;
      expect(this.hook3).to.have.been.calledOnce;
      expect(this.hook4).to.have.been.calledOnce;
    });
  });

  describe('#removal', () => {
    before(() => {
      sinon.stub(sequelize, 'queryRaw').resolves([{
        _previousDataValues: {},
        dataValues: { id: 1, name: 'abc' },
      }]);
    });

    after(() => {
      sequelize.queryRaw.restore();
    });

    it('should be able to remove by name', async () => {
      const User = sequelize.define('User');

      const hook1 = sinon.spy();
      const hook2 = sinon.spy();

      User.addHook('beforeCreate', 'sasuke', hook1);
      User.addHook('beforeCreate', 'naruto', hook2);

      await User.create({ username: 'makunouchi' });
      expect(hook1).to.have.been.calledOnce;
      expect(hook2).to.have.been.calledOnce;
      User.removeHook('beforeCreate', 'sasuke');
      await User.create({ username: 'sendo' });
      expect(hook1).to.have.been.calledOnce;
      expect(hook2).to.have.been.calledTwice;
    });

    it('should be able to remove by reference', async () => {
      const User = sequelize.define('User');

      const hook1 = sinon.spy();
      const hook2 = sinon.spy();

      User.addHook('beforeCreate', hook1);
      User.addHook('beforeCreate', hook2);

      await User.create({ username: 'makunouchi' });
      expect(hook1).to.have.been.calledOnce;
      expect(hook2).to.have.been.calledOnce;
      User.removeHook('beforeCreate', hook1);
      await User.create({ username: 'sendo' });
      expect(hook1).to.have.been.calledOnce;
      expect(hook2).to.have.been.calledTwice;
    });
  });
});


text:
using System.Collections.Generic;

namespace Nancy.WebApi.Demo
{
    public class ModuleRouteSummary
    {
        public string ModuleName { get; set; }
        public string HelpModulePath { get; }

        public List<RouteSummary> Routes { get; set; }

        public ModuleRouteSummary(string moduleName, string helpModulePath)
        {
            ModuleName = moduleName;
            HelpModulePath = helpModulePath;
            Routes = new List<RouteSummary>();
        }
    }
}


text:
<package>
  <description brief="social_navigation_layers">

  </description>
  <author>David!!</author>
  <license>BSD</license>
  <url>http://ros.org/wiki/social_navigation_layers</url>
  <depend package="pluginlib"/>
  <depend package="roscpp"/>
  <depend package="costmap_2d"/>
  <depend package="people_msgs"/>
  <depend package="dynamic_reconfigure"/>
<export>
  <costmap_2d plugin="${prefix}/costmap_plugins.xml" />
</export>
</package>


text:
package com.facebook.buck.apple;

import com.facebook.buck.cxx.CxxCompilationDatabase;
import com.facebook.buck.cxx.CxxDescriptionEnhancer;
import com.facebook.buck.cxx.CxxPlatform;
import com.facebook.buck.cxx.CxxStrip;
import com.facebook.buck.cxx.Linker;
import com.facebook.buck.cxx.NativeLinkable;
import com.facebook.buck.cxx.NativeLinkables;
import com.facebook.buck.cxx.StripStyle;
import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.model.BuildTargets;
import com.facebook.buck.model.Either;
import com.facebook.buck.model.Flavor;
import com.facebook.buck.model.FlavorDomain;
import com.facebook.buck.model.FlavorDomainException;
import com.facebook.buck.model.Flavored;
import com.facebook.buck.model.ImmutableFlavor;
import com.facebook.buck.parser.NoSuchBuildTargetException;
import com.facebook.buck.rules.AbstractBuildRule;
import com.facebook.buck.rules.BuildContext;
import com.facebook.buck.rules.BuildRule;
import com.facebook.buck.rules.BuildRuleParams;
import com.facebook.buck.rules.BuildRuleResolver;
import com.facebook.buck.rules.BuildRuleType;
import com.facebook.buck.rules.BuildRules;
import com.facebook.buck.rules.BuildTargetSourcePath;
import com.facebook.buck.rules.BuildableContext;
import com.facebook.buck.rules.Description;
import com.facebook.buck.rules.ImplicitDepsInferringDescription;
import com.facebook.buck.rules.Label;
import com.facebook.buck.rules.PathSourcePath;
import com.facebook.buck.rules.SourcePath;
import com.facebook.buck.rules.SourcePathResolver;
import com.facebook.buck.rules.SourcePaths;
import com.facebook.buck.rules.TargetGraph;
import com.facebook.buck.step.Step;
import com.facebook.buck.step.fs.MakeCleanDirectoryStep;
import com.facebook.buck.util.HumanReadableException;
import com.facebook.buck.zip.UnzipStep;
import com.facebook.infer.annotation.SuppressFieldNotInitialized;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Sets;

import java.nio.file.Path;
import java.util.Set;

public class AppleTestDescription implements
    Description<AppleTestDescription.Arg>,
    Flavored,
    ImplicitDepsInferringDescription<AppleTestDescription.Arg> {

  public static final BuildRuleType TYPE = BuildRuleType.of("apple_test");

  /**
   * Flavors for the additional generated build rules.
   */
  private static final Flavor LIBRARY_FLAVOR = ImmutableFlavor.of("apple-test-library");
  public static final Flavor BUNDLE_FLAVOR = ImmutableFlavor.of("apple-test-bundle");
  private static final Flavor UNZIP_XCTOOL_FLAVOR = ImmutableFlavor.of("unzip-xctool");

  private static final Set<Flavor> SUPPORTED_FLAVORS = ImmutableSet.of(
      LIBRARY_FLAVOR, BUNDLE_FLAVOR);

  private static final Predicate<Flavor> IS_SUPPORTED_FLAVOR = Predicates.in(SUPPORTED_FLAVORS);

  private static final Set<Flavor> NON_LIBRARY_FLAVORS = ImmutableSet.of(
      CxxCompilationDatabase.COMPILATION_DATABASE,
      CxxDescriptionEnhancer.HEADER_SYMLINK_TREE_FLAVOR,
      CxxDescriptionEnhancer.EXPORTED_HEADER_SYMLINK_TREE_FLAVOR,
      AppleDebugFormat.DWARF_AND_DSYM.getFlavor(),
      AppleDebugFormat.DWARF.getFlavor(),
      AppleDebugFormat.NONE.getFlavor());

  private final AppleConfig appleConfig;
  private final AppleLibraryDescription appleLibraryDescription;
  private final FlavorDomain<CxxPlatform> cxxPlatformFlavorDomain;
  private final FlavorDomain<AppleCxxPlatform> appleCxxPlatformFlavorDomain;
  private final CxxPlatform defaultCxxPlatform;
  private final CodeSignIdentityStore codeSignIdentityStore;
  private final ProvisioningProfileStore provisioningProfileStore;
  private final Supplier<Optional<Path>> xcodeDeveloperDirectorySupplier;
  private final AppleDebugFormat defaultDebugFormat;

  public AppleTestDescription(
      AppleConfig appleConfig,
      AppleLibraryDescription appleLibraryDescription,
      FlavorDomain<CxxPlatform> cxxPlatformFlavorDomain,
      FlavorDomain<AppleCxxPlatform> appleCxxPlatformFlavorDomain,
      CxxPlatform defaultCxxPlatform,
      CodeSignIdentityStore codeSignIdentityStore,
      ProvisioningProfileStore provisioningProfileStore,
      Supplier<Optional<Path>> xcodeDeveloperDirectorySupplier,
      AppleDebugFormat defaultDebugFormat) {
    this.appleConfig = appleConfig;
    this.appleLibraryDescription = appleLibraryDescription;
    this.cxxPlatformFlavorDomain = cxxPlatformFlavorDomain;
    this.appleCxxPlatformFlavorDomain = appleCxxPlatformFlavorDomain;
    this.defaultCxxPlatform = defaultCxxPlatform;
    this.codeSignIdentityStore = codeSignIdentityStore;
    this.provisioningProfileStore = provisioningProfileStore;
    this.xcodeDeveloperDirectorySupplier = xcodeDeveloperDirectorySupplier;
    this.defaultDebugFormat = defaultDebugFormat;
  }

  @Override
  public BuildRuleType getBuildRuleType() {
    return TYPE;
  }

  @Override
  public Arg createUnpopulatedConstructorArg() {
    return new Arg();
  }

  @Override
  public boolean hasFlavors(ImmutableSet<Flavor> flavors) {
    return FluentIterable.from(flavors).allMatch(IS_SUPPORTED_FLAVOR) ||
        appleLibraryDescription.hasFlavors(flavors);
  }

  @Override
  public <A extends Arg> BuildRule createBuildRule(
      TargetGraph targetGraph,
      BuildRuleParams params,
      BuildRuleResolver resolver,
      A args) throws NoSuchBuildTargetException {
    AppleDebugFormat debugFormat = AppleDebugFormat.FLAVOR_DOMAIN
        .getValue(params.getBuildTarget())
        .or(defaultDebugFormat);
    if (params.getBuildTarget().getFlavors().contains(debugFormat.getFlavor())) {
      params = params.withoutFlavor(debugFormat.getFlavor());
    }

    String extension = args.extension.isLeft() ?
        args.extension.getLeft().toFileExtension() :
        args.extension.getRight();
    if (!AppleBundleExtensions.VALID_XCTOOL_BUNDLE_EXTENSIONS.contains(extension)) {
      throw new HumanReadableException(
          "Invalid bundle extension for apple_test rule: %s (must be one of %s)",
          extension,
          AppleBundleExtensions.VALID_XCTOOL_BUNDLE_EXTENSIONS);
    }
    boolean createBundle = Sets.intersection(
        params.getBuildTarget().getFlavors(),
        NON_LIBRARY_FLAVORS).isEmpty();
    Sets.SetView<Flavor> nonLibraryFlavors = Sets.difference(
        params.getBuildTarget().getFlavors(),
        NON_LIBRARY_FLAVORS);
    boolean addDefaultPlatform = nonLibraryFlavors.isEmpty();
    ImmutableSet.Builder<Flavor> extraFlavorsBuilder = ImmutableSet.builder();
    if (createBundle) {
      extraFlavorsBuilder.add(
          LIBRARY_FLAVOR,
          CxxDescriptionEnhancer.MACH_O_BUNDLE_FLAVOR);
    }
    extraFlavorsBuilder.add(debugFormat.getFlavor());
    if (addDefaultPlatform) {
      extraFlavorsBuilder.add(defaultCxxPlatform.getFlavor());
    }

    CxxPlatform cxxPlatform = cxxPlatformFlavorDomain
        .getValue(params.getBuildTarget())
        .or(defaultCxxPlatform);

    Optional<AppleBundle> testHostApp;
    Optional<SourcePath> testHostAppBinarySourcePath;
    ImmutableSet<BuildTarget> blacklist;
    if (args.testHostApp.isPresent()) {
      BuildRule rule = resolver.requireRule(
          BuildTarget.builder(args.testHostApp.get())
              .addAllFlavors(nonLibraryFlavors)
              .addFlavors(debugFormat.getFlavor())
              .addFlavors(StripStyle.NON_GLOBAL_SYMBOLS.getFlavor())
              .build());

      if (!(rule instanceof AppleBundle)) {
        throw new HumanReadableException(
            "Apple test rule '%s' has test_host_app '%s' not of type '%s'.",
            params.getBuildTarget(),
            args.testHostApp.get(),
            AppleBundleDescription.TYPE);
      }

      testHostApp = Optional.of((AppleBundle) rule);
      testHostAppBinarySourcePath = Optional.<SourcePath>of(
          new BuildTargetSourcePath(testHostApp.get().getBinaryBuildRule().getBuildTarget()));

      ImmutableMap<BuildTarget, NativeLinkable> roots =
          NativeLinkables.getNativeLinkableRoots(
              testHostApp.get().getBinary().get().getDeps(),
              Predicates.alwaysTrue());
      ImmutableMap<BuildTarget, NativeLinkable> nativeLinkables =
          NativeLinkables.getTransitiveNativeLinkables(cxxPlatform, roots.values());
      blacklist = ImmutableSet.copyOf(nativeLinkables.keySet());
    } else {
      testHostApp = Optional.absent();
      testHostAppBinarySourcePath = Optional.absent();
      blacklist = ImmutableSet.of();
    }

    BuildTarget libraryTarget = params.getBuildTarget()
        .withAppendedFlavors(extraFlavorsBuilder.build())
        .withAppendedFlavor(debugFormat.getFlavor());
    BuildRule library = createTestLibraryRule(
        params,
        resolver,
        args,
        testHostAppBinarySourcePath,
        blacklist,
        libraryTarget);
    if (!createBundle) {
      return library;
    }

    AppleCxxPlatform appleCxxPlatform;
    try {
      appleCxxPlatform = appleCxxPlatformFlavorDomain.getValue(cxxPlatform.getFlavor());
    } catch (FlavorDomainException e) {
      throw new HumanReadableException(
          e,
          "%s: Apple test requires an Apple platform, found '%s'",
          params.getBuildTarget(),
          cxxPlatform.getFlavor().getName());
    }

    ImmutableSet.Builder<SourcePath> resourceDirsBuilder = ImmutableSet.builder();
    ImmutableSet.Builder<SourcePath> dirsContainingResourceDirsBuilder = ImmutableSet.builder();
    ImmutableSet.Builder<SourcePath> resourceFilesBuilder = ImmutableSet.builder();
    ImmutableSet.Builder<SourcePath> resourceVariantFilesBuilder = ImmutableSet.builder();

    AppleResources.collectResourceDirsAndFiles(
        targetGraph,
        Preconditions.checkNotNull(targetGraph.get(params.getBuildTarget())),
        resourceDirsBuilder,
        dirsContainingResourceDirsBuilder,
        resourceFilesBuilder,
        resourceVariantFilesBuilder);

    ImmutableSet<SourcePath> resourceDirs = resourceDirsBuilder.build();
    ImmutableSet<SourcePath> dirsContainingResourceDirs = dirsContainingResourceDirsBuilder.build();
    ImmutableSet<SourcePath> resourceFiles = resourceFilesBuilder.build();
    ImmutableSet<SourcePath> resourceVariantFiles = resourceVariantFilesBuilder.build();
    SourcePathResolver sourcePathResolver = new SourcePathResolver(resolver);

    Optional<AppleAssetCatalog> assetCatalog =
        AppleDescriptions.createBuildRuleForTransitiveAssetCatalogDependencies(
            targetGraph,
            params,
            sourcePathResolver,
            appleCxxPlatform.getAppleSdk().getApplePlatform(),
            appleCxxPlatform.getActool());

    String platformName = appleCxxPlatform.getAppleSdk().getApplePlatform().getName();

    BuildRule bundle = AppleDescriptions.createAppleBundle(
        cxxPlatformFlavorDomain,
        defaultCxxPlatform,
        appleCxxPlatformFlavorDomain,
        targetGraph,
        params.copyWithChanges(
            params.getBuildTarget().withAppendedFlavors(
                BUNDLE_FLAVOR,
                debugFormat.getFlavor(),
                AppleDescriptions.NO_INCLUDE_FRAMEWORKS_FLAVOR),
            // We have to add back the original deps here, since they're likely
            // stripped from the library link above (it doesn't actually depend on them).
            Suppliers.ofInstance(
                ImmutableSortedSet.<BuildRule>naturalOrder()
                    .add(library)
                    .addAll(assetCatalog.asSet())
                    .addAll(params.getDeclaredDeps().get())
                    .addAll(
                        BuildRules.toBuildRulesFor(
                            params.getBuildTarget(),
                            resolver,
                            SourcePaths.filterBuildTargetSourcePaths(
                                Iterables.concat(
                                    resourceFiles,
                                    resourceDirs,
                                    dirsContainingResourceDirs,
                                    resourceVariantFiles))))
                    .build()),
            params.getExtraDeps()),
        resolver,
        codeSignIdentityStore,
        provisioningProfileStore,
        library.getBuildTarget(),
        args.getExtension(),
        Optional.<String>absent(),
        args.infoPlist,
        args.infoPlistSubstitutions,
        args.deps.get(),
        args.getTests(),
        debugFormat);

    // If xctool is specified as a build target in the buck config, it's wrapping ZIP file which
    // we need to unpack to get at the actual binary.  Otherwise, if it's specified as a path, we
    // can use that directly.
    Optional<SourcePath> xctool;
    if (appleConfig.getXctoolZipTarget().isPresent()) {
      final BuildRule xctoolZipBuildRule = resolver.getRule(appleConfig.getXctoolZipTarget().get());
      BuildTarget unzipXctoolTarget =
          BuildTarget.builder(xctoolZipBuildRule.getBuildTarget())
              .addFlavors(UNZIP_XCTOOL_FLAVOR)
              .build();
      final Path outputDirectory = BuildTargets.getGenPath(unzipXctoolTarget, "%s/unzipped");
      if (!resolver.getRuleOptional(unzipXctoolTarget).isPresent()) {
        BuildRuleParams unzipXctoolParams =
            params.copyWithChanges(
                unzipXctoolTarget,
                Suppliers.ofInstance(ImmutableSortedSet.of(xctoolZipBuildRule)),
                Suppliers.ofInstance(ImmutableSortedSet.<BuildRule>of()));
        resolver.addToIndex(
            new AbstractBuildRule(unzipXctoolParams, sourcePathResolver) {
              @Override
              public ImmutableList<Step> getBuildSteps(
                  BuildContext context,
                  BuildableContext buildableContext) {
                buildableContext.recordArtifact(outputDirectory);
                return ImmutableList.of(
                    new MakeCleanDirectoryStep(getProjectFilesystem(), outputDirectory),
                    new UnzipStep(
                        getProjectFilesystem(),
                        Preconditions.checkNotNull(xctoolZipBuildRule.getPathToOutput()),
                        outputDirectory));
              }
              @Override
              public Path getPathToOutput() {
                return outputDirectory;
              }
            });
      }
      xctool =
          Optional.<SourcePath>of(
              new BuildTargetSourcePath(unzipXctoolTarget, outputDirectory.resolve("bin/xctool")));
    } else if (appleConfig.getXctoolPath().isPresent()) {
      xctool =
          Optional.<SourcePath>of(
              new PathSourcePath(params.getProjectFilesystem(), appleConfig.getXctoolPath().get()));
    } else {
      xctool = Optional.absent();
    }

    return new AppleTest(
        xctool,
        appleConfig.getXctoolStutterTimeoutMs(),
        appleCxxPlatform.getXctest(),
        appleCxxPlatform.getOtest(),
        appleConfig.getXctestPlatformNames().contains(platformName),
        platformName,
        appleConfig.getXctoolDefaultDestinationSpecifier(),
        args.destinationSpecifier,
        params.copyWithDeps(
            Suppliers.ofInstance(ImmutableSortedSet.<BuildRule>of(bundle)),
            Suppliers.ofInstance(ImmutableSortedSet.<BuildRule>of())),
        sourcePathResolver,
        bundle,
        testHostApp,
        extension,
        args.contacts.get(),
        args.labels.get(),
        args.getRunTestSeparately(),
        xcodeDeveloperDirectorySupplier,
        appleConfig.getTestLogDirectoryEnvironmentVariable(),
        appleConfig.getTestLogLevelEnvironmentVariable(),
        appleConfig.getTestLogLevel());
  }

  private <A extends Arg> BuildRule createTestLibraryRule(
      BuildRuleParams params,
      BuildRuleResolver resolver,
      A args,
      Optional<SourcePath> testHostAppBinarySourcePath,
      ImmutableSet<BuildTarget> blacklist,
      BuildTarget libraryTarget) throws NoSuchBuildTargetException {
    BuildTarget existingLibraryTarget = libraryTarget
        .withAppendedFlavors(AppleDebuggableBinary.RULE_FLAVOR, CxxStrip.RULE_FLAVOR)
        .withAppendedFlavor(StripStyle.NON_GLOBAL_SYMBOLS.getFlavor());
    Optional<BuildRule> existingLibrary = resolver.getRuleOptional(existingLibraryTarget);
    BuildRule library;
    if (existingLibrary.isPresent()) {
      library = existingLibrary.get();
    } else {
      library = appleLibraryDescription.createLibraryBuildRule(
          params.copyWithBuildTarget(libraryTarget),
          resolver,
          args,
          // For now, instead of building all deps as dylibs and fixing up their install_names,
          // we'll just link them statically.
          Optional.of(Linker.LinkableDepType.STATIC),
          testHostAppBinarySourcePath,
          blacklist);
      resolver.addToIndex(library);
    }
    return library;
  }

  @Override
  public Iterable<BuildTarget> findDepsForTargetFromConstructorArgs(
      BuildTarget buildTarget,
      Function<Optional<String>, Path> cellRoots,
      AppleTestDescription.Arg constructorArg) {
    // TODO(bhamiltoncx, Coneko): This should technically only be a runtime dependency;
    // doing this adds it to the extra deps in BuildRuleParams passed to
    // the bundle and test rule.
    ImmutableSet.Builder<BuildTarget> deps = ImmutableSet.builder();
    Optional<BuildTarget> xctoolZipTarget = appleConfig.getXctoolZipTarget();
    if (xctoolZipTarget.isPresent()) {
      deps.add(xctoolZipTarget.get());
    }
    return deps.build();
  }

  @SuppressFieldNotInitialized
  public static class Arg extends AppleNativeTargetDescriptionArg implements HasAppleBundleFields {
    public Optional<ImmutableSortedSet<String>> contacts;
    public Optional<ImmutableSortedSet<Label>> labels;
    public Optional<Boolean> canGroup;
    public Optional<Boolean> runTestSeparately;
    public Optional<BuildTarget> testHostApp;

    // Bundle related fields.
    public Either<AppleBundleExtension, String> extension;
    public SourcePath infoPlist;
    public Optional<ImmutableMap<String, String>> infoPlistSubstitutions;
    public Optional<String> xcodeProductType;
    public Optional<String> productName;

    public Optional<ImmutableMap<String, String>> destinationSpecifier;

    @Override
    public Either<AppleBundleExtension, String> getExtension() {
      return extension;
    }

    @Override
    public SourcePath getInfoPlist() {
      return infoPlist;
    }

    @Override
    public Optional<String> getXcodeProductType() {
      return xcodeProductType;
    }

    public boolean canGroup() {
      return canGroup.or(false);
    }

    public boolean getRunTestSeparately() {
      return runTestSeparately.or(false);
    }
  }
}


text:
<?php

namespace OC\Hooks;

abstract class BasicEmitter implements Emitter {

	/**
	 * @var (callable[])[] $listeners
	 */
	protected $listeners = array();

	/**
	 * @param string $scope
	 * @param string $method
	 * @param callable $callback
	 */
	public function listen($scope, $method, $callback) {
		$eventName = $scope . '::' . $method;
		if (!isset($this->listeners[$eventName])) {
			$this->listeners[$eventName] = array();
		}
		if (array_search($callback, $this->listeners[$eventName]) === false) {
			$this->listeners[$eventName][] = $callback;
		}
	}

	/**
	 * @param string $scope optional
	 * @param string $method optional
	 * @param callable $callback optional
	 */
	public function removeListener($scope = null, $method = null, $callback = null) {
		$names = array();
		$allNames = array_keys($this->listeners);
		if ($scope and $method) {
			$name = $scope . '::' . $method;
			if (isset($this->listeners[$name])) {
				$names[] = $name;
			}
		} elseif ($scope) {
			foreach ($allNames as $name) {
				$parts = explode('::', $name, 2);
				if ($parts[0] == $scope) {
					$names[] = $name;
				}
			}
		} elseif ($method) {
			foreach ($allNames as $name) {
				$parts = explode('::', $name, 2);
				if ($parts[1] == $method) {
					$names[] = $name;
				}
			}
		} else {
			$names = $allNames;
		}

		foreach ($names as $name) {
			if ($callback) {
				$index = array_search($callback, $this->listeners[$name]);
				if ($index !== false) {
					unset($this->listeners[$name][$index]);
				}
			} else {
				$this->listeners[$name] = array();
			}
		}
	}

	/**
	 * @param string $scope
	 * @param string $method
	 * @param array $arguments optional
	 */
	protected function emit($scope, $method, $arguments = array()) {
		$eventName = $scope . '::' . $method;
		if (isset($this->listeners[$eventName])) {
			foreach ($this->listeners[$eventName] as $callback) {
				call_user_func_array($callback, $arguments);
			}
		}
	}
}


text:
require 'rest-client'
require 'sentimental'
require 'nokogiri'
require 'open-uri'
require 'launchy'
require_relative '../lib/hashdata'
require_relative '../lib/rantbot'


text:
<!doctype html>

  <meta charset="utf-8">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  <title>Akshat Mishra | PMO Mobile App Contest</title>
  <meta name="description" content="Participating in the nationwide contest to create the official Prime Minister's Office Application.">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <meta property="og:title" content="PMO Mobile App Contest">
  <meta property="og:type" content="website">
  <meta property="og:url" content="http://localhost:4000/posts/pmo-mobile-application">
  <meta property="og:description" content="Participating in the nationwide contest to create the official Prime Minister's Office Application.">
  <meta property="og:site_name" content="Akshat Mishra">
  <meta property="og:image" content="http://localhost:4000/assets/og-image.jpg">

  <meta name="twitter:card" content="summary">
  <meta name="twitter:url" content="http://localhost:4000/posts/pmo-mobile-application">
  <meta name="twitter:title" content="PMO Mobile App Contest">
  <meta name="twitter:description" content="Participating in the nationwide contest to create the official Prime Minister's Office Application.">
  <meta name="twitter:image" content="http://localhost:4000/assets/og-image.jpg">
  <link rel="shortcut icon" href="favicon.ico" />

  <link rel="apple-touch-icon" href="/assets/apple-touch-icon.png">

  <link type="text/css" rel="stylesheet" href="/assets/light.css">

  Akshat Mishra

          Me

          LinkedIn

          Mail

PMO Mobile App Contest

Participating in the nationwide contest to create the official Prime Minister's Office Application.

                July, 2015

The Prime Minister's Office in collaboration with Google organized a contest to create the official Android application for Prime Minister's Office. The competition was divided into three phases, with the first phase being the submission of ideas for the app. I participated in the second phase of the contest along with my colleagues in which we had to submit wireframes based on the app blueprint.

Find the wireframes here.

Phase 2

After weeks of designing and brainstorming, we submitted wireframes which documented interactions for 46 screens. The wireframes were designed keeping the strict guidelines given in the app specification document. We were elated when we found out that we had made it to the top ten submissions across the nation.

The next step was to make a presentation in front of a jury consisting of industry experts and top government officials. Based on innovation, uniqueness, technical ability and user friendliness of the designs; we made it to the top five teams.

Phase 3

For the final phase of the contest, we were mentored by Google designers and engineers. The complete app had to be developed in a span of eight weeks which was very challenging considering it was to be used in a country with over a billion people. Thus, scalability and accessibility were the two biggest concerns which were addressed in a separate session at the Hyderabad Office of Google.

Images from the app

Under the guidance of our new mentors, we used Volley to batch and optimize network requests and Glide to implement caching to tackle low internet speeds and frequent disconnections. The application developed also used Soundcloud APIs to implement the Prime Minister's Address to the Nation, Twitter APIs to create a Social Feed and the PMO APIs for fetching latest images and news.

Experience

This experience made me realize the importance of implementing accessibility features because if not present, a large section of the potential users is cut off. Working with engineers from Google and getting the opportunity to develop an app that is being used by the nation was an unforgettable experience.

    Back to top -
    About Me

    Powered by Jekyll and theme by Nielsen Ramon.


text:
package org.apache.hadoop.yarn.server.resourcemanager.webapp.dao;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;

import org.apache.hadoop.yarn.api.records.Resource;
import org.apache.hadoop.yarn.util.resource.Resources;

/**
 * This class represents queue capacities for a given partition
 */
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class PartitionQueueCapacitiesInfo {
  private String partitionName;

  private float capacity;
  private float usedCapacity;
  private float maxCapacity = 100;
  private float absoluteCapacity;
  private float absoluteUsedCapacity;
  private float absoluteMaxCapacity  = 100;
  private float maxAMLimitPercentage;
  private ResourceInfo configuredMinResource;
  private ResourceInfo configuredMaxResource;
  private ResourceInfo effectiveMinResource;
  private ResourceInfo effectiveMaxResource;

  public PartitionQueueCapacitiesInfo() {
  }

  public PartitionQueueCapacitiesInfo(String partitionName, float capacity,
      float usedCapacity, float maxCapacity, float absCapacity,
      float absUsedCapacity, float absMaxCapacity, float maxAMLimitPercentage,
      Resource confMinRes, Resource confMaxRes, Resource effMinRes,
      Resource effMaxRes) {
    super();
    this.partitionName = partitionName;
    this.capacity = capacity;
    this.usedCapacity = usedCapacity;
    this.maxCapacity = maxCapacity;
    this.absoluteCapacity = absCapacity;
    this.absoluteUsedCapacity = absUsedCapacity;
    this.absoluteMaxCapacity = absMaxCapacity;
    this.maxAMLimitPercentage = maxAMLimitPercentage;
    this.configuredMinResource = new ResourceInfo(confMinRes);
    this.configuredMaxResource = new ResourceInfo(confMaxRes);
    this.effectiveMinResource = new ResourceInfo(effMinRes);
    this.effectiveMaxResource = new ResourceInfo(effMaxRes);
  }

  public float getCapacity() {
    return capacity;
  }

  public void setCapacity(float capacity) {
    this.capacity = capacity;
  }

  public float getUsedCapacity() {
    return usedCapacity;
  }

  public void setUsedCapacity(float usedCapacity) {
    this.usedCapacity = usedCapacity;
  }

  public float getMaxCapacity() {
    return maxCapacity;
  }

  public void setMaxCapacity(float maxCapacity) {
    this.maxCapacity = maxCapacity;
  }

  public String getPartitionName() {
    return partitionName;
  }

  public void setPartitionName(String partitionName) {
    this.partitionName = partitionName;
  }

  public float getAbsoluteCapacity() {
    return absoluteCapacity;
  }

  public void setAbsoluteCapacity(float absoluteCapacity) {
    this.absoluteCapacity = absoluteCapacity;
  }

  public float getAbsoluteUsedCapacity() {
    return absoluteUsedCapacity;
  }

  public void setAbsoluteUsedCapacity(float absoluteUsedCapacity) {
    this.absoluteUsedCapacity = absoluteUsedCapacity;
  }

  public float getAbsoluteMaxCapacity() {
    return absoluteMaxCapacity;
  }

  public void setAbsoluteMaxCapacity(float absoluteMaxCapacity) {
    this.absoluteMaxCapacity = absoluteMaxCapacity;
  }

  public float getMaxAMLimitPercentage() {
    return maxAMLimitPercentage;
  }

  public void setMaxAMLimitPercentage(float maxAMLimitPercentage) {
    this.maxAMLimitPercentage = maxAMLimitPercentage;
  }

  public ResourceInfo getConfiguredMinResource() {
    return configuredMinResource;
  }

  public ResourceInfo getConfiguredMaxResource() {
    if (configuredMaxResource.getResource().equals(Resources.none())) {
      return null;
    }
    return configuredMaxResource;
  }

  public ResourceInfo getEffectiveMinResource() {
    return effectiveMinResource;
  }

  public ResourceInfo getEffectiveMaxResource() {
    return effectiveMaxResource;
  }
}


text:
<?php
class egreso_nomina extends table{
	public function info(){
		$this->table_name = 'egresos_nomina';
		$this->objects['cct'] = 'escuela';
		$this->objects['rfc'] = 'maestro';
	}
}
class maestro extends table{
	public function info(){
		$this->table_name = 'maestros';
		$this->key = 'rfc';

	}

}
?>


text:
extern C_Handler *gMainHandler;
extern void CampaignJoinKeepAlive(void);

// Maximum size data block we can send per message
// Since this needs an instance of the message to really be sized correctly,
// I wait and calculate it the first chance I get.
ulong gObjBlockSize = 0;

FalconSendObjData::FalconSendObjData(VU_ID entityId, VuTargetEntity *target, VU_BOOL loopback) : FalconEvent(SendObjData, FalconEvent::CampaignThread, entityId, target, loopback)
{
    dataBlock.objData = NULL;
    dataBlock.size = 0;
}

FalconSendObjData::FalconSendObjData(VU_MSG_TYPE type, VU_ID senderid, VU_ID target) : FalconEvent(SendObjData, FalconEvent::CampaignThread, senderid, target)
{
    dataBlock.objData = NULL;
    dataBlock.size = 0;
}

FalconSendObjData::~FalconSendObjData()
{
    delete[] dataBlock.objData;
}

int FalconSendObjData::Size() const
{
    ShiAssert(dataBlock.size >= 0);
    return sizeof(dataBlock) + dataBlock.size + FalconEvent::Size();
}

int FalconSendObjData::Decode(VU_BYTE **buf, long *rem)
{
    long init = *rem;

    memcpychk(&dataBlock, buf, sizeof(dataBlock), rem);
    ShiAssert(dataBlock.size >= 0);
    dataBlock.objData = new VU_BYTE[dataBlock.size];
    memcpychk(dataBlock.objData, buf, dataBlock.size, rem);
    FalconEvent::Decode(buf, rem);

    //ShiAssert ( size == Size() );

    CampaignJoinKeepAlive();

    return init - *rem;
    //size;
}

int FalconSendObjData::Encode(VU_BYTE **buf)
{
    int size = 0;

    ShiAssert(dataBlock.size >= 0);
    memcpy(*buf, &dataBlock, sizeof(dataBlock));
    *buf += sizeof(dataBlock);
    size += sizeof(dataBlock);
    memcpy(*buf, dataBlock.objData, dataBlock.size);
    *buf += dataBlock.size;
    size += dataBlock.size;
    size += FalconEvent::Encode(buf);

    ShiAssert(size == Size());

    return size;
}

int FalconSendObjData::Process(uchar autodisp)
{
    uchar *bufptr;
    FalconSessionEntity *session = (FalconSessionEntity*) vuDatabase->Find(dataBlock.owner);

    if (autodisp or not TheCampaign.IsPreLoaded() or not session)
        return -1;

    if (TheCampaign.Flags bitand CAMP_NEED_OBJ_DELTAS)
    {
        CampaignJoinKeepAlive();

        if (dataBlock.set not_eq session->objDataReceiveSet)
        {
            // New data - toss the old stuff
            delete session->objDataReceiveBuffer;
            session->objDataReceiveBuffer = NULL;
            session->objDataReceiveSet = dataBlock.set;
            memset(session->objDataReceived, 0, FS_MAXBLK / 8);
        }

        if ( not session->objDataReceiveBuffer)
            session->objDataReceiveBuffer = new uchar[dataBlock.totalSize];

        // Find the block size, if we havn't already
        if ( not gObjBlockSize)
            gObjBlockSize = F4VuMaxTCPMessageSize - (Size() - dataBlock.size);

        bufptr = session->objDataReceiveBuffer + dataBlock.block * gObjBlockSize;
        memcpy(bufptr, dataBlock.objData, dataBlock.size);

#ifdef DEBUG_STARTUP
        MonoPrint("Got Obj Block #%d\n", dataBlock.block);
#endif

        // Mark this block as being received.
        session->objDataReceived[dataBlock.block / 8] or_eq (1 << (dataBlock.block % 8));

        // Check if we've gotten all our blocks
        for (int i = 0; i < dataBlock.totalBlocks; i++)
        {
            if ( not (session->objDataReceived[i / 8] bitand (1 << (i % 8))))
                return 0;
        }

        // If we get here, it's because all blocks are read
        TheCampaign.Flags and_eq compl CAMP_NEED_OBJ_DELTAS;
        bufptr = session->objDataReceiveBuffer;

        CampEnterCriticalSection();
        //sfr: added for checks
        long bufSize = gObjBlockSize;
#ifdef MP_DEBUG
        DecodeObjectiveDeltas((VU_BYTE**) &bufptr, &bufSize, session);
#else

        try
        {
            DecodeObjectiveDeltas((VU_BYTE**) &bufptr, &bufSize, session);
        }
        catch (...)
        {
            char err[200];
            sprintf(err, "%s %d: error decoding objective deltas", __FILE__, __LINE__);
            throw InvalidBufferException(err);
        }

#endif
        CampLeaveCriticalSection();

        session->objDataReceiveBuffer = NULL;
        session->objDataReceiveSet = 0;

        // Let the UI know we've received some data
        if (gMainHandler)
            PostMessage(gMainHandler->GetAppWnd(), FM_GOT_CAMPAIGN_DATA, CAMP_NEED_OBJ_DELTAS, 0);
    }
    else
    {
        MonoPrint("**** Re-received OBJ DELTAS\n");
    }

    return 0;
}

// =========================================
// Global functions
// =========================================

void SendObjectiveDeltas(FalconSessionEntity *session, VuTargetEntity *target, uchar *blocksNeeded)
{
    int blocks, needed = 0, curBlock = 0, blocksize;
    ulong sizeleft;
    uchar *buffer, *bufptr;
    FalconSendObjData *msg;

    if ( not blocksNeeded)
    {
        int set = rand();

        if ( not set)
            set++;

        // Encode the objective data
        session->objDataSendSize = EncodeObjectiveDeltas((VU_BYTE**)&buffer, NULL);
        session->objDataSendBuffer = buffer;
        session->objDataSendSet = (short)set;
    }

    // Find the block size, if we havn't already
    if ( not gObjBlockSize)
    {
        // This is a temporary message, purely for sizing purposes
        FalconSendObjData msg(session->Id(), target);
        gObjBlockSize = F4VuMaxTCPMessageSize - msg.Size();
    }

    sizeleft = session->objDataSendSize;
    blocks = (session->objDataSendSize + gObjBlockSize - 1) / gObjBlockSize;

#ifdef DEBUG_STARTUP

    if ( not blocksNeeded)
        MonoPrint("Sending objective data (%d of %d blocks): ", needed, blocks);
    else
        MonoPrint("Resending objective data (%d of %d blocks): ", needed, blocks);

#endif

    buffer = bufptr = session->objDataSendBuffer;

    while (sizeleft)
    {
        if (sizeleft < gObjBlockSize)
        {
            // The last block to send
            blocksize = sizeleft;
            sizeleft = 0;
        }
        else
        {
            // Any old block
            blocksize = gObjBlockSize;
            sizeleft -= gObjBlockSize;
        }

        if ( not blocksNeeded or not (blocksNeeded[curBlock / 8] bitand (1 << (curBlock % 8))))
        {
            msg = new FalconSendObjData(session->Id(), target);
            msg->dataBlock.size = (short)blocksize;
            msg->dataBlock.objData = new uchar[blocksize];
            memcpy(msg->dataBlock.objData, bufptr, blocksize);
            bufptr += blocksize;
            msg->dataBlock.owner = FalconLocalSessionId;
            msg->dataBlock.set = session->objDataSendSet;
            msg->dataBlock.totalSize = session->objDataSendSize;
            msg->dataBlock.block = (uchar)curBlock;
            msg->dataBlock.totalBlocks = (uchar)blocks;

#ifdef DEBUG_STARTUP
            MonoPrint("%d:%d ", msg->dataBlock.block, msg->dataBlock.size);
#endif

            FalconSendMessage(msg, TRUE);
            msg = NULL;
        }

        curBlock++;
    }

#ifdef DEBUG_STARTUP
    MonoPrint("\n");
#endif
}


text:
<?php
$user = $db_panel->getLoginByID($_SESSION['user_id']);

?>
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>ExileAdmin | <?php if(empty($title)) {echo 'Dashboard'; } else { echo $title;}?></title>

    <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">

    <link rel="stylesheet" href="bootstrap/css/bootstrap.min.css">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.5.0/css/font-awesome.min.css">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/ionicons/2.0.1/css/ionicons.min.css">

    <link rel="stylesheet" href="dist/css/AdminLTE.min.css">

    <link rel="stylesheet" href="plugins/datatables/dataTables.bootstrap.css">

    <link rel="stylesheet" href="dist/css/skins/skin-blue.min.css">

    <link rel="stylesheet" href="dist/css/dashboard.css">

            EAD

            ExileAdmin

                Toggle navigation

                            <img src="<?php echo $user['picture'] ?>" class="user-image img-responsive" alt="User Image">

                            <?php echo $user['username'] ?>

                                <img src="<?php echo $user['picture'] ?>" class="img-circle" alt="User Image">

                                    <?php echo $user['username'] ?>
                                    Member since Nov. 2012

                                    Profile

                                    Sign out

                    <img src="<?php echo $user['picture'] ?>" class="img-circle img-responsive" alt="User Image">

<?php echo $user['username'] ?>

                     Online

            <form action="search" method="get" class="sidebar-form">

                    <input type="text" name="q" class="form-control" placeholder="Name / SteamID">

                <button type="submit" id="search-btn" class="btn btn-flat">
                </button>

            </form>

<?php if (isset($_SESSION['error'])) {
                        echo $_SESSION['error'];
                        unset($_SESSION['error']);
                    } ?>

Main Navigation

 Dashboard

 Territories<?php echo number_format(implode(array_column($db_exile->sumTerritories(), 'sum'))); ?>

 Vehicles<?php echo number_format(implode(array_column($db_exile->sumVehicles(), 'sum'))); ?>

 Banlist

 Logs


text:
#include <QProcess>
#include <QTimer>
#include <QGraphicsPixmapItem>
#include <QTemporaryFile>
#include <QCloseEvent>
#include <QInputDialog>
#include <QScreen>
#include <QMediaPlayer>

#include <../netif.h>
#include <../utils.h>

#include <sys/types.h>
#include <pwd.h>
#include <unistd.h>

#include "backend.h"
#include "ui_firstboot.h"
#include "firstboot.h"
#include "helpText.h"

#define DEBUG 0 //ONLY USED FOR INTERNAL BUILD/TESTING
// DO NOT COMMIT CHANGES WITH DEBUG==1 !!!

Installer::Installer(QWidget *parent) : QMainWindow(parent, Qt::Window | Qt::FramelessWindowHint | Qt::WindowStaysOnBottomHint)
{
    setupUi(this);
    //Setup the window
    if(!DEBUG){ this->setGeometry( QApplication::primaryScreen()->geometry() ); }//full screen
    else{ this->setWindowFlags(Qt::Window); } //don't keep on bottom/frameless for testing

    translator = new QTranslator();

    connect(backButton, SIGNAL(clicked()), this, SLOT(slotBack()));
    connect(nextButton, SIGNAL(clicked()), this, SLOT(slotNext()));

    connect(helpButton, SIGNAL(clicked()), this, SLOT(slotHelp()));
    connect(pushTouchKeyboard, SIGNAL(clicked()), this, SLOT(slotPushVirtKeyboard()));
    connect(pushChangeKeyLayout, SIGNAL(clicked()), this, SLOT(slotPushKeyLayout()));

    connect(lineHostname,SIGNAL(textChanged(const QString)),this,SLOT(slotCheckHost()));
    connect(lineDomainName, SIGNAL(textChanged(const QString &)), this, SLOT(slotCheckDomainName()) );

    connect(lineRootPW, SIGNAL(textChanged ( const QString &)), this, SLOT(slotCheckRootPW()));
    connect(lineRootPW2, SIGNAL(textChanged ( const QString &)), this, SLOT(slotCheckRootPW()));

    connect(lineName,SIGNAL(textChanged(const QString)),this,SLOT(slotCheckUser()));
    connect(lineName,SIGNAL(editingFinished()),this,SLOT(slotSuggestUsername()));
    connect(lineUsername,SIGNAL(textChanged(const QString)),this,SLOT(slotCheckUser()));
    connect(linePW,SIGNAL(textChanged(const QString)),this,SLOT(slotCheckUser()));
    connect(linePW2,SIGNAL(textChanged(const QString)),this,SLOT(slotCheckUser()));
    connect(line_PCpass, SIGNAL(textChanged(const QString)), this, SLOT(slotCheckUser())) ;
    connect(line_PCpass_repeat, SIGNAL(textChanged(const QString)), this, SLOT(slotCheckUser())) ;
    connect(group_usePC, SIGNAL(toggled(bool)), this, SLOT(slotCheckUser()) );
    connect(push_PC_device, SIGNAL(clicked()), this, SLOT(slotGetPCDevice()) );

    connect(tool_testAudio, SIGNAL(clicked()), this, SLOT(slotPlayAudioTest()) );
    connect(slider_volume, SIGNAL(valueChanged(int)), this, SLOT(slotAudioVolumeChanged()) );
    connect(combo_audiodevice, SIGNAL(currentIndexChanged(int)), this, SLOT(slotSetAudioDev()) );
    backButton->setText(tr("&Back"));
    nextButton->setText(tr("&Next"));

    // Load the keyboard info
    keyModels = Scripts::Backend::keyModels();
    keyLayouts = Scripts::Backend::keyLayouts();

    // If we have a saved keyboard layout from installation, use it first
    QString kD;
    if ( QFile::exists("/var/.wizardKeyboard") ) {
      QFile kFile("/var/.wizardKeyboard");
      if ( kFile.open(QIODevice::ReadOnly | QIODevice::Text) ) {
         kD = kFile.readLine().simplified();
         kFile.close();

         kbMod = kD.section(" ", 0, 0);
         kbLay = kD.section(" ", 1, 1);
         kbVar = kD.section(" ", 2, 2);
	 Scripts::Backend::changeKbMap(kbMod, kbLay, kbVar);
      }
    }

    // Load the timezones
    comboBoxTimezone->clear();
    QString curZone = Scripts::Backend::guessTimezone();
    comboBoxTimezone->addItems(Scripts::Backend::timezones());
    if ( ! curZone.isEmpty() ) {
      int index = comboBoxTimezone->findText(curZone, Qt::MatchStartsWith);
      if (index != -1) {
         comboBoxTimezone->setCurrentIndex(index);
      } else {
        // Set America/New_York to default
        index = comboBoxTimezone->findText("America/New_York", Qt::MatchStartsWith);
        if (index != -1)
           comboBoxTimezone->setCurrentIndex(index);
      }
    } else {
      // Set America/New_York to default
      int index = comboBoxTimezone->findText("America/New_York", Qt::MatchStartsWith);
      if (index != -1)
         comboBoxTimezone->setCurrentIndex(index);
    }

    // Load the hostname
     lineHostname->setText(Utils::getConfFileValue("/etc/rc.conf", "hostname=", 1).section(".",0,0));

    // Load the domain name
    lineDomainName->setText(Utils::getConfFileValue("/etc/rc.conf", "hostname=",1).section(".",1,100));

    //Load the available Services into the UI
    LoadServices();

    // Start on the first screen
    installStackWidget->setCurrentIndex(0);
    backButton->setVisible(false);

    // Update the status bar
    // This makes the status text more "visible" instead of using the blue background
    //statusBar()->setStyleSheet("background: white");

    //Load the audio settings values
    combo_audiodevice->clear();
    QStringList devs = Utils::runShellCommand("cat /dev/sndstat");
    //qDebug() << "Sound Devices:" <<devs;
    int def = -1;
    for(int i=0; i<devs.length(); i++){
      if(!devs[i].startsWith("pcm")){ devs.removeAt(i); i--; continue; }
      combo_audiodevice->addItem(devs[i], devs[i].section(":",0,0)); //<full text>, <pcmID>
      if(devs[i].contains(" default")){ def = i; }
    }
    if(def<0 && !devs.isEmpty()){ def=0; }
    if(def<0){
      //No audio devices found - disable this functionality
      Page_Audio->setEnabled(false); //just do the whole page - nothing will work
    }else{
      combo_audiodevice->setCurrentIndex(def); //make sure this item is initially selected
      slotSetAudioDev(); //make sure to run the setup command initially
    }
    slider_volume->setValue(100);
    slotAudioVolumeChanged(); //update the volume % label

}

Installer::~Installer()
{
    //delete ui;
}

void Installer::slotSuggestUsername()
{
  if ( ! lineUsername->text().isEmpty() || lineName->text().isEmpty() )
    return;
  QString name;
  if ( lineName->text().indexOf(" ") != -1 ) {
    name = lineName->text().section(' ', 0, 0).toLower();
    name.truncate(1);
  }
  name = name + lineName->text().section(' ', -1, -1).toLower();
  lineUsername->setText(name);
  slotCheckUser();
}

void Installer::slotPushKeyLayout()
{
  wKey = new widgetKeyboard();
  wKey->programInit(keyModels, keyLayouts);
  wKey->setWindowModality(Qt::ApplicationModal);
  connect(wKey, SIGNAL(changedLayout(QString, QString, QString)), this, SLOT(slotKeyLayoutUpdated(QString, QString, QString)));
  wKey->show();
  wKey->raise();
}

// Start xvkbd
void Installer::slotPushVirtKeyboard()
{
   system("killall -9 xvkbd; xvkbd -compact &");
}

void Installer::initInstall()
{
    // load languages
    QString langCode;
    QString curLang;
    curLang = "en_US";
    bool foundLang = false;
    comboLanguage->clear();
    languages = Scripts::Backend::languages();
    if ( QFile::exists("/var/.wizardlang") ) {
      QFile lFile("/var/.wizardlang");
      if ( lFile.open(QIODevice::ReadOnly | QIODevice::Text) ) {
         curLang = lFile.readLine().simplified();
         lFile.close();
      }
    }

    qDebug() << curLang;

    // Now set languages
    for (int i=0; i < languages.count(); ++i) {
        QString languageStr = languages.at(i);
        QString language = languageStr.split("-").at(0);
        comboLanguage->addItem(language.trimmed());

        // Grab the language code
        langCode = languageStr;
        langCode.truncate(langCode.lastIndexOf(")"));
        langCode.remove(0, langCode.lastIndexOf("(") + 1);
        if ( curLang == langCode ) {
          comboLanguage->setCurrentIndex(i);
          foundLang = true;
        }
    }

    // If we found a language to default to
    if ( foundLang )
      slotChangeLanguage();

    connect(comboLanguage, SIGNAL(currentIndexChanged(QString)), this, SLOT(slotChangeLanguage()));
}

void Installer::proceed(bool forward)
{
    int count = installStackWidget->count() - 1;
    int index = installStackWidget->currentIndex();

    index = forward ?
            (index == count ? count : index + 1) :
            (index == 0 ? 0 : index - 1);

    installStackWidget->setCurrentIndex(index);
}

// Check root pw
void Installer::slotCheckRootPW()
{
  nextButton->setEnabled(false);

  if ( lineRootPW->text().isEmpty() )
     return;
  if ( lineRootPW2->text().isEmpty() )
     return;
  if ( lineRootPW->text() != lineRootPW2->text() )
     return;
  // if we get this far, all the fields are filled in
  nextButton->setEnabled(true);
}

void Installer::slotCheckHost()
{
  QRegExp hostnameRegExp("^(([a-zA-Z0-9][a-zA-Z0-9-].*[a-zA-Z0-9])|([a-zA-Z0-9]+))$");
  nextButton->setEnabled(false);
  if (lineHostname->text().isEmpty())
  {
     lineHostname->setToolTip(tr("Please enter a hostname"));
     return;
  }
  else if (hostnameRegExp.indexIn(lineHostname->text()) == -1)
  {
     lineHostname->setToolTip(tr("Hostname may only contain letters and numbers"));
     return;
  }
  nextButton->setEnabled(true);
}

void Installer::slotCheckDomainName()
{
  QRegExp hostnameRegExp("^(([a-zA-Z0-9][a-zA-Z0-9-].*[a-zA-Z0-9])|([a-zA-Z0-9]+))$");
  nextButton->setEnabled(false);
  if (lineHostname->text().isEmpty())
  {
     lineHostname->setToolTip(tr("Please enter a domain name"));
     return;
  }
  else if (hostnameRegExp.indexIn(lineHostname->text()) == -1)
  {
     lineHostname->setToolTip(tr("Domain name may only contain letters and numbers"));
     return;
  }
  nextButton->setEnabled(true);
}

void Installer::slotCheckUser()
{
  nextButton->setEnabled(false);
  if ( lineName->text().isEmpty() )
     return;
  if ( lineUsername->text().isEmpty() )
     return;
  if ( lineUsername->text().contains(" ") )
     return;
  else if( getpwnam(lineUsername->text().toUtf8()) != NULL )
     return;
  if ( linePW->text().isEmpty() )
     return;
  if ( linePW2->text().isEmpty() )
     return;
  if ( linePW->text() != linePW2->text() )
     return;
  if(group_usePC->isChecked()){
    if(line_PCpass->text().isEmpty() || line_PCpass_repeat->text().isEmpty())
       return;
    if(line_PCpass->text() != line_PCpass_repeat->text())
      return;
    if(push_PC_device->whatsThis().isEmpty())
      return;
    if( !QFile::exists("/dev/"+push_PC_device->whatsThis()) ){
      push_PC_device->setWhatsThis(""); //clear this for later
      push_PC_device->setText(tr("Select")); //reset back to initial text
      return;
    }
  }

  nextButton->setEnabled(true);
}

// Slot which is called when the Finish button is clicked
void Installer::slotFinished()
{
  qApp->quit();
}

void Installer::slotNext()
{
   QString tmp;
   backButton->setVisible(true);
   if(DEBUG){ qDebug() << "Starting Index:" << installStackWidget->currentIndex(); }
   // Check rootPW match
   if ( installStackWidget->currentIndex() == 1)
     slotCheckRootPW();
   // Check user info
   if ( installStackWidget->currentIndex() == 2)
     slotCheckUser();

   // Check if we have a wireless device
   if ( installStackWidget->currentIndex() == 4) {
     if ( system("ifconfig wlan0") == 0 ) {
       haveWifi = true;
       QTimer::singleShot(50,this,SLOT(slotScanNetwork()));
       connect(pushButtonRescan, SIGNAL(clicked()), this, SLOT(slotScanNetwork()));
       connect(listWidgetWifi, SIGNAL(itemPressed(QListWidgetItem *)), this, SLOT(slotAddNewWifi()));
     } else {
       haveWifi = false;
       installStackWidget->setCurrentIndex(5); //skip the wifi page
       if(DEBUG){ qDebug() << "Skipping Wifi - now index:" << installStackWidget->currentIndex(); }
     }
   }

   // If not doing a wireless connection
   /*if ( installStackWidget->currentIndex() == 4 && ! haveWifi) {

   }*/

    /*  // Save the settings
      saveSettings();
      nextButton->setText(tr("&Finish"));
      backButton->setVisible(false);
      nextButton->disconnect();
      connect(nextButton, SIGNAL(clicked()), this, SLOT(slotFinished()));
      return;
   }*/
   //Check that there are services available to be enabled
   if( installStackWidget->currentIndex()==5 ){
     if(DEBUG){ qDebug() << "Available Services:" << SERVICELIST.length(); }
     if(SERVICELIST.isEmpty()){
       installStackWidget->setCurrentIndex(6); //skip the services page
       if(DEBUG){ qDebug() << "Skipping Services - now index:" << installStackWidget->currentIndex(); }
     }
   }

   // Finished screen
   if ( installStackWidget->currentIndex() >= 6 ) {
      // Save the settings
      if(!DEBUG){ saveSettings(); }
      nextButton->setText(tr("&Finish"));
      backButton->setVisible(false);
      nextButton->disconnect();
      connect(nextButton, SIGNAL(clicked()), this, SLOT(slotFinished()));
   }

   proceed(true);
}

void Installer::slotBack()
{
   nextButton->setEnabled(true);

   if ( installStackWidget->currentIndex() == 1 )
     backButton->setVisible(false);
   else
     backButton->setVisible(true);

   proceed(false);
}

void Installer::slotChangeLanguage()
{
    if ( comboLanguage->currentIndex() == -1 )
      return;

    // Figure out the language code
    QString langCode = languages.at(comboLanguage->currentIndex());

    // Grab the language code
    langCode.truncate(langCode.lastIndexOf(")"));
    langCode.remove(0, langCode.lastIndexOf("(") + 1);

    // Check what directory our app is in
    QString appDir;
    if ( QFile::exists("/usr/local/bin/pc-sysinstaller") )
      appDir = "/usr/local/share/trueos";
    else
      appDir = QCoreApplication::applicationDirPath();

    //QTranslator *translator = new QTranslator();
    qDebug() << "Remove the translator";
    if ( ! translator->isEmpty() )
      QCoreApplication::removeTranslator(translator);

    if (translator->load( QString("FirstBoot_") + langCode, appDir + "/i18n/" )) {
      qDebug() << "Load new Translator" << langCode;
      QCoreApplication::installTranslator(translator);
      this->retranslateUi(this);
    }
    LoadServices(); //need to re-fetch the translations for the services
}

void Installer::changeLang(QString code)
{
   // Change the language in the combobox with the current running one
   comboLanguage->disconnect();

   for (int i=0; i < languages.count(); ++i) {
      if ( languages.at(i).indexOf("(" + code + ")" ) != -1 ) {
        comboLanguage->setCurrentIndex(i);
      }
   }

   connect(comboLanguage, SIGNAL(currentIndexChanged(QString)), this, SLOT(slotChangeLanguage()));
}

void Installer::slotHelp()
{
	pcHelp = new dialogHelp();
	switch (installStackWidget->currentIndex()) {
	case 0:
		pcHelp->dialogInit(HELPTEXT0);
		break;
	case 1:
		pcHelp->dialogInit(HELPTEXT1);
		break;
	case 2:
		pcHelp->dialogInit(HELPTEXT2);
		break;
	case 3:
		pcHelp->dialogInit(HELPTEXT3);
		break;
	case 4:
		pcHelp->dialogInit(HELPTEXT4);
		break;
	case 5:
		pcHelp->dialogInit(HELPTEXT5);
		break;
	case 6:
		pcHelp->dialogInit(HELPTEXT6);
		break;
	case 7:
		pcHelp->dialogInit(HELPTEXT7);
		break;
	default:
		pcHelp->dialogInit("No additional information for this page.");
		break;
	}
	pcHelp->show();
}

void Installer::slotScanNetwork()
{
  QString strength, ssid, security, FileLoad;
  QStringList ifconfout;
  int foundItem = 0;

  // Clear the list box and disable the add button
  listWidgetWifi->clear();

  // Start the scan and get the output
  //ifconfout = Utils::runShellCommand("ifconfig -v wlan0 up list scan");
  ifconfout = Utils::runShellCommand("ifconfig -v wlan0 list scan");

  qDebug() << ifconfout;

  //display the info for each wifi access point
  QStringList wap;
  for(int i=1; i<ifconfout.size(); i++){    //Skip the header line by starting at 1
    QStringList ifline = NetworkInterface::parseWifiScanLine(ifconfout[i],true); //get a single line
    //save the info for this wifi
    ssid = ifline[0];
    strength = ifline[4];
    //determine the icon based on if there is security encryption
    security = ifline[6]; //NetworkInterface::getWifiSecurity(ssid,DeviceName);
    if(security.toLower()=="error"){ continue; } //skip this wifi point - will not work properly
    wap << strength+"::::"+security+"::::"+ssid; //save this for sorting later
  }
  wap.sort(); //sort these by signal strength (low->high)
  for(int i=wap.length()-1; i>=0; i--){ //now add them in reverse order (high->low)
    strength = wap[i].section("::::",0,0);
    security = wap[i].section("::::",1,1);
    ssid = wap[i].section("::::",2,50);
    if(security.contains("None")){
      FileLoad = ":/modules/images/object-unlocked.png";
    }else{
      FileLoad = ":/modules/images/object-locked.png";
    }
    //Add the wifi access point to the list
    if(strength.contains("100")){ //This gets sorted down with the 10% range - add it to the top
      listWidgetWifi->insertItem(0, new QListWidgetItem(QIcon(FileLoad), ssid + " (signal: " +strength + ")") );
    }else{
      listWidgetWifi->addItem(new QListWidgetItem(QIcon(FileLoad), ssid + " (signal: " +strength + ")") );
    }
    foundItem = 1; //set the flag for wifi signals found
  }

  if ( foundItem == 1 )
    listWidgetWifi->setCurrentRow(-1);
}

void Installer::slotAddNewWifi()
{
  if ((listWidgetWifi->currentRow()) ==-1 )
     return;

  QString line = listWidgetWifi->item(listWidgetWifi->currentRow())->text();
  QString ssidc = line.section(" (",0,0,QString::SectionSkipEmpty);
  addNetworkProfile(ssidc);
}

void Installer::addNetworkProfile(QString ssid)
{
  //get the full SSID string
  QString dat = Utils::runShellCommandSearch("ifconfig -v wlan0 list scan",ssid);
  QStringList wdat = NetworkInterface::parseWifiScanLine(dat,true);
  QString SSID = wdat[0];

  //Get the Security Type
  QString sectype = wdat[6];

  if(sectype == "None"){
    //run the Quick-Connect slot without a key
    slotQuickConnect("",SSID);
  }else{
    //Open the dialog to prompt for the Network Security Key
    dialogNetKey = new netKey(this, sectype);
    //Insert the SSID into the dialog
    dialogNetKey->setSSID(SSID);
    //connect the signal from the dialog to the quick-connect slot
    connect(dialogNetKey,SIGNAL( saved(QString,QString) ),this,SLOT( slotQuickConnect(QString,QString) ) );
    //Activate the dialog
    dialogNetKey->exec();
  }
}

void Installer::slotQuickConnect(QString key,QString SSID){

  // Run the wifiQuickConnect function
  NetworkInterface::wifiQuickConnect(SSID,key,"wlan0");

  // Move to the next page screen
  nextButton->click();
  /*installStackWidget->setCurrentIndex(5);

  // Save the settings
  saveSettings();
  nextButton->setText(tr("&Finish"));
  backButton->setVisible(false);
  nextButton->disconnect();
  connect(nextButton, SIGNAL(clicked()), this, SLOT(slotFinished()));*/
}

void Installer::slotGetPCDevice(){
  //This will find any personacrypt capable devices
  QStringList devs = Utils::runShellCommand("personacrypt list -r");
  if(devs.isEmpty()){
    QMessageBox::warning(this, tr("No Devices Found"), tr("Please connect a removable device and try again") );
     return;
  }
  bool ok = false;
  QString device = QInputDialog::getItem(this, tr("Select Removable Device"), tr("Warning: Any existing data on the selected device will be deleted during the user creation process."), devs, 0, false, &ok);
  if(!ok || device.isEmpty()){ return; } //cancelled
  push_PC_device->setText(device.section(":",0,0));
  push_PC_device->setWhatsThis(device.section(":",0,0)); //save the device ID here for later use
  slotCheckUser(); //Update the UI
}

// Set the current audio device
void Installer::slotSetAudioDev(){
   //Get the currently selected device
  QString dev = combo_audiodevice->currentData().toString().section("pcm",1,-1);
  if(dev.isEmpty()){ return; }
  //Now set the device
  Utils::setConfFileValue("/etc/sysctl.conf", "hw.snd.default_unit=", "hw.snd.default_unit=" + dev, -1); //set it for usage on reboot
  QProcess::execute("sysctl hw.snd.default_unit="+dev); //turn it on right now
}

//Update the audio volume percentage
void Installer::slotAudioVolumeChanged(){
  label_volume->setText( QString::number(slider_volume->value())+"%" );
}

// Play the test audio clip
void Installer::slotPlayAudioTest(){
  //Ensure the volume is set to te specified value
  QProcess::execute("mixer vol "+QString::number(slider_volume->value()));
  //Now play the audio clip
  static QMediaPlayer *mediaobj = 0;
  if(mediaobj==0){
    mediaobj = new QMediaPlayer();

  }else{
    mediaobj->stop();
    QApplication::processEvents();
  }
  mediaobj->setMedia( QUrl("qrc:/testsound.ogg"));
  mediaobj->setVolume(100);
  QApplication::processEvents();
  mediaobj->play();
}

void Installer::LoadServices(){
  SERVICELIST = Services::getServiceList();
    list_services->clear();
    for(int i=0; i<SERVICELIST.length(); i++){
      QListWidgetItem *it = new QListWidgetItem(SERVICELIST[i].name);
	it->setToolTip(SERVICELIST[i].description);
	it->setWhatsThis(SERVICELIST[i].ID);
	it->setCheckState(Qt::Unchecked);
      list_services->addItem(it);
    }
    list_services->sortItems(); //arrange alphabetically (by translated name)
}

void Installer::saveSettings()
{
  // Check if we need to change the language
  if ( comboLanguage->currentIndex() != 0 ) {
    QString lang = languages.at(comboLanguage->currentIndex());
    // Grab the language code
    lang.truncate(lang.lastIndexOf(")"));
    lang.remove(0, lang.lastIndexOf("(") + 1);
    qDebug() << "Set Lang:" << lang;
    system("/usr/local/share/trueos/scripts/set-lang.sh " + lang.toLatin1());
  }

  // Set the timezone
  QString tz = comboBoxTimezone->currentText();
  if ( tz.indexOf(":") != -1 )
   tz = tz.section(":", 0, 0);
  system("cp /usr/share/zoneinfo/" + tz.toLatin1() + " /etc/localtime");

  // Using UTC bios?
  if ( checkUTC->isChecked() )
     system("rm /etc/wall_cmos_clock >/dev/null 2>/dev/null");
  else
     system("touch /etc/wall_cmos_clock");

  // Set the root PW
  QTemporaryFile rfile("/tmp/.XXXXXXXX");
  if ( rfile.open() ) {
    QTextStream stream( &rfile );
      stream << lineRootPW->text();
    rfile.close();
  }
  system("cat " + rfile.fileName().toLatin1() + " | pw usermod root -h 0 ");
  rfile.remove();

  // Create the new home-directory
  system("/usr/local/share/trueos/scripts/mkzfsdir.sh /usr/home/" + lineUsername->text().toLatin1() );

  // Create the new username
  QTemporaryFile ufile("/tmp/.XXXXXXXX");
  if ( ufile.open() ) {
    QTextStream stream( &ufile );
      stream << linePW->text();
    ufile.close();
  }

  QString userCmd;
  if ( QFile::exists("/usr/local/bin/VirtualBox") )
  {
    userCmd = " | pw useradd -n \"" + lineUsername->text() + "\" -u "+spin_UID->cleanText()+" -c \"" + lineName->text().toUtf8() + "\" -h 0 -s \"/bin/csh\" -m -d \"/usr/home/" + lineUsername->text() + "\" -G \"wheel,operator,vboxusers\"";
  } else {
    userCmd = " | pw useradd -n \"" + lineUsername->text() + "\" -u "+spin_UID->cleanText()+" -c \"" + lineName->text().toUtf8() + "\" -h 0 -s \"/bin/csh\" -m -d \"/usr/home/" + lineUsername->text() + "\" -G \"wheel,operator\"";
  }
  system("cat " + ufile.fileName().toLatin1() + userCmd.toLatin1());
  ufile.remove();

  // Sync after adding the user
  sync();

  //Create the personacrypt device (if selected)
  if(group_usePC->isChecked()){
    QTemporaryFile tmpfile("/tmp/.XXXXXXXXXXXXXXXXX");
    if( tmpfile.open() ){
      QTextStream ostream(&tmpfile);
	ostream << line_PCpass->text();
      tmpfile.close();
      QProcess::execute("personacrypt init \""+lineUsername->text()+"\" \""+tmpfile.fileName()+"\" "+push_PC_device->whatsThis());
    }
  }

  // Enable Flash for the new user
  QProcess::execute("su", QStringList() << lineUsername->text() << "-c" << "/usr/local/bin/flashpluginctl on" );

  // Do we need to change the system hostname, and set a domain name?
  if ( lineDomainName->text() != Utils::getConfFileValue("/etc/rc.conf", "hostname=lineHostname.lineDomainName", 1) )
  {
           Utils::setConfFileValue("/etc/rc.conf", "hostname=", "hostname=\"" + lineHostname->text() + "." + lineDomainName->text() + "\"", -1);
           Utils::setConfFileValue("/etc/hosts", "::1", "::1\t\t\tlocalhost " + lineHostname->text() + "." + lineDomainName->text() + " " + lineHostname->text(), -1);
           Utils::setConfFileValue("/etc/hosts", "127.0.0.1", "127.0.0.1\t\tlocalhost " + lineHostname->text() + "." + lineDomainName->text() + " " + lineHostname->text(), -1);

      // Now set the hostname on the system
      sethostname(lineHostname->text().toLatin1(), lineHostname->text().length());
      // Now set the domain name on the system
      sethostname(lineDomainName->text().toLatin1(), lineDomainName->text().length());
      QProcess::execute(QString("hostname ") + lineHostname->text() + "." + lineDomainName->text());
  }
  // Do we need to change the system hostname?
  else if ( lineHostname->text() != Utils::getConfFileValue("/etc/rc.conf", "hostname=", 1) )
  {
      Utils::setConfFileValue("/etc/rc.conf", "hostname=", "hostname=\"" + lineHostname->text() + "\"", -1);
      Utils::setConfFileValue("/etc/hosts", "::1", "::1\t\t\tlocalhost " + lineHostname->text(), -1);
      Utils::setConfFileValue("/etc/hosts", "127.0.0.1", "127.0.0.1\t\tlocalhost " + lineHostname->text(), -1);

      // Now set the hostname on the system
      sethostname(lineHostname->text().toLatin1(), lineHostname->text().length());
      QProcess::execute(QString("hostname ") + lineHostname->text());
  }

  // Save the PCDM default lang / inputs
  QString curLang;
  if ( comboLanguage->currentIndex() != -1 ) {
    // Figure out the language code
    curLang = languages.at(comboLanguage->currentIndex());

    // Grab the language code
    curLang.truncate(curLang.lastIndexOf(")"));
    curLang.remove(0, curLang.lastIndexOf("(") + 1);
  }

  system("mkdir -p /var/db/pcdm 2>/dev/null");
  QFile pcdmfile("/var/db/pcdm/defaultInputs");
  if (pcdmfile.open(QIODevice::WriteOnly | QIODevice::Text)) {
    QTextStream out(&pcdmfile);
    out << "Lang=" << curLang << "\n";

    if ( kbMod.isEmpty() )
      out << "KeyModel=pc104\n";
    else
      out << "KeyModel=" << kbMod << "\n";

    if ( kbLay.isEmpty() )
      out << "KeyLayout=us\n";
    else
      out << "KeyLayout=" << kbLay << "\n";

    if ( kbVar.isEmpty() )
      out << "KeyVariant=";
    else
      out << "KeyVariant=" << kbVar;

    pcdmfile.close();
  } else {
    qDebug() << "Error opening /var/db/pcdm/defaultInputs";
  }

  //Now enable any selected services
  for(int i=0; i<list_services->count(); i++){
    if(list_services->item(i)->checkState() != Qt::Unchecked){
      QString ID = list_services->item(i)->whatsThis();
      //Find the data structure and enable the service
      for(int s=0; s<SERVICELIST.length(); s++){
        if(SERVICELIST[s].ID == ID){
          Services::enableService(SERVICELIST[s]);
	  break;
	}
      }
    }
  }
  //Now do any special patches/fixes for particular releases/versions
  //Lumina 1.0.0-Beta2 (July/August 2016)
  system("sed -ie \'s/desktop_visiblepanels=2/desktop_visiblepanels=1/g\' /usr/local/etc/luminaDesktop.conf.dist"); //Error in Lumina 1.0.0-Beta1 TRUEOS defaults
  system("sed -ie \'s/_ifexists=lumina-terminal.desktop/_ifexists=qterminal.desktop/g\' /usr/local/etc/luminaDesktop.conf.dist"); //Error in Lumina 1.0.0-Beta2 TRUEOS defaults
}

void Installer::slotKeyLayoutUpdated(QString mod, QString lay, QString var)
{
  kbMod = mod;
  kbLay = lay;
  kbVar = var;
}

void Installer::closeEvent(QCloseEvent *event)
{
   event->ignore();
}


text: export { default } from 'shared/components/form-reservation/component';


text:
<?php

namespace Cake\Console;

use Cake\Core\App;
use Cake\Core\Configure;
use Cake\Core\Plugin;
use Cake\Filesystem\Folder;
use Cake\Utility\Inflector;

/**
 * Used by CommandCollection and CommandTask to scan the filesystem
 * for command classes.
 *
 * @internal
 */
class CommandScanner
{
    /**
     * Scan CakePHP internals for shells & commands.
     *
     * @return array A list of command metadata.
     */
    public function scanCore()
    {
        $coreShells = $this->scanDir(
            dirname(__DIR__) . DIRECTORY_SEPARATOR . 'Shell' . DIRECTORY_SEPARATOR,
            'Cake\Shell\\',
            '',
            ['command_list']
        );
        $coreCommands = $this->scanDir(
            dirname(__DIR__) . DIRECTORY_SEPARATOR . 'Command' . DIRECTORY_SEPARATOR,
            'Cake\Command\\',
            '',
            ['command_list']
        );

        return array_merge($coreShells, $coreCommands);
    }

    /**
     * Scan the application for shells & commands.
     *
     * @return array A list of command metadata.
     */
    public function scanApp()
    {
        $appNamespace = Configure::read('App.namespace');
        $appShells = $this->scanDir(
            App::path('Shell')[0],
            $appNamespace . '\Shell\\',
            '',
            []
        );
        $appCommands = $this->scanDir(
            App::path('Command')[0],
            $appNamespace . '\Command\\',
            '',
            []
        );

        return array_merge($appShells, $appCommands);
    }

    /**
     * Scan the named plugin for shells and commands
     *
     * @param string $plugin The named plugin.
     * @return array A list of command metadata.
     */
    public function scanPlugin($plugin)
    {
        if (!Plugin::loaded($plugin)) {
            return [];
        }
        $path = Plugin::classPath($plugin);
        $namespace = str_replace('/', '\\', $plugin);
        $prefix = Inflector::underscore($plugin) . '.';

        $commands = $this->scanDir($path . 'Command', $namespace . '\Command\\', $prefix, []);
        $shells = $this->scanDir($path . 'Shell', $namespace . '\Shell\\', $prefix, []);

        return array_merge($shells, $commands);
    }

    /**
     * Scan a directory for .php files and return the class names that
     * should be within them.
     *
     * @param string $path The directory to read.
     * @param string $namespace The namespace the shells live in.
     * @param string $prefix The prefix to apply to commands for their full name.
     * @param array $hide A list of command names to hide as they are internal commands.
     * @return array The list of shell info arrays based on scanning the filesystem and inflection.
     */
    protected function scanDir($path, $namespace, $prefix, array $hide)
    {
        $dir = new Folder($path);
        $contents = $dir->read(true, true);
        if (empty($contents[1])) {
            return [];
        }

        $classPattern = '/(Shell|Command)$/';
        $shells = [];
        foreach ($contents[1] as $file) {
            if (substr($file, -4) !== '.php') {
                continue;
            }
            $shell = substr($file, 0, -4);
            if (!preg_match($classPattern, $shell)) {
                continue;
            }

            $name = Inflector::underscore(preg_replace($classPattern, '', $shell));
            if (in_array($name, $hide, true)) {
                continue;
            }

            $class = $namespace . $shell;
            if (!is_subclass_of($class, Shell::class) && !is_subclass_of($class, Command::class)) {
                continue;
            }

            $shells[] = [
                'file' => $path . $file,
                'fullName' => $prefix . $name,
                'name' => $name,
                'class' => $class
            ];
        }

        return $shells;
    }
}