text:
require 'helper'
require 'json'

describe Octokit::Client do

  before do
    Octokit.reset!
  end

  after do
    Octokit.reset!
  end

  describe "module configuration" do

    before do
      Octokit.reset!
      Octokit.configure do |config|
        Octokit::Configurable.keys.each do |key|
          config.send("#{key}=", "Some #{key}")
        end
      end
    end

    after do
      Octokit.reset!
    end

    it "inherits the module configuration" do
      client = Octokit::Client.new
      Octokit::Configurable.keys.each do |key|
        expect(client.instance_variable_get(:"@#{key}")).to eq("Some #{key}")
      end
    end

    describe "with class level configuration" do

      before do
        @opts = {
          :connection_options => {:ssl => {:verify => false}},
          :per_page => 40,
          :login    => "defunkt",
          :password => "il0veruby"
        }
      end

      it "overrides module configuration" do
        client = Octokit::Client.new(@opts)
        expect(client.per_page).to eq(40)
        expect(client.login).to eq("defunkt")
        expect(client.instance_variable_get(:"@password")).to eq("il0veruby")
        expect(client.auto_paginate).to eq(Octokit.auto_paginate)
        expect(client.client_id).to eq(Octokit.client_id)
      end

      it "can set configuration after initialization" do
        client = Octokit::Client.new
        client.configure do |config|
          @opts.each do |key, value|
            config.send("#{key}=", value)
          end
        end
        expect(client.per_page).to eq(40)
        expect(client.login).to eq("defunkt")
        expect(client.instance_variable_get(:"@password")).to eq("il0veruby")
        expect(client.auto_paginate).to eq(Octokit.auto_paginate)
        expect(client.client_id).to eq(Octokit.client_id)
      end

      it "masks passwords on inspect" do
        client = Octokit::Client.new(@opts)
        inspected = client.inspect
        expect(inspected).not_to include("il0veruby")
      end

      it "masks tokens on inspect" do
        client = Octokit::Client.new(:access_token => '87614b09dd141c22800f96f11737ade5226d7ba8')
        inspected = client.inspect
        expect(inspected).not_to include("87614b09dd141c22800f96f11737ade5226d7ba8")
      end

      it "masks bearer token on inspect" do
        client = Octokit::Client.new(bearer_token: 'secret JWT')
        inspected = client.inspect
        expect(inspected).not_to include("secret JWT")
      end

      it "masks client secrets on inspect" do
        client = Octokit::Client.new(:client_secret => '87614b09dd141c22800f96f11737ade5226d7ba8')
        inspected = client.inspect
        expect(inspected).not_to include("87614b09dd141c22800f96f11737ade5226d7ba8")
      end

      describe "with .netrc" do
        before do
          File.chmod(0600, File.join(fixture_path, '.netrc'))
        end

        it "can read .netrc files" do
          Octokit.reset!
          client = Octokit::Client.new(:netrc => true, :netrc_file => File.join(fixture_path, '.netrc'))
          expect(client.login).to eq("sferik")
          expect(client.instance_variable_get(:"@password")).to eq("il0veruby")
        end

        it "can read non-standard API endpoint creds from .netrc" do
          Octokit.reset!
          client = Octokit::Client.new(:netrc => true, :netrc_file => File.join(fixture_path, '.netrc'), :api_endpoint => 'http://api.github.dev')
          expect(client.login).to eq("defunkt")
          expect(client.instance_variable_get(:"@password")).to eq("il0veruby")
        end
      end
    end
  end

  describe "content type" do
    it "sets a default Content-Type header" do
      gist_request = stub_post("/gists").
        with({
          :headers => {"Content-Type" => "application/json"}})

      Octokit.client.post "/gists", {}
      assert_requested gist_request
    end
    it "fixes % bug", :vcr do
      new_gist = {
        :description => "%A gist from Octokit",
        :public      => true,
        :files       => {
          "zen.text" => { :content => "Keep it logically awesome." }
        }
      }

      Octokit.client.post "/gists", new_gist
      expect(Octokit.client.last_response.status).to eq(201)
    end
  end

  describe "authentication" do
    before do
      Octokit.reset!
      @client = Octokit.client
    end

    describe "with module level config" do
      before do
        Octokit.reset!
      end

      it "sets basic auth creds with .configure" do
        Octokit.configure do |config|
          config.login = 'pengwynn'
          config.password = 'il0veruby'
        end
        expect(Octokit.client).to be_basic_authenticated
      end

      it "sets basic auth creds with module methods" do
        Octokit.login = 'pengwynn'
        Octokit.password = 'il0veruby'
        expect(Octokit.client).to be_basic_authenticated
      end

      it "sets oauth token with .configure" do
        Octokit.configure do |config|
          config.access_token = 'd255197b4937b385eb63d1f4677e3ffee61fbaea'
        end
        expect(Octokit.client).not_to be_basic_authenticated
        expect(Octokit.client).to be_token_authenticated
      end

      it "sets oauth token with module methods" do
        Octokit.access_token = 'd255197b4937b385eb63d1f4677e3ffee61fbaea'
        expect(Octokit.client).not_to be_basic_authenticated
        expect(Octokit.client).to be_token_authenticated
      end

      it "sets bearer token with module method" do
        Octokit.bearer_token = 'secret JWT'
        expect(Octokit.client).to be_bearer_authenticated
      end

      it "sets bearer token with .configure" do
        Octokit.configure do |config|
          config.bearer_token = 'secret JWT'
        end
        expect(Octokit.client).not_to be_basic_authenticated
        expect(Octokit.client).not_to be_token_authenticated
        expect(Octokit.client).to be_bearer_authenticated
      end

      it "sets oauth application creds with .configure" do
        Octokit.configure do |config|
          config.client_id     = '97b4937b385eb63d1f46'
          config.client_secret = 'd255197b4937b385eb63d1f4677e3ffee61fbaea'
        end
        expect(Octokit.client).not_to be_basic_authenticated
        expect(Octokit.client).not_to be_token_authenticated
        expect(Octokit.client).to be_application_authenticated
      end

      it "sets oauth token with module methods" do
        Octokit.client_id     = '97b4937b385eb63d1f46'
        Octokit.client_secret = 'd255197b4937b385eb63d1f4677e3ffee61fbaea'
        expect(Octokit.client).not_to be_basic_authenticated
        expect(Octokit.client).not_to be_token_authenticated
        expect(Octokit.client).to be_application_authenticated
      end
    end

    describe "with class level config" do
      it "sets basic auth creds with .configure" do
        @client.configure do |config|
          config.login = 'pengwynn'
          config.password = 'il0veruby'
        end
        expect(@client).to be_basic_authenticated
      end
      it "sets basic auth creds with instance methods" do
        @client.login = 'pengwynn'
        @client.password = 'il0veruby'
        expect(@client).to be_basic_authenticated
      end
      it "sets oauth token with .configure" do
        @client.access_token = 'd255197b4937b385eb63d1f4677e3ffee61fbaea'
        expect(@client).not_to be_basic_authenticated
        expect(@client).to be_token_authenticated
      end
      it "sets oauth token with instance methods" do
        @client.access_token = 'd255197b4937b385eb63d1f4677e3ffee61fbaea'
        expect(@client).not_to be_basic_authenticated
        expect(@client).to be_token_authenticated
      end
      it "sets oauth application creds with .configure" do
        @client.configure do |config|
          config.client_id     = '97b4937b385eb63d1f46'
          config.client_secret = 'd255197b4937b385eb63d1f4677e3ffee61fbaea'
        end
        expect(@client).not_to be_basic_authenticated
        expect(@client).not_to be_token_authenticated
        expect(@client).to be_application_authenticated
      end
      it "sets oauth token with module methods" do
        @client.client_id     = '97b4937b385eb63d1f46'
        @client.client_secret = 'd255197b4937b385eb63d1f4677e3ffee61fbaea'
        expect(@client).not_to be_basic_authenticated
        expect(@client).not_to be_token_authenticated
        expect(@client).to be_application_authenticated
      end
    end

    describe "when basic authenticated"  do
      it "makes authenticated calls" do
        Octokit.configure do |config|
          config.login = 'pengwynn'
          config.password = 'il0veruby'
        end

        root_request = stub_get("https://pengwynn:il0veruby@api.github.com/")
        Octokit.client.get("/")
        assert_requested root_request
      end
    end

    describe "when token authenticated", :vcr do
      it "makes authenticated calls" do
        client = oauth_client

        root_request = stub_get("/").
          with(:headers => {:authorization => "token #{test_github_token}"})
        client.get("/")
        assert_requested root_request
      end
      it "fetches and memoizes login" do
        client = oauth_client

        expect(client.login).to eq(test_github_login)
        assert_requested :get, github_url('/user')
      end
    end

    describe "when bearer authenticated", :vcr do
      it "makes authenticated calls" do
        jwt = 'secret JWT'
        client = Octokit::Client.new(bearer_token: jwt)

        root_request = stub_get("/").
          with(:headers => {:authorization => "Bearer #{jwt}"})
        client.get("/")
        assert_requested root_request
      end
    end

    describe "when application authenticated" do
      it "makes authenticated calls" do
        client = Octokit.client
        client.client_id     = '97b4937b385eb63d1f46'
        client.client_secret = 'd255197b4937b385eb63d1f4677e3ffee61fbaea'

        root_request = stub_get("/?client_id=97b4937b385eb63d1f46&client_secret=d255197b4937b385eb63d1f4677e3ffee61fbaea")
        client.get("/")
        assert_requested root_request
      end
    end
  end

  describe ".agent" do
    before do
      Octokit.reset!
    end
    it "acts like a Sawyer agent" do
      expect(Octokit.client.agent).to respond_to :start
    end
    it "caches the agent" do
      agent = Octokit.client.agent
      expect(agent.object_id).to eq(Octokit.client.agent.object_id)
    end
  end # .agent

  describe ".root" do
    it "fetches the API root" do
      Octokit.reset!
      VCR.use_cassette 'root' do
        root = Octokit.client.root
        expect(root.rels[:issues].href).to eq("https://api.github.com/issues")
      end
    end

    it "passes app creds in the query string" do
      root_request = stub_get("/?client_id=97b4937b385eb63d1f46&client_secret=d255197b4937b385eb63d1f4677e3ffee61fbaea")
      client = Octokit.client
      client.client_id     = '97b4937b385eb63d1f46'
      client.client_secret = 'd255197b4937b385eb63d1f4677e3ffee61fbaea'
      client.root
      assert_requested root_request
    end
  end

  describe ".last_response", :vcr do
    it "caches the last agent response" do
      Octokit.reset!
      client = Octokit.client
      expect(client.last_response).to be_nil
      client.get "/"
      expect(client.last_response.status).to eq(200)
    end
  end # .last_response

  describe ".get", :vcr do
    before(:each) do
      Octokit.reset!
    end
    it "handles query params" do
      Octokit.get "/", :foo => "bar"
      assert_requested :get, "https://api.github.com?foo=bar"
    end
    it "handles headers" do
      request = stub_get("/zen").
        with(:query => {:foo => "bar"}, :headers => {:accept => "text/plain"})
      Octokit.get "/zen", :foo => "bar", :accept => "text/plain"
      assert_requested request
    end
  end # .get

  describe ".head", :vcr do
    it "handles query params" do
      Octokit.reset!
      Octokit.head "/", :foo => "bar"
      assert_requested :head, "https://api.github.com?foo=bar"
    end
    it "handles headers" do
      Octokit.reset!
      request = stub_head("/zen").
        with(:query => {:foo => "bar"}, :headers => {:accept => "text/plain"})
      Octokit.head "/zen", :foo => "bar", :accept => "text/plain"
      assert_requested request
    end
  end # .head

  describe "when making requests" do
    before do
      Octokit.reset!
      @client = Octokit.client
    end
    it "Accepts application/vnd.github.v3+json by default" do
      VCR.use_cassette 'root' do
        root_request = stub_get("/").
          with(:headers => {:accept => "application/vnd.github.v3+json"})
        @client.get "/"
        assert_requested root_request
        expect(@client.last_response.status).to eq(200)
      end
    end
    it "allows Accept'ing another media type" do
      root_request = stub_get("/").
        with(:headers => {:accept => "application/vnd.github.beta.diff+json"})
      @client.get "/", :accept => "application/vnd.github.beta.diff+json"
      assert_requested root_request
      expect(@client.last_response.status).to eq(200)
    end
    it "sets a default user agent" do
      root_request = stub_get("/").
        with(:headers => {:user_agent => Octokit::Default.user_agent})
      @client.get "/"
      assert_requested root_request
      expect(@client.last_response.status).to eq(200)
    end
    it "sets a custom user agent" do
      user_agent = "Mozilla/5.0 I am Spartacus!"
      root_request = stub_get("/").
        with(:headers => {:user_agent => user_agent})
      client = Octokit::Client.new(:user_agent => user_agent)
      client.get "/"
      assert_requested root_request
      expect(client.last_response.status).to eq(200)
    end
    it "sets a proxy server" do
      Octokit.configure do |config|
        config.proxy = 'http://proxy.example.com:80'
      end
      conn = Octokit.client.send(:agent).instance_variable_get(:"@conn")
      expect(conn.proxy[:uri].to_s).to eq('http://proxy.example.com')
    end
    it "sets an ssl verify mode" do
      Octokit.configure do |config|
        config.ssl_verify_mode = OpenSSL::SSL::VERIFY_NONE
      end
      conn = Octokit.client.send(:agent).instance_variable_get(:"@conn")
      expect(conn.ssl[:verify_mode]).to eq(OpenSSL::SSL::VERIFY_NONE)
    end
    it "ensures ssl verify mode is set to default when no override provided" do
      conn = Octokit.client.send(:agent).instance_variable_get(:"@conn")
      expect(conn.ssl[:verify_mode]).to eq(OpenSSL::SSL::VERIFY_PEER)
    end
    it "passes along request headers for POST" do
      headers = {"X-GitHub-Foo" => "bar"}
      root_request = stub_post("/").
        with(:headers => headers).
        to_return(:status => 201)
      client = Octokit::Client.new
      client.post "/", :headers => headers
      assert_requested root_request
      expect(client.last_response.status).to eq(201)
    end
    it "adds app creds in query params to anonymous requests" do
      client = Octokit::Client.new
      client.client_id     = key = '97b4937b385eb63d1f46'
      client.client_secret = secret = 'd255197b4937b385eb63d1f4677e3ffee61fbaea'
      root_request = stub_get "/?client_id=#{key}&client_secret=#{secret}"

      client.get("/")
      assert_requested root_request
    end
    it "omits app creds in query params for basic requests" do
      client = Octokit::Client.new :login => "login", :password => "passw0rd"
      client.client_id     = key = '97b4937b385eb63d1f46'
      client.client_secret = secret = 'd255197b4937b385eb63d1f4677e3ffee61fbaea'
      root_request = stub_get basic_github_url("/?foo=bar", :login => "login", :password => "passw0rd")

      client.get("/", :foo => "bar")
      assert_requested root_request
    end
    it "omits app creds in query params for token requests" do
      client = Octokit::Client.new(:access_token => '87614b09dd141c22800f96f11737ade5226d7ba8')
      client.client_id     = key = '97b4937b385eb63d1f46'
      client.client_secret = secret = 'd255197b4937b385eb63d1f4677e3ffee61fbaea'
      root_request = stub_get(github_url("/?foo=bar")).with \
        :headers => {"Authorization" => "token 87614b09dd141c22800f96f11737ade5226d7ba8"}

      client.get("/", :foo => "bar")
      assert_requested root_request
    end
  end

  describe "redirect handling" do
    it "follows redirect for 301 response" do
      client = oauth_client

      original_request = stub_get("/foo").
        to_return(:status => 301, :headers => { "Location" => "/bar" })
      redirect_request = stub_get("/bar").to_return(:status => 200)

      client.get("/foo")
      assert_requested original_request
      assert_requested redirect_request
    end

    it "follows redirect for 302 response" do
      client = oauth_client

      original_request = stub_get("/foo").
        to_return(:status => 302, :headers => { "Location" => "/bar" })
      redirect_request = stub_get("/bar").to_return(:status => 200)

      client.get("/foo")
      assert_requested original_request
      assert_requested redirect_request
    end

    it "follows redirect for 307 response" do
      client = oauth_client

      original_request = stub_post(github_url("/foo")).
        with(:body => { :some_property => "some_value" }.to_json).
        to_return(:status => 307, :headers => { "Location" => "/bar" })
      redirect_request = stub_post(github_url("/bar")).
        with(:body => { :some_property => "some_value" }.to_json).
        to_return(:status => 201, :headers => { "Location" => "/bar" })

      client.post("/foo", { :some_property => "some_value" })
      assert_requested original_request
      assert_requested redirect_request
    end

    it "follows redirects for supported HTTP methods" do
      client = oauth_client

      http_methods = [:head, :get, :post, :put, :patch, :delete]

      http_methods.each do |http|
        original_request = stub_request(http, github_url("/foo")).
          to_return(:status => 301, :headers => { "Location" => "/bar" })
        redirect_request = stub_request(http, github_url("/bar")).
          to_return(:status => 200)

        client.send(http, "/foo")
        assert_requested original_request
        assert_requested redirect_request
      end
    end

    it "does not change HTTP method when following a redirect" do
      client = oauth_client

      original_request = stub_delete("/foo").
        to_return(:status => 301, :headers => { "Location" => "/bar" })
      redirect_request = stub_delete("/bar").to_return(:status => 200)

      client.delete("/foo")
      assert_requested original_request
      assert_requested redirect_request

      other_methods = [:head, :get, :post, :put, :patch]
      other_methods.each do |http|
        assert_not_requested http, github_url("/bar")
      end
    end

    it "keeps authentication info when redirecting to the same host" do
      client = oauth_client

      original_request = stub_get("/foo").
        with(:headers => {"Authorization" => "token #{test_github_token}"}).
        to_return(:status => 301, :headers => { "Location" => "/bar" })
      redirect_request = stub_get("/bar").
        with(:headers => {"Authorization" => "token #{test_github_token}"}).
        to_return(:status => 200)

      client.get("/foo")
      assert_requested original_request
      assert_requested redirect_request
    end

    it "drops authentication info when redirecting to a different host" do
      client = oauth_client

      original_request = stub_request(:get, github_url("/foo")).
        with(:headers => {"Authorization" => "token #{test_github_token}"}).
        to_return(:status => 301, :headers => { "Location" => "https://example.com/bar" })
      redirect_request = stub_request(:get, "https://example.com/bar").
        to_return(:status => 200)

      client.get("/foo")

      assert_requested original_request
      assert_requested(:get, "https://example.com/bar") { |req|
        req.headers["Authorization"].nil?
      }
    end

    it "follows at most 3 consecutive redirects" do
      client = oauth_client

      original_request = stub_get("/a").
        to_return(:status => 302, :headers => { "Location" => "/b" })
      first_redirect = stub_get("/b").
        to_return(:status => 302, :headers => { "Location" => "/c" })
      second_redirect = stub_get("/c").
        to_return(:status => 302, :headers => { "Location" => "/d" })
      third_redirect = stub_get("/d").
        to_return(:status => 302, :headers => { "Location" => "/e" })
      fourth_redirect = stub_get("/e").to_return(:status => 200)

      expect { client.get("/a") }.to raise_error(Octokit::Middleware::RedirectLimitReached)
      assert_requested original_request
      assert_requested first_redirect
      assert_requested second_redirect
      assert_requested third_redirect
      assert_not_requested fourth_redirect
    end
  end

  describe "auto pagination", :vcr do
    before do
      Octokit.reset!
      Octokit.configure do |config|
        config.auto_paginate = true
        config.per_page = 1
      end
    end

    after do
      Octokit.reset!
    end

    it "fetches all the pages" do
      url = '/search/users?q=user:joeyw user:pengwynn user:sferik'
      Octokit.client.paginate url
      assert_requested :get, github_url("#{url}&per_page=1")
      (2..3).each do |i|
        assert_requested :get, github_url("#{url}&per_page=1&page=#{i}")
      end
    end

    it "accepts a block for custom result concatination" do
      results = Octokit.client.paginate("/search/users?per_page=1&q=user:pengwynn+user:defunkt",
        :per_page => 1) { |data, last_response|
        data.items.concat last_response.data.items
      }

      expect(results.total_count).to eq(2)
      expect(results.items.length).to eq(2)
    end

    it "sets headers for all pages" do
      url = "/search/repositories?q=octokit+language:Python"
      accept_text_match = "application/vnd.github.v3.text-match+json"
      github_media_type_header = "github.v3; param=text-match; format=json"
      Octokit.client.paginate url, :accept => accept_text_match
      expect(Octokit.client.last_response.headers["x-github-media-type"]).to eq(github_media_type_header)
    end
  end

  describe ".as_app" do
    before do
      @client_id = '97b4937b385eb63d1f46'
      @client_secret = 'd255197b4937b385eb63d1f4677e3ffee61fbaea'

      Octokit.reset!
      Octokit.configure do |config|
        config.access_token  = 'a' * 40
        config.client_id     = @client_id
        config.client_secret = @client_secret
        config.per_page      = 50
      end

      @root_request = stub_get basic_github_url "/",
        :login => @client_id, :password => @client_secret
    end

    it "uses preconfigured client and secret" do
      client = Octokit.client
      login = client.as_app do |c|
        c.login
      end
      expect(login).to eq(@client_id)
    end

    it "requires a client and secret" do
      Octokit.reset!
      client = Octokit.client
      expect {
        client.as_app do |c|
          c.get
        end
      }.to raise_error Octokit::ApplicationCredentialsRequired
    end

    it "duplicates the client" do
      client = Octokit.client
      page_size = client.as_app do |c|
        c.per_page
      end
      expect(page_size).to eq(client.per_page)
    end

    it "uses client and secret as Basic auth" do
      client = Octokit.client
      app_client = client.as_app do |c|
        c
      end
      expect(app_client).to be_basic_authenticated
    end

    it "makes authenticated requests" do
      stub_get github_url("/user")

      client = Octokit.client
      client.get "/user"
      client.as_app do |c|
        c.get "/"
      end

      assert_requested @root_request
    end
  end

  context "error handling" do
    before do
      Octokit.reset!
      VCR.turn_off!
    end

    after do
      VCR.turn_on!
    end

    it "raises on 404" do
      stub_get('/booya').to_return(:status => 404)
      expect { Octokit.get('/booya') }.to raise_error Octokit::NotFound
    end

    it "raises on 500" do
      stub_get('/boom').to_return(:status => 500)
      expect { Octokit.get('/boom') }.to raise_error Octokit::InternalServerError
    end

    it "includes a message" do
      stub_get('/boom').
        to_return \
        :status => 422,
        :headers => {
          :content_type => "application/json",
        },
        :body => {:message => "No repository found for hubtopic"}.to_json
      begin
        Octokit.get('/boom')
      rescue Octokit::UnprocessableEntity => e
        expect(e.message).to include("GET https://api.github.com/boom: 422 - No repository found")
      end
    end

    it "includes an error" do
      stub_get('/boom').
        to_return \
        :status => 422,
        :headers => {
          :content_type => "application/json",
        },
        :body => {:error => "No repository found for hubtopic"}.to_json
      begin
        Octokit.get('/boom')
      rescue Octokit::UnprocessableEntity => e
        expect(e.message).to include("GET https://api.github.com/boom: 422 - Error: No repository found")
      end
    end

    it "includes an error summary" do
      stub_get('/boom').
        to_return \
        :status => 422,
        :headers => {
          :content_type => "application/json",
        },
        :body => {
          :message => "Validation Failed",
          :errors => [
            "Position is invalid",
            :resource => "Issue",
            :field    => "title",
            :code     => "missing_field"
          ]
        }.to_json
      begin
        Octokit.get('/boom')
      rescue Octokit::UnprocessableEntity => e
        expect(e.message).to include("GET https://api.github.com/boom: 422 - Validation Failed")
        expect(e.message).to include("  Position is invalid")
        expect(e.message).to include("  resource: Issue")
        expect(e.message).to include("  field: title")
        expect(e.message).to include("  code: missing_field")
      end
    end

    it "exposes errors array" do
      stub_get('/boom').
        to_return \
        :status => 422,
        :headers => {
          :content_type => "application/json",
        },
        :body => {
          :message => "Validation Failed",
          :errors => [
            :resource => "Issue",
            :field    => "title",
            :code     => "missing_field"
          ]
        }.to_json
      begin
        Octokit.get('/boom')
      rescue Octokit::UnprocessableEntity => e
        expect(e.errors.first[:resource]).to eq("Issue")
        expect(e.errors.first[:field]).to eq("title")
        expect(e.errors.first[:code]).to eq("missing_field")
      end
    end

    it "knows the difference between different kinds of forbidden" do
      stub_get('/some/admin/stuffs').to_return(:status => 403)
      expect { Octokit.get('/some/admin/stuffs') }.to raise_error Octokit::Forbidden

      stub_get('/users/mojomobo').to_return \
        :status => 403,
        :headers => {
          :content_type => "application/json",
        },
        :body => {:message => "API rate limit exceeded"}.to_json
      expect { Octokit.get('/users/mojomobo') }.to raise_error Octokit::TooManyRequests

      stub_get('/user').to_return \
        :status => 403,
        :headers => {
          :content_type => "application/json",
        },
        :body => {:message => "Maximum number of login attempts exceeded"}.to_json
      expect { Octokit.get('/user') }.to raise_error Octokit::TooManyLoginAttempts

      stub_get('/user').to_return \
        :status => 403,
        :headers => {
          :content_type => "application/json",
        },
        :body => {:message => "You have triggered an abuse detection mechanism and have been temporarily blocked from content creation. Please retry your request again later."}.to_json
      expect { Octokit.get('/user') }.to raise_error Octokit::AbuseDetected

      stub_get('/blocked/repository').to_return \
        :status => 403,
        :headers => {
          :content_type => "application/json",
        },
        :body => {:message => "Repository access blocked"}.to_json
      expect { Octokit.get("/blocked/repository") }.to raise_error Octokit::RepositoryUnavailable

      stub_post('/user/repos').to_return \
        :status => 403,
        :headers => {
          :content_type => "application/json",
        },
        :body => {:message => "At least one email address must be verified to do that"}.to_json
      expect { Octokit.post("/user/repos") }.to raise_error Octokit::UnverifiedEmail

      stub_post('/user/repos').to_return \
        :status => 403,
        :headers => {
            :content_type => "application/json",
        },
        :body => {:message => "Sorry. Your account was suspended. Please contact github-enterprise@example.com"}.to_json
      expect { Octokit.post("/user/repos") }.to raise_error Octokit::AccountSuspended

      stub_get('/torrentz').to_return \
        :status => 451,
        :headers => {
          :content_type => "application/json",
        }
        expect { Octokit.get('/torrentz') }.to raise_error Octokit::UnavailableForLegalReasons
    end

    it "raises on unknown client errors" do
      stub_get('/user').to_return \
        :status => 418,
        :headers => {
          :content_type => "application/json",
        },
        :body => {:message => "I'm a teapot"}.to_json
      expect { Octokit.get('/user') }.to raise_error Octokit::ClientError
    end

    it "raises on unknown server errors" do
      stub_get('/user').to_return \
        :status => 509,
        :headers => {
          :content_type => "application/json",
        },
        :body => {:message => "Bandwidth exceeded"}.to_json
      expect { Octokit.get('/user') }.to raise_error Octokit::ServerError
    end

    it "handles documentation URLs in error messages" do
      stub_get('/user').to_return \
        :status => 415,
        :headers => {
          :content_type => "application/json",
        },
        :body => {
          :message => "Unsupported Media Type",
          :documentation_url => "http://developer.github.com/v3"
        }.to_json
      begin
        Octokit.get('/user')
      rescue Octokit::UnsupportedMediaType => e
        msg = "415 - Unsupported Media Type"
        expect(e.message).to include(msg)
        expect(e.documentation_url).to eq("http://developer.github.com/v3")
      end
    end

    it "handles an error response with an array body" do
      stub_get('/user').to_return \
        :status => 500,
        :headers => {
          :content_type => "application/json"
        },
        :body => [].to_json
      expect { Octokit.get('/user') }.to raise_error Octokit::ServerError
    end

    it "exposes the response status code" do
      stub_get('/boom').
        to_return \
        :status => 422,
        :headers => {
          :content_type => "application/json",
        },
        :body => {:error => "No repository found for hubtopic"}.to_json
      begin
        Octokit.get('/boom')
      rescue Octokit::UnprocessableEntity => e
        expect(e.response_status).to eql 422
      end
    end

    it "exposes the response headers" do
      stub_get('/boom').
        to_return \
        :status => 422,
        :headers => {
          :content_type => "application/json",
        },
        :body => {:error => "No repository found for hubtopic"}.to_json
      begin
        Octokit.get('/boom')
      rescue Octokit::UnprocessableEntity => e
        expect(e.response_headers).to eql({ "content-type" => "application/json" })
      end
    end

    it "exposes the response body" do
      stub_get('/boom').
        to_return \
        :status => 422,
        :headers => {
          :content_type => "application/json",
        },
        :body => {:error => "No repository found for hubtopic"}.to_json
      begin
        Octokit.get('/boom')
      rescue Octokit::UnprocessableEntity => e
        expect(e.response_body).to eql({:error => "No repository found for hubtopic"}.to_json)
      end
    end
  end

  it "knows the difference between unauthorized and needs OTP" do
      stub_get('/authorizations').to_return(:status => 401)
      expect { Octokit.get('/authorizations') }.to raise_error Octokit::Unauthorized

      stub_get('/authorizations/1').to_return \
        :status => 401,
        :headers => {
          :content_type => "application/json",
          "X-GitHub-OTP" => "required; sms"
        },
        :body => {:message => "Must specify two-factor authentication OTP code."}.to_json
      expect { Octokit.get('/authorizations/1') }.to raise_error Octokit::OneTimePasswordRequired
  end

  it "knows the password delivery mechanism when needs OTP" do
    stub_get('/authorizations/1').to_return \
      :status => 401,
      :headers => {
        :content_type => "application/json",
        "X-GitHub-OTP" => "required; app"
      },
      :body => {:message => "Must specify two-factor authentication OTP code."}.to_json

    begin
      Octokit.get('/authorizations/1')
    rescue Octokit::OneTimePasswordRequired => otp_error
      expect(otp_error.password_delivery).to eql 'app'
    end
  end

  describe "module call shortcut" do
    before do
      Octokit.reset!
      @client = oauth_client
      @ent_management_console = enterprise_management_console_client
    end

    it "has no method collisions" do
      client_methods = collect_methods(Octokit::Client)
      admin_client = collect_methods(Octokit::EnterpriseAdminClient)
      console_client = collect_methods(Octokit::EnterpriseManagementConsoleClient)

      expect(client_methods & admin_client).to eql []
      expect(client_methods & console_client).to eql []
      expect(admin_client & console_client).to eql []
    end

    it "uniquely separates method missing calls" do
      expect { @ent_management_console.public_events }.to raise_error NoMethodError
    end

    def collect_methods(clazz)
      clazz.included_modules.select { |m| m.to_s =~ Regexp.new(clazz.to_s) } \
                            .collect { |m| m.public_instance_methods }.flatten
    end
  end

  describe "rels parsing" do
    before do
      Octokit.reset!
      @client = oauth_client
    end

    it "handles git@github ssh URLs", :vcr do
      repo = @client.repository("octokit/octokit.rb")
      expect(repo.rels[:ssh].href).to eq("git@github.com:octokit/octokit.rb.git")
    end
  end
end


text:
n=2
# the length of profile
l=2000

PROJECT_HOME="`dirname $0`/.."
BIN_DIR="$PROJECT_HOME/bin"
TRAIN_DIR="$PROJECT_HOME/db/langid/data/train"
OUTPUT_DIR="$BIN_DIR/profile"
PROFILE_EXE="$BIN_DIR/langid_create_profile"

if test -d $OUTPUT_DIR
then
    echo $OUTPUT_DIR exists.
else
    echo $OUTPUT_DIR not exists, create it.
    mkdir $OUTPUT_DIR
fi

count=0
for file in `find ${TRAIN_DIR}/`
do
	if test -f $file
	then
        INPUT_NAME="`basename $file`"

		echo === training file $INPUT_NAME

        OUTPUT_FILE="$OUTPUT_DIR/$INPUT_NAME.profile"

        $PROFILE_EXE $file $OUTPUT_FILE -n $n -l $l

        let ++count
        echo
	fi
done

echo "=== $count profiles are created."

# create encoding.bin
ENCODING_EXE="$BIN_DIR/langid_build_encoding_model"
$ENCODING_EXE $PROJECT_HOME/db/langid/config/encoding.config encoding.bin
echo "=== encoding.bin is created."

# create language.bin
LANGUAGE_EXE="$BIN_DIR/langid_build_language_model"
$LANGUAGE_EXE language.bin
echo "=== language.bin is created."

redpajama_set_name: RedPajamaGithub


text:
USING_NAMESPACE(std);
USING_NAMESPACE(clu);

class ModuleOperator : public NumberOperator
{
public:
	ModuleOperator(int mod) : m_mod(mod)
	{
	}
	virtual bool OnNumberRead(double number)
	{
		int res = (int)number % m_mod;
		m_OutputHandler->OutputInteger(res);
		return true;
	}
private:
	int m_mod;
};

REGISTER_SINGLE_INTEGER("mod", ModuleOperator)->SetHelp("Module math operator");


text:
<!doctype html>
<script src="../../resources/testharness.js"></script>
<script src="../../resources/testharnessreport.js"></script>
<script src="../assert_selection.js"></script>
<script src="spellcheck_test.js"></script>
<input id=input>
<textarea id=textarea></textarea>
<script>
spellcheck_test(
    '<input>',
    document => {
      const input = document.querySelector('input');
      document.getSelection().setClipboardData('zz.');
      input.focus();
      document.execCommand('paste');
      document.execCommand('paste');
      input.blur();
    },
    '<input value="zz.zz.">',
    'Markers should not be added to INPUT without focus.');
</script>


text:
package std

import (
	"bufio"
	"bytes"
	"errors"
	progressPkg "github.com/opslabjpl/gotx/progress"
	"github.com/opslabjpl/gotx/tx"
	"io"
	"io/ioutil"
	"os"
	"sync"
)

type chunk struct {
	src    *source
	err    error
	num    int
	offset int64
	isLast bool
	size   int
	data   []byte
}

func (this *chunk) Fetch(progress chan<- int64) error {
	// Do nothing, we pre-fetched the data
	return nil
}

func (this *chunk) Reader() (io.ReadSeeker, error) {
	return bytes.NewReader(this.data), nil
}

func (this *chunk) Num() int {
	return this.num
}

func (this *chunk) Size() int {
	return this.size
}

func (this *chunk) Offset() int64 {
	return this.offset
}

func (this *chunk) IsLast() bool {
	return this.isLast
}

func (this *chunk) Source() tx.Source {
	return this.src
}

func (this *chunk) Error() error {
	return this.err
}

type source struct {
	file      *os.File
	buf       *bufio.Reader
	chunkSize int
	stream    bool
	size      int64
	num       int
	offset    int64
	eof       bool
}

func NewSource(file *os.File, chunkSize int) (tx.Source, error) {
	src := &source{}
	info, err := file.Stat()
	if err != nil {
		return nil, err
	}
	src.file = file
	src.buf = bufio.NewReader(file)
	src.chunkSize = chunkSize
	src.stream = !info.Mode().IsRegular()
	if src.stream {
		src.size = -1
	} else {
		src.size = info.Size()
	}
	src.num = 1
	src.offset = 0
	return src, nil
}

func (this *source) ChunkSize() int {
	return this.chunkSize
}

func (this *source) NextChunk(progress chan<- int64) (tx.Chunk, error) {
	if this.eof {
		return nil, nil
	}
	c := &chunk{}
	c.src = this
	c.err = nil
	reader := progressPkg.NewReader(io.LimitReader(this.buf, int64(this.chunkSize)), progress)
	data, err := ioutil.ReadAll(reader)
	if err != nil {
		this.eof = true
		return nil, err
	}
	if len(data) < this.chunkSize {
		this.eof = true
		c.isLast = true
	} else if (len(data) == this.chunkSize) && (this.buf.Buffered() == 0) {
		// If the amount of data read is equal to the chunk size, do some buffer hax to determine if
		// this is the last chunk.
		_, err = this.buf.ReadByte()
		if err != nil {
			this.eof = true
			if err == io.EOF {
				c.isLast = true
			} else {
				return nil, err
			}
		}
		err = this.buf.UnreadByte()
		if err != nil {
			this.eof = true
			return nil, err
		}
	}
	c.num = this.num
	this.num++
	c.offset = this.offset
	this.offset += int64(len(data))
	c.data = data
	c.size = len(data)
	return c, nil
}

func (this *source) IsPreFetch() bool {
	return true
}

func (this *source) Size() int64 {
	return this.size
}

type destination struct {
	file   *os.File
	stream bool
	mutex  sync.Mutex
}

func NewDestination(file *os.File) (tx.Destination, error) {
	dst := &destination{}
	dst.file = file
	info, err := file.Stat()
	if err != nil {
		return nil, err
	}
	dst.stream = !info.Mode().IsRegular()
	dst.mutex = sync.Mutex{}
	return dst, nil
}

func (this *destination) PutChunk(chunk tx.Chunk, progress chan<- int64) error {
	reader, err := chunk.Reader()
	if err != nil {
		return err
	}
	this.mutex.Lock()
	defer this.mutex.Unlock()
	// Only attempt to seek if this is a regular file!
	if !this.stream {
		o, err := this.file.Seek(chunk.Offset(), 0)
		if o != chunk.Offset() {
			return errors.New("couldn't seek to offset " + string(o))
		}
		if err != nil {
			return err
		}
	}
	writer := progressPkg.NewWriter(this.file, progress)
	n, err := io.Copy(writer, reader)
	if err != nil {
		return err
	}
	if n != int64(chunk.Size()) {
		return io.ErrUnexpectedEOF
	}
	return nil
}

func (this *destination) Finish() (err error) {
	if !this.stream {
		err = this.file.Close()
	}
	return
}

func (this *destination) Abort() {
	if !this.stream {
		this.file.Close()
	}
}


text:
classdef (Abstract) audio < matlab.mixin.Copyable
%AUDIO Abstract superclass providing audio-related properties and methods.
%
%   The IOSR.DSP.AUDIO superclass is an abstract class that defines
%   audio-related properties and methods. As an abstract class, it cannot
%   be instantiated.
%
%   IOSR.DSP.AUDIO is a subclass of MATLAB.MIXIN.COPYABLE, which is a
%   subclass of the HANDLE class. Hence subclasses of AUDIO are handle
%   classes.
%
%   IOSR.DSP.AUDIO properties:
%       filename        - Name of the corresponding audio file
%       fs              - Sampling frequency (Hz)
%       signal          - The sampled data (read-only)
%
%   IOSR.DSP.AUDIO methods:
%       sound           - Replay the audio signal
%     Static methods:
%       up_down_mix     - Remix a source to a designated channel count
%       normalize       - Normalize an audio signal
%       spat            - Spatialise a sound using a SOFA file
%
%   See also IOSR.BSS.MIXTURE, IOSR.BSS.SOURCE, HANDLE,
%            MATLAB.MIXIN.COPYABLE.

%   Copyright 2016 University of Surrey.

    properties (AbortSet)
        filename            % Name of the audio file
        fs = 16000          % Sampling frequency (Hz)
    end

    properties (Abstract, Dependent, SetAccess = protected)
        signal              % The sampled data (read-only)
    end

    properties (Access = protected)
        rendered = false    % Flag indicates whether files match object
    end

    methods % public methods

        function obj = audio(filename,fs)
        %AUDIO Create the audio object

            if nargin > 0
                obj.filename = filename;
            end
            if nargin > 1
                obj.fs = fs;
            end

        end

        function sound(obj)
        %SOUND Replay the audio signal
        %
        %   IOSR.DSP.AUDIO.SOUND() replays the audio signal.

            obj.replay(obj.signal)

        end

        % validate properties

        % validate filename
        function set.filename(obj,val)
            assert(ischar(val) || isempty(val), 'iosr:audio:invalidFile', 'FILENAME must be a char array or an empty array')
            obj.filename = val;
            obj.property_changed('filename',val);
        end

        % validate fs
        function set.fs(obj,val)
            assert(isscalar(val), 'iosr:audio:invalidFs', 'FS must be a scalar')
            assert(val > 0, 'iosr:audio:invalidFs', 'FS must be greater than 0')
            obj.fs = val;
            obj.property_changed('fs',val);
        end

    end

    methods (Access = protected)

        function property_changed(obj,name,val) %#ok<INUSD>
        %PROPERTY_CHANGED handle property changes

            obj.rendered = false;
        end

        function replay(obj,x)
        %REPLAY Replay any audio signal

            sound(obj.normalize(x),obj.fs) % replay

        end

        function set_properties(obj,vgin,propNames)
        %SET_PROPERTIES Parse varargin input to set object properties
        %
        %   IOSR.DSP.AUDIO.SET_PROPERTIES(VGIN,PROPNAMES) searches through
        %   the cell array VGIN (a cell array of parameter/value pairs) for
        %   properties specified in the cell array PROPNAMES. Any matching
        %   properties are written to OBJ.

            % count arguments
            nArgs = length(vgin);
            if round(nArgs/2)~=nArgs/2
               error('iosr:audio:nameValuePair',[class(obj) ' needs propertyName/propertyValue pairs'])
            end
            % overwrite defults
            for pair = reshape(vgin,2,[]) % pair is {propName;propValue}
               IX = strcmpi(pair{1},propNames); % find match parameter names
               if any(IX)
                  % do the overwrite
                  obj.(propNames{IX}) = pair{2};
               else
                  error('iosr:audio:unknownOption','%s is not a recognized parameter name',pair{1})
               end
            end

        end

        function cpObj = copyElement(obj)
        %COPYELEMENT Overload copy method with additional functionality

            % Make a shallow copy of all properties
            cpObj = copyElement@matlab.mixin.Copyable(obj);

        end

    end

    methods (Static)

        function [y,gain] = normalize(x)
        %NORMALIZE Normalize an audio signal
        %
        %   Y = IOSR.DSP.AUDIO.NORMALIZE(X) normalises X such that
        %   ABS(Y(:))<1.
        %
        %   [Y,GAIN] = IOSR.DSP.AUDIO.NORMALIZE(X) returns the scalar gain
        %   GAIN applied to X in order to normalize it.

            gain = (1-((2*16)/(2^16)))/max(abs(x(:)));
            y = x.*gain;

        end

        function y = spat(SOFAfile,x,azimuth,elevation,fs)
        %SPAT Spatialise a sound using a SOFA file
        %
        %   IOSR.DSP.AUDIO.SPAT(SOFAFILE,X,AZIMUTH,ELEVATION) spatialises
        %   the signal X using spatialisation data contained in the SOFA
        %   file SOFAFILE at the corresponding AZIMUTH and ELEVATION. The
        %   sampling frequency is that of the SOFA data. X should be a
        %   column vector; if it is not, it will be down-mixed to a column
        %   vector.
        %
        %   IOSR.DSP.AUDIO.SPAT(...,FS) uses the sampling frequency FS for
        %   the spatialisation. If the SOFA data are not at the sampling
        %   rate FS, the data are resampled.

            assert(size(x,1)>1, 'iosr:audio:invalidX', 'X should be a column vector. Matrices will be downmixed to a column vector');

            if size(x,2)>1 % mix to mono
                x = audio.up_down_mix(x,1);
            end
            SOFAobj = SOFAload(SOFAfile); % load SOFA object
            if ~exist('fs','var')==1 % set default FS
                fs = SOFAobj.Data.SamplingRate;
            end

            % convert navigational coordinates to spherical coordinates
            if azimuth<0
                [azimuth,elevation] = nav2sph(azimuth,elevation);
            end

            % find index of corresponding IR is SOFA obj
            dist = (SOFAobj.SourcePosition(:,1)-azimuth).^2 + ...
                (SOFAobj.SourcePosition(:,2)-elevation).^2;
            [~,idx] = min(dist);

            % return IR
            IR = squeeze(SOFAobj.Data.IR(idx,:,:))';

            % resample?
            if SOFAobj.Data.SamplingRate~=fs
                disp(['Resampling audio to ' num2str(fs) ' Hz.'])
                IR = resample(IR,fs,SOFAobj.Data.SamplingRate);
            end

            % convolve
            y = zeros(length(x)+size(IR,1)-1,size(IR,2));
            for c = 1:size(IR,2)
                y(:,c) = iosr.dsp.convFft(x,IR(:,c));
            end

            % crop
            y = y(1:length(x),:);

        end

        function y = up_down_mix(x,N)
        %UP_DOWN_MIX Remix a source to a designated channel count
        %
        %   Y = IOSR.DSP.AUDIO.UP_DOWN_MIX(X,N) mixes the signal X to have
        %   the specified channel count N. Data for each channel in X
        %   should be stored down its columns. For input channel count M,
        %   the up-/down-mix coefficients are calculated as
        %   ONES(M,N)./(M*N).

            M = size(x,2);
            y = x*(ones(M,N)./(M*N));

        end

    end

    methods (Static, Access = protected)

        function ensure_path(filename)
        %ENSURE_PATH Ensure path exists for specified filename

            % get path
            filepath = fileparts(filename);
            if ~isempty(filepath)
                % ensure path exits
                if exist(filepath,'dir')~=7
                    mkdir(filepath)
                end
            end

        end

    end

end


text:
ACCEPTED

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

#### Published in
Fungal Diversity 25: 177 (2007)

#### Original name
Hyalocamposporium Révay & J. Gönczöl

### Remarks
null


text:
```
git clone git@github.com:tijptjik/thegodsproject.git && cd thegodsproject
git submodule update --init --recursive
```

### Install python dependencies
```
conda env create -n thegodsproject -f environment.yml
source activate thegodsproject
```
**NOTE** : You should always run `source activate thegodsproject` when running the pelican project locally as it activated the conda environment with all the python dependencies in it.

## Project Structure

```bash
thegodsproject
|-- content # Markdown posts for the blog
|   `-- extra # Misc files - explicitly mapped to output in pelicanconf.py
|-- develop_server.sh
|-- environment.yml # Conda Environement with Python Dependencies
|-- nest # theme
|   `-- static # CSS and fonts
|   `-- templates # HTML jinja templates
|-- Makefile # Make Tasks
|-- pelicanconf.py # Main config
|-- plugins # Submodules - don't edit
|-- publishconf.py # Config file with additional settings for production
`-- readme.md # You are here
```

### Config Files

So based on the project structure, the config is managed by :

* `pelicanconf.py`
* `publishconf.py`

## Site Development

Site development isdone following the conventions for `Pelican` [themes](http://docs.getpelican.com/en/3.6.3/themes.html) which uses [Jinja](http://jinja.pocoo.org/docs/dev/) for its templates`.

The Jinja templates are located at `nesttemplates`. Inspect the following three Jinja templates to get an idea of the site structure:

```bash
nest/templates/base.html # All pages should extend the base template
nest/templates/index.html # The landing page
nest/templates/article.html # Basis for all articles
```

### Tasks

From the project root

#### Generation for Development

```bash
make html
```

#### Live Reload

```bash
make regenerate
```

#### Web Server with Live Reload

```bash
./develop_server.sh start # generate & run server
./develop_server.sh stop # stop backgrounded server
# or
make devserver
```

#### Publish to Github Pages

```bash
make github
```

#### Config Options

* [Available Markdown Extensions](http://pythonhosted.org/Markdown/extensions/)
* [Available Pelican Plugins](https://github.com/getpelican/pelican-plugins#pelican-plugins)


text:
package com.example.android.architecture.blueprints.todoapp.addedittask;

import android.os.Bundle;
import android.support.annotation.VisibleForTesting;
import android.support.test.espresso.IdlingResource;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;

import com.example.android.architecture.blueprints.todoapp.Injection;
import com.example.android.architecture.blueprints.todoapp.R;
import com.example.android.architecture.blueprints.todoapp.util.ActivityUtils;
import com.example.android.architecture.blueprints.todoapp.util.EspressoIdlingResource;

/**
 * Displays an add or edit task screen.
 */
public class AddEditTaskActivity extends AppCompatActivity {

    public static final int REQUEST_ADD_TASK = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.addtask_act);

        // Set up the toolbar.
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setDisplayShowHomeEnabled(true);

        AddEditTaskFragment addEditTaskFragment =
                (AddEditTaskFragment) getSupportFragmentManager().findFragmentById(R.id.contentFrame);

        String taskId = getIntent().getStringExtra(AddEditTaskFragment.ARGUMENT_EDIT_TASK_ID);

        if (addEditTaskFragment == null) {
            addEditTaskFragment = AddEditTaskFragment.newInstance();

            if (getIntent().hasExtra(AddEditTaskFragment.ARGUMENT_EDIT_TASK_ID)) {
                actionBar.setTitle(R.string.edit_task);
                Bundle bundle = new Bundle();
                bundle.putString(AddEditTaskFragment.ARGUMENT_EDIT_TASK_ID, taskId);
                addEditTaskFragment.setArguments(bundle);
            } else {
                actionBar.setTitle(R.string.add_task);
            }

            ActivityUtils.addFragmentToActivity(getSupportFragmentManager(),
                    addEditTaskFragment, R.id.contentFrame);
        }

        // Create the presenter
        AddEditTaskPresenter presenter =  new AddEditTaskPresenter(
                taskId,
                Injection.provideTasksRepository(getApplicationContext()),
                addEditTaskFragment,
                Injection.providerSchedulerProvider());

        // Create the ViewModel
        AddEditTaskViewModel addEditTaskViewModel =
                new AddEditTaskViewModel(presenter);
        addEditTaskFragment.setViewModel(addEditTaskViewModel);
    }

    @Override
    public boolean onSupportNavigateUp() {
        onBackPressed();
        return true;
    }

    @VisibleForTesting
    public IdlingResource getCountingIdlingResource() {
        return EspressoIdlingResource.getIdlingResource();
    }
}


text:
<?php

// File Security Check
if ( ! defined( 'ABSPATH' ) ) exit;
?>
<?php
/*-----------------------------------------------------------------------------------
WP Email Template Admin Page

TABLE OF CONTENTS

- var menu_slug
- var page_data

- __construct()
- page_init()
- page_data()
- add_admin_menu()
- tabs_include()
- admin_settings_page()

-----------------------------------------------------------------------------------*/

class WP_Email_Template_Admin_Page extends WP_Email_Tempate_Admin_UI
{
	/**
	 * @var string
	 */
	private $menu_slug = 'wp_email_template';

	/**
	 * @var array
	 */
	private $page_data;

	/*-----------------------------------------------------------------------------------*/
	/* __construct() */
	/* Settings Constructor */
	/*-----------------------------------------------------------------------------------*/
	public function __construct() {
		$this->page_init();
		$this->tabs_include();
	}

	/*-----------------------------------------------------------------------------------*/
	/* page_init() */
	/* Page Init */
	/*-----------------------------------------------------------------------------------*/
	public function page_init() {

		add_filter( $this->plugin_name . '_add_admin_menu', array( $this, 'add_admin_menu' ) );
	}

	/*-----------------------------------------------------------------------------------*/
	/* page_data() */
	/* Get Page Data */
	/*-----------------------------------------------------------------------------------*/
	public function page_data() {

		$page_data = array(
			array(
				'type'				=> 'menu',
				'page_title'		=> __( 'WP Email', 'wp_email_template' ),
				'menu_title'		=> __( 'WP Email', 'wp_email_template' ),
				'capability'		=> 'manage_options',
				'menu_slug'			=> $this->menu_slug,
				'function'			=> 'wp_email_template_admin_page_show',
				'icon_url'			=> '',
				'position'			=> '50.2456',
				'admin_url'			=> 'admin.php',
				'callback_function' => '',
				'script_function' 	=> '',
				'view_doc'			=> '',
			),
			array(
				'type'				=> 'submenu',
				'parent_slug'		=> $this->menu_slug,
				'page_title'		=> __( 'Template', 'wp_email_template' ),
				'menu_title'		=> __( 'Template', 'wp_email_template' ),
				'capability'		=> 'manage_options',
				'menu_slug'			=> $this->menu_slug,
				'function'			=> 'wp_email_template_admin_page_show',
				'admin_url'			=> 'admin.php',
				'callback_function' => '',
				'script_function' 	=> '',
				'view_doc'			=> '',
			)
		);

		if ( $this->page_data ) return $this->page_data;
		return $this->page_data = $page_data;

	}

	/*-----------------------------------------------------------------------------------*/
	/* add_admin_menu() */
	/* Add This page to menu on left sidebar */
	/*-----------------------------------------------------------------------------------*/
	public function add_admin_menu( $admin_menu ) {

		//if ( ! is_array( $admin_menu ) ) $admin_menu = array();
		//$admin_menu[] = $this->page_data();
		if ( ! is_array( $admin_menu ) ) $admin_menu = array();
		$admin_menu = array_merge( $this->page_data(), $admin_menu );

		return $admin_menu;
	}

	// fix conflict with mandrill plugin
	public function remove_mandrill_notice() {
		remove_action( 'admin_notices', array( 'wpMandrill', 'adminNotices' ) );
		global $wp_et_send_wp_emails;
		remove_action( 'admin_notices', array( $wp_et_send_wp_emails, 'wp_mail_declared' ) );
	}

	/*-----------------------------------------------------------------------------------*/
	/* tabs_include() */
	/* Include all tabs into this page
	/*-----------------------------------------------------------------------------------*/
	public function tabs_include() {

		if ( is_admin() && in_array (basename($_SERVER['PHP_SELF']), array('admin.php') ) && isset( $_GET['page'] ) && $_GET['page'] == 'wp_email_template' ) {
			require_once( ABSPATH . 'wp-includes/pluggable.php' );
			add_action('init' , array( $this, 'remove_mandrill_notice' ) );
		}

		include_once( $this->admin_plugin_dir() . '/tabs/admin-general-tab.php' );
		include_once( $this->admin_plugin_dir() . '/tabs/admin-style-header-image-tab.php' );
		include_once( $this->admin_plugin_dir() . '/tabs/admin-style-header-tab.php' );
		include_once( $this->admin_plugin_dir() . '/tabs/admin-style-body-tab.php' );
		include_once( $this->admin_plugin_dir() . '/tabs/admin-style-footer-tab.php' );
		include_once( $this->admin_plugin_dir() . '/tabs/admin-social-media-tab.php' );
		include_once( $this->admin_plugin_dir() . '/tabs/admin-exclude-emails-tab.php' );

	}

	/*-----------------------------------------------------------------------------------*/
	/* admin_settings_page() */
	/* Show Settings Page */
	/*-----------------------------------------------------------------------------------*/
	public function admin_settings_page() {
		global $wp_email_template_admin_init;
		$my_page_data = $this->page_data();
		$my_page_data = array_values( $my_page_data );

		$wp_email_template_admin_init->admin_settings_page( $my_page_data[1] );
	}

}

global $wp_email_template_admin_page;
$wp_email_template_admin_page = new WP_Email_Template_Admin_Page();

/**
 * wp_email_template_admin_page_show()
 * Define the callback function to show page content
 */
function wp_email_template_admin_page_show() {
	global $wp_email_template_admin_page;
	$wp_email_template_admin_page->admin_settings_page();
}

?>


text:
const Paint = require('./paint');
const Pathways = require('./pathways');
const Search = require('./search');
const Interactions = require('./interactions');
const Enrichment = require('./enrichment');
const Factoids = require('./factoids');

module.exports = {
  Paint,
  Search,
  Pathways,
  Interactions,
  Enrichment,
  Factoids
};