text:
require "test_helper"

class RubygemTest < ActiveSupport::TestCase
  context "with a saved rubygem" do
    setup do
      @rubygem = Rubygem.new(name: "SomeGem")
    end
    subject { @rubygem }

    should have_many(:owners).through(:ownerships)
    should have_many(:ownerships).dependent(:destroy)
    should have_many(:subscribers).through(:subscriptions)
    should have_many(:subscriptions).dependent(:destroy)
    should have_many(:versions).dependent(:destroy)
    should have_many(:web_hooks).dependent(:destroy)
    should have_one(:linkset).dependent(:destroy)
    should validate_uniqueness_of(:name).case_insensitive
    should allow_value("rails").for(:name)
    should allow_value("awesome42").for(:name)
    should allow_value("factory_girl").for(:name)
    should allow_value("rack-test").for(:name)
    should allow_value("perftools.rb").for(:name)
    should_not allow_value("\342\230\203").for(:name)
    should_not allow_value("2.2").for(:name)
    should_not allow_value("Ruby").for(:name)
    should_not allow_value(".omghi").for(:name)
    should_not allow_value("-omghi").for(:name)
    should_not allow_value("_omghi").for(:name)

    context "that has an invalid name already persisted" do
      setup do
        subject.save!
        subject.update_column(:name, "_")
      end

      should "consider the gem valid" do
        assert_predicate subject, :valid?
      end
    end

    should "be invalid with name longer than maximum field length" do
      @rubygem.name = "r" * (Gemcutter::MAX_FIELD_LENGTH + 1)
      refute_predicate @rubygem, :valid?
      assert_equal(["is too long (maximum is 255 characters)"], @rubygem.errors.messages[:name])
    end

    should "reorder versions with platforms properly" do
      version3_ruby  = create(:version, rubygem: @rubygem, number: "3.0.0", platform: "ruby")
      version3_mswin = create(:version, rubygem: @rubygem, number: "3.0.0", platform: "mswin")
      version2_ruby  = create(:version, rubygem: @rubygem, number: "2.0.0", platform: "ruby")
      version1_linux = create(:version, rubygem: @rubygem, number: "1.0.0", platform: "linux")

      @rubygem.reorder_versions

      assert_equal 0, version3_ruby.reload.position
      assert_equal 0, version3_mswin.reload.position
      assert_equal 1, version2_ruby.reload.position
      assert_equal 2, version1_linux.reload.position

      latest_versions = Version.latest
      assert_includes latest_versions, version3_ruby
      assert_includes latest_versions, version3_mswin

      assert_equal version3_ruby, @rubygem.versions.most_recent
    end

    should "order latest platform gems with latest uniquely" do
      pre  = create(:version,
        rubygem: @rubygem,
        number: "1.5.0.pre",
        platform: "ruby",
        prerelease: true)
      ming = create(:version,
        rubygem: @rubygem,
        number: "1.4.2.1",
        platform: "x86-mingw32")
      win = create(:version,
        rubygem: @rubygem,
        number: "1.4.2.1",
        platform: "x86-mswin32")
      ruby = create(:version,
        rubygem: @rubygem,
        number: "1.4.2",
        platform: "ruby")
      java = create(:version,
        rubygem: @rubygem,
        number: "1.4.2",
        platform: "java")
      old = create(:version,
        rubygem: @rubygem,
        number: "1.4.1",
        platform: "ruby")

      @rubygem.reorder_versions

      refute pre.reload.latest
      refute old.reload.latest
      assert ming.reload.latest
      assert win.reload.latest
      assert ruby.reload.latest
      assert java.reload.latest
    end

    should "not return platform gem for latest if the ruby version is old" do
      version3_mswin = create(:version, rubygem: @rubygem, number: "3.0.0", platform: "mswin")
      version2_ruby  = create(:version, rubygem: @rubygem, number: "2.0.0", platform: "ruby")

      @rubygem.reorder_versions

      assert_equal version2_ruby.reload, @rubygem.versions.most_recent
      assert version3_mswin.reload.latest
    end

    should "not have a most recent version if no versions exist" do
      assert_nil @rubygem.versions.most_recent
    end

    should "return the ruby version for most_recent if one exists" do
      create(:version,
        rubygem: @rubygem,
        number: "3.0.0",
        platform: "mswin",
        built_at: 1.year.from_now)
      version3_ruby = create(:version, rubygem: @rubygem, number: "3.0.0", platform: "ruby")

      @rubygem.reorder_versions

      assert_equal version3_ruby, @rubygem.versions.most_recent
    end

    should "have a most_recent version if only a platform version exists" do
      version1 = create(:version, rubygem: @rubygem, number: "1.0.0", platform: "linux")

      assert_equal version1, @rubygem.reload.versions.most_recent
    end

    should "return the release version for most_recent if one exists" do
      create(:version, rubygem: @rubygem, number: "2.0.pre", platform: "ruby")
      version1 = create(:version, rubygem: @rubygem, number: "1.0.0", platform: "ruby")

      assert_equal version1, @rubygem.reload.versions.most_recent
    end

    should "have a most_recent version if only a prerelease version exists" do
      version1pre = create(:version, rubygem: @rubygem, number: "1.0.pre", platform: "ruby")

      assert_equal version1pre, @rubygem.reload.versions.most_recent
    end

    should "return the most_recent indexed version when a more recent yanked version exists" do
      create(:version, rubygem: @rubygem, number: "0.1.1", indexed: false)
      indexed_v1 = create(:version, rubygem: @rubygem, number: "0.1.0", indexed: true)

      assert_equal indexed_v1.reload, @rubygem.reload.versions.most_recent
    end

    should "return latest version on the basis of version number" do
      version = create(:version, rubygem: @rubygem, number: "0.1.1", platform: "ruby", latest: true)
      create(:version, rubygem: @rubygem, number: "0.1.2.rc1", platform: "ruby")
      create(:version, rubygem: @rubygem, number: "0.1.0", platform: "jruby", latest: true)

      assert_equal version, @rubygem.latest_version
    end

    context "#public_versions_with_extra_version" do
      setup do
        @first_version = FactoryBot.create(:version,
          rubygem: @rubygem,
          number: "1.0.0",
          position: 1)
        @extra_version = FactoryBot.create(:version,
          rubygem: @rubygem,
          number: "0.1.0",
          position: 2)
      end
      should "include public versions" do
        assert_includes @rubygem.public_versions_with_extra_version(@extra_version), @first_version
      end
      should "include extra version" do
        assert_includes @rubygem.public_versions_with_extra_version(@extra_version), @extra_version
      end
      should "maintain proper ordering" do
        versions = @rubygem.public_versions_with_extra_version(@extra_version)
        assert_equal versions, versions.sort_by(&:position)
      end
      should "not duplicate versions" do
        versions = @rubygem.public_versions_with_extra_version(@first_version)
        assert_equal versions.count, versions.uniq.count
      end
    end

    should "update references in dependencies when destroyed" do
      @rubygem.save!
      dependency = create(:dependency, rubygem: @rubygem)

      @rubygem.destroy

      dependency.reload
      assert_nil dependency.rubygem_id
      assert_equal dependency.unresolved_name, @rubygem.name
    end
  end

  context "with reverse dependencies" do
    setup do
      @dependency            = create(:rubygem)
      @gem_one               = create(:rubygem)
      @gem_two               = create(:rubygem)
      gem_three              = create(:rubygem)
      gem_four               = create(:rubygem)
      version_one            = create(:version, rubygem: @gem_one)
      version_two            = create(:version, rubygem: @gem_two)
      _version_three_latest  = create(:version, rubygem: gem_three, number: "1.0")
      version_three_earlier  = create(:version, rubygem: gem_three, number: "0.5")
      yanked_version         = create(:version, :yanked, rubygem: gem_four)

      create(:dependency, :runtime, version: version_one, rubygem: @dependency)
      create(:dependency, :development, version: version_two, rubygem: @dependency)
      create(:dependency, version: version_three_earlier, rubygem: @dependency)
      create(:dependency, version: yanked_version, rubygem: @dependency)
    end

    context "#reverse_dependencies" do
      should "return dependent gems of latest indexed version" do
        gem_list = @dependency.reverse_dependencies

        assert_equal 2, gem_list.size

        assert_includes gem_list, @gem_one
        assert_includes gem_list, @gem_two
        refute_includes gem_list, @gem_three
        refute_includes gem_list, @gem_four
      end
    end

    context "#reverse_runtime_dependencies" do
      should "return runtime dependent rubygems" do
        gem_list = @dependency.reverse_runtime_dependencies
        assert_equal 1, gem_list.size

        assert_includes gem_list, @gem_one
        refute_includes gem_list, @gem_two
      end
    end

    context "#reverse_development_dependencies" do
      should "return development dependent rubygems" do
        gem_list = @dependency.reverse_development_dependencies
        assert_equal 1, gem_list.size

        assert_includes gem_list, @gem_two
        refute_includes gem_list, @gem_one
      end
    end
  end

  context "with a rubygem" do
    setup do
      @rubygem = build(:rubygem, linkset: nil)
    end

    ["1337", "Snakes!"].each do |bad_name|
      should "not accept #{bad_name.inspect} as a name" do
        @rubygem.name = bad_name
        refute_predicate @rubygem, :valid?
        assert_match(/Name/, @rubygem.all_errors)
      end
    end

    should "not accept an Array as name" do
      @rubygem.name = ["zomg"]
      refute_predicate @rubygem, :valid?
    end

    should "return linkset errors in #all_errors" do
      @specification = gem_specification_from_gem_fixture("test-0.0.0")
      @specification.homepage = "badurl.com"

      assert_raise ActiveRecord::RecordInvalid do
        @rubygem.update_linkset!(@specification)
      end

      assert_equal "Home does not appear to be a valid URL", @rubygem.all_errors
    end

    should "return version errors in #all_errors" do
      @version = build(:version)
      @specification = gem_specification_from_gem_fixture("test-0.0.0")
      @specification.authors = [3]

      assert_raise ActiveRecord::RecordInvalid do
        @rubygem.update_versions!(@version, @specification)
      end

      assert_equal "Authors must be an Array of Strings", @rubygem.all_errors(@version)
    end

    should "return array of author names in #authors_array" do
      @version = build(:version)
      assert_equal ["Joe User"], @version.authors_array
    end

    should "return more than one error joined for #all_errors" do
      @specification = gem_specification_from_gem_fixture("test-0.0.0")
      @specification.homepage = "badurl.com"
      @rubygem.name = "1337"

      refute_predicate @rubygem, :valid?
      assert_raise ActiveRecord::RecordInvalid do
        @rubygem.update_linkset!(@specification)
      end

      assert_match "Name must include at least one letter, Home does not appear to be a valid URL",
        @rubygem.all_errors
    end

    context "with a user" do
      setup do
        @user = create(:user)
        @rubygem.save
      end

      should "be able to assign ownership when no owners exist" do
        @rubygem.create_ownership(@user)
        assert_equal @rubygem.reload.owners, [@user]
      end

      should "not be able to assign ownership when owners exist" do
        @new_user = create(:user)
        create(:ownership, rubygem: @rubygem, user: @new_user)
        @rubygem.create_ownership(@user)
        assert_equal @rubygem.reload.owners, [@new_user]
      end
    end

    context "with a user" do
      setup do
        @rubygem.save
        @user = create(:user)
      end

      should "be owned by a user in ownership" do
        create(:ownership, user: @user, rubygem: @rubygem)
        assert @rubygem.owned_by?(@user)
        refute_predicate @rubygem, :unowned?
      end

      should "be not owned if no ownerships" do
        assert_empty @rubygem.ownerships
        refute @rubygem.owned_by?(@user)
        assert_predicate @rubygem, :unowned?
      end

      should "be not owned if no user" do
        refute @rubygem.owned_by?(nil)
        assert_predicate @rubygem, :unowned?
      end
    end

    context "with subscribed users" do
      setup do
        @subscribed_user   = create(:user)
        @unsubscribed_user = create(:user)
        create(:subscription, rubygem: @rubygem, user: @subscribed_user)
      end

      should "only fetch the subscribed users with #subscribers" do
        assert_contains @rubygem.subscribers, @subscribed_user
        assert_does_not_contain @rubygem.subscribers, @unsubscribed_user
      end
    end

    should "return name with version for #to_s" do
      @rubygem.save
      create(:version, number: "0.0.0", rubygem: @rubygem)
      assert_equal "#{@rubygem.name} (#{@rubygem.versions.most_recent})", @rubygem.to_s
    end

    should "return name for #to_s if current version doesn't exist" do
      assert_equal @rubygem.name, @rubygem.to_s
    end

    should "return name as slug with only allowed characters" do
      @rubygem.name = "rails?!"
      assert_equal "rails", @rubygem.to_param
    end

    should "return a bunch of json" do
      version = create(:version, rubygem: @rubygem)
      run_dep = create(:dependency, :runtime, version: version)
      dev_dep = create(:dependency, :development, version: version)

      hash = JSON.load(@rubygem.to_json)

      assert_equal @rubygem.name, hash["name"]
      assert_equal @rubygem.downloads, hash["downloads"]
      assert_equal @rubygem.versions.most_recent.number, hash["version"]
      assert_equal @rubygem.versions.most_recent.created_at.as_json, hash["version_created_at"]
      assert_equal @rubygem.versions.most_recent.downloads_count, hash["version_downloads"]
      assert_equal @rubygem.versions.most_recent.platform, hash["platform"]
      assert_equal @rubygem.versions.most_recent.authors, hash["authors"]
      assert_equal @rubygem.versions.most_recent.info, hash["info"]
      assert_equal @rubygem.versions.most_recent.metadata, hash["metadata"]
      assert_equal "#{Gemcutter::PROTOCOL}://#{Gemcutter::HOST}/gems/#{@rubygem.name}",
        hash["project_uri"]
      assert_equal "#{Gemcutter::PROTOCOL}://#{Gemcutter::HOST}/gems/" \
                   "#{@rubygem.versions.most_recent.full_name}.gem", hash["gem_uri"]

      assert_equal JSON.load(dev_dep.to_json), hash["dependencies"]["development"].first
      assert_equal JSON.load(run_dep.to_json), hash["dependencies"]["runtime"].first
    end

    should "return a bunch of xml" do
      version = create(:version, rubygem: @rubygem)
      run_dep = create(:dependency, :runtime, version: version)
      dev_dep = create(:dependency, :development, version: version)

      doc = Nokogiri.parse(@rubygem.to_xml)

      assert_equal "rubygem",
        doc.root.name
      assert_equal @rubygem.name,
        doc.at_css("rubygem > name").content
      assert_equal @rubygem.downloads.to_s,
        doc.at_css("downloads").content
      assert_equal @rubygem.versions.most_recent.number,
        doc.at_css("version").content
      assert_equal @rubygem.versions.most_recent.downloads_count.to_s,
        doc.at_css("version-downloads").content
      assert_equal @rubygem.versions.most_recent.authors,
        doc.at_css("authors").content
      assert_equal @rubygem.versions.most_recent.info,
        doc.at_css("info").content
      assert_equal @rubygem.versions.most_recent.metadata["foo"],
        doc.at_css("metadata foo").content
      assert_equal @rubygem.versions.most_recent.sha256_hex,
        doc.at_css("sha").content
      assert_equal "#{Gemcutter::PROTOCOL}://#{Gemcutter::HOST}/gems/#{@rubygem.name}",
        doc.at_css("project-uri").content
      assert_equal "#{Gemcutter::PROTOCOL}://#{Gemcutter::HOST}/gems/" \
                   "#{@rubygem.versions.most_recent.full_name}.gem", doc.at_css("gem-uri").content

      assert_equal dev_dep.name, doc.at_css("dependencies development dependency name").content
      assert_equal run_dep.name, doc.at_css("dependencies runtime dependency name").content
    end

    context "with metadata" do
      setup do
        @rubygem.linkset = build(:linkset)
        @version = create(:version, rubygem: @rubygem)
      end

      should "prefer metadata over links in JSON" do
        @version.update!(
          metadata: {
            "homepage_uri" => "http://example.com/home",
            "wiki_uri" => "http://example.com/wiki",
            "documentation_uri" => "http://example.com/docs",
            "mailing_list_uri" => "http://example.com/mail",
            "source_code_uri" => "http://example.com/code",
            "bug_tracker_uri" => "http://example.com/bugs",
            "changelog_uri" => "http://example.com/change",
            "funding_uri" => "http://example.com/funding"
          }
        )

        hash = MultiJson.load(@rubygem.to_json)

        assert_equal "http://example.com/home", hash["homepage_uri"]
        assert_equal "http://example.com/wiki", hash["wiki_uri"]
        assert_equal "http://example.com/docs", hash["documentation_uri"]
        assert_equal "http://example.com/mail", hash["mailing_list_uri"]
        assert_equal "http://example.com/code", hash["source_code_uri"]
        assert_equal "http://example.com/bugs", hash["bug_tracker_uri"]
        assert_equal "http://example.com/change", hash["changelog_uri"]
        assert_equal "http://example.com/funding", hash["funding_uri"]
      end

      should "return version documentation url if metadata and linkset docs is empty" do
        @version.update!(metadata: {})
        @rubygem.linkset.update_attribute(:docs, "")

        hash = JSON.load(@rubygem.to_json)

        assert_equal "https://www.rubydoc.info/gems/#{@rubygem.name}/#{@version.number}", hash["documentation_uri"]
      end
    end

    context "with a linkset" do
      setup do
        @rubygem = build(:rubygem)
        @version = create(:version, rubygem: @rubygem)
      end

      should "return a bunch of JSON" do
        hash = JSON.load(@rubygem.to_json)

        assert_equal @rubygem.linkset.home, hash["homepage_uri"]
        assert_equal @rubygem.linkset.wiki, hash["wiki_uri"]
        assert_equal @rubygem.linkset.docs, hash["documentation_uri"]
        assert_equal @rubygem.linkset.mail, hash["mailing_list_uri"]
        assert_equal @rubygem.linkset.code, hash["source_code_uri"]
        assert_equal @rubygem.linkset.bugs, hash["bug_tracker_uri"]
      end

      should "return version documentation uri if linkset docs is empty" do
        @rubygem.linkset.docs = ""
        hash = JSON.load(@rubygem.to_json)

        assert_equal "https://www.rubydoc.info/gems/#{@rubygem.name}/#{@version.number}", hash["documentation_uri"]
      end

      should "return a bunch of XML" do
        doc = Nokogiri.parse(@rubygem.to_xml)

        assert_equal @rubygem.linkset.home, doc.at_css("homepage-uri").content
        assert_equal @rubygem.linkset.wiki, doc.at_css("wiki-uri").content
        assert_equal @rubygem.linkset.docs, doc.at_css("documentation-uri").content
        assert_equal @rubygem.linkset.mail, doc.at_css("mailing-list-uri").content
        assert_equal @rubygem.linkset.code, doc.at_css("source-code-uri").content
        assert_equal @rubygem.linkset.bugs, doc.at_css("bug-tracker-uri").content
      end
    end
  end

  context "with some rubygems" do
    setup do
      @rubygem_without_version = create(:rubygem)
      @rubygem_with_version = create(:rubygem)
      @rubygem_with_versions = create(:rubygem)

      create(:version, rubygem: @rubygem_with_version)
      3.times { create(:version, rubygem: @rubygem_with_versions) }

      @owner = create(:user)
      create(:ownership, rubygem: @rubygem_with_version, user: @owner)
      create(:ownership, rubygem: @rubygem_with_versions, user: @owner)
    end

    should "return only gems with one version" do
      refute_includes Rubygem.with_one_version, @rubygem_without_version
      assert_includes Rubygem.with_one_version, @rubygem_with_version
      refute_includes Rubygem.with_one_version, @rubygem_with_versions
    end

    should "return only gems with versions for #with_versions" do
      refute_includes Rubygem.with_versions, @rubygem_without_version
      assert_includes Rubygem.with_versions, @rubygem_with_version
      assert_includes Rubygem.with_versions, @rubygem_with_versions
    end

    should "be hosted or not" do
      refute_predicate @rubygem_without_version, :hosted?
      assert_predicate @rubygem_with_version, :hosted?
    end

    context "when yanking the last version of a gem with an owner" do
      setup do
        @rubygem_with_version.versions.first.update! indexed: false
      end

      should "still be owned" do
        assert @rubygem_with_version.owned_by?(@owner)
      end

      should "no longer be indexed" do
        assert_predicate @rubygem_with_version.versions.indexed.count, :zero?
      end
    end

    context "when yanking one of many versions of a gem" do
      setup do
        @rubygem_with_versions.versions.first.update! indexed: false
      end
      should "remain owned" do
        refute_predicate @rubygem_with_versions.reload, :unowned?
      end
      should "then know there is a yanked version" do
        assert_predicate @rubygem_with_versions, :yanked_versions?
      end
    end
  end

  context "with some gems and some that don't have versions" do
    setup do
      @thin = create(:rubygem, name: "thin", created_at: 1.year.ago,  downloads: 20)
      @rake = create(:rubygem, name: "rake", created_at: 1.month.ago, downloads: 10)
      @json = create(:rubygem, name: "json", created_at: 1.week.ago,  downloads: 5)
      @thor = create(:rubygem, name: "thor", created_at: 2.days.ago,  downloads: 3)
      @rack = create(:rubygem, name: "rack", created_at: 1.day.ago,   downloads: 2)
      @dust = create(:rubygem, name: "dust", created_at: 3.days.ago,  downloads: 1)
      @haml = create(:rubygem, name: "haml")
      @new = build(:rubygem)

      @gems = [@thin, @rake, @json, @thor, @rack, @dust]
      @gems.each { |g| create(:version, rubygem: g) }
    end

    should "be pushable if gem is a new record" do
      assert_predicate @new, :pushable?
    end

    context "gem has no versions" do
      should "be pushable if gem is less than one month old" do
        assert_predicate @haml, :pushable?
      end

      should "be pushable if gem was yanked more than 100 days ago" do
        @haml.update(created_at: 101.days.ago, updated_at: 101.days.ago)
        assert_predicate @haml, :pushable?
      end

      should "not be pushable if gem is older than a month and yanked less than 100 days ago" do
        @haml.update(created_at: 99.days.ago, updated_at: 99.days.ago)
        refute_predicate @haml, :pushable?
      end
    end

    should "not be pushable if it has versions" do
      refute_predicate @thin, :pushable?
    end

    should "only return the latest gems with versions" do
      assert_equal [@rack, @thor, @dust, @json, @rake],        Rubygem.latest
      assert_equal [@rack, @thor, @dust, @json, @rake, @thin], Rubygem.latest(6)
    end

    should "only latest downloaded versions" do
      assert_equal [@thin, @rake, @json, @thor, @rack],        Rubygem.downloaded
      assert_equal [@thin, @rake, @json, @thor, @rack, @dust], Rubygem.downloaded(6)
    end

    context ".total_count" do
      setup { @expected_total = 6 }

      should "give a count of only rubygems with versions" do
        assert_equal @expected_total, Rubygem.total_count
      end
    end
  end

  context "when some gems exist with titles and versions" do
    setup do
      @apple_pie = create(:rubygem, name: "apple", downloads: 1)
      create(:version, description: "pie", rubygem: @apple_pie)

      @apple_crisp = create(:rubygem, name: "apple_crisp", downloads: 10)
      create(:version, description: "pie", rubygem: @apple_crisp)

      @orange_julius = create(:rubygem, name: "orange")
      create(:version, description: "julius", rubygem: @orange_julius)
    end

    context "#legacy_search" do
      should "find rubygems by name" do
        assert_includes Rubygem.legacy_search("apple"), @apple_pie
        assert_includes Rubygem.legacy_search("orange"), @orange_julius

        refute_includes Rubygem.legacy_search("apple"), @orange_julius
        refute_includes Rubygem.legacy_search("orange"), @apple_pie
      end

      should "find rubygems by name with extra spaces" do
        assert_includes Rubygem.legacy_search("apple  "), @apple_pie
        assert_includes Rubygem.legacy_search("orange   "), @orange_julius
        assert_equal Rubygem.legacy_search("apple"), Rubygem.legacy_search("apple ")

        refute_includes Rubygem.legacy_search("apple  "), @orange_julius
        refute_includes Rubygem.legacy_search("orange   "), @apple_pie
      end

      should "find rubygems case insensitively" do
        assert_includes Rubygem.legacy_search("APPLE"), @apple_pie
      end

      should "find rubygems with missing punctuation" do
        assert_includes Rubygem.legacy_search("apple crisp"), @apple_crisp
        refute_includes Rubygem.legacy_search("apple crisp"), @apple_pie
      end

      should "sort results by number of downloads, descending" do
        assert_equal [@apple_crisp, @apple_pie], Rubygem.legacy_search("apple")
      end
    end

    should "find exact match by name on #name_is" do
      assert_equal @apple_crisp, Rubygem.name_is("apple_crisp").first
    end

    should "find exact match by name with extra spaces on #name_is" do
      assert_equal @apple_crisp, Rubygem.name_is("apple_crisp ").first
    end
  end

  context "building a new Rubygem" do
    context "from a Gem::Specification with no dependencies" do
      setup do
        @specification = gem_specification_from_gem_fixture("test-0.0.0")
        @rubygem       = Rubygem.new(name: @specification.name)
        @version       = @rubygem.find_or_initialize_version_from_spec(@specification)
        @version.sha256 = "dummy"
        @rubygem.update_attributes_from_gem_specification!(@version, @specification)
      end

      should "create a rubygem and associated records" do
        refute_predicate @rubygem, :new_record?
        assert_predicate @rubygem.versions, :present?
      end

      should "have the homepage set properly" do
        assert_equal @specification.homepage, @rubygem.linkset.home
      end
    end

    context "from a Gem::Specification with dependencies on unknown gems" do
      setup do
        @specification = gem_specification_from_gem_fixture("with_dependencies-0.0.0")
        @rubygem       = Rubygem.new(name: @specification.name)
        @version       = @rubygem.find_or_initialize_version_from_spec(@specification)
        @version.sha256 = "dummy"
      end

      should "save the gem" do
        @rubygem.update_attributes_from_gem_specification!(@version, @specification)

        assert Rubygem.find_by_name("with_dependencies")
        assert_nil Rubygem.find_by_name("thoughtbot-shoulda")
        assert_nil Rubygem.find_by_name("rake")

        assert_equal %w[rake thoughtbot-shoulda],
          @version.dependencies.map(&:unresolved_name).sort
      end
    end

    context "that was previous an unresolved dependency" do
      setup do
        @specification = gem_specification_from_gem_fixture("with_dependencies-0.0.0")
        @rubygem       = Rubygem.new(name: @specification.name)
        @version       = @rubygem.find_or_initialize_version_from_spec(@specification)
        @version.sha256 = "dummy"

        @rubygem.update_attributes_from_gem_specification!(@version, @specification)

        @rack_dep = @version.dependencies.find_by(unresolved_name: "rake")
      end

      should "update the dependency" do
        rubygem = Rubygem.create(name: "rake")

        dependency = Dependency.find_by_id(@rack_dep.id)
        assert_nil dependency.unresolved_name
        assert_equal rubygem, dependency.rubygem
      end
    end

    context "from a Gem::Specification with pre-existing dependencies" do
      setup do
        @specification = gem_specification_from_gem_fixture("with_dependencies-0.0.0")
        Rubygem.create(name: "thoughtbot-shoulda")
        Rubygem.create(name: "rake")

        @rubygem       = Rubygem.new(name: @specification.name)
        @version       = @rubygem.find_or_initialize_version_from_spec(@specification)
        @version.sha256 = "dummy"
      end

      should "save the gem" do
        assert_nothing_raised do
          @rubygem.update_attributes_from_gem_specification!(@version, @specification)
        end

        refute_predicate @rubygem, :new_record?
        refute_predicate @version, :new_record?
        assert_equal 1, @rubygem.versions.count
        assert_equal 1, @rubygem.versions_count
        assert_equal 2, @version.dependencies.count
        assert Rubygem.exists?(name: "thoughtbot-shoulda")
        assert Rubygem.exists?(name: "rake")
      end
    end

    context "from a Gem:Specification of older version" do
      setup do
        linkset  = create(:linkset, home: "http://latest.com")
        @rubygem = create(:rubygem, name: "test", number: "1.0.0", linkset: linkset)
        gemspec  = new_gemspec("test", "0.0.1", "test", "ruby") { |spec| spec.homepage = "http://test.com" }
        version  = @rubygem.find_or_initialize_version_from_spec(gemspec)
        @rubygem.update_attributes_from_gem_specification!(version, gemspec)
      end

      should "not update linkset" do
        assert_equal "http://latest.com", @rubygem.linkset.home
      end
    end
  end

  context "#protected_days" do
    setup do
      @rubygem = create(:rubygem)
      @rubygem.update_attribute(:updated_at, 99.days.ago)
    end

    should "return number of days left till the gem namespace is protected" do
      assert_equal 1, @rubygem.protected_days
    end
  end

  context "with downloaded gems and versions created at specific times" do
    setup do
      @rubygem1 = create(:rubygem, downloads: 10)
      @rubygem2 = create(:rubygem, downloads: 20)
      @rubygem3 = create(:rubygem, downloads: 30)
      create(:version, rubygem: @rubygem1, created_at: (Gemcutter::NEWS_DAYS_LIMIT - 2.days).ago)
      create(:version, rubygem: @rubygem2, created_at: (Gemcutter::NEWS_DAYS_LIMIT - 1.day).ago)
      create(:version, rubygem: @rubygem3, created_at: (Gemcutter::POPULAR_DAYS_LIMIT + 1.day).ago)
    end

    context ".news" do
      setup do
        @news = Rubygem.news(Gemcutter::NEWS_DAYS_LIMIT)
      end

      should "not include gems updated prior to Gemcutter::NEWS_DAYS_LIMIT days ago" do
        assert_not_includes @news, @rubygem3
      end

      should "order by created_at of gem version" do
        expected_order = [@rubygem1, @rubygem2]
        assert_equal expected_order, @news
      end
    end

    context ".popular" do
      setup do
        @popular_gems = Rubygem.popular(Gemcutter::POPULAR_DAYS_LIMIT)
      end

      should "not include gems updated prior to Gemcutter::POPULAR_DAYS_LIMIT days ago" do
        assert_not_includes @popular_gems, @rubygem3
      end

      should "order by number of downloads" do
        expected_order = [@rubygem2, @rubygem1]
        assert_equal expected_order, @popular_gems
      end
    end
  end

  context "unconfirmed ownership" do
    setup do
      @rubygem               = create(:rubygem)
      @confirmed_owner       = create(:user)
      @unconfirmed_owner     = create(:user)
      @unconfirmed_ownership = create(:ownership, :unconfirmed, rubygem: @rubygem, user: @unconfirmed_owner)

      create(:ownership, rubygem: @rubygem, user: @confirmed_owner)
    end

    context "#unconfirmed_ownerships" do
      should "return only unconfirmed ownerships" do
        assert_equal [@unconfirmed_ownership], @rubygem.unconfirmed_ownerships
      end
    end

    context "#unconfirmed_ownership?" do
      should "return false when user is confirmed owner" do
        refute @rubygem.unconfirmed_ownership?(@confirmed_owner)
      end

      should "return true when user is unconfirmed owner" do
        assert @rubygem.unconfirmed_ownership?(@unconfirmed_owner)
      end
    end
  end

  context ".mfa_recommended scope" do
    should "not return gems with fewer downloads than the recommended threshold" do
      rubygem = create(:rubygem)
      GemDownload.increment(
        Rubygem::MFA_RECOMMENDED_THRESHOLD,
        rubygem_id: rubygem.id
      )

      assert_empty Rubygem.mfa_recommended
    end

    should "return gems with more downloads than the recommended threshold" do
      rubygem = create(:rubygem)
      GemDownload.increment(
        Rubygem::MFA_RECOMMENDED_THRESHOLD + 1,
        rubygem_id: rubygem.id
      )

      refute_empty Rubygem.mfa_recommended
    end
  end

  context ".mfa_required scope" do
    should "not return gems with fewer downloads than the required threshold" do
      rubygem = create(:rubygem)
      GemDownload.increment(
        Rubygem::MFA_REQUIRED_THRESHOLD,
        rubygem_id: rubygem.id
      )

      assert_empty Rubygem.mfa_required
    end

    should "return gems with more downloads than the required threshold" do
      rubygem = create(:rubygem)
      GemDownload.increment(
        Rubygem::MFA_REQUIRED_THRESHOLD + 1,
        rubygem_id: rubygem.id
      )

      assert_includes Rubygem.mfa_required, rubygem
    end
  end

  context "#mfa_requirement_satisfied_for?" do
    setup do
      @rubygem = create(:rubygem)
      @owner   = create(:user)
      create(:ownership, user: @owner, rubygem: @rubygem)
    end

    context "rubygems_mfa_required is set" do
      setup do
        metadata = { "rubygems_mfa_required" => "true" }
        create(:version, rubygem: @rubygem, number: "1.0.0", metadata: metadata)
      end

      should "not be satisfied if owner has not enabled mfa" do
        refute @rubygem.mfa_requirement_satisfied_for?(@owner)
      end

      should "be satisfied if owner has enabled mfa" do
        @owner.enable_mfa!(ROTP::Base32.random_base32, :ui_and_api)
        assert @rubygem.mfa_requirement_satisfied_for?(@owner)
      end
    end

    context "rubygems_mfa_required is unset for latest version" do
      setup do
        create(:version, rubygem: @rubygem, number: "1.0.0")
      end

      should "be satisfied" do
        assert @rubygem.mfa_requirement_satisfied_for?(@owner)
      end

      context "rubygems_mfa_required was set for older version" do
        setup do
          metadata = { "rubygems_mfa_required" => "true" }
          create(:version, rubygem: @rubygem, number: "0.0.9", metadata: metadata)
        end

        should "be satisfied" do
          assert @rubygem.mfa_requirement_satisfied_for?(@owner)
        end
      end
    end
  end

  context "#mfa_required_since_version" do
    setup do
      @rubygem = create(:rubygem)
      metadata = { "rubygems_mfa_required" => "true" }
      @version = create(:version, number: "1.0.0", rubygem: @rubygem, metadata: metadata)
    end

    context "rubygems_mfa_required is set on the latest version" do
      should "return latest version number" do
        assert_equal @version.number, @rubygem.mfa_required_since_version
      end
    end

    context "rubygems_mfa_required was unset and set" do
      setup do
        create(:version, number: "1.0.1", rubygem: @rubygem)
        create(:version, number: "1.0.2", rubygem: @rubygem, metadata: { "rubygems_mfa_required" => "true" })
      end

      should "return latest version number with mfa required" do
        assert_equal "1.0.2", @rubygem.mfa_required_since_version
      end
    end

    context "rubygems_mfa_required is not set on the latest version" do
      setup do
        create(:version, number: "1.0.1", rubygem: @rubygem)
      end

      should "return nil" do
        assert_nil @rubygem.mfa_required_since_version
      end
    end
  end
end


text:
#pragma checksum "D:\Masaüstü\Cahil misin\Cahil misin\Sayfalar\classicgame.xaml" "{406ea660-64cf-4c82-b6f0-42d48172a799}" "E41408A9A7139E81B1EABD1A67D74E34"
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.42000
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

using Microsoft.Phone.Controls;
using System;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Automation.Peers;
using System.Windows.Automation.Provider;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Resources;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace Lord_of_the_Math.Sayfalar {

    public partial class classicgame : Microsoft.Phone.Controls.PhoneApplicationPage {

        internal System.Windows.Media.Animation.Storyboard zaman1;

        internal System.Windows.Media.Animation.Storyboard zaman2;

        internal System.Windows.Media.Animation.Storyboard zaman3;

        internal System.Windows.Media.Animation.Storyboard zaman4;

        internal System.Windows.Media.Animation.Storyboard zaman5;

        internal System.Windows.Media.Animation.Storyboard zaman6;

        internal System.Windows.Media.Animation.Storyboard zaman7;

        internal System.Windows.Media.Animation.Storyboard zaman8;

        internal System.Windows.Media.Animation.Storyboard zaman9;

        internal System.Windows.Media.Animation.Storyboard zaman10;

        internal System.Windows.Media.Animation.Storyboard zaman11;

        internal System.Windows.Controls.Grid LayoutRoot;

        internal System.Windows.Controls.Grid Anagrid;

        internal System.Windows.Controls.Border btn2;

        internal System.Windows.Controls.TextBlock cevap2;

        internal System.Windows.Controls.Border btn1;

        internal System.Windows.Controls.TextBlock cevap1;

        internal System.Windows.Controls.TextBlock txt1;

        internal System.Windows.Controls.TextBlock txt2;

        internal System.Windows.Controls.TextBlock sonuc1;

        internal System.Windows.Controls.TextBlock puantext;

        internal System.Windows.Controls.Image eksi;

        internal System.Windows.Controls.TextBlock txtson;

        internal System.Windows.Controls.Border border;

        internal System.Windows.Controls.TextBlock isaret;

        internal System.Windows.Controls.TextBlock txt1_Copy1;

        internal System.Windows.Controls.MediaElement media;

        internal System.Windows.Controls.Border btn4;

        internal System.Windows.Controls.TextBlock cevap4;

        internal System.Windows.Controls.Border btn3;

        internal System.Windows.Controls.TextBlock cevap3;

        private bool _contentLoaded;

        /// <summary>
        /// InitializeComponent
        /// </summary>
        [System.Diagnostics.DebuggerNonUserCodeAttribute()]
        public void InitializeComponent() {
            if (_contentLoaded) {
                return;
            }
            _contentLoaded = true;
            System.Windows.Application.LoadComponent(this, new System.Uri("/Cahil%20misin;component/Sayfalar/classicgame.xaml", System.UriKind.Relative));
            this.zaman1 = ((System.Windows.Media.Animation.Storyboard)(this.FindName("zaman1")));
            this.zaman2 = ((System.Windows.Media.Animation.Storyboard)(this.FindName("zaman2")));
            this.zaman3 = ((System.Windows.Media.Animation.Storyboard)(this.FindName("zaman3")));
            this.zaman4 = ((System.Windows.Media.Animation.Storyboard)(this.FindName("zaman4")));
            this.zaman5 = ((System.Windows.Media.Animation.Storyboard)(this.FindName("zaman5")));
            this.zaman6 = ((System.Windows.Media.Animation.Storyboard)(this.FindName("zaman6")));
            this.zaman7 = ((System.Windows.Media.Animation.Storyboard)(this.FindName("zaman7")));
            this.zaman8 = ((System.Windows.Media.Animation.Storyboard)(this.FindName("zaman8")));
            this.zaman9 = ((System.Windows.Media.Animation.Storyboard)(this.FindName("zaman9")));
            this.zaman10 = ((System.Windows.Media.Animation.Storyboard)(this.FindName("zaman10")));
            this.zaman11 = ((System.Windows.Media.Animation.Storyboard)(this.FindName("zaman11")));
            this.LayoutRoot = ((System.Windows.Controls.Grid)(this.FindName("LayoutRoot")));
            this.Anagrid = ((System.Windows.Controls.Grid)(this.FindName("Anagrid")));
            this.btn2 = ((System.Windows.Controls.Border)(this.FindName("btn2")));
            this.cevap2 = ((System.Windows.Controls.TextBlock)(this.FindName("cevap2")));
            this.btn1 = ((System.Windows.Controls.Border)(this.FindName("btn1")));
            this.cevap1 = ((System.Windows.Controls.TextBlock)(this.FindName("cevap1")));
            this.txt1 = ((System.Windows.Controls.TextBlock)(this.FindName("txt1")));
            this.txt2 = ((System.Windows.Controls.TextBlock)(this.FindName("txt2")));
            this.sonuc1 = ((System.Windows.Controls.TextBlock)(this.FindName("sonuc1")));
            this.puantext = ((System.Windows.Controls.TextBlock)(this.FindName("puantext")));
            this.eksi = ((System.Windows.Controls.Image)(this.FindName("eksi")));
            this.txtson = ((System.Windows.Controls.TextBlock)(this.FindName("txtson")));
            this.border = ((System.Windows.Controls.Border)(this.FindName("border")));
            this.isaret = ((System.Windows.Controls.TextBlock)(this.FindName("isaret")));
            this.txt1_Copy1 = ((System.Windows.Controls.TextBlock)(this.FindName("txt1_Copy1")));
            this.media = ((System.Windows.Controls.MediaElement)(this.FindName("media")));
            this.btn4 = ((System.Windows.Controls.Border)(this.FindName("btn4")));
            this.cevap4 = ((System.Windows.Controls.TextBlock)(this.FindName("cevap4")));
            this.btn3 = ((System.Windows.Controls.Border)(this.FindName("btn3")));
            this.cevap3 = ((System.Windows.Controls.TextBlock)(this.FindName("cevap3")));
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
import { TestBed, waitForAsync } from '@angular/core/testing';
import { NoopAnimationsModule } from '@angular/platform-browser/animations';

import { HttpClientTestingModule } from '@angular/common/http/testing';
import { MatIconModule } from '@angular/material/icon';
import { Dashboard } from './dashboard.component';

import { Router } from '@angular/router';
import { RouterTestingModule } from '@angular/router/testing';

import { MatDialogModule, MAT_DIALOG_DATA, MatDialogRef,
} from '@angular/material/dialog';

import { LoadingSpinnerComponent,
} from '../common-components/loading-spinner.component';

import { HomepageBase } from './homepage-base.component';

describe('HomepageBase', () => {
  let component: HomepageBase;
  let router: Router;

  beforeEach(waitForAsync(() => {
    TestBed.configureTestingModule({
        declarations: [
          Dashboard,
          LoadingSpinnerComponent,
          HomepageBase,
        ],
        imports: [
          NoopAnimationsModule,
          MatIconModule,
          HttpClientTestingModule,
          RouterTestingModule,
          MatDialogModule,
        ],
        providers: [
          { provide: MAT_DIALOG_DATA, useValue: {} },
          { provide: MatDialogRef, useValue: {} },
        ],
      })
      .compileComponents();

      router = TestBed.inject(Router);
      router.initialNavigation();
    }));

  beforeEach(() => {
    const fixture = TestBed.createComponent(HomepageBase);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});


text:
<?php

/**
 * @file
 * Contains \Drupal\book\Plugin\Block\BookNavigationBlock.
 */

namespace Drupal\book\Plugin\Block;

use Drupal\block\BlockBase;
use Drupal\block\Annotation\Block;
use Drupal\Core\Annotation\Translation;

/**
 * Provides a 'Book navigation' block.
 *
 * @Block(
 *   id = "book_navigation",
 *   admin_label = @Translation("Book navigation")
 * )
 */
class BookNavigationBlock extends BlockBase {

  /**
   * Overrides \Drupal\block\BlockBase::settings().
   */
  public function settings() {
    return array(
      'cache' => DRUPAL_CACHE_PER_PAGE | DRUPAL_CACHE_PER_ROLE,
      'block_mode' => "all pages",
    );
  }

  /**
   * Overrides \Drupal\block\BlockBase::blockForm()
   */
  function blockForm($form, &$form_state) {
    $options = array(
      'all pages' => t('Show block on all pages'),
      'book pages' => t('Show block only on book pages'),
    );
    $form['book_block_mode'] = array(
      '#type' => 'radios',
      '#title' => t('Book navigation block display'),
      '#options' => $options,
      '#default_value' => $this->configuration['block_mode'],
      '#description' => t("If Show block on all pages is selected, the block will contain the automatically generated menus for all of the site's books. If Show block only on book pages is selected, the block will contain only the one menu corresponding to the current page's book. In this case, if the current page is not in a book, no block will be displayed. The Page specific visibility settings or other visibility settings can be used in addition to selectively display this block."),
      );

    return $form;
  }

  /**
   * Overrides \Drupal\block\BlockBase::blockSubmit().
   */
  public function blockSubmit($form, &$form_state) {
    $this->configuration['block_mode'] = $form_state['values']['book_block_mode'];
  }

  /**
   * {@inheritdoc}
   */
  public function build() {
    $current_bid = 0;
    if ($node = menu_get_object()) {
      $current_bid = empty($node->book['bid']) ? 0 : $node->book['bid'];
    }
    if ($this->configuration['block_mode'] == 'all pages') {
      $book_menus = array();
      $pseudo_tree = array(0 => array('below' => FALSE));
      foreach (book_get_books() as $book_id => $book) {
        if ($book['bid'] == $current_bid) {
          // If the current page is a node associated with a book, the menu
          // needs to be retrieved.
          $book_menus[$book_id] = menu_tree_output(menu_tree_all_data($node->book['menu_name'], $node->book));
        }
        else {
          // Since we know we will only display a link to the top node, there
          // is no reason to run an additional menu tree query for each book.
          $book['in_active_trail'] = FALSE;
          // Check whether user can access the book link.
          $book_node = node_load($book['nid']);
          $book['access'] = node_access('view', $book_node);
          $pseudo_tree[0]['link'] = $book;
          $book_menus[$book_id] = menu_tree_output($pseudo_tree);
        }
      }
      if ($book_menus) {
        return array(
          '#theme' => 'book_all_books_block',
          $book_menus
        );
      }
    }
    elseif ($current_bid) {
      // Only display this block when the user is browsing a book.
      $select = db_select('node', 'n')
        ->fields('n', array('nid'))
        ->condition('n.nid', $node->book['bid'])
        ->addTag('node_access');
      $nid = $select->execute()->fetchField();
      // Only show the block if the user has view access for the top-level node.
      if ($nid) {
        $tree = menu_tree_all_data($node->book['menu_name'], $node->book);
        // There should only be one element at the top level.
        $data = array_shift($tree);
        $below = menu_tree_output($data['below']);
        if (!empty($below)) {
          $book_title_link = array('#theme' => 'book_title_link', '#link' => $data['link']);
          return array(
            '#title' => drupal_render($book_title_link),
            $below,
          );
        }
      }
    }
    return array();
  }

}


text:
using System.Globalization;
using System.Windows.Controls;
using ElasticSea.Wintile.Utils;

namespace ElasticSea.Wintile.View.Rules
{
    public class IntegerValidationRule : ValidationRule
    {
        public int Min { get; set; }
        public int Max { get; set; }

        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            var integer = (value as string).ToInt(0);
            if (integer < Min) return new ValidationResult(false, $"Number is smaller than {Min}");
            if (integer > Max) return new ValidationResult(false, $"Number is larger than {Max}");
            return new ValidationResult(true, null);
        }
    }
}


text:
using google_breakpad::scoped_ptr;

namespace dwarf2reader {

CULineInfoHandler::CULineInfoHandler(std::vector<SourceFileInfo>* files,
                                     std::vector<string>* dirs,
                                     LineMap* linemap):linemap_(linemap),
                                                       files_(files),
                                                       dirs_(dirs) {
  // The dirs and files are 1 indexed, so just make sure we put
  // nothing in the 0 vector.
  assert(dirs->size() == 0);
  assert(files->size() == 0);
  dirs->push_back("");
  SourceFileInfo s;
  s.name = "";
  s.lowpc = ULLONG_MAX;
  files->push_back(s);
}

void CULineInfoHandler::DefineDir(const string& name, uint32_t dir_num) {
  // These should never come out of order, actually
  assert(dir_num == dirs_->size());
  dirs_->push_back(name);
}

void CULineInfoHandler::DefineFile(const string& name,
                                   int32 file_num, uint32_t dir_num,
                                   uint64_t mod_time, uint64_t length) {
  assert(dir_num >= 0);
  assert(dir_num < dirs_->size());

  // These should never come out of order, actually.
  if (file_num == (int32)files_->size() || file_num == -1) {
    string dir = dirs_->at(dir_num);

    SourceFileInfo s;
    s.lowpc = ULLONG_MAX;

    if (dir == "") {
      s.name = name;
    } else {
      s.name = dir + "/" + name;
    }

    files_->push_back(s);
  } else {
    fprintf(stderr, "error in DefineFile");
  }
}

void CULineInfoHandler::AddLine(uint64_t address, uint64_t length,
                                uint32_t file_num, uint32_t line_num,
                                uint32_t column_num) {
  if (file_num < files_->size()) {
    linemap_->insert(
        std::make_pair(address,
                       std::make_pair(files_->at(file_num).name.c_str(),
                                      line_num)));

    if (address < files_->at(file_num).lowpc) {
      files_->at(file_num).lowpc = address;
    }
  } else {
    fprintf(stderr, "error in AddLine");
  }
}

bool CUFunctionInfoHandler::StartCompilationUnit(uint64_t offset,
                                                 uint8_t address_size,
                                                 uint8_t offset_size,
                                                 uint64_t cu_length,
                                                 uint8_t dwarf_version) {
  current_compilation_unit_offset_ = offset;
  return true;
}

// For function info, we only care about subprograms and inlined
// subroutines. For line info, the DW_AT_stmt_list lives in the
// compile unit tag.

bool CUFunctionInfoHandler::StartDIE(uint64_t offset, enum DwarfTag tag) {
  switch (tag) {
    case DW_TAG_subprogram:
    case DW_TAG_inlined_subroutine: {
      current_function_info_ = new FunctionInfo;
      current_function_info_->lowpc = current_function_info_->highpc = 0;
      current_function_info_->name = "";
      current_function_info_->line = 0;
      current_function_info_->file = "";
      offset_to_funcinfo_->insert(std::make_pair(offset,
                                                 current_function_info_));
    };
      // FALLTHROUGH
    case DW_TAG_compile_unit:
      return true;
    default:
      return false;
  }
  return false;
}

// Only care about the name attribute for functions

void CUFunctionInfoHandler::ProcessAttributeString(uint64_t offset,
                                                   enum DwarfAttribute attr,
                                                   enum DwarfForm form,
                                                   const string &data) {
  if (current_function_info_) {
    if (attr == DW_AT_name)
      current_function_info_->name = data;
    else if (attr == DW_AT_MIPS_linkage_name)
      current_function_info_->mangled_name = data;
  }
}

void CUFunctionInfoHandler::ProcessAttributeUnsigned(uint64_t offset,
                                                     enum DwarfAttribute attr,
                                                     enum DwarfForm form,
                                                     uint64_t data) {
  if (attr == DW_AT_stmt_list) {
    SectionMap::const_iterator iter = sections_.find("__debug_line");
    assert(iter != sections_.end());

    scoped_ptr<LineInfo> lireader(new LineInfo(iter->second.first + data,
                                               iter->second.second  - data,
                                               reader_, linehandler_));
    lireader->Start();
  } else if (current_function_info_) {
    switch (attr) {
      case DW_AT_low_pc:
        current_function_info_->lowpc = data;
        break;
      case DW_AT_high_pc:
        current_function_info_->highpc = data;
        break;
      case DW_AT_decl_line:
        current_function_info_->line = data;
        break;
      case DW_AT_decl_file:
        current_function_info_->file = files_->at(data).name;
        break;
      case DW_AT_ranges:
        current_function_info_->ranges = data;
        break;
      default:
        break;
    }
  }
}

void CUFunctionInfoHandler::ProcessAttributeReference(uint64_t offset,
                                                      enum DwarfAttribute attr,
                                                      enum DwarfForm form,
                                                      uint64_t data) {
  if (current_function_info_) {
    switch (attr) {
      case DW_AT_specification: {
        // Some functions have a "specification" attribute
        // which means they were defined elsewhere. The name
        // attribute is not repeated, and must be taken from
        // the specification DIE. Here we'll assume that
        // any DIE referenced in this manner will already have
        // been seen, but that's not really required by the spec.
        FunctionMap::iterator iter = offset_to_funcinfo_->find(data);
        if (iter != offset_to_funcinfo_->end()) {
          current_function_info_->name = iter->second->name;
          current_function_info_->mangled_name = iter->second->mangled_name;
        } else {
          // If you hit this, this code probably needs to be rewritten.
          fprintf(stderr,
                  "Error: DW_AT_specification was seen before the referenced "
                  "DIE! (Looking for DIE at offset %08llx, in DIE at "
                  "offset %08llx)\n", data, offset);
        }
        break;
      }
      default:
        break;
    }
  }
}

void CUFunctionInfoHandler::EndDIE(uint64_t offset) {
  if (current_function_info_ && current_function_info_->lowpc)
    address_to_funcinfo_->insert(std::make_pair(current_function_info_->lowpc,
                                                current_function_info_));
}

}  // namespace dwarf2reader


text:
import os

try:
    from setuptools import setup, find_packages
except ImportError:
    from ez_setup import use_setuptools
    use_setuptools()
    from setuptools import setup, find_packages  # noqa

rel_file = lambda *args: os.path.join(
    os.path.dirname(
        os.path.abspath(__file__),
    ), *args)

def get_file(filename):
    with open(rel_file(filename)) as f:
        return f.read()

def get_description():
    return get_file('README.md')

setup(
    name="shutdown_if_idle",
    version="0.0.1",
    description="Shutdown machine if considered idle",
    author="Jason Ward",
    author_email="jason.louard.ward@gmail.com",
    url="http://github.com/PolicyStat/shutdown-if-idle/",
    platforms=["any"],
    license="BSD",
    packages=find_packages(),
    scripts=[],
    zip_safe=False,
    install_requires=[],
    cmdclass={},
    classifiers=[
        "Development Status :: 3 - Alpha",
        "Programming Language :: Python",
        "Programming Language :: Python :: 2.6",
        "Programming Language :: Python :: 2.7",
        "Programming Language :: Python :: 3.3",
        "Intended Audience :: Developers",
        "License :: OSI Approved :: BSD License",
        "Operating System :: OS Independent",
        "Topic :: Text Processing :: Markup :: HTML",
        "Topic :: Text Processing :: Markup :: XML",
    ],
    long_description=get_description(),
    entry_points={
        'console_scripts': [
            'shutdown-if-idle = shutdown_if_no_usage:entry_point',
        ],
    },
)


text:
@implementation CIAPIListOpenPositionsRequest

@synthesize tradingAccountId;

- (CIAPIListOpenPositionsRequest*)initWithTradingAccountId:(NSInteger)_tradingAccountId{
  self = [super init];

  if (self)
  {
    self.tradingAccountId = _tradingAccountId;
  }

  return self;
}

// If we have array parameters, vend the array types from a function for
// automatic object construction

- (enum CIAPIRequestType)requestType
{
    return CIAPIRequestGET;
}

- (NSString*)urlTemplate
{
    return @"order/order/openpositions?TradingAccountId={tradingAccountId}";
}

- (Class)responseClass
{
    return [CIAPIListOpenPositionsResponse class];
}

@end


text:
{-# LANGUAGE Rank2Types #-}

module Opaleye.Internal.PackMap where

import qualified Opaleye.Internal.Tag as T

import qualified Opaleye.Internal.HaskellDB.PrimQuery as HPQ

import           Control.Applicative (Applicative, pure, (<*>), liftA2)
import qualified Control.Monad.Trans.State as State
import           Data.Profunctor (Profunctor, dimap, rmap)
import           Data.Profunctor.Product (ProductProfunctor, empty, (***!))
import qualified Data.Profunctor.Product as PP
import qualified Data.Functor.Identity as I

-- This is rather like a Control.Lens.Traversal with the type
-- parameters switched but I'm not sure if it should be required to
-- obey the same laws.
--
-- TODO: We could attempt to generalise this to
--
-- data LensLike f a b s t = LensLike ((a -> f b) -> s -> f t)
--
-- i.e. a wrapped, argument-flipped Control.Lens.LensLike
--
-- This would allow us to do the Profunctor and ProductProfunctor
-- instances (requiring just Functor f and Applicative f respectively)
-- and share them between many different restrictions of f.  For
-- example, TableColumnMaker is like a Setter so we would restrict f
-- to the Distributive case.

-- | A 'PackMap' @a@ @b@ @s@ @t@ encodes how an @s@ contains an
-- updatable sequence of @a@ inside it.  Each @a@ in the sequence can
-- be updated to a @b@ (and the @s@ changes to a @t@ to reflect this
-- change of type).
--
-- 'PackMap' is just like a @Traversal@ from the lens package.
-- 'PackMap' has a different order of arguments to @Traversal@ because
-- it typically needs to be made a 'Profunctor' (and indeed
-- 'ProductProfunctor') in @s@ and @t@.  It is unclear at this point
-- whether we want the same @Traversal@ laws to hold or not.  Our use
-- cases may be much more general.
newtype PackMap a b s t = PackMap (forall f. Applicative f => (a -> f b) -> s -> f t)

-- | Replaces the targeted occurences of @a@ in @s@ with @b@ (changing
-- the @s@ to a @t@ in the process).  This can be done via an
-- 'Applicative' action.
--
-- 'traversePM' is just like @traverse@ from the @lens@ package.
-- 'traversePM' used to be called @packmap@.
traversePM :: Applicative f => PackMap a b s t -> (a -> f b) -> s -> f t
traversePM (PackMap f) = f

-- | Modify the targeted occurrences of @a@ in @s@ with @b@ (changing
-- the @s@ to a @t@ in the process).
--
-- 'overPM' is just like @over@ from the @lens@ pacakge.
overPM :: PackMap a b s t -> (a -> b) -> s -> t
overPM p f = I.runIdentity . traversePM p (I.Identity . f)

-- {

-- | A helpful monad for writing columns in the AST
type PM a = State.State (a, Int)

new :: PM a String
new = do
  (a, i) <- State.get
  State.put (a, i + 1)
  return (show i)

write :: a -> PM [a] ()
write a = do
  (as, i) <- State.get
  State.put (as ++ [a], i)

run :: PM [a] r -> (r, [a])
run m = (r, as)
  where (r, (as, _)) = State.runState m ([], 0)

-- }

-- { General functions for writing columns in the AST

-- | Make a fresh name for an input value (the variable @primExpr@
-- type is typically actually a 'HPQ.PrimExpr') based on the supplied
-- function and the unique 'T.Tag' that is used as part of our
-- @QueryArr@.
--
-- Add the fresh name and the input value it refers to to the list in
-- the state parameter.
extractAttrPE :: (primExpr -> String -> String) -> T.Tag -> primExpr
               -> PM [(HPQ.Symbol, primExpr)] HPQ.PrimExpr
extractAttrPE mkName t pe = do
  i <- new
  let s = HPQ.Symbol (mkName pe i) t
  write (s, pe)
  return (HPQ.AttrExpr s)

-- | As 'extractAttrPE' but ignores the 'primExpr' when making the
-- fresh column name and just uses the supplied 'String' and 'T.Tag'.
extractAttr :: String -> T.Tag -> primExpr
               -> PM [(HPQ.Symbol, primExpr)] HPQ.PrimExpr
extractAttr s = extractAttrPE (const (s ++))

-- }

eitherFunction :: (PP.SumProfunctor p, Functor f)
               => p a  (f b)
               -> p a' (f b')
               -> p (Either a a') (f (Either b b'))
eitherFunction f g = rmap (either (fmap Left) (fmap Right)) (f PP.+++! g)

-- | Like 'Control.Lens.Iso.iso'.  In practice it won't actually be
-- used as an isomorphism, but it seems to be appropriate anyway.
iso :: (s -> a) -> (b -> t) -> PackMap a b s t
iso h g = PackMap (dimap h (fmap g))

-- {

-- Boilerplate instance definitions.  There's no choice here apart
-- from the order in which the applicative is applied.

instance Functor (PackMap a b s) where
  fmap f (PackMap g) = PackMap ((fmap . fmap . fmap) f g)

instance Applicative (PackMap a b s) where
  pure x = PackMap (pure (pure (pure x)))
  PackMap f <*> PackMap x = PackMap (liftA2 (liftA2 (<*>)) f x)

instance Profunctor (PackMap a b) where
  dimap f g (PackMap q) = PackMap (fmap (dimap f (fmap g)) q)

instance ProductProfunctor (PackMap a b) where
  empty = PP.defaultEmpty
  (***!) = PP.defaultProfunctorProduct

instance PP.SumProfunctor (PackMap a b) where
  PackMap f +++! PackMap g = PackMap (\x -> eitherFunction (f x) (g x))

-- }


text:
	/* Lines with autodrowing */

	$(function () {
		// we use an inline data source in the example, usually data would
		// be fetched from a server
		var data = [], totalPoints = 25;
		function getRandomData() {
			if (data.length > 0)
				data = data.slice(1);

			// do a random walk
			while (data.length < totalPoints) {
				var prev = data.length > 0 ? data[data.length - 1] : 5;
				var y = prev + Math.random() * 10 - 5;
				if (y < 0)
					y = 0;
				if (y > 20)
					y = 20;
				data.push(y);
			}

			// zip the generated y values with the x values
			var res = [];
			for (var i = 0; i < data.length; ++i)
				res.push([i, data[i]])
			return res;
		}

		// setup control widget
		var updateInterval = 1000;
		$("#updateInterval").val(updateInterval).change(function () {
			var v = $(this).val();
			if (v && !isNaN(+v)) {
				updateInterval = +v;
				if (updateInterval < 1)
					updateInterval = 1;
				if (updateInterval > 2000)
					updateInterval = 2000;
				$(this).val("" + updateInterval);
			}
		});

		// setup plot
		var options = {
			yaxis: { min: 0, max: 20, reserveSpace: false, font: { size: 11, lineHeight: 1, color: "#ffffff" } },
			xaxis: { min: 0, max: 20, tickLength: 0, show: false },
			colors: ["#ffffff"],
			grid: { hoverable: true, clickable: true, tickColor: "rgba(255,255,255,0.16)" },
			series: {
					   lines: {
							lineWidth: 2,
							fill: false,
							fillColor: { colors: [ { opacity: 0.5 }, { opacity: 0.2 } ] },
							show: true
						},
			            points: {
			                show: true,
			                radius: 2.5,
			                fill: true,
			                fillColor: "#ffffff",
			                symbol: "circle",
			                lineWidth: 1.1
			            }
				   }
		};
		var plot = $.plot($("#updating-widget-2"), [ getRandomData() ], options);

		function update() {
			plot.setData([ getRandomData() ]);
			// since the axes don't change, we don't need to call plot.setupGrid()
			plot.draw();

			setTimeout(update, updateInterval);
		}

		update();
	});


text:
"""
Copyright (c) 2016, Donald E. Willcox
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
  list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice,
  this list of conditions and the following disclaimer in the documentation
  and/or other materials provided with the distribution.

* Neither the name of the copyright holder nor the names of its
  contributors may be used to endorse or promote products derived from
  this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""
import sympy
from .Row import Row
from .Element import Element1D, Element2D

class GaussJordan(object):
    def __init__(self, structure_file=None, compressed_sparse_row=False, out_py=None, out_f95=None, out_cpp=None, smp=None, expand=False, cse=None, verbose=None):
        self.infile = structure_file
        self.cse_rep = None
        self.verbose = verbose
        self.sparsity = None # Original matrix system sparsity pattern
        self.symtab = {}
        self.compressed_sparse_row = compressed_sparse_row

        if self.infile:
            self.readfile()
            if self.verbose:
                self.printEquation()
            self.pivotSolve()
            if smp:
                print('Simplifying')
                self.simplify()
            if cse:
                print('Eliminating CSE')
                self.elim_cse()
            if expand and (not cse) and (not smp):
                print('Expanding expressions')
                self.expand()
            if self.verbose:
                self.printSolution()
            if out_py:
                self.writeCode_Python(out_py)
            if out_f95:
                self.writeCode_Fortran95(out_f95)
            if out_cpp:
                if not self.compressed_sparse_row:
                    print('Error: C++ output only supported for a matrix in CSR format.')
                    exit()
                else:
                    self.writeCode_Cpp(out_cpp)

    def readfile(self):
        # Read in the array mask and store in amat as either 'False'
        # or the string 'amat(i,j)' where i is the row number and
        # j the column number (starting at 1).
        try:
            file = open(self.infile,'r')
        except:
            raise

        lines = []
        for l in file:
            lines.append(l.strip())
        file.close()

        amat_t = []
        ncols = None
        for iline, line in enumerate(lines):
            if iline == 0:
                continue # This is the size of the square matrix, useful for Fortran
            if line=='':
                continue
            elif line[0]=='#':
                continue
            cols = []
            for e in line.split():
                if e=='0':
                    cols.append(False)
                else:
                    cols.append(True)
            if not ncols:
                ncols = len(cols)
            else:
                if ncols != len(cols):
                    print('Error: inconsistent number of columns!')
                    print(cols)
                    print(ncols)
                    exit()
            amat_t.append(cols)

        if self.verbose:
            print(amat_t)
            print(ncols)

        if len(amat_t) != ncols:
            print('Error: number of rows not equal to number of columns.')
            exit()

        self.asym = []
        index_csr = 1
        for i, r in enumerate(amat_t):
            r_s = []
            for j, a_ij in enumerate(r):
                if self.verbose:
                    print(a_ij)
                if a_ij:
                    symrep = None
                    if self.compressed_sparse_row:
                        symrep = 'A_'+str(index_csr)+'_'
                        self.symtab[symrep] = Element1D('A', index_csr)
                    else:
                        symrep = 'A_'+str(i+1)+'_'+str(j+1)+'_'
                        self.symtab[symrep] = Element2D('A', i+1, j+1)
                    r_s.append(sympy.symbols(symrep))
                    index_csr += 1
                else:
                    r_s.append(0)
            symrep = 'b_'+str(i+1)+'_'
            self.symtab[symrep] = Element1D('b', i+1)
            r_s.append(sympy.symbols(symrep))
            self.asym.append(Row(r_s))

        # Save a copy of the original sparsity
        self.sparsity = [r for r in self.asym]

    def get_number_nonzero(self):
        nnz = 0
        for r in self.asym:
            nnz += r.get_number_nonzero()
        return nnz

    def printEquation(self):
        print('Symbolic array equation [A|b]:')
        for r in self.asym:
            s = ''
            for ri in r:
                s = s + '{:20}'.format(str(ri))
            print(s)

    def pivotSolve(self):
        self.nvars = len(self.asym)
        vpivot = 0
        # Check if already in reduced-row-echelon (minus the row swapping)
        # Pivot for variable vpivot
        for i in range(vpivot, self.nvars):
            vrows = []
            for j, r in enumerate(self.asym):
                # Make a list of rows with nonzero elements in the ith position
                if self.verbose:
                    print('Checking row {}'.format(j))
                    print('row {}, index {}: {}'.format(j, i, str(r.elements[i])))
                if not r.zero_at(i):
                    vrows.append(j)
            for j, r in enumerate(self.asym):
                n, e = r.fnzero()
                if n==i:
                    ## Pivot using jth Row
                    # Copy the matrix
                    asym_pivot = [r for r in self.asym]
                    # Normalize element in the pivot position
                    asym_pivot[j] = asym_pivot[j]/e
                    # Pivot other rows with a nonzero element in ith position
                    for vj in vrows:
                        if vj != j:
                            # Get elimination prefactor
                            prefactor = asym_pivot[vj].elements[i]
                            # Eliminate into this row
                            asym_pivot[vj] = asym_pivot[vj] - prefactor * asym_pivot[j]
                    ## The following uses only the first available elimination
                    # Replace the original matrix with the pivot matrix
                    self.asym = [r for r in asym_pivot]
                    break

        # Rearrange rows into RREF
        asym_temp = []
        for i in range(len(self.asym)):
            for r in self.asym:
                n, e = r.fnzero()
                if n == i:
                    asym_temp.append(r)
        self.asym = [r for r in asym_temp]

        # Find solution vector
        self.solution = [r.elements[-1] for r in self.asym]

    def simplify(self):
        # Simplify solutions using simplify
        # ratio=1 requires the number of operations in the simplified
        # expression to be at most the number of operations in the original
        if self.verbose:
            print('Finding simplifications...')
        for i, s in enumerate(self.solution):
            sres = sympy.simplify(s, ratio=1)
            self.solution[i] = sres
            if self.verbose:
                print('----------------------------------------')
                print('Simplify Solution {} Report:'.format(i))
                if str(sres) != str(s):
                    print('Shorter Representation Found')
                    print('Un-Simplified:')
                    print(s)
                    print('Simplified:')
                    print(sres)
                else:
                    print('No Shorter Representation Found')
                print('----------------------------------------')

    def expand(self):
        # Expand solutions.
        for i, s in enumerate(self.solution):
            sres = sympy.expand(s)
            self.solution[i] = sres
            if self.verbose:
                print('----------------------------------------')
                print('Expand Solution {} Report:'.format(i))
                print('Un-Expanded:')
                print(s)
                print('Expanded:')
                print(sres)
                print('----------------------------------------')

    def elim_cse(self):
        ## Apply common sub-expressions elimination to solution
        scratch_sym = sympy.utilities.numbered_symbols('scratch_')
        cse_rep, cse_sol = sympy.cse(self.solution, symbols=scratch_sym, order='none')
        self.cse_rep = cse_rep
        if self.verbose:
            print('--> Eliminated Common Sub-Expressions')
            print('Scratch Variables:')
            for rep in cse_rep:
                print('{} = {}'.format(rep[0], rep[1]))
            print('Solution:')
        self.solution = cse_sol

    def printSolution(self):
        print('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
        print('Solution:')
        print('')
        for i, sol in enumerate(self.solution):
            print('X{} = {}'.format(i+1, sol))
            print('')

    def pythonify(self,s):
        # Python-ify string s by replacing A_i_j_ with A[i][j]
        # and b_i_ with b[i].
        # Also start indexing at 0 instead of 1.
        sout = str(s)
        for k in self.symtab.keys():
            sout = sout.replace(k, self.symtab[k].pyrep)
        return sout

    def cify(self,s):
        return self.pythonify(s)

    def fortranify(self,s):
        # Fortran-ify string s by replacing A_i_j_ with A(i,j)
        # and b_i_ with b(i)
        sout = str(s)
        for k in self.symtab.keys():
            sout = sout.replace(k, self.symtab[k].fnrep)
        return sout

    def writeCode_Python(self, outname):
        ## Write Python Solver Function
        try:
            fo = open(outname, 'w')
        except:
            raise
        indent = ' '*4
        fo.write('import numpy as np\n')
        fo.write('\n')
        fo.write('def gauss_jordan_solve(A, b):\n')
        fo.write('{}x = np.empty({}, dtype=np.float64)\n'.format(indent, self.nvars))
        fo.write('\n')
        if self.cse_rep:
            for rep in self.cse_rep:
                fo.write('{}{} = {}\n'.format(indent, rep[0], self.pythonify(rep[1])))
            fo.write('\n')
        for i, sol in enumerate(self.solution):
            fo.write('{}x[{}] = {}\n'.format(indent, i, self.pythonify(sol)))
        fo.write('\n')
        fo.write('{}return x\n'.format(indent))
        fo.close()

    def writeCode_Cpp(self, outname):
        ## Write C Solver Function
        try:
            fo = open(outname, 'w')
        except:
            raise
        indent = ' '*2
        fo.write('class SparseGaussJordan {\n')
        fo.write('public:\n'.format(indent))
        fo.write('{}__host__ __device__\n'.format(indent))
        fo.write('{}static void solve(Real* A, Real* x, Real* b)'.format(indent) + ' {\n')

        if self.cse_rep:
            for rep in self.cse_rep:
                rep_value = self.cify(sympy.ccode(rep[1], precision = 15))
                fo.write('{}Real {} = {};\n'.format(indent*2, rep[0], rep_value))
        fo.write('\n')
        for i, sol in enumerate(self.solution):
            sol_value = self.cify(sympy.ccode(sol, precision = 15))
            fo.write('{}x[{}] = {};\n'.format(indent*2, i, sol_value))

        fo.write('{}'.format(indent) + '}\n')
        fo.write('};\n')
        fo.close()

    def writeCode_Fortran95(self, outname):
        ## Write Fortran-95 Solver Subroutine
        try:
            fo = open(outname, 'w')
        except:
            raise
        indent = ' '*2
        fo.write('module gauss_jordan_module\n')
        fo.write('{}implicit none\n'.format(indent))
        fo.write('\n')
        fo.write('contains\n')
        fo.write('\n')
        fo.write('{}subroutine gauss_jordan_solve(A, x, b)\n'.format(indent))
        fo.write('{}double precision, dimension({},{}), intent(in) :: A\n'.format(
            indent*2, self.nvars, self.nvars))
        fo.write('{}double precision, dimension({}), intent(out) :: x\n'.format(
            indent*2, self.nvars))
        fo.write('{}double precision, dimension({}), intent(in) :: b\n'.format(
            indent*2, self.nvars))
        if self.cse_rep:
            for rep in self.cse_rep:
                fo.write('{}double precision :: {}\n'.format(indent*2, rep[0]))
            fo.write('\n')
            for rep in self.cse_rep:
                rep_value = self.fortranify(sympy.fcode(rep[1], precision = 15,
                                                        source_format = 'free',
                                                        standard = 95))
                fo.write('{}{} = {}\n'.format(indent*2, rep[0], rep_value))
        fo.write('\n')
        for i, sol in enumerate(self.solution):
            sol_value = self.fortranify(sympy.fcode(sol, precision = 15,
                                                    source_format = 'free',
                                                    standard = 95))
            fo.write('{}x({}) = {}\n'.format(indent*2, i+1, sol_value))
        fo.write('{}end subroutine gauss_jordan_solve\n'.format(indent))
        fo.write('end module gauss_jordan_module\n')
        fo.close()


text:
package br.com.dorigon.pontoeletronico.api.security.dtos;

/**
 * @author Luiz Otávio Dorigon <luiz.otavio.dorigon@gmail.com>  on 12/09/17.
 */
public class TokenDto {

    private String token;

    public TokenDto() {
    }

    public TokenDto(String token) {
        this.token = token;
    }

    public String getToken() {
        return token;
    }

    public void setToken(String token) {
        this.token = token;
    }

}


text:
from django.db import migrations, models
from django.db.backends.postgresql.schema import BaseDatabaseSchemaEditor
from django.db.migrations.state import StateApps

def make_zero_invalid_for_message_delete_limit(
    apps: StateApps, schema_editor: BaseDatabaseSchemaEditor
) -> None:
    Realm = apps.get_model("zerver", "Realm")
    Realm.DEFAULT_MESSAGE_CONTENT_DELETE_LIMIT_SECONDS = 600

    Realm.objects.filter(
        allow_message_deleting=True, message_content_delete_limit_seconds=0
    ).update(message_content_delete_limit_seconds=None)

    Realm.objects.filter(
        allow_message_deleting=False, message_content_delete_limit_seconds=0
    ).update(
        message_content_delete_limit_seconds=Realm.DEFAULT_MESSAGE_CONTENT_DELETE_LIMIT_SECONDS
    )

def reverse_make_zero_invalid_for_message_delete_limit(
    apps: StateApps, schema_editor: BaseDatabaseSchemaEditor
) -> None:
    Realm = apps.get_model("zerver", "Realm")
    Realm.DEFAULT_MESSAGE_CONTENT_DELETE_LIMIT_SECONDS = 600

    Realm.objects.filter(
        allow_message_deleting=True, message_content_delete_limit_seconds=None
    ).update(message_content_delete_limit_seconds=0)

class Migration(migrations.Migration):
    atomic = False

    dependencies = [
        ("zerver", "0353_remove_realm_default_twenty_four_hour_time"),
    ]

    operations = [
        migrations.AlterField(
            model_name="realm",
            name="message_content_delete_limit_seconds",
            field=models.IntegerField(default=600, null=True),
        ),
        migrations.RunPython(
            make_zero_invalid_for_message_delete_limit,
            reverse_code=reverse_make_zero_invalid_for_message_delete_limit,
            elidable=True,
        ),
        migrations.AlterField(
            model_name="realm",
            name="message_content_delete_limit_seconds",
            field=models.PositiveIntegerField(default=600, null=True),
        ),
    ]


text:
package org.apereo.cas.config;

import org.junit.jupiter.api.Tag;
import org.springframework.test.context.TestPropertySource;

/**
 * This is {@link CasSamlSPSecuringTheHumanConfigurationTests}.
 *
 * @author Misagh Moayyed
 * @since 6.2.0
 */
@Tag("SAML")

@TestPropertySource(properties = {
    "cas.saml-sp.sans-sth.metadata=classpath:/metadata/sp-metadata.xml",
    "cas.saml-sp.sans-sth.name-id-attribute=cn",
    "cas.saml-sp.sans-sth.name-id-format=transient"
})
public class CasSamlSPSecuringTheHumanConfigurationTests extends BaseCasSamlSPConfigurationTests {

}


text:
package com.pubnub.api;

import java.util.Hashtable;
import java.util.Vector;

class SubscribeWorker extends AbstractSubscribeWorker {

    private Exception excp = null;

    SubscribeWorker(Vector _requestQueue, int connectionTimeout,
                    int requestTimeout, int maxRetries, int retryInterval, Hashtable headers) {
        super(_requestQueue, connectionTimeout, requestTimeout,
              maxRetries, retryInterval, headers);
    }

    SubscribeWorker(Vector _requestQueue, int connectionTimeout,
                    int requestTimeout, int maxRetries, int retryInterval, int windowInterval, Hashtable headers) {
        super(_requestQueue, connectionTimeout, requestTimeout,
              maxRetries, retryInterval, windowInterval, headers);
    }

    void process(HttpRequest hreq) {
        HttpResponse hresp = null;
        int currentRetryAttempt = (hreq.isDar())?1:maxRetries;
        log.verbose("disconnectAndResubscribe is " + hreq.isDar());
        boolean sleep = false;
        if (!hreq.isSubzero() && windowInterval != 0) {
            try {
                Thread.sleep(windowInterval);
            } catch (InterruptedException e) {
            }
        }
        while (!_die && currentRetryAttempt <= maxRetries) {
            if (sleep) {
                try {
                    Thread.sleep(retryInterval);
                } catch (InterruptedException e) {
                }
                sleep = true;
            }
            try {
                log.debug(hreq.getUrl());
                hresp = httpclient.fetch(hreq.getUrl(), hreq.getHeaders());
                if (hresp != null
                        && HttpUtil.checkResponseSuccess(hresp
                                                         .getStatusCode())) {
                    currentRetryAttempt = 1;
                    break;
                }
            } /*catch (SocketTimeoutException e) {
                log.verbose("No Traffic , Read Timeout Exception in Fetch : " + e.toString());
                if (hreq.isDar()) {
                    hreq.getResponseHandler().handleBackFromDar(hreq);
                    return;
                }
                break;

            }*/catch (PubnubException e) {
                excp = e;
                switch (e.getPubnubError().errorCode) {
                case PubnubError.PNERR_FORBIDDEN:
                case PubnubError.PNERR_UNAUTHORIZED:
                    log.verbose("Authentication Failure : " + e.toString());
                    currentRetryAttempt = maxRetries + 1;
                    break;
                default:
                    log.verbose("Retry Attempt : " + ((currentRetryAttempt == maxRetries)?"last":String.valueOf(currentRetryAttempt))
                                + " Exception in Fetch : " + e.toString());
                    currentRetryAttempt++;
                    break;
                }

            } catch (Exception e) {
                log.verbose("Retry Attempt : " + ((currentRetryAttempt == maxRetries)?"last":String.valueOf(currentRetryAttempt))
                            + " Exception in Fetch : " + e.toString());
                currentRetryAttempt++;
            }

        }
        if (!_die) {
            if (hresp == null) {
                log.debug("Error in fetching url : " + hreq.getUrl());
                if (hreq.isDar()) {
                    log.verbose("Exhausted number of retries");
                    hreq.getResponseHandler().handleTimeout(hreq);
                } else {
                    if (excp != null && excp instanceof PubnubException && ((PubnubException) excp).getPubnubError() != null) {
                        hreq.getResponseHandler().handleError(hreq, ((PubnubException) excp).getPubnubError());
                    } else {
                        hreq.getResponseHandler().handleError(hreq, PubnubError.getErrorObject(PubnubError.PNERROBJ_HTTP_ERROR, 1));
                    }
                }
                return;
            }
            log.debug(hresp.getResponse());
            hreq.getResponseHandler().handleResponse(hreq, hresp.getResponse());
        }

    }
    public void shutdown() {
        if (httpclient != null) httpclient.shutdown();
    }

}


text: Command to browse package history for configurations in versionner


text:
测试$.cookie插件

		<button id='create_cookie'>create_cookie</button>
		<button id='read_cookie'>read_cookie</button>
		<button id='delete_cookie'>delete_cookie</button>

测试layer插件

		<button id="layer_alert">layer.alert</button>


text:
created by Serhii Lysyi
based on Zend
settings in .htaccess based on host provider  specificity (http://hvosting.ua/, not VirtualHost), you can change it


text:
var Selection = (function () {
    function Selection(mode) {
        this.mode = mode;
        this.selectedRows = 0;
        this.eventIdCount = -1;
        this.eventCallBacks = [];
        this.selection = new Set([]);
    }
    Selection.prototype.triggerEvent = function (event) {
        var _this = this;
        this.eventCallBacks.forEach(function (FN, i) {
            if (FN !== null) {
                var alive = FN(event);
                if (!alive) {
                    _this.eventCallBacks[i] = null;
                }
            }
        });
    };
    Selection.prototype.addEventListener = function (callback) {
        this.eventIdCount++;
        this.eventCallBacks.push(callback);
        return this.eventIdCount;
    };
    Selection.prototype.getLength = function () {
        return this.selection.size;
    };
    Selection.prototype.getMode = function () {
        return this.mode;
    };
    Selection.prototype.getRowKey = function (row) {
        return row;
    };
    Selection.prototype.getRowKeys = function () {
        return [];
    };
    Selection.prototype.overrideGetRowKey = function (fn) {
        this.getRowKey = fn;
    };
    Selection.prototype.overrideGetRowKeys = function (fn) {
        this.getRowKeys = fn;
    };
    Selection.prototype.isSelected = function (row) {
        var result = false;
        if (this.selectedRows > 0) {
            result = this.selection.has(this.getRowKey(row));
        }
        return result;
    };
    Selection.prototype.deSelectAll = function () {
        this.selection.clear();
        this.selectedRows = this.selection.size;
        this.triggerEvent('selection_changed');
    };
    Selection.prototype.deSelect = function (row) {
        this.selection.delete(this.getRowKey(row));
        this.selectedRows = this.selection.size;
        this.triggerEvent('selection_changed');
    };
    Selection.prototype.select = function (row, add) {
        switch (this.mode) {
            case 'none':
            case null:
            case undefined:
                break;
            case 'single':
                this.selection.clear();
                this.selection.add(this.getRowKey(row));
                this.selectedRows = this.selection.size;
                break;
            case 'multiple':
                if (!add) {
                    this.selection.clear();
                    this.selection.add(this.getRowKey(row));
                    this.selectedRows = this.selection.size;
                }
                else {
                    this.selection.add(this.getRowKey(row));
                    this.selectedRows = this.selection.size;
                }
                break;
            default:
        }
        this.triggerEvent('selection_changed');
    };
    Selection.prototype.selectRange = function (start, end) {
        if (this.mode === 'multiple') {
            this.selection.clear();
            for (var i = start; i < end + 1; i++) {
                this.selection.add(this.getRowKey(i));
            }
            this.selectedRows = this.selection.size;
            this.triggerEvent('selection_changed');
        }
    };
    Selection.prototype.getSelectedRows = function () {
        var _this = this;
        var array = [];
        var keys = this.getRowKeys();
        if (this.selectedRows > 0) {
            keys.forEach(function (key, index) {
                if (_this.selection.has(key) === true) {
                    array.push(index);
                }
            });
        }
        return array;
    };
    Selection.prototype.setSelectedRows = function (newRows) {
        if (this.selectedRows > 0) {
            this.selection.clear();
        }
        for (var i = 0; i < newRows.length; i++) {
            this.selection.add(this.getRowKey(newRows[i]));
        }
        this.selectedRows = this.selection.size;
        this.triggerEvent('selection_changed');
    };
    Selection.prototype.reset = function () {
        if (this.selectedRows > 0) {
            this.selection.clear();
        }
        this.selectedRows = this.selection.size;
        this.triggerEvent('selection_changed');
    };
    return Selection;
}());
export { Selection };
//# sourceMappingURL=selection.js.map


text:
import {
  AsyncTestCompleter,
  TestComponentBuilder,
  beforeEach,
  beforeEachBindings,
  ddescribe,
  describe,
  el,
  expect,
  iit,
  inject,
  it,
  xit,
} from 'angular2/test_lib';
import {DebugElement} from 'angular2/src/core/debug/debug_element';

import {Component, View, ViewMetadata, UrlResolver, bind} from 'angular2/core';

import {MdButton, MdAnchor} from 'angular2_material/src/components/button/button';

import {TestUrlResolver} from './test_url_resolver';

import {XHR} from 'angular2/src/core/compiler/xhr';
import {XHRImpl} from 'angular2/src/core/compiler/xhr_impl';

export function main() {
  describe('MdButton', () => {
    let builder: TestComponentBuilder;

    beforeEachBindings(() => [
      // Need a custom URL resolver for ng-material template files in order for them to work
      // with both JS and Dart output.
      bind(UrlResolver)
          .toValue(new TestUrlResolver()),

      // Need to use the real XHR implementation (instead of the mock) so we can actually request
      // the template files, since Angular 2 doesn't have anything like $templateCache. This should
      // eventually be replaced with a preprocessor that inlines templates.
      bind(XHR).toClass(XHRImpl)
    ]);

    beforeEach(inject([TestComponentBuilder], (tcb) => { builder = tcb; }));

    describe('button[md-button]', () => {
      it('should handle a click on the button', inject([AsyncTestCompleter], (async) => {
           builder.createAsync(TestApp).then(rootTestComponent => {
             let testComponent = rootTestComponent.debugElement.componentInstance;
             let buttonDebugElement =
                 getChildDebugElement(rootTestComponent.debugElement, 'button');

             buttonDebugElement.nativeElement.click();
             expect(testComponent.clickCount).toBe(1);

             async.done();
           });
         }), 1000);

      it('should disable the button', inject([AsyncTestCompleter], (async) => {
           builder.createAsync(TestApp).then(rootTestComponent => {
             let testAppComponent = rootTestComponent.debugElement.componentInstance;
             let buttonDebugElement =
                 getChildDebugElement(rootTestComponent.debugElement, 'button');
             let buttonElement = buttonDebugElement.nativeElement;

             // The button should initially be enabled.
             expect(buttonElement.disabled).toBe(false);

             // After the disabled binding has been changed.
             testAppComponent.isDisabled = true;
             rootTestComponent.detectChanges();

             // The button should should now be disabled.
             expect(buttonElement.disabled).toBe(true);

             // Clicking the button should not invoke the handler.
             buttonElement.click();
             expect(testAppComponent.clickCount).toBe(0);
             async.done();
           });
         }), 1000);
    });

    describe('a[md-button]', () => {
      const anchorTemplate = `<a md-button href="http://google.com" [disabled]="isDisabled">Go</a>`;

      beforeEach(() => {
        builder = builder.overrideView(
            TestApp, new ViewMetadata({template: anchorTemplate, directives: [MdAnchor]}));
      });

      it('should remove disabled anchors from tab order', inject([AsyncTestCompleter], (async) => {
           builder.createAsync(TestApp).then(rootTestComponent => {
             let testAppComponent = rootTestComponent.debugElement.componentInstance;
             let anchorDebugElement = getChildDebugElement(rootTestComponent.debugElement, 'a');
             let anchorElement = anchorDebugElement.nativeElement;

             // The anchor should initially be in the tab order.
             expect(anchorElement.tabIndex).toBe(0);

             // After the disabled binding has been changed.
             testAppComponent.isDisabled = true;
             rootTestComponent.detectChanges();

             // The anchor should now be out of the tab order.
             expect(anchorElement.tabIndex).toBe(-1);

             async.done();
           });

           it('should preventDefault for disabled anchor clicks',
              inject([AsyncTestCompleter], (async) => {
                // No clear way to test this; see https://github.com/angular/angular/issues/3782
                async.done();
              }));
         }), 1000);
    });
  });
}

/** Gets a child DebugElement by tag name. */
function getChildDebugElement(parent: DebugElement, tagName: string): DebugElement {
  return parent.query(debugEl => debugEl.nativeElement.tagName.toLowerCase() == tagName);
}

/** Test component that contains an MdButton. */
@Component({selector: 'test-app'})
@View({
  directives: [MdButton],
  template:
      `<button md-button type="button" (click)="increment()" [disabled]="isDisabled">Go</button>`
})
class TestApp {
  clickCount: number = 0;
  isDisabled: boolean = false;

  increment() {
    this.clickCount++;
  }
}


text:
import { Export32 } from "../../";

export = Export32;