text:
require 'spec_helper'

describe PhoneClassifier do

  context "it classifies a phone number" do

    let(:phone_number) { "41791234567" }

    context "mobile numbers" do
      it "correctly classifies a mobile number" do
        PhoneClassifier.new(phone_number).kind.should == :mobile
      end

      it "correctly classifies a mobile number" do
        PhoneClassifier.new(phone_number).mobile?.should == true
      end

    end

    context "forbidden numbers" do
      let(:phone_number) { "4180012345" }
      it "correctly classifies a forbidden number" do
        PhoneClassifier.new(phone_number).kind.should == :forbidden
      end

      it "correctly classifies a forbidden number" do
        PhoneClassifier.new(phone_number).forbidden?.should == true
      end
    end

  end

  context "kinds of numbers" do

    context "Argentinan Numbers" do

      it "should set AG mobile numbers" do
        phone_number = "54111234566"
        PhoneClassifier.new(phone_number).kind.should == :mobile
      end

    end

    context "Austrian Numbers" do

      it "should set AT mobile numbers" do
        phone_number = "4369911031234"
        PhoneClassifier.new(phone_number).kind.should == :mobile
      end

    end

    context "Australian Numbers" do

      it "should set AU mobile numbers" do
        phone_number = "61412123123"
        PhoneClassifier.new(phone_number).kind.should == :mobile
      end

      it "should set AU forbideen numbers" do
        phone_number = "61190123123"
        PhoneClassifier.new(phone_number).kind.should == :forbidden
      end

    end
    context "Belgium Numbers" do

      it "should set BE mobile numbers" do
        phone_number = "32497546747"
        PhoneClassifier.new(phone_number).kind.should == :mobile
      end

      it "should set BE land numbers" do
        phone_number = "326279584"
        PhoneClassifier.new(phone_number).kind.should == :landline

      end

    end

    context 'Brazil numbers' do
      # see http://www.itu.int/dms_pub/itu-t/oth/02/02/T020200001D0001PDFE.pdf

      before(:each) do
        @new_mobile_numbering_ndcs = %w{11 12 13 14 15 16 17 18 19 21 22 24 27 28 91 92 93 94 95 96 97 98 99}
        @old_mobile_numbering_ndcs = %w{31 32 33 34 35 37 38 41 42 43 44 45 46 47 48 49 51 52 53 54 55 61 62 63 64 65 66 67 68 69 71 73 74 75 77 79 81 82 83 84 85 86 87 88 89}
      end

      it 'returns "mobile" for special states converted to new numbering plan from ANATEL (9\d{8})' do
        @new_mobile_numbering_ndcs.each do |state_code|
          phone_number = "55#{state_code}993051123"
          PhoneClassifier.new(phone_number).kind.should eq(:mobile), phone_number
        end
      end

      it 'returns "mobile" for states still using old mobile numbering plan' do
        # the old numbering plan used 9,8,7,6 as the first digit in the subscriber number to indicate a mobile number
        @old_mobile_numbering_ndcs.each do |state_code|
          6.upto(9).each do |initial_digit|
            phone_number = "55#{state_code}#{initial_digit}3051123"
            PhoneClassifier.new(phone_number).kind.should eq(:mobile), phone_number
          end
        end
      end

      it 'returns "landline" for special states already using the new mobile numbering plan' do
        @new_mobile_numbering_ndcs.each do |state_code|
          0.upto(8).each do |initial_digit|
            phone_number = "55#{state_code}#{initial_digit}3051123"
            PhoneClassifier.new(phone_number).kind.should eq(:landline), phone_number
          end
        end
      end

      it 'returns "landline" for states still using old mobile numbering plan' do
        @old_mobile_numbering_ndcs.each do |state_code|
          0.upto(5).each do |initial_digit|
            phone_number = "55#{state_code}#{initial_digit}3051123"
            PhoneClassifier.new(phone_number).kind.should eq(:landline), phone_number
          end
        end
      end

      it 'Mobino distributor checks' do
        %w(5511999089149 5511976076005).each do |phone_number|
          PhoneClassifier.new(phone_number).kind.should eq(:mobile), phone_number
        end
      end

    end

    context "Swiss Numbers" do

      it "should set CH mobile numbers" do
        phone_number = "41791234567"
        PhoneClassifier.new(phone_number).kind.should == :mobile

      end

      it "should set CH land numbers" do
        phone_number = "41444010930"
        PhoneClassifier.new(phone_number).kind.should == :landline
      end

    end

    context "Swedish Numbers" do

      it "should set SE mobile numbers" do
        phone_number = "46729443333"
        PhoneClassifier.new(phone_number).kind.should == :mobile
      end

      it 'properly formats the number' do
        phone_number = '46729443333'
        Phony.format(phone_number, format: :+).should eq('+46 72 944 33 33'), phone_number

        phone_number = '46734177166'
        Phony.format(phone_number, format: :+).should eq('+46 73 417 71 66'), phone_number
      end

    end

    context "Slovenian Numbers" do

      it "should set SL mobile numbers" do
        phone_number = "38651336595"
        PhoneClassifier.new(phone_number).kind.should == :mobile

      end

    end

    context "German Numbers" do

      it "should set DE mobile numbers" do
        phone_number = "49170123456"
        PhoneClassifier.new(phone_number).kind.should == :mobile
      end

      it "should set DE land numbers" do
        phone_number = "4977317983830"
        PhoneClassifier.new(phone_number).kind.should == :landline
      end

      it "should set DE service and paid numbers" do
        phone_number = "491805878323"
        PhoneClassifier.new(phone_number).kind.should == :forbidden
      end

    end

    context "Danish Numbers" do

      it "should set DK mobile numbers" do
        phone_number = "4540532577"
        PhoneClassifier.new(phone_number).kind.should == :mobile
      end

      it "should set DK mobile numbers" do
        phone_number = "4529727515"
        PhoneClassifier.new(phone_number).kind.should == :mobile
      end

      it "should set DK forbidden numbers" do
        phone_number = "4580727515"
        PhoneClassifier.new(phone_number).kind.should == :forbidden
      end

      it "should set DK land numbers" do
        phone_number = "4545862577"
        PhoneClassifier.new(phone_number).kind.should == :landline
      end

    end

    context "French Numbers" do

      it "should set FR forbidden numbers" do
        phone_number = "33810459827"
        PhoneClassifier.new(phone_number).kind.should == :forbidden
      end

      it "should set FR mobile numbers (6)" do
        phone_number = "33653832227"
        PhoneClassifier.new(phone_number).kind.should == :mobile
      end

      it "should set FR mobile numbers (7)" do
        phone_number = "33753832227"
        PhoneClassifier.new(phone_number).kind.should == :mobile
      end

      it "should set FR land numbers" do
        phone_number = "33953832227"
        PhoneClassifier.new(phone_number).kind.should == :landline
      end

    end

    context "Italian Numbers" do

      it "should set IT mobile numbers" do
        phone_number = "393357210499"
        PhoneClassifier.new(phone_number).kind.should == :mobile
      end

      it "should set IT land numbers" do
        phone_number = "390117210499"
        PhoneClassifier.new(phone_number).kind.should == :landline
      end

    end

    context 'Mexican Numbers' do
      it 'defines the numbers as mobile numbers' do
        # NOTE: to dial Mexican cell phones from abroad, you need to add 1 following the country code
        # In our case, this is how the numbers are stored and this is why when we check for a mobile/landline
        # we require that the 1 be present following the country code

        phone_number = "5215531048111"
        PhoneClassifier.new(phone_number).kind.should eq(:mobile), phone_number

        phone_number = "5216641231212"
        PhoneClassifier.new(phone_number).kind.should eq(:mobile), phone_number
      end

      it 'defines the numbers as landline numbers' do
        phone_number = "525531048111"
        PhoneClassifier.new(phone_number).kind.should eq(:landline), phone_number

        phone_number = "526641231212"
        PhoneClassifier.new(phone_number).kind.should eq(:landline), phone_number
      end
    end
    context "Netherlands Numbers" do

      it "should set NL mobile numbers" do
        phone_number = "31612345678"
        PhoneClassifier.new(phone_number).kind.should == :mobile
      end

      it "should set NL land numbers" do
        phone_number = "31201234567"
        PhoneClassifier.new(phone_number).kind.should == :landline
      end
      it "should set NL forbidden numbers" do
        phone_number = "318001234567"
        PhoneClassifier.new(phone_number).kind.should == :forbidden
      end

    end

    context "Polish Numbers" do

      it "should set PL mobile numbers" do
        phone_number = "48501224455"
        PhoneClassifier.new(phone_number).kind.should == :mobile
      end

      it "should set PL land numbers" do
        phone_number = "48121123123"
        PhoneClassifier.new(phone_number).kind.should == :landline
      end

      it "should set PL forbidden numbers" do
        phone_number = "488001234567"
        PhoneClassifier.new(phone_number).kind.should == :forbidden
      end

    end

    context "Spanish Numbers" do

      it "should set ES mobile numbers" do
        phone_number = "34 611 123 123"
        PhoneClassifier.new(phone_number).kind.should == :mobile
      end

      it "should set ES forbidden numbers (800)" do
        phone_number = "34800 123 123"
        PhoneClassifier.new(phone_number).kind.should == :forbidden
      end

      it "should set ES forbidden numbers (900)" do
        phone_number = "34901 123 123"
        PhoneClassifier.new(phone_number).kind.should == :forbidden
      end

      it "should set ES land numbers" do
        phone_number = "34822 123 123"
        PhoneClassifier.new(phone_number).kind.should == :landline
      end

    end

    context "Nigerian Numbers" do
      # http://www.ncc.gov.ng/index.php?option=com_content&view=article&id=113&Itemid=102
      # http://www.ncc.gov.ng/index.php?option=com_docman&task=doc_download&gid=92&Itemid=

      %w(70 80 81 90).each do |prefix|
        (0..9).each do |suffix|
          ndc = "#{prefix}#{suffix}"
          phone_number = "234#{ndc}1234567"

          it "classifies the number #{phone_number} as a valid, mobile number" do
            PhoneClassifier.new(phone_number).kind.should eq(:mobile), phone_number
            Phony.plausible?(phone_number).should eq(true), phone_number
          end
        end
      end

      %w(70 80 81 90).each do |prefix|
        (0..9).each do |suffix|
          ndc = "#{prefix}#{suffix}"
          phone_number = "234#{ndc}123456"

          it "classifies the number #{phone_number} as possibly valid mobile number" do
            PhoneClassifier.new(phone_number).kind.should eq(:mobile), phone_number
            Phony.plausible?(phone_number).should eq(false), phone_number
          end
        end
      end

      %w(70 80 81 90).each do |prefix|
        (0..9).each do |suffix|
          ndc = "#{prefix}#{suffix}"
          phone_number = "234#{ndc}12345678"

          it "classifies the number #{phone_number} as a possibly valid mobile number" do
            PhoneClassifier.new(phone_number).kind.should eq(:mobile), phone_number
            Phony.plausible?(phone_number).should eq(false), phone_number
          end
        end
      end
    end

    context "Luxemborgian Numbers" do

      it "should set Luxembourg mobile numbers" do
        phone_number = "352661 555 555"
        PhoneClassifier.new(phone_number).kind.should == :mobile
      end

      it "should set Luxemborgian land numbers" do
        phone_number = "3522467 55 55 55"
        PhoneClassifier.new(phone_number).kind.should == :landline
      end

      #it "should set Luxemborgian forbidden numbers" do
      #  phone_number = TelephoneNumber.make(:base_number => "800 5 55 55",
      #                                          :country_code => "352",
      #                                          :telephonable => @client)
      #  phone_number.valid?
      #  phone_number.kind.should == :forbidden
      #end

    end

  end

  context "Haitian Numbers" do

    it "should set mobile numbers" do
      phone_number = "509 34 12 1234"
      PhoneClassifier.new(phone_number).kind.should == :mobile
    end

    it "should set service numbers " do
      phone_number = "509 81 12 1234"
      PhoneClassifier.new(phone_number).kind.should == :forbidden
    end
  end

  context "Hong Kong Numbers" do

    it "should set mobile numbers" do
      phone_number = "852 6123 1234"
      PhoneClassifier.new(phone_number).kind.should == :mobile
    end

    it "should set service numbers " do
      phone_number = "852 8123 1234"
      PhoneClassifier.new(phone_number).kind.should == :forbidden
    end
  end

  context 'Indian Numbers' do

    it 'should set mobile numbers' do
      phone_number = '91 99 111 22 111'
      PhoneClassifier.new(phone_number).kind.should == :mobile
    end

    it 'should set service numbers ' do
      phone_number = '91 96 111 22 111'
      PhoneClassifier.new(phone_number).kind.should == :forbidden
    end
  end

  context "Iranian Numbers" do
    # http://en.wikipedia.org/wiki/Telephone_numbers_in_Iran
    # http://www.itu.int/dms_pub/itu-t/oth/02/02/T02020000660001PDFE.pd

    it "should set landline numbers" do
      phone_number = "98 21 1123 1234"
      PhoneClassifier.new(phone_number).kind.should == :landline
    end

    it "should set service numbers" do
      phone_number = "98 961 123 1234"
      PhoneClassifier.new(phone_number).kind.should == :forbidden
    end

    [901, 902].push( (910..939).to_a ).flatten.each do |ndc|
      phone_number = "98#{ndc}1234567"

      it "classifies the number #{phone_number} as a valid, mobile number" do
        PhoneClassifier.new(phone_number).kind.should eq(:mobile), phone_number
        Phony.plausible?(phone_number).should eq(true), phone_number
      end
    end

    [901, 902].push( (910..939).to_a ).flatten.each do |ndc|
      phone_number = "98#{ndc}123456"

      it "classifies the number #{phone_number} as a possibly valid mobile number" do
        PhoneClassifier.new(phone_number).kind.should eq(:mobile), phone_number
        Phony.plausible?(phone_number).should eq(false), phone_number
      end
    end

    [901, 902].push( (910..939).to_a ).flatten.each do |ndc|
      phone_number = "98#{ndc}12345678"

      it "classifies the number #{phone_number} as a possibly valid mobile number" do
        PhoneClassifier.new(phone_number).kind.should eq(:mobile), phone_number
        Phony.plausible?(phone_number).should eq(false), phone_number
      end
    end
  end

  context "Iraqi Numbers" do

    it "should set landline numbers" do
      phone_number = "964 40 123 456"
      PhoneClassifier.new(phone_number).kind.should == :landline
    end

    it "should set mobile numbers" do
      phone_number = "964 753 123 4567"
      PhoneClassifier.new(phone_number).kind.should == :mobile
    end

  end

  context 'Israelian numbers' do
    it 'sets landline number' do
      phone_number = "972 2 123 1234"
      PhoneClassifier.new(phone_number).kind.should == :landline
    end

    it 'sets mobile numbers' do
      phone_number = "972 59 123 1234"
      PhoneClassifier.new(phone_number).kind.should == :mobile
    end

    it 'sets service numbers' do
      phone_number = "972 1 123 1234"
      PhoneClassifier.new(phone_number).kind.should == :forbidden
    end
  end

  context 'Ivory Coast numbers' do
    # http://www.itu.int/dms_pub/itu-t/oth/02/02/T02020000310001PDFE.pdf
    # http://en.wikipedia.org/wiki/Telephone_numbers_in_Ivory_Coast

    %w(20 21 22 23 24 30 31 32 33 34 35 36).each do |ndc|
      phone_number = "225#{ndc}123456"

      it "classifies the number #{phone_number} as a valid, landline number" do
        PhoneClassifier.new(phone_number).kind.should eq(:landline), phone_number
        Phony.plausible?(phone_number).should eq(true), phone_number
      end
    end

    %w(01 02 03 04 05 06 07 08 09 44 45 46 47 48 49 50 54 60 66 67 69 77 78).each do |ndc|
      phone_number = "225#{ndc}123456"

      it "classifies the number #{phone_number} as a valid, mobile number" do
        PhoneClassifier.new(phone_number).kind.should eq(:mobile), phone_number
        Phony.plausible?(phone_number).should eq(true), phone_number
      end
    end

    %w(01 02 03 04 05 06 07 08 09 44 45 46 47 48 49 50 54 60 66 67 69 77 78).each do |ndc|
      phone_number = "225#{ndc}12345"

      it "classifies the number #{phone_number} as a possibly valid mobile number" do
        PhoneClassifier.new(phone_number).kind.should eq(:mobile), phone_number
        Phony.plausible?(phone_number).should eq(false), phone_number
      end
    end

    %w(01 02 03 04 05 06 07 08 09 44 45 46 47 48 49 50 54 60 66 67 69 77 78).each do |ndc|
      phone_number = "225#{ndc}1234567"

      it "classifies the number #{phone_number} as a possibly valid mobile number" do
        PhoneClassifier.new(phone_number).kind.should eq(:mobile), phone_number
        Phony.plausible?(phone_number).should eq(false), phone_number
      end
    end
  end

  context "Malaysian Numbers" do

    it "should set Malaysian mobile numbers" do
      phone_number = "60 11 1234 5678"
      PhoneClassifier.new(phone_number).kind.should == :mobile
    end

  end

  context "Moroccan Numbers" do
    # http://en.wikipedia.org/wiki/Telephone_numbers_in_Morocco

    it "classifies the number 212612345678 as a valid, mobile number" do
      phone_number = "212612345678"

      PhoneClassifier.new(phone_number).kind.should eq(:mobile), phone_number
      Phony.plausible?(phone_number).should eq(true), phone_number
    end

    it "classifies the number 21261234567 as a possibly valid mobile number" do
      phone_number = "21261234567"

      PhoneClassifier.new(phone_number).kind.should eq(:mobile), phone_number
      Phony.plausible?(phone_number).should eq(false), phone_number
    end

    it "classifies the number 2126123456789 as a possibly valid mobile number" do
      phone_number = "2126123456789"

      PhoneClassifier.new(phone_number).kind.should eq(:mobile), phone_number
      Phony.plausible?(phone_number).should eq(false), phone_number
    end

    it "should set Moroccan landline numbers " do
      phone_number = "212 45 1234 123"
      PhoneClassifier.new(phone_number).kind.should == :landline
    end
  end

  context "Myanmar Numbers" do
    it "should set mobile numbers" do
      phone_number = "95 9 250 233 058"
      PhoneClassifier.new(phone_number).kind.should == :mobile
    end
  end

  context "Seychelle Numbers" do

    it "should set mobile numbers" do
      phone_number = "248 2 12 34 56"
      PhoneClassifier.new(phone_number).kind.should == :mobile
    end

    it "should set service numbers " do
      phone_number = "248 8 12 34 56"
      PhoneClassifier.new(phone_number).kind.should == :forbidden
    end
  end

  context "Singapore Numbers" do

    it "should set mobile numbers" do
      phone_number = "65 8123 1234"
      PhoneClassifier.new(phone_number).kind.should == :mobile
    end

    it "should set service numbers " do
      phone_number = "65 3123 1234"
      PhoneClassifier.new(phone_number).kind.should == :forbidden
    end
  end

  context 'South Africa' do
    # http://www.itu.int/dms_pub/itu-t/oth/02/02/T02020000C10001PDFE.pdf
    # Page 25, Table 4
    %w(60 61 62 63 64 65 70 71 72 73 74 76 77 78 79 81 82 83 84).each do |ndc|
      phone_number = "27#{ndc}1234567"
      it "classifies the number #{phone_number} as a valid, mobile number" do
        PhoneClassifier.new(phone_number).kind.should eq(:mobile), phone_number
        Phony.plausible?(phone_number).should eq(true), phone_number
      end
    end
  end

  context "Sri Lanka Numbers" do

    it "should set mobile numbers" do
      phone_number = "94 071 123 12 12"
      PhoneClassifier.new(phone_number).kind.should == :mobile
    end

  end

  context "Tanzania Numbers" do

    it "should set mobile numbers" do
      phone_number = "255 61 123 1234"
      PhoneClassifier.new(phone_number).kind.should == :mobile
    end

    it "should set service numbers " do
      phone_number = "255 801 23 1234"
      PhoneClassifier.new(phone_number).kind.should == :forbidden
    end
  end

  context 'Turkey numbers' do
    phone_number = "90 532 412 5111"
    PhoneClassifier.new(phone_number).kind.should == :mobile
  end

  context "UK Numbers" do

    %w(447412121314 447785330971).each do |phone_number|
      it "classifies the number #{phone_number} as a valid UK mobile" do
        PhoneClassifier.new(phone_number).kind.should eq(:mobile), phone_number
        Phony.plausible?(phone_number).should eq(true), phone_number
      end
    end

    %w(44741 447412 4474123 44741234 447412345 44741234567 4474123456789 44741234567890).each do |phone_number|
      it "classifies the number #{phone_number} as an invalid UK mobile" do
        Phony.plausible?(phone_number).should eq(false), phone_number
      end
    end

    it 'classifies the number 442012121314 as a valid UK landline' do
      phone_number = '442012121314'
      PhoneClassifier.new(phone_number).kind.should eq(:landline), phone_number
      Phony.plausible?(phone_number).should eq(true), phone_number
    end

    it 'classifies the number 4480012121314 as a forbidden UK number' do
      phone_number = '4480012121314'
      PhoneClassifier.new(phone_number).kind.should == :forbidden
    end

  end

  context 'Uzbekistan' do
    # http://www.itu.int/dms_pub/itu-t/oth/02/02/T02020000E10001MSWE.doc
    %w(90 91 92 93 94 97 98 99).each do |ndc|
      phone_number = "998#{ndc}1234567"
      it "classifies the number #{phone_number} as a valid, mobile number" do
        PhoneClassifier.new(phone_number).kind.should eq(:mobile), phone_number
        Phony.plausible?(phone_number).should eq(true), phone_number
      end
    end

    %w(90 91 92 93 94 97 98 99).each do |ndc|
      phone_number = "998#{ndc}123456"
      it "classifies the number #{phone_number} as a possible mobile number" do
        PhoneClassifier.new(phone_number).kind.should eq(:mobile), phone_number
        Phony.plausible?(phone_number).should eq(false), phone_number
      end
    end

    %w(90 91 92 93 94 97 98 99).each do |ndc|
      phone_number = "998#{ndc}12345678"
      it "classifies the number #{phone_number} as a possible mobile number" do
        PhoneClassifier.new(phone_number).kind.should eq(:mobile), phone_number
        Phony.plausible?(phone_number).should eq(false), phone_number
      end
    end

    %w(61 62 65 66 67 69 71 72 73 74 75 76 79).each do |ndc|
      phone_number = "998#{ndc}1234567"
      it "classifies the number #{phone_number} as a valid, landline number" do
        PhoneClassifier.new(phone_number).kind.should eq(:landline), phone_number
        Phony.plausible?(phone_number).should eq(true), phone_number
      end
    end
  end

  context 'Zambian numbers' do
    # see http://www.itu.int/oth/T02020000E8/en

    it 'returns "mobile" for CellZ' do
      phone_number = '260955123456'
      PhoneClassifier.new(phone_number).kind.should eq(:mobile), phone_number
    end

    it 'returns "mobile" for MTN' do
      phone_number = '260966123456'
      PhoneClassifier.new(phone_number).kind.should eq(:mobile), phone_number
    end

    it 'returns "mobile" for Celtel' do
      phone_number = '260977123456'
      PhoneClassifier.new(phone_number).kind.should eq(:mobile), phone_number

      phone_number = '260978123456'
      PhoneClassifier.new(phone_number).kind.should eq(:mobile), phone_number

      phone_number = '260979123456'
      PhoneClassifier.new(phone_number).kind.should eq(:mobile), phone_number
    end

    it 'returns "landline" for non-mobile 95xxx numbers' do
      ([*0..9] - [5]).each do |digit|
        # 5 is the mobile indicator for the ndc 95
        phone_number = "26095#{digit}123456"
        PhoneClassifier.new(phone_number).kind.should eq(:landline), phone_number
      end
    end

    it 'returns "landline" for non-mobile 96xxx numbers' do
      ([*0..9] - [6]).each do |digit|
        # 6 is the mobile indicator for the ndc 96
        phone_number = "26096#{digit}123456"
        PhoneClassifier.new(phone_number).kind.should eq(:landline), phone_number
      end
    end

    it 'returns "landline" for non-mobile 97xxx numbers' do
      0.upto(6).each do |digit|
        # 7-9 is the mobile indicator for the ndc 97
        phone_number = "26097#{digit}123456"
        PhoneClassifier.new(phone_number).kind.should eq(:landline), phone_number
      end
    end

    it 'returns "landline" for landline numbers' do
      # 021Y XXXXXX where Y is in [1..8]
      1.upto(8).each do |digit|
        phone_number = "26021#{digit}123456"
        PhoneClassifier.new(phone_number).kind.should eq(:landline), phone_number
      end
    end
  end

  context 'Zimbabwean numbers' do
    # http://www.itu.int/dms_pub/itu-t/oth/02/02/T02020000E90002PDFE.pdf
    # Page 5, Section 6 (Public Mobile Telecommunication Network Services)

      { 'NetOne Celluar'     => %w(71),
        'Telecel Zimbabwe'   => %w(73),
        'Econet Wireless'    => %w(77 78) }.each do |operator, ndcs|

        ndcs.each do |ndc|
          phone_number = "263#{ndc}2345678"
          it "classifies the number #{phone_number} as a valid, mobile number for the operator '#{operator}'" do
            PhoneClassifier.new(phone_number).kind.should eq(:mobile), phone_number
            Phony.plausible?(phone_number).should eq(true), phone_number
          end
        end

      end
  end

  context 'Brazil numbers' do
    # see http://www.itu.int/dms_pub/itu-t/oth/02/02/T020200001D0001PDFE.pdf

    before(:each) do
      @new_mobile_numbering_ndcs = %w{11 12 13 14 15 16 17 18 19 21 22 24 27 28 91 92 93 94 95 96 97 98 99}
      @old_mobile_numbering_ndcs = %w{31 32 33 34 35 37 38 41 42 43 44 45 46 47 48 49 51 52 53 54 55 61 62 63 64 65 66 67 68 69 71 73 74 75 77 79 81 82 83 84 85 86 87 88 89}
    end

    it 'returns "mobile" for special states converted to new numbering plan from ANATEL (9\d{8})' do
      @new_mobile_numbering_ndcs.each do |state_code|
        phone_number = "55#{state_code}993051123"
        PhoneClassifier.new(phone_number).kind.should eq(:mobile), phone_number
      end
    end

    it 'returns "mobile" for states still using old mobile numbering plan' do
      # the old numbering plan used 9,8,7,6 as the first digit in the subscriber number to indicate a mobile number
      @old_mobile_numbering_ndcs.each do |state_code|
        6.upto(9).each do |initial_digit|
          phone_number = "55#{state_code}#{initial_digit}3051123"
          PhoneClassifier.new(phone_number).kind.should eq(:mobile), phone_number
        end
      end
    end

    it 'returns "landline" for special states already using the new mobile numbering plan' do
      @new_mobile_numbering_ndcs.each do |state_code|
        0.upto(8).each do |initial_digit|
          phone_number = "55#{state_code}#{initial_digit}3051123"
          PhoneClassifier.new(phone_number).kind.should eq(:landline), phone_number
        end
      end
    end

    it 'returns "landline" for states still using old mobile numbering plan' do
      @old_mobile_numbering_ndcs.each do |state_code|
        0.upto(5).each do |initial_digit|
          phone_number = "55#{state_code}#{initial_digit}3051123"
          PhoneClassifier.new(phone_number).kind.should eq(:landline), phone_number
        end
      end
    end

    it 'Mobino distributor checks' do
      %w(5511999089149 5511976076005).each do |phone_number|
        PhoneClassifier.new(phone_number).kind.should eq(:mobile), phone_number
        Phony.plausible?(phone_number).should eq(true), phone_number
      end
    end

  end

end


text:
<?php

namespace Rawebone\Ormish\Actions;

use Rawebone\Ormish\Table;
use Rawebone\Ormish\Database;
use Rawebone\Ormish\GatewayInterface;
use Rawebone\Ormish\Executor;
use Rawebone\Ormish\SqlGeneratorInterface;
use Rawebone\Ormish\Utilities\Populater;
use Rawebone\Ormish\Utilities\ObjectCreator;
use Rawebone\Ormish\Utilities\EntityManager;

/**
 * Handles creating instance of Action objects, this is more convenient for
 * working with actions in the Gateway.
 */
class ActionFactory
{
    protected $entityManager;
    protected $executor;
    protected $generator;
    protected $objectCreator;
    protected $populater;

    public function __construct(EntityManager $em, Executor $ex, Populater $pop,
        SqlGeneratorInterface $gen, ObjectCreator $oc)
    {
        $this->entityManager = $em;
        $this->executor = $ex;
        $this->generator = $gen;
        $this->populater = $pop;
        $this->objectCreator = $oc;
    }

    public function create($name, Database $db, Table $tbl, GatewayInterface $gw)
    {
        return $this->objectCreator->create($name, array(
                $db,
                $gw,
                $this->entityManager,
                $tbl,
                $this->executor,
                $this->populater,
                $this->generator
            ));
    }
}

redpajama_set_name: RedPajamaGithub


text:
export MAGICK_TMPDIR="/work/$(whoami)"

DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
CHUNK_SIZE=50
SBATCH_OPTIONS="-n 1 -N 1 --time=$((CHUNK_SIZE * 6)) --mem-per-cpu=4096"
CONVERT_OPTIONS="-type Grayscale -background white +matte -depth 32"
declare -a extensions=("_jp2.zip" "_tif.zip" "_raw_jp2.zip" ".pdf" "_bw.pdf")

LANG="${1}"
shift

while (($#)); do
  for extension in "${extensions[@]}"; do
    url="https://archive.org/download/${1}/${1}${extension}"
    curl_output=$(curl --fail -L -I "${url}" 2>&1)
    if [ $? -eq 0 ]; then
      mkdir -pv "${1}"
      pushd "${1}"
      filename="${1}${extension}"
      if [ ! -f "$filename" ]; then
        echo "Downloading $filename from $url"
        curl -s -L ${url} -o "${filename}"
        case "${filename##*.}" in
          zip)
            echo "Unzipping..."
            unzip -ojq "${filename}" && rm "${filename}" && touch "${filename}"
            ;;
          pdf)
            echo "Converting..."
            convert -density 300 "${filename}" $CONVERT_OPTIONS "${1}_%05d.png" && rm "${filename}" && touch "${filename}"
            ;;
          *)
            echo "Unknown extension"
            ;;
        esac
      fi

      # dwnload any existing Latin OCR results; anyone else using this script should probably delete this block
      wget "https://github.com/latin-ocr/${1}/archive/master.zip"
      if [ $? -eq 0 ]; then
        unzip -j -o master.zip
        rm *.hocr master.zip
      fi

      find . \( -name '*.jp2' -o -name '*.tif' -o -name '*.png' \) -print0 | xargs -0 -r -n $CHUNK_SIZE sbatch -J ${1} $SBATCH_OPTIONS $DIR/archive-ocr-slurm-runocr.sh "${LANG}"
      popd
      break
    fi
  done
  shift
done

echo "Done."


text:
package tpe.oo.interfaces.test;

import org.junit.Test;

import tpe.oo.interfaces.api.AnalogController;
import tpe.oo.interfaces.impl.AnalogControllerImpl;

/**
 * Tests für einen analogen Joystick.
 */
public class TestAnalogController extends TestDigitalController {

    /**
     * Testet einen anlogen Controller.
     */
    @Test
    public void testAnalogController() {
        AnalogController c = new AnalogControllerImpl();
        testAnalogController(c);
    }

    /**
     * Interne Hilfsmethode zum Test von analogen Controllern.
     *
     * @param c Controller, der getestet wird
     */
    protected void testAnalogController(AnalogController c) {
        c.up(0.5);
        assertPointEquals(0, 0, c.getPosition());
        c.up(0.5);
        assertPointEquals(0, -1, c.getPosition());

        c.left(0.3);
        c.left(0.3);
        c.left(0.3);
        assertPointEquals(0, -1, c.getPosition());
        c.left(0.2);
        assertPointEquals(-1, -1, c.getPosition());

        c.down(1.0);
        assertPointEquals(-1, 0, c.getPosition());

        c.down(1.0);
        assertPointEquals(-1, 1, c.getPosition());
        c.down(1.0);
        assertPointEquals(-1, 2, c.getPosition());

        c.right(0.5);
        c.right(0.5);
        c.right(0.5);
        assertPointEquals(0, 2, c.getPosition());
    }
}


text:
     <link rel="stylesheet" type="text/css" href="panelStyle.css">

    	<button id="addPageToPrefs">Add</button> this page to the website list

    	<button id="goToPrefs">Go</button> to preferences


text:
/**
 *
 * /brief functions for stub resolving
 *
 */

/*
 * Copyright (c) 2013, NLnet Labs, Verisign, Inc.
 * 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 names of the copyright holders 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 Verisign, Inc. 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.
 */

#ifndef STUB_H_
#define STUB_H_

#include "getdns/getdns.h"
#include "types-internal.h"

getdns_return_t _getdns_submit_stub_request(getdns_network_req *netreq);

void _getdns_cancel_stub_request(getdns_network_req *netreq);

#endif

/* stub.h */


text:
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SpotLists.WP8.MusixMatch
{
    public class MatcherTrackGetResponse
    {
        [JsonProperty("message")]
        public MatchTrackerGetMessage Message { get;set;}
    }
}


text:
<?php

/**
 * This is the global start file.
 * It's where you can put anything you want loaded before the rest of the app, e.g.
 * helper functions, global constants, ini_set calls, etc.
 *
 * You can also make environment-specific start files by creating a new file named
 * from your computername/hostname in lowercase + '.php' in the app/start folder.
 */


text:
package com.github.cambierr.ovhapi.exception;

/**
 * Fired when trying to access a non-loaded field from a partial object
 *
 * @author cambierr
 */
public class PartialObjectException extends RuntimeException {

    public PartialObjectException() {
    }

    public PartialObjectException(String msg) {
        super(msg);
    }
}


text:
//using System;
//using System.Collections.Generic;
//using System.Linq;
//using System.Text;
//using System.Threading.Tasks;
//using OfficeOpenXml;
//using System.IO;

//namespace Evolution.Framework.Excel
//{
//    public class Excel2007:IExcel
//    {
//        public Excel2007(string path)
//        { filePath = path; }

//        private string filePath = "";
//        private ExcelWorkbook book = null;
//        private int sheetCount = 0;
//        private bool ifOpen = false;
//        private int currentSheetIndex = 0;
//        private ExcelWorksheet currentSheet = null;
//        private ExcelPackage ep = null;

//        public bool Open(string sheetName)
//        {
//            try
//            {
//                ep = new ExcelPackage(new FileInfo(filePath));

//                if (ep == null) return false;
//                book =ep.Workbook;
//                sheetCount = book.Worksheets.Count;
//                currentSheetIndex = 0;
//                currentSheet = book.Worksheets[sheetName];
//                ifOpen = true;
//            }
//            catch (Exception ex)
//            {
//                throw new Exception("打开文件失败,详细信息:" + ex.Message);
//            }
//            return true;
//        }

//        public void Close()
//        {
//            if (!ifOpen || ep == null) return;
//            ep.Dispose();
//        }

//        public bool ExistSheet(string sheetName)
//        {
//            int c = book.Worksheets.Where(t => t.Name == sheetName).Count();
//            return c > 0;
//        }

//        public ExcelVersion Version
//        { get { return ExcelVersion.Excel07; } }

//        public string FilePath
//        {
//            get { return filePath; }
//            set { filePath = value; }
//        }

//        public bool IfOpen
//        { get { return ifOpen; } }

//        public int SheetCount
//        { get { return sheetCount; } }

//        public int CurrentSheetIndex
//        {
//            get  { return currentSheetIndex; }
//            set
//            {
//                if (value != currentSheetIndex)
//                {
//                    if (value >= sheetCount)
//                        throw new Exception("工作表序号超出范围");
//                    currentSheetIndex = value;
//                    currentSheet =book.Worksheets[currentSheetIndex+1];
//                }
//            }
//        }

//        public int GetRowCount()
//        {
//            if (currentSheet == null) return 0;
//            return currentSheet.Dimension.End.Row;
//        }

//        public int GetColumnCount()
//        {
//            if (currentSheet == null) return 0;
//            return currentSheet.Dimension.End.Column;
//        }

//        public int GetCellCountInRow(int Row)
//        {
//            if (currentSheet == null) return 0;
//            if (Row >= currentSheet.Dimension.End.Row) return 0;
//            return currentSheet.Dimension.End.Column;
//        }

//        public string GetCellValue(int Row, int Col)
//        {
//            if (currentSheet == null) return "";
//            if (Row >= currentSheet.Dimension.End.Row || Col >= currentSheet.Dimension.End.Column) return "";
//            object tmpO =currentSheet.GetValue(Row + 1, Col + 1);
//            if (tmpO == null) return "";
//            return tmpO.ToString();
//        }
//    }
//}


text:
namespace trm {

//
// Класс используется для подсчёта меток.
//
// Метод 'getFree' позволяет взять номер
// первой свободной метки.
//
// Пример, где может понадобится подсчёт меток:
// definition f1
// label 1:
// clear_first_and_second F1
//
// Для трансляции данного блока кода,
// нам понадобятся две свободные метки.
// Т.к. метка 1 занята, то будет использоваться
// следующая за ней свободная метка 2.
//
// В результате получаем:
// definition f1
// label 1:
// move t1, 0
// label 2:
// move F1[t1], 0
// inc t1
// cmp t1, 2
// jne 2
//
class LabelsCounter : public ICounter {
public:
    void process(const Json::Value &program) override;
    void updateState(const Json::Value &nextCmd) override;
    size_t getFree(size_t index) override;

private:
    std::unordered_map<std::string, size_t> counters;
    std::string currentProcedure;
    Optional<size_t> givenLabel;
};

}  // namespace trm


text:
package org.dynmap.hdmap;

import static org.dynmap.JSONUtils.s;

import java.io.IOException;
import java.util.BitSet;
import java.util.List;

import org.dynmap.Color;
import org.dynmap.ConfigurationNode;
import org.dynmap.DynmapCore;
import org.dynmap.MapManager;
import org.dynmap.common.DynmapCommandSender;
import org.dynmap.exporter.OBJExport;
import org.dynmap.renderer.DynmapBlockState;
import org.dynmap.utils.DynLongHashMap;
import org.dynmap.utils.MapChunkCache;
import org.dynmap.utils.MapIterator;
import org.dynmap.utils.BlockStep;
import org.json.simple.JSONObject;

public class TopoHDShader implements HDShader {
    private final String name;
    private final Color linecolor;  /* Color for topo lines */
    private final Color fillcolor[];  /* Color for nontopo surfaces */
    private final Color watercolor;
    private BitSet hiddenids;
    private final int linespacing;

    public TopoHDShader(DynmapCore core, ConfigurationNode configuration) {
        name = (String) configuration.get("name");

        fillcolor = new Color[256];   /* Color by Y */
        /* Load defined colors from parameters */
        for(int i = 0; i < 256; i++) {
            fillcolor[i] = configuration.getColor("color" + i,  null);
        }
        linecolor = configuration.getColor("linecolor", null);
        watercolor = configuration.getColor("watercolor", null);
        float wateralpha = configuration.getFloat("wateralpha", 1.0F);
        if (wateralpha < 1.0) {
            watercolor.setAlpha((int)(255 * wateralpha));
        }
        /* Now, interpolate missing colors */
        if(fillcolor[0] == null) {
            fillcolor[0] = new Color(0, 0, 0);
        }
        if(fillcolor[255] == null) {
            fillcolor[255] = new Color(255, 255, 255);
        }
        int starty = 0;
        for(int i = 1; i < 256; i++) {
            if(fillcolor[i] != null) {  /* Found color? */
                int delta = i - starty;
                Color c0 = fillcolor[starty];
                Color c1 = fillcolor[i];
                /* Interpolate missing colors since last one */
                for(int j = 1; j < delta; j++) {
                    fillcolor[starty + j] = new Color((c0.getRed()*(delta-j) + c1.getRed()*j)/delta, (c0.getGreen()*(delta-j) + c1.getGreen()*j)/delta, (c0.getBlue()*(delta-j) + c1.getBlue()*j)/delta);
                }
                starty = i;  /* New start color */
            }
        }
        hiddenids = new BitSet();
        setHidden(DynmapBlockState.AIR_BLOCK);  /* Air is hidden always */
        List<Object> hidden = configuration.getList("hiddennames");
        if(hidden != null) {
            for(Object o : hidden) {
                if(o instanceof String) {
                    setHidden((String) o);
                }
            }
        }
        linespacing = configuration.getInteger("linespacing", 1);
    }

    private void setHidden(String bn) {
        DynmapBlockState bs = DynmapBlockState.getBaseStateByName(bn);
        for (int i = 0; i < bs.getStateCount(); i++) {
            DynmapBlockState b = bs.getState(i);
            hiddenids.set(b.globalStateIndex);
        }
    }

    @Override
    public boolean isBiomeDataNeeded() {
        return false;
    }

    @Override
    public boolean isRawBiomeDataNeeded() {
        return false;
    }

    @Override
    public boolean isHightestBlockYDataNeeded() {
        return false;
    }

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

    @Override
    public boolean isSkyLightLevelNeeded() {
        return false;
    }

    @Override
    public boolean isEmittedLightLevelNeeded() {
        return false;
    }

    @Override
    public String getName() {
        return name;
    }

    private class OurShaderState implements HDShaderState {
        private Color color[];
        private Color tmpcolor[];
        private Color c;
        protected MapIterator mapiter;
        protected HDMap map;
        private HDLighting lighting;
        private int scale;
        private int heightshift;    /* Divide to keep in 0-127 range of colors */
        private boolean inWater;
        final int[] lightingTable;

        private OurShaderState(MapIterator mapiter, HDMap map, MapChunkCache cache, int scale) {
            this.mapiter = mapiter;
            this.map = map;
            this.lighting = map.getLighting();
            if(lighting.isNightAndDayEnabled()) {
                color = new Color[] { new Color(), new Color() };
                tmpcolor = new Color[] { new Color(), new Color() };
            }
            else {
                color = new Color[] { new Color() };
                tmpcolor = new Color[] { new Color() };
            }
            this.scale = scale;
            c = new Color();
            /* Compute divider for Y - to map to existing color range */
            int wh = mapiter.getWorldHeight();
            heightshift = 0;
            while(wh > 256) {
                heightshift++;
                wh >>= 1;
            }
            if (MapManager.mapman.useBrightnessTable()) {
                lightingTable = cache.getWorld().getBrightnessTable();
            }
            else {
                lightingTable = null;
            }
            inWater = false;
        }
        /**
         * Get our shader
         */
        public HDShader getShader() {
            return TopoHDShader.this;
        }

        /**
         * Get our map
         */
        public HDMap getMap() {
            return map;
        }

        /**
         * Get our lighting
         */
        public HDLighting getLighting() {
            return lighting;
        }

        /**
         * Reset renderer state for new ray
         */
        public void reset(HDPerspectiveState ps) {
            for(int i = 0; i < color.length; i++)
                color[i].setTransparent();
            inWater = false;
        }

        private final boolean isHidden(DynmapBlockState blk) {
            return hiddenids.get(blk.globalStateIndex);
        }

        /**
         * Process next ray step - called for each block on route
         * @return true if ray is done, false if ray needs to continue
         */
        public boolean processBlock(HDPerspectiveState ps) {
            DynmapBlockState blocktype = ps.getBlockState();

            if (isHidden(blocktype)) {
                return false;
            }
            int y = mapiter.getY();
            if (y < 0) y = 0;	// Clamp at zero for now
            /* See if we're close to an edge */
            int[] xyz = ps.getSubblockCoord();
            // Only color lines when spacing is matched
            Color lcolor = ((y % linespacing) == 0)?linecolor:null;

            /* See which face we're on (only do lines on top face) */
            switch(ps.getLastBlockStep()) {
            case Y_MINUS:
            case Y_PLUS:
                if((lcolor != null) &&
                        (((xyz[0] == 0) && (isHidden(mapiter.getBlockTypeAt(BlockStep.X_MINUS)))) ||
                        ((xyz[0] == (scale-1)) && (isHidden(mapiter.getBlockTypeAt(BlockStep.X_PLUS)))) ||
                        ((xyz[2] == 0) && (isHidden(mapiter.getBlockTypeAt(BlockStep.Z_MINUS)))) ||
                        ((xyz[2] == (scale-1)) && (isHidden(mapiter.getBlockTypeAt(BlockStep.Z_PLUS)))))) {
                    c.setColor(lcolor);
                    inWater = false;
                }
                else if ((watercolor != null) && blocktype.isWater()) {
                    if (!inWater) {
                        c.setColor(watercolor);
                        inWater = true;
                    }
                    else {
                        return false;
                    }
                }
                else {
                    c.setColor(fillcolor[y >> heightshift]);
                    inWater = false;
                }
                break;
            default:
                if((lcolor != null) && (xyz[1] == (scale-1))) {
                    c.setColor(lcolor);
                    inWater = false;
                }
                else if ((watercolor != null) && blocktype.isWater()) {
                    if (!inWater) {
                        c.setColor(watercolor);
                        inWater = true;
                    }
                    else {
                        return false;
                    }
                }
                else {
                    c.setColor(fillcolor[y >> heightshift]);
                    inWater = false;
                }
                break;
            }
            /* Handle light level, if needed */
            lighting.applyLighting(ps, this, c, tmpcolor);

            /* If no previous color contribution, use new color */
            if(color[0].isTransparent()) {
                for(int i = 0; i < color.length; i++)
                    color[i].setColor(tmpcolor[i]);
                return (color[0].getAlpha() == 255);
            }
            /* Else, blend and generate new alpha */
            else {
                int alpha = color[0].getAlpha();
                int alpha2 = tmpcolor[0].getAlpha() * (255-alpha) / 255;
                int talpha = alpha + alpha2;
                if(talpha > 0)
                    for(int i = 0; i < color.length; i++)
                        color[i].setRGBA((tmpcolor[i].getRed()*alpha2 + color[i].getRed()*alpha) / talpha,
                              (tmpcolor[i].getGreen()*alpha2 + color[i].getGreen()*alpha) / talpha,
                              (tmpcolor[i].getBlue()*alpha2 + color[i].getBlue()*alpha) / talpha, talpha);
                else
                    for(int i = 0; i < color.length; i++)
                        color[i].setTransparent();

                return (talpha >= 254);   /* If only one short, no meaningful contribution left */
            }
        }
        /**
         * Ray ended - used to report that ray has exited map (called if renderer has not reported complete)
         */
        public void rayFinished(HDPerspectiveState ps) {
        }
        /**
         * Get result color - get resulting color for ray
         * @param c - object to store color value in
         * @param index - index of color to request (renderer specific - 0=default, 1=day for night/day renderer
         */
        public void getRayColor(Color c, int index) {
            c.setColor(color[index]);
        }
        /**
         * Clean up state object - called after last ray completed
         */
        public void cleanup() {
        }
        @Override
        public DynLongHashMap getCTMTextureCache() {
            return null;
        }
        @Override
        public int[] getLightingTable() {
            return lightingTable;
        }
        @Override
        public void setLastBlockState(DynmapBlockState new_lastbs) {
        }
    }

    /**
     *  Get renderer state object for use rendering a tile
     * @param map - map being rendered
     * @param cache - chunk cache containing data for tile to be rendered
     * @param mapiter - iterator used when traversing rays in tile
     * @param scale - scale of perspecitve
     * @return state object to use for all rays in tile
     */
    @Override
    public HDShaderState getStateInstance(HDMap map, MapChunkCache cache, MapIterator mapiter, int scale) {
        return new OurShaderState(mapiter, map, cache, scale);
    }

    /* Add shader's contributions to JSON for map object */
    public void addClientConfiguration(JSONObject mapObject) {
        s(mapObject, "shader", name);
    }
    @Override
    public void exportAsMaterialLibrary(DynmapCommandSender sender, OBJExport out) throws IOException {
        throw new IOException("Export unsupported");
    }
    private static final String[] nulllist = new String[0];
    @Override
    public String[] getCurrentBlockMaterials(DynmapBlockState blk, MapIterator mapiter, int[] txtidx, BlockStep[] steps) {
        return nulllist;
    }
}


text:
<?xml version="1.0" encoding="UTF-8" ?>
<class xmlns="http://xml.phpdox.net/src" full="PharFileInfo" namespace="" name="PharFileInfo">
  <extends name="SplFileInfo" full="SplFileInfo"/>
  <method name="chmod" abstract="false" static="false" visibility="public" final="false">
    <docblock>
      <description compact="Sets file-specific permission bits"/>
      <return type="void"/>
    </docblock>
    <parameter name="permissions" optional="false" byreference="false" type="int"/>
  </method>
  <method name="compress" abstract="false" static="false" visibility="public" final="false">
    <docblock>
      <description compact="Compresses the current Phar entry with either zlib or bzip2 compression"/>
      <return type="bool"/>
    </docblock>
    <parameter name="compression" optional="false" byreference="false" type="int"/>
  </method>
  <constructor name="__construct" abstract="false" static="false" visibility="public" final="false">
    <docblock>
      <description compact="Construct a Phar entry object"/>
      <return type="void"/>
    </docblock>
    <parameter name="entry" optional="false" byreference="false" type="string"/>
  </constructor>
  <method name="decompress" abstract="false" static="false" visibility="public" final="false">
    <docblock>
      <description compact="Decompresses the current Phar entry within the phar"/>
      <return type="bool"/>
    </docblock>
  </method>
  <method name="delMetadata" abstract="false" static="false" visibility="public" final="false">
    <docblock>
      <description compact="Deletes the metadata of the entry"/>
      <return type="bool"/>
    </docblock>
  </method>
  <method name="getCRC32" abstract="false" static="false" visibility="public" final="false">
    <docblock>
      <description compact="Returns CRC32 code or throws an exception if CRC has not been verified"/>
      <return type="int"/>
    </docblock>
  </method>
  <method name="getCompressedSize" abstract="false" static="false" visibility="public" final="false">
    <docblock>
      <description compact="Returns the actual size of the file (with compression) inside the Phar archive"/>
      <return type="int"/>
    </docblock>
  </method>
  <method name="getMetadata" abstract="false" static="false" visibility="public" final="false">
    <docblock>
      <description compact="Returns file-specific meta-data saved with a file"/>
      <return type="mixed"/>
    </docblock>
  </method>
  <method name="getPharFlags" abstract="false" static="false" visibility="public" final="false">
    <docblock>
      <description compact="Returns the Phar file entry flags"/>
      <return type="int"/>
    </docblock>
  </method>
  <method name="hasMetadata" abstract="false" static="false" visibility="public" final="false">
    <docblock>
      <description compact="Returns the metadata of the entry"/>
      <return type="bool"/>
    </docblock>
  </method>
  <method name="isCRCChecked" abstract="false" static="false" visibility="public" final="false">
    <docblock>
      <description compact="Returns whether file entry has had its CRC verified"/>
      <return type="bool"/>
    </docblock>
  </method>
  <method name="isCompressed" abstract="false" static="false" visibility="public" final="false">
    <docblock>
      <description compact="Returns whether the entry is compressed"/>
      <return type="bool"/>
    </docblock>
    <parameter name="compression_type" optional="true" byreference="false" type="int"/>
  </method>
  <method name="isCompressedBZIP2" abstract="false" static="false" visibility="public" final="false">
    <docblock>
      <description compact="Returns whether the entry is compressed using bzip2">This method has been removed from the phar extension as of version 2.0.0. Alternative implementations are available using PharFileInfo::isCompressed, PharFileInfo::decompress, and PharFileInfo::compress.</description>
      <return type="bool"/>
    </docblock>
  </method>
  <method name="isCompressedGZ" abstract="false" static="false" visibility="public" final="false">
    <docblock>
      <description compact="Returns whether the entry is compressed using gz">This method has been removed from the phar extension as of version 2.0.0. Alternative implementations are available using PharFileInfo::isCompressed, PharFileInfo::decompress, and PharFileInfo::compress.</description>
      <return type="bool"/>
    </docblock>
  </method>
  <method name="setCompressedBZIP2" abstract="false" static="false" visibility="public" final="false">
    <docblock>
      <description compact="Compresses the current Phar entry within the phar using Bzip2 compression">This method has been removed from the phar extension as of version 2.0.0. Alternative implementations are available using PharFileInfo::isCompressed, PharFileInfo::decompress, and PharFileInfo::compress.</description>
      <return type="bool"/>
    </docblock>
  </method>
  <method name="setCompressedGZ" abstract="false" static="false" visibility="public" final="false">
    <docblock>
      <description compact="Compresses the current Phar entry within the phar using gz compression">This method has been removed from the phar extension as of version 2.0.0. Alternative implementations are available using PharFileInfo::isCompressed, PharFileInfo::decompress, and PharFileInfo::compress.</description>
      <return type="bool"/>
    </docblock>
  </method>
  <method name="setMetadata" abstract="false" static="false" visibility="public" final="false">
    <docblock>
      <description compact="Sets file-specific meta-data saved with a file">PharFileInfo::setMetadata should only be used to store customized data in a file that cannot be represented with existing information stored with a file. Meta-data can significantly slow down the performance of loading a phar archive if the data is large, or if there are many files containing meta-data. It is important to note that file permissions are natively supported inside a phar; it is possible to set them with the PharFileInfo::chmod method. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed if the file is within a Phar archive. Files within PharData archives do not have this restriction.</description>
      <return type="void"/>
    </docblock>
    <parameter name="metadata" optional="false" byreference="false" type="object" class="mixed"/>
  </method>
  <method name="setUncompressed" abstract="false" static="false" visibility="public" final="false">
    <docblock>
      <description compact="Uncompresses the current Phar entry within the phar, if it is compressed">This method has been removed from the phar extension as of version 2.0.0. Alternative implementations are available using PharFileInfo::isCompressed, PharFileInfo::decompress, and PharFileInfo::compress.</description>
      <return type="bool"/>
    </docblock>
  </method>
</class>


text:
export run from './run.js';
export parse from './parse.js';
export evaluate from './evaluate.js';

export REPL from './repl.js';
export Context from './context.js';


text:
package com.hazelcast.internal.networking;

import javax.net.ssl.SSLEngine;
import java.io.Closeable;
import java.io.IOException;
import java.net.Socket;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.util.concurrent.ConcurrentMap;

/**
 * A Channel is a construct that can send/receive like Packets/ClientMessages etc. Connections use a channel to do the real
 * work; but there is no dependency of the com.hazelcast.internal.networking to a Connection (no cycles). This means that a
 * Channel can be used perfectly without Connection.
 *
 * The standard channel implementation is the {@link com.hazelcast.internal.networking.nio.NioChannel} that uses TCP in
 * combination with selectors to transport data. In the future also other channel implementations could be added, e.g.
 * UDP based.
 *
 * Channel data is read using a {@link ChannelInboundHandler}. E.g data from a socket is received and needs to get processed.
 * The {@link ChannelInboundHandler} can convert this to e.g. a Packet.
 *
 * Channel data is written using a {@link ChannelOutboundHandler}. E.g. a packet needs to be converted to bytes.
 *
 * A Channel gets initialized using the {@link ChannelInitializer}.
 *
 *
Future note

 * Below you can find some notes about the future of the Channel. This will hopefully act as a guide how to move forward.
 *
 *
Fragmentation

 * Packets are currently not fragmented, meaning that they are send as 1 atomic unit and this can cause a 2 way communication
 * blackout for operations (since either operation or response can get blocked). Fragmentation needs to be added to make sure
 * the system doesn't suffer from head of line blocking.
 *
 *
Ordering

 * In a channel messages don't need to be ordered. Currently they are, but as soon as we add packet fragmentation, packets
 * can get out of order. Under certain conditions you want to keep ordering, e.g. for events. In this case it should be possible
 * to have multiple streams in a channel. Within a stream there will be ordering.
 *
 *
Reliability

 * A channel doesn't provide reliability. TCP/IP does provide reliability, but 1: who says we want to keep using TCP/IP, but
 * if a TCP/IP connection is lost and needs to be re-established, packets are lost. Reliability can be added, just like TCP/IP
 * adds it; we don't discard the data until it has been acknowledged.
 *
 *
Flow and congestion control

 * On the Channel level we have no flow of congestion control; frames are always accepted no matter if on the sending side
 * the write-queue is overloaded, or on the receiving side the system is overloaded (e.g. many pending operations on the
 * operation queue). Just like with TCP/IP, flow and congestion control should be added.
 *
 *
UDP

 * With ordering, reliability and flow and congestion control in place, we can ask ourselves the question if UDP is not a
 * more practical solution.
 */
public interface Channel extends Closeable {

    /**
     * Returns the attribute map.
     *
     * Attribute map can be used to store data into a socket. For example to find the Connection for a Channel, one can
     * store the Connection in this channel using some well known key.
     *
     * @return the attribute map.
     */
    ConcurrentMap attributeMap();

    /**
     * @see java.nio.channels.SocketChannel#socket()
     *
     * This method will be removed from the interface. Only an explicit cast to NioChannel will expose the Socket.
     *
     * It is very important that the socket isn't closed directly; but one goes through the {@link #close()} method so that
     * interal administration of the channel is in sync with that of the socket.
     */
    Socket socket();

    /**
     * @return the remote address. Returned value could be null.
     */
    SocketAddress getRemoteSocketAddress();

    /**
     * @return the local address. Returned value could be null
     */
    SocketAddress getLocalSocketAddress();

    /**
     * Returns the last {@link com.hazelcast.util.Clock#currentTimeMillis()} a read of the socket was done.
     *
     * @return the last time a read from the socket was done.
     */
    long lastReadTimeMillis();

    /**
     * Returns the last {@link com.hazelcast.util.Clock#currentTimeMillis()} that a write to the socket completed.
     *
     * Writing to the socket doesn't mean that data has been send or received; it means that data was written to the
     * SocketChannel. It could very well be that this data is stuck somewhere in an io-buffer.
     *
     * @return the last time something was written to the socket.
     */
    long lastWriteTimeMillis();

    /**
     * This method will be removed from the Channel in the near future.
     *
     * @see java.nio.channels.SocketChannel#read(ByteBuffer)
     */
    int read(ByteBuffer dst) throws IOException;

    /**
     * This method will be removed from the Channel in the near future.
     *
     * @see java.nio.channels.SocketChannel#write(ByteBuffer)
     */
    int write(ByteBuffer src) throws IOException;

    /**
     * Closes inbound.
     *
     *
Not thread safe. Should be called in channel reader thread.

     *
     * Method will be removed once the TLS integration doesn't rely on subclassing this channel.
     *
     * @throws IOException
     */
    void closeInbound() throws IOException;

    /**
     * Closes outbound.
     *
     *
Not thread safe. Should be called in channel writer thread.

     *
     * Method will be removed once the TLS integration doesn't rely on subclassing this channel.
     *
     * @throws IOException
     */
    void closeOutbound() throws IOException;

    /**
     * Closes the Channel.
     *
     * When the channel already is closed, the call is ignored.
     */
    void close() throws IOException;

    /**
     * Checks if this Channel is closed. This method is very cheap to make.
     *
     * @return true if closed, false otherwise.
     */
    boolean isClosed();

    /**
     * Adds a ChannelCloseListener.
     *
     * @param listener the listener to register.
     * @throws NullPointerException if listener is null.
     */
    void addCloseListener(ChannelCloseListener listener);

    /**
     * Checks if this side is the Channel is in client mode or server mode.
     *
     * A channel is in client-mode if it initiated the connection, and in server-mode if it was the one accepting the connection.
     *
     * One of the reasons this property is valuable is for protocol/handshaking so that it is clear distinction between the
     * side that initiated the connection, or accepted the connection.
     *
     * @return true if this channel is in client-mode, false when in server-mode.
     * @see SSLEngine#getUseClientMode()
     */
    boolean isClientMode();

    /**
     * Queues the {@link OutboundFrame} to be written at some point in the future. No guarantee is made that the
     * frame actually is going to be written or received.
     *
     * @param frame the frame to write.
     * @return true if the frame was queued; false if rejected.
     */
    boolean write(OutboundFrame frame);

    /**
     * Flushes whatever needs to be written.
     *
     * Normally this call doesn't need to be made since {@link #write(OutboundFrame)} write the content; but in case of protocol
     * and TLS handshaking, such triggers are needed.
     */
    void flush();
}


text:
module.exports = {
    get passwordreset() {
        return require('./passwordreset');
    },

    get setup() {
        return require('./setup');
    },

    get posts() {
        return require('./posts');
    },

    get pages() {
        return require('./pages');
    },

    get invites() {
        return require('./invites');
    },

    get invitations() {
        return require('./invitations');
    },

    get members() {
        return require('./members');
    },

    get settings() {
        return require('./settings');
    },

    get tags() {
        return require('./tags');
    },

    get labels() {
        return require('./labels');
    },

    get users() {
        return require('./users');
    },

    get images() {
        return require('./images');
    },

    get oembed() {
        return require('./oembed');
    }
};


text:
package com.adenops.moustack.agent.client;

import com.adenops.moustack.agent.DeploymentException;

public abstract class AbstractPackagingClient {
	public abstract void init() throws DeploymentException;

	public abstract boolean install(String... packages) throws DeploymentException;

	public abstract boolean remove(String... packages) throws DeploymentException;
}


text:
Application = function() {
}

Application.prototype = {
    init: function(input, output, sync) {
        var that = this;

        this.input = input;
        this.output = output;
        this.update_outut_label();

        this.input_editor = this.setup_editor("input-source", false, this.input);
        $("#input-source").on('keyup change', function() {
            that.translate_code();
        });
        this.output_editor = this.setup_editor("output-source", true, this.output);

        if ( sync ) {
            this.input_editor.getSession().on('changeScrollTop', function(scroll) {
                that.output_editor.getSession().setScrollTop(scroll);
            });
            this.output_editor.getSession().on('changeScrollTop', function(scroll) {
                that.input_editor.getSession().setScrollTop(scroll);
            });
        }

        $("#menu-java").on('click', function() {
            that.output = "java";
            that.update_outut_label();
            that.update_mode(that.output_editor, that.output);
            that.translate_code();
        });
        $("#menu-csharp").on('click', function() {
            that.output = "csharp";
            that.update_outut_label();
            that.update_mode(that.output_editor, that.output);
            that.translate_code();
        });
        $("#menu-objch").on('click', function() {
            that.output = "objch";
            that.update_outut_label();
            that.update_mode(that.output_editor, that.output);
            that.translate_code();
        });
        $("#menu-objcmm").on('click', function() {
            that.output = "objcmm";
            that.update_outut_label();
            that.update_mode(that.output_editor, that.output);
            that.translate_code();
        });
    },

    setup_editor: function(id, readonly, language) {
        var editor = ace.edit($("#" + id).get(0));
        editor.$blockScrolling = Infinity;
        editor.setReadOnly(readonly);
        editor.setPrintMarginColumn(120);
        this.update_mode(editor, language);
        return editor;
    },

    update_outut_label: function() {
        if ( "java" == this.output ) {
            $("#label-output").text("Java");
        } else if ( "csharp" == this.output ) {
            $("#label-output").text("C#");
        } else if ( "objch" == this.output ) {
            $("#label-output").text("Objective-C - Header");
        } else if ( "objcmm" == this.output ) {
            $("#label-output").text("Objective-C - Source");
        }
    },

    update_mode(editor, language) {
        if ( "cpp" == language ) {
            editor.getSession().setMode("ace/mode/c_cpp");
        } else if ( "java" == language ) {
            editor.getSession().setMode("ace/mode/java");
        } else if ( "csharp" == language ) {
            editor.getSession().setMode("ace/mode/csharp");
        } else if ( "objch" == language || "objcmm" == language ) {
            editor.getSession().setMode("ace/mode/objectivec");
        }
    },

    translate_code: function() {
        var that = this;
        $.post("/api/v1/translate?output=" + this.output, this.input_editor.getValue(), function(response) {
            if ( !response ) {
                return;
            }
            that.output_editor.setValue(response);
            that.output_editor.session.selection.clearSelection();
            that.output_editor.getSession().setScrollTop(that.output_editor.getSession().getScrollTop());
        });
    },

    load_snippet: function(name) {
        var that = this;
        $.get("/content/" + name, function(response) {
            that.input_editor.setValue(response);
            that.input_editor.session.selection.clearSelection();
            that.translate_code();
        });
    }
};


text:
package org.apache.camel.processor;

import java.io.Serializable;

/**
 *
 */
// START SNIPPET: e1
public class Animal implements Serializable {
    private static final long serialVersionUID = 1L;
    private int id;
    private String name;

    public Animal() {
    }

    public Animal(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public Animal deepClone() {
        Animal clone = new Animal();
        clone.setId(getId());
        clone.setName(getName());
        return clone;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return id + " " + name;
    }
}
// END SNIPPET: e1


text:
package org.nmrg.model.client;

import java.io.Serializable;

import org.nmrg.entity.BaseEntity;
import org.nmrg.model.BaseModel;

/**
 * 用户设备信息
 * Created by admin on 2017/9/20.
 */
public class EquipmentModel implements Serializable {

    private static final long serialVersionUID = -8219874461856605060L;

    // --- 设备名[移动端是显示手持设备品牌:华为/小米/苹果。。。]
    private String name;
    // --- 设备型号[移动端设备型号]
    private String equipmentType;
    // --- 操作平台名[系统名]
    private String systemPlatformName;
    // --- 操作系统版本
    private String systemVersion;
    // --- 浏览器名
    private String browserName;
    // --- 浏览器版本
    private String browserVersion;
    // --- 浏览器语言
    private String browserLanguage;
    // --- 浏览器内核
    private String browserCore;
    // --- 分辨率
    private String resolutionRatio;
    // --- userAgent
    private String userAgent;

    public EquipmentModel() {
    }

    public EquipmentModel(String name, String equipmentType, String systemPlatformName, String systemVersion, String browserName, String browserVersion, String browserLanguage, String browserCore, String resolutionRatio) {
        this.name = name;
        this.equipmentType = equipmentType;
        this.systemPlatformName = systemPlatformName;
        this.systemVersion = systemVersion;
        this.browserName = browserName;
        this.browserVersion = browserVersion;
        this.browserLanguage = browserLanguage;
        this.browserCore = browserCore;
        this.resolutionRatio = resolutionRatio;
    }

    public EquipmentModel(String name, String equipmentType, String systemPlatformName, String systemVersion, String browserName, String browserVersion, String browserLanguage, String browserCore, String resolutionRatio, String userAgent) {
        this.name = name;
        this.equipmentType = equipmentType;
        this.systemPlatformName = systemPlatformName;
        this.systemVersion = systemVersion;
        this.browserName = browserName;
        this.browserVersion = browserVersion;
        this.browserLanguage = browserLanguage;
        this.browserCore = browserCore;
        this.resolutionRatio = resolutionRatio;
        this.userAgent = userAgent;
    }

    public static long getSerialVersionUID() {
        return serialVersionUID;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEquipmentType() {
        return equipmentType;
    }

    public void setEquipmentType(String equipmentType) {
        this.equipmentType = equipmentType;
    }

    public String getSystemPlatformName() {
        return systemPlatformName;
    }

    public void setSystemPlatformName(String systemPlatformName) {
        this.systemPlatformName = systemPlatformName;
    }

    public String getSystemVersion() {
        return systemVersion;
    }

    public void setSystemVersion(String systemVersion) {
        this.systemVersion = systemVersion;
    }

    public String getBrowserName() {
        return browserName;
    }

    public void setBrowserName(String browserName) {
        this.browserName = browserName;
    }

    public String getBrowserVersion() {
        return browserVersion;
    }

    public void setBrowserVersion(String browserVersion) {
        this.browserVersion = browserVersion;
    }

    public String getBrowserLanguage() {
        return browserLanguage;
    }

    public void setBrowserLanguage(String browserLanguage) {
        this.browserLanguage = browserLanguage;
    }

    public String getBrowserCore() {
        return browserCore;
    }

    public void setBrowserCore(String browserCore) {
        this.browserCore = browserCore;
    }

    public String getResolutionRatio() {
        return resolutionRatio;
    }

    public void setResolutionRatio(String resolutionRatio) {
        this.resolutionRatio = resolutionRatio;
    }

    public String getUserAgent() {
        return userAgent;
    }

    public void setUserAgent(String userAgent) {
        this.userAgent = userAgent;
    }
}


text:
"""
Copyright [2009-2019] EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
     http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""

# ----------------------------------- IMPORTS ---------------------------------

import argparse
import shutil
import os
from subprocess import check_output, CalledProcessError, Popen, PIPE
from pathlib import Path
from yaml import dump
import logging

# ----------------------------------- GLOBALS ---------------------------------

REFERENCE_DB_NAME = 'RF02567.cm' # This needs to be modified

CWL_EXECUTOR = 'cwltool'

CWL_WORKFLOW_OPTIONS = ['--singularity']

current_dir = os.path.dirname(__file__)

WORKFLOW_PATH = os.path.realpath(os.path.join(current_dir, os.pardir, 'release', 'nc_rna_workflow.cwl'))

REFERENCE_CM_DB = os.path.realpath(os.path.join(current_dir, os.pardir, 'db', REFERENCE_DB_NAME))

GENOME_FILE_FORMATS = ('.fa', '.fasta')

CONFIG_FILENAME = 'config.yaml'

# -----------------------------------------------------------------------------

def validate_workflow():
    """
    Simple function to validate the workflow is running
    """
    logging.info('Validating CWL workflow')

    cmd = [CWL_EXECUTOR, '--validate', WORKFLOW_PATH]

    try:
        check_output(cmd)

    except CalledProcessError:
        cmd = ' '.join(cmd)
        raise EnvironmentError(f'Failed to validate workflow, debug using "{cmd}".')

# -----------------------------------------------------------------------------

def check_setup():
    """
    Checks the required components to run a project exist
    """

    logging.info('Checking project setup')

    if not shutil.which(CWL_EXECUTOR):
        raise EnvironmentError(f'CWL executor {CWL_EXECUTOR} not found in path.')

    if not os.path.exists(WORKFLOW_PATH):
        raise EnvironmentError(f'Workflow not found. {WORKFLOW_PATH}')

    if not os.path.exists(REFERENCE_CM_DB):
        raise EnvironmentError(f'CM db not found at path {REFERENCE_CM_DB}.')

    validate_workflow()

# -----------------------------------------------------------------------------

def parse_args():
    """
    Function to parse command line arguments
    """

    parser = argparse.ArgumentParser(description='Tool to find and execute nc_rna_pipeline for all genome fasta files')
    parser.add_argument('directory', help='Directory to search for fasta files')
    parser.add_argument('--dry-mode', action='store_true', help='logging.info pipeline commands without launching them')
    parser.add_argument('--skip-setup-check', action='store_true', help='Skips workflow validation')
    parser.add_argument('-v', '--verbose', action='store_true')

    return parser.parse_args()

# -----------------------------------------------------------------------------

def find_seq_datasets(directory):
    """
    """

    files = Path(directory).glob('**/*')
    fasta_files = filter(lambda fp: any([str(fp).endswith(fmt) for fmt in GENOME_FILE_FORMATS]), files)
    fasta_files = map(lambda fp: fp.resolve(), fasta_files)

    return list(fasta_files)

# -----------------------------------------------------------------------------

def write_cwl_config_file(config_dir, fasta_file):
    """
    Function to generate the cwl config file for the running project

    config_dir:
    fasta_file:
    """

    logging.info('\twriting config')

    config = {
        'sequences': {
            'class': 'File',
            'format': 'http://edamontology.org/format_1929',
            'path': fasta_file
        },
        'covariance_model_database': {
            'class': 'File',
            'path': REFERENCE_CM_DB
        }
    }

    outfile = os.path.join(config_dir, CONFIG_FILENAME)

    with open(outfile, 'w') as f:
        dump(config, f)

    return outfile

# -----------------------------------------------------------------------------

def launch_pipeline(outdir, config):
    """

    outdir:
    config:
    """

    logging.info('\tlaunching pipeline')

    cmd = [CWL_EXECUTOR, *CWL_WORKFLOW_OPTIONS, '--outdir', outdir, WORKFLOW_PATH, config]
    p = Popen(cmd, stdout=PIPE, stderr=PIPE)
    logging.info('\tpipeline running')
    logging.debug('\t' + ' '.join(cmd))

    output, err = p.communicate()

    rc = p.returncode

    if rc:
        logging.info('\tAn error occurred in workflow')
        logging.info(err.decode('UTF-8'))

    else:
        logging.info('\tWorkflow completed successfully')

# -----------------------------------------------------------------------------

def main():
    """

    """

    # parse command line arguments
    args = parse_args()
    logging.basicConfig(format='%(message)s', level=logging.DEBUG if args.verbose else logging.INFO)

    # check the project is runnable
    if not args.skip_setup_check:
        check_setup()

    logging.info(f'Searching for mags in {args.directory}')

    #
    seq_datasets = find_seq_datasets(args.directory)

    logging.info(f'Found {len(seq_datasets)} mags...')

    for sd in seq_datasets:
        logging.info(f'Processing {os.path.basename(sd)}')
        outdir = os.path.join(os.path.dirname(sd), 'out')
        os.makedirs(outdir, exist_ok=True)

        if args.dry_mode:
            logging.info('Skipping config + pipeline (dry mode)')

        else:
            config = write_cwl_config_file(os.path.dirname(sd), str(sd))
            launch_pipeline(outdir, config)

        logging.info('\n')

# -----------------------------------------------------------------------------

if __name__ == '__main__':

    main()


text:
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * LogoutController
 *

 * Handles user logout
 *

 * Author: Ben Sutter
 * Updated: 5/10/16
 */
public class LogoutController extends BaseController {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        super.doGet(request, response);

        this.setUser(null);
        this.setLoggedIn(false);

        response.sendRedirect(this.getBaseURL());
    }
}


text:
<?php

final class PhabricatorPolicyTestCase extends PhabricatorTestCase {

  /**
   * Verify that any user can view an object with POLICY_PUBLIC.
   */
  public function testPublicPolicyEnabled() {
    $env = PhabricatorEnv::beginScopedEnv();
    $env->overrideEnvConfig('policy.allow-public', true);

    $this->expectVisibility(
      $this->buildObject(PhabricatorPolicies::POLICY_PUBLIC),
      array(
        'public'  => true,
        'user'    => true,
        'admin'   => true,
      ),
      pht('Public Policy (Enabled in Config)'));
  }

  /**
   * Verify that POLICY_PUBLIC is interpreted as POLICY_USER when public
   * policies are disallowed.
   */
  public function testPublicPolicyDisabled() {
    $env = PhabricatorEnv::beginScopedEnv();
    $env->overrideEnvConfig('policy.allow-public', false);

    $this->expectVisibility(
      $this->buildObject(PhabricatorPolicies::POLICY_PUBLIC),
      array(
        'public'  => false,
        'user'    => true,
        'admin'   => true,
      ),
      pht('Public Policy (Disabled in Config)'));
  }

  /**
   * Verify that any logged-in user can view an object with POLICY_USER, but
   * logged-out users can not.
   */
  public function testUsersPolicy() {
    $this->expectVisibility(
      $this->buildObject(PhabricatorPolicies::POLICY_USER),
      array(
        'public'  => false,
        'user'    => true,
        'admin'   => true,
      ),
      pht('User Policy'));
  }

  /**
   * Verify that only administrators can view an object with POLICY_ADMIN.
   */
  public function testAdminPolicy() {
    $this->expectVisibility(
      $this->buildObject(PhabricatorPolicies::POLICY_ADMIN),
      array(
        'public'  => false,
        'user'    => false,
        'admin'   => true,
      ),
      pht('Admin Policy'));
  }

  /**
   * Verify that no one can view an object with POLICY_NOONE.
   */
  public function testNoOnePolicy() {
    $this->expectVisibility(
      $this->buildObject(PhabricatorPolicies::POLICY_NOONE),
      array(
        'public'  => false,
        'user'    => false,
        'admin'   => false,
      ),
      pht('No One Policy'));
  }

  /**
   * Test offset-based filtering.
   */
  public function testOffsets() {
    $results = array(
      $this->buildObject(PhabricatorPolicies::POLICY_NOONE),
      $this->buildObject(PhabricatorPolicies::POLICY_NOONE),
      $this->buildObject(PhabricatorPolicies::POLICY_NOONE),
      $this->buildObject(PhabricatorPolicies::POLICY_USER),
      $this->buildObject(PhabricatorPolicies::POLICY_USER),
      $this->buildObject(PhabricatorPolicies::POLICY_USER),
    );

    $query = new PhabricatorPolicyAwareTestQuery();
    $query->setResults($results);
    $query->setViewer($this->buildUser('user'));

    $this->assertEqual(
      3,
      count($query->setLimit(3)->setOffset(0)->execute()),
      pht('Invisible objects are ignored.'));

    $this->assertEqual(
      0,
      count($query->setLimit(3)->setOffset(3)->execute()),
      pht('Offset pages through visible objects only.'));

    $this->assertEqual(
      2,
      count($query->setLimit(3)->setOffset(1)->execute()),
      pht('Offsets work correctly.'));

    $this->assertEqual(
      2,
      count($query->setLimit(0)->setOffset(1)->execute()),
      pht('Offset with no limit works.'));
  }

  /**
   * Test limits.
   */
  public function testLimits() {
    $results = array(
      $this->buildObject(PhabricatorPolicies::POLICY_USER),
      $this->buildObject(PhabricatorPolicies::POLICY_USER),
      $this->buildObject(PhabricatorPolicies::POLICY_USER),
      $this->buildObject(PhabricatorPolicies::POLICY_USER),
      $this->buildObject(PhabricatorPolicies::POLICY_USER),
      $this->buildObject(PhabricatorPolicies::POLICY_USER),
    );

    $query = new PhabricatorPolicyAwareTestQuery();
    $query->setResults($results);
    $query->setViewer($this->buildUser('user'));

    $this->assertEqual(
      3,
      count($query->setLimit(3)->setOffset(0)->execute()),
      pht('Limits work.'));

    $this->assertEqual(
      2,
      count($query->setLimit(3)->setOffset(4)->execute()),
      pht('Limit + offset work.'));
  }

  /**
   * Test that omnipotent users bypass policies.
   */
  public function testOmnipotence() {
    $results = array(
      $this->buildObject(PhabricatorPolicies::POLICY_NOONE),
    );

    $query = new PhabricatorPolicyAwareTestQuery();
    $query->setResults($results);
    $query->setViewer(PhabricatorUser::getOmnipotentUser());

    $this->assertEqual(
      1,
      count($query->execute()));
  }

  /**
   * Test that invalid policies reject viewers of all types.
   */
  public function testRejectInvalidPolicy() {
    $invalid_policy = 'the duck goes quack';
    $object = $this->buildObject($invalid_policy);

    $this->expectVisibility(
      $object = $this->buildObject($invalid_policy),
      array(
        'public'  => false,
        'user'    => false,
        'admin'   => false,
      ),
      pht('Invalid Policy'));
  }

  /**
   * Test that extended policies work.
   */
  public function testExtendedPolicies() {
    $object = $this->buildObject(PhabricatorPolicies::POLICY_USER)
      ->setPHID('PHID-TEST-1');

    $this->expectVisibility(
      $object,
      array(
        'public'  => false,
        'user'    => true,
        'admin'   => true,
      ),
      pht('No Extended Policy'));

    // Add a restrictive extended policy.
    $extended = $this->buildObject(PhabricatorPolicies::POLICY_ADMIN)
      ->setPHID('PHID-TEST-2');
    $object->setExtendedPolicies(
      array(
        PhabricatorPolicyCapability::CAN_VIEW => array(
          array($extended, PhabricatorPolicyCapability::CAN_VIEW),
        ),
      ));

    $this->expectVisibility(
      $object,
      array(
        'public'  => false,
        'user'    => false,
        'admin'   => true,
      ),
      pht('With Extended Policy'));

    // Depend on a different capability.
    $object->setExtendedPolicies(
      array(
        PhabricatorPolicyCapability::CAN_VIEW => array(
          array($extended, PhabricatorPolicyCapability::CAN_EDIT),
        ),
      ));

    $extended->setCapabilities(array(PhabricatorPolicyCapability::CAN_EDIT));
    $extended->setPolicies(
      array(
        PhabricatorPolicyCapability::CAN_EDIT =>
          PhabricatorPolicies::POLICY_NOONE,
      ));

    $this->expectVisibility(
      $object,
      array(
        'public'  => false,
        'user'    => false,
        'admin'   => false,
      ),
      pht('With Extended Policy + Edit'));
  }

  /**
   * Test that cyclic extended policies are arrested properly.
   */
  public function testExtendedPolicyCycles() {
    $object = $this->buildObject(PhabricatorPolicies::POLICY_USER)
      ->setPHID('PHID-TEST-1');

    $this->expectVisibility(
      $object,
      array(
        'public'  => false,
        'user'    => true,
        'admin'   => true,
      ),
      pht('No Extended Policy'));

    // Set a self-referential extended policy on the object. This should
    // make it fail all policy checks.
    $object->setExtendedPolicies(
      array(
        PhabricatorPolicyCapability::CAN_VIEW => array(
          array($object, PhabricatorPolicyCapability::CAN_VIEW),
        ),
      ));

    $this->expectVisibility(
      $object,
      array(
        'public'  => false,
        'user'    => false,
        'admin'   => false,
      ),
      pht('Extended Policy with Cycle'));
  }

  /**
   * An omnipotent user should be able to see even objects with invalid
   * policies.
   */
  public function testInvalidPolicyVisibleByOmnipotentUser() {
    $invalid_policy = 'the cow goes moo';
    $object = $this->buildObject($invalid_policy);

    $results = array(
      $object,
    );

    $query = new PhabricatorPolicyAwareTestQuery();
    $query->setResults($results);
    $query->setViewer(PhabricatorUser::getOmnipotentUser());

    $this->assertEqual(
      1,
      count($query->execute()));
  }

  public function testAllQueriesBelongToActualApplications() {
    $queries = id(new PhutilClassMapQuery())
      ->setAncestorClass('PhabricatorPolicyAwareQuery')
      ->execute();

    foreach ($queries as $qclass => $query) {
      $class = $query->getQueryApplicationClass();
      if (!$class) {
        continue;
      }
      $this->assertTrue(
        (bool)PhabricatorApplication::getByClass($class),
        pht(
          "Application class '%s' for query '%s'.",
          $class,
          $qclass));
    }
  }

  public function testMultipleCapabilities() {
    $object = new PhabricatorPolicyTestObject();
    $object->setCapabilities(
      array(
        PhabricatorPolicyCapability::CAN_VIEW,
        PhabricatorPolicyCapability::CAN_EDIT,
      ));
    $object->setPolicies(
      array(
        PhabricatorPolicyCapability::CAN_VIEW
          => PhabricatorPolicies::POLICY_USER,
        PhabricatorPolicyCapability::CAN_EDIT
          => PhabricatorPolicies::POLICY_NOONE,
      ));

    $filter = new PhabricatorPolicyFilter();
    $filter->requireCapabilities(
      array(
        PhabricatorPolicyCapability::CAN_VIEW,
        PhabricatorPolicyCapability::CAN_EDIT,
      ));
    $filter->setViewer($this->buildUser('user'));

    $result = $filter->apply(array($object));

    $this->assertEqual(array(), $result);
  }

  public function testPolicyStrength() {
    $public = PhabricatorPolicyQuery::getGlobalPolicy(
      PhabricatorPolicies::POLICY_PUBLIC);
    $user = PhabricatorPolicyQuery::getGlobalPolicy(
      PhabricatorPolicies::POLICY_USER);
    $admin = PhabricatorPolicyQuery::getGlobalPolicy(
      PhabricatorPolicies::POLICY_ADMIN);
    $noone = PhabricatorPolicyQuery::getGlobalPolicy(
      PhabricatorPolicies::POLICY_NOONE);

    $this->assertFalse($public->isStrongerThan($public));
    $this->assertFalse($public->isStrongerThan($user));
    $this->assertFalse($public->isStrongerThan($admin));
    $this->assertFalse($public->isStrongerThan($noone));

    $this->assertTrue($user->isStrongerThan($public));
    $this->assertFalse($user->isStrongerThan($user));
    $this->assertFalse($user->isStrongerThan($admin));
    $this->assertFalse($user->isStrongerThan($noone));

    $this->assertTrue($admin->isStrongerThan($public));
    $this->assertTrue($admin->isStrongerThan($user));
    $this->assertFalse($admin->isStrongerThan($admin));
    $this->assertFalse($admin->isStrongerThan($noone));

    $this->assertTrue($noone->isStrongerThan($public));
    $this->assertTrue($noone->isStrongerThan($user));
    $this->assertTrue($noone->isStrongerThan($admin));
    $this->assertFalse($admin->isStrongerThan($noone));
  }

  /**
   * Test an object for visibility across multiple user specifications.
   */
  private function expectVisibility(
    PhabricatorPolicyTestObject $object,
    array $map,
    $description) {

    foreach ($map as $spec => $expect) {
      $viewer = $this->buildUser($spec);

      $query = new PhabricatorPolicyAwareTestQuery();
      $query->setResults(array($object));
      $query->setViewer($viewer);

      $caught = null;
      $result = null;
      try {
        $result = $query->executeOne();
      } catch (PhabricatorPolicyException $ex) {
        $caught = $ex;
      }

      if ($expect) {
        $this->assertEqual(
          $object,
          $result,
          pht('%s with user %s should succeed.', $description, $spec));
      } else {
        $this->assertTrue(
          $caught instanceof PhabricatorPolicyException,
          pht('%s with user %s should fail.', $description, $spec));
      }
    }
  }

  /**
   * Build a test object to spec.
   */
  private function buildObject($policy) {
    $object = new PhabricatorPolicyTestObject();
    $object->setCapabilities(
      array(
        PhabricatorPolicyCapability::CAN_VIEW,
      ));
    $object->setPolicies(
      array(
        PhabricatorPolicyCapability::CAN_VIEW => $policy,
      ));

    return $object;
  }

  /**
   * Build a test user to spec.
   */
  private function buildUser($spec) {
    $user = new PhabricatorUser();

    switch ($spec) {
      case 'public':
        break;
      case 'user':
        $user->setPHID(1);
        break;
      case 'admin':
        $user->setPHID(1);
        $user->setIsAdmin(true);
        break;
      default:
        throw new Exception(pht("Unknown user spec '%s'.", $spec));
    }

    return $user;
  }

}


text:
import { getLocale } from "../locale/locales";
import { deprecate } from "../utils/deprecate";

// If passed a locale key, it will set the locale for this
// instance.  Otherwise, it will return the locale configuration
// variables for this instance.
export function locale (key) {
    var newLocaleData;

    if (key === undefined) {
        return this._locale._abbr;
    } else {
        newLocaleData = getLocale(key);
        if (newLocaleData != null) {
            this._locale = newLocaleData;
        }
        return this;
    }
}

export var lang = deprecate(
    'moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.',
    function (key) {
        if (key === undefined) {
            return this.localeData();
        } else {
            return this.locale(key);
        }
    }
);

export function localeData () {
    return this._locale;
}