text:
require 'spec_helper'

def reset_mongo_class(uploader = MongoUploader)
  define_mongo_class('MongoUser') do
    include Mongoid::Document
    store_in :collection => 'users'
    field :folder, :default => ''
    mount_uploader :image, uploader
  end
end

class MongoUploader < CarrierWave::Uploader::Base; end
class AnotherMongoUploader < CarrierWave::Uploader::Base; end

class IntegrityErrorUploader < CarrierWave::Uploader::Base
  process :monkey
  def monkey
    raise CarrierWave::IntegrityError
  end
  def extension_white_list
    %w(jpg)
  end
end

class ProcessingErrorUploader < CarrierWave::Uploader::Base
  process :monkey
  def monkey
    raise CarrierWave::ProcessingError
  end
  def extension_white_list
    %w(jpg)
  end
end

describe CarrierWave::Mongoid do

  after do
    MongoUser.collection.drop if MongoUser.count > 0
  end

  describe '#image' do

    context "when nothing is assigned" do

      before do
        mongo_user_klass = reset_mongo_class
        @document = mongo_user_klass.new
      end

      it "returns a blank uploader" do
        expect(@document.image).to be_blank
      end

    end

    context "when an empty string is assigned" do

      before do
        mongo_user_klass = reset_mongo_class
        @document = mongo_user_klass.new(:image => "")
        @document.save
      end

      it "returns a blank uploader" do
        @saved_doc = MongoUser.first
        expect(@saved_doc.image).to be_blank
      end

    end

    context "when a filename is saved in the database" do

      before do
        mongo_user_klass = reset_mongo_class
        @document = mongo_user_klass.new
        # should retrieve a file from the storage if a value is stored in the database
        @document[:image] = "test.jpg" # NOT @document.image = 'text.jpg'
        @document.save
        @doc = MongoUser.first
      end

      it "returns an uploader" do
        expect(@doc.image).to be_an_instance_of(MongoUploader)
      end

      it "sets the path to the store directory" do
        expect(@doc.image.current_path).to eq public_path('uploads/test.jpg')
      end

      it "should return valid JSON when to_json is called when image is nil" do
        @doc[:image] = nil
        hash = JSON.parse(@doc.to_json)
        expect(hash.keys).to include("image")
        expect(hash["image"].keys).to include("url")
        expect(hash["image"]["url"]).to be_nil
      end

      it "should return valid JSON when to_json is called when image is present" do
        @doc[:image] = 'test.jpeg'
        @doc.save!
        @doc.reload

        expect(JSON.parse(@doc.to_json)["image"]).to eq("url" => "/uploads/test.jpeg")
      end

      it "should return valid JSON when to_json is called on a collection containing uploader from a model" do
        @doc[:image] = 'test.jpeg'
        @doc.save!
        @doc.reload

        if Gem::Version.new(CarrierWave::VERSION) >= Gem::Version.new("1.0.beta")
          expect(JSON.parse({:data => @doc.image}.to_json)).to eq({"data"=>{"url"=>"/uploads/test.jpeg"}})
        else
          expect(JSON.parse({:data => @doc.image}.to_json)).to eq("data"=>{"image" => {"url"=>"/uploads/test.jpeg"}})
        end
      end

      it "should respect options[:only] when passed to to_json for the serializable hash" do
        @doc[:image] = 'test.jpeg'
        @doc.save!
        @doc.reload
        expect(JSON.parse(@doc.to_json({:only => [:_id]}))).to eq("_id" => @doc.id.as_json)
      end

      it "should respect options[:except] when passed to to_json for the serializable hash" do
        @doc[:image] = 'test.jpeg'
        @doc.save!
        @doc.reload

        expect(JSON.parse(@doc.to_json({:except => [:_id, :image]}))).to eq("folder" => "")
      end

    end

  end

  describe '#image=' do

    before do
      mongo_user_klass = reset_mongo_class
      @doc = mongo_user_klass.new
    end

    context "when nil is assigned" do

      it "does not set the value" do
        @doc.image = nil
        expect(@doc.image).to be_blank
      end

    end

    context "when an empty string is assigned" do

      it "does not set the value" do
        @doc.image = ''
        expect(@doc.image).to be_blank
      end

    end

    context "when a file is assigned" do

      it "should cache a file" do
        @doc.image = stub_file('test.jpeg')
        expect(@doc.image).to be_an_instance_of(MongoUploader)
      end

      it "should write nothing to the database, to prevent overridden filenames to fail because of unassigned attributes" do
        expect(@doc[:image]).to be_nil
      end

      it "should copy a file into into the cache directory" do
        @doc.image = stub_file('test.jpeg')
        expect(@doc.image.current_path).to match /^#{public_path('uploads\/tmp')}/
      end

    end

    context 'when validating integrity' do
      before do
        mongo_user_klass = reset_mongo_class(IntegrityErrorUploader)
        @doc = mongo_user_klass.new
        @doc.image = stub_file('test.jpg')
      end

      it "should make the document invalid when an integrity error occurs" do
        expect(@doc).to_not be_valid
      end

      it "should use I18n for integrity error messages" do
        translations = { mongoid: { errors: { messages: { carrierwave_integrity_error: 'is not of an allowed file type' }}}}
        change_locale_and_store_translations(:en, translations) do
          @doc.valid?
          expect(@doc.errors[:image]).to eq ['is not of an allowed file type']
        end

        translations = { mongoid: { errors: { messages: { carrierwave_integrity_error: 'tipo de imagem não permitido.' }}}}
        change_locale_and_store_translations(:pt, translations) do
          @doc.valid?
          expect(@doc.errors[:image]).to eq ['tipo de imagem não permitido.']
        end
      end
    end

    context 'when validating processing' do
      before do
        mongo_user_klass = reset_mongo_class(ProcessingErrorUploader)
        @doc = mongo_user_klass.new
        @doc.image = stub_file('test.jpg')
      end

      it "should make the document invalid when a processing error occurs" do
        expect(@doc).to_not be_valid
      end

      it "should use I18n for processing error messages" do
        translations = { mongoid: { errors: { messages: { carrierwave_processing_error: 'failed to be processed' }}}}
        change_locale_and_store_translations(:en, translations) do
          @doc.valid?
          expect(@doc.errors[:image]).to eq ['failed to be processed']
        end

        translations = { mongoid: { errors: { messages: { carrierwave_processing_error: 'falha ao processar imagem.' }}}}
        change_locale_and_store_translations(:pt, translations) do
          @doc.valid?
          expect(@doc.errors[:image]).to eq ['falha ao processar imagem.']
        end
      end
    end

  end

  describe '#remove_image=' do
    before do
      mongo_user_klass = reset_mongo_class
      @doc = mongo_user_klass.new
    end

    it "treats true argument such that attribute is marked as changed" do
      @doc.remove_image = true
      expect(@doc).to be_image_changed
    end

    it "treats '1' argument such that attribute is marked as changed" do
      @doc.remove_image = '1'
      expect(@doc).to be_image_changed
    end

    it "treats false argument such that attribute is not marked as changed" do
      @doc.remove_image = false
      expect(@doc).to_not be_image_changed
    end

    it "treats nil argument such that attribute is not marked as changed" do
      @doc.remove_image = nil
      expect(@doc).to_not be_image_changed
    end

    it "treats '0' argument such that attribute is not marked as changed" do
      @doc.remove_image = '0'
      expect(@doc).to_not be_image_changed
    end
  end

  describe "#save" do

    it "after it was initialized with params" do
      doc = reset_mongo_class.new(:image => stub_file('test.jpg'))
      expect(doc.save).to be_truthy
      expect(doc.image).to be_an_instance_of(MongoUploader)
      expect(doc.image.current_path).to eq public_path('uploads/test.jpg')
    end

    before do
      mongo_user_klass = reset_mongo_class
      @doc = mongo_user_klass.new
    end

    context "when no file is assigned" do

      it "image is blank" do
        expect(@doc.save).to be_truthy
        expect(@doc.image).to be_blank
      end

    end

    context "when a file is assigned" do

      it "copies the file to the upload directory" do
        @doc.image = stub_file('test.jpg')
        expect(@doc.save).to be_truthy
        expect(@doc.image).to be_an_instance_of(MongoUploader)
        expect(@doc.image.current_path).to eq public_path('uploads/test.jpg')
      end

      it "saves the filename in the database" do
        @doc.image = stub_file('test.jpg')
        expect(@doc.save).to be_truthy
        expect(@doc[:image]).to eq 'test.jpg'
        expect(@doc.image_identifier).to eq 'test.jpg'
      end

      context "when remove_image? is true" do

        it "removes the image" do
          @doc.image = stub_file('test.jpeg')
          @doc.save
          @doc.remove_image = true
          expect(@doc.save).to be_truthy
          @doc.reload
          expect(@doc.image).to be_blank
          expect(@doc.image_identifier).to be_blank
        end

      end

      it "should mark image as changed when saving a new image" do
        expect(@doc.image_changed?).to be_falsey
        @doc.image = stub_file("test.jpeg")
        expect(@doc.image_changed?).to be_truthy
        @doc.save
        @doc.reload
        expect(@doc.image_changed?).to be_falsey
        @doc.image = stub_file("test.jpg")
        expect(@doc.image_changed?).to be_truthy
      end

    end

  end

  describe '#update' do

    before do
      mongo_user_klass = reset_mongo_class
      @doc = mongo_user_klass.new
      @doc.image = stub_file('test.jpeg')
      @doc.save
      @doc.reload
    end

    it "replaced it by a file with the same name" do
      @doc.image = stub_file('test.jpeg')
      @doc.save
      @doc.reload
      expect(@doc[:image]).to eq 'test.jpeg'
      expect(@doc.image_identifier).to eq 'test.jpeg'
    end

  end

  describe '#destroy' do

    before do
      mongo_user_klass = reset_mongo_class
      @doc = mongo_user_klass.new
    end

    describe "when file assigned" do

      it "removes the file from the filesystem" do
        @doc.image = stub_file('test.jpeg')
        expect(@doc.save).to be_truthy
        expect(File.exist?(public_path('uploads/test.jpeg'))).to be_truthy
        expect(@doc.image).to be_an_instance_of(MongoUploader)
        expect(@doc.image.current_path).to eq public_path('uploads/test.jpeg')
        @doc.destroy
        expect(File.exist?(public_path('uploads/test.jpeg'))).to be_falsey
      end

    end

    describe "when file is not assigned" do

      it "deletes the instance of MongoUser after save" do
        @doc.save
        expect(MongoUser.count).to eq(1)
        @doc.destroy
      end

      it "deletes the instance of MongoUser after save and then re-looking up the instance" do
        @doc.save
        expect(MongoUser.count).to eq(1)
        @doc = MongoUser.first
        @doc.destroy
      end

    end

  end

  describe '#reload' do

    before do
      @mongo_user_klass = reset_mongo_class
      @doc = @mongo_user_klass.new
      @doc.save
    end

    it 'reset cached value on reload' do
      new = @mongo_user_klass.find(@doc.id)
      new.image = stub_file('test.jpeg')
      new.save

      expect(@doc.reload.image).to_not be_blank
    end

  end

  describe '#mount_uploader removing old files' do

    before do
      @uploader = Class.new(MongoUploader)
      @class = reset_mongo_class(@uploader)
      @class.field :foo
      @doc = @class.new
      @doc.image = stub_file('old.jpeg')
      expect(@doc.save).to be_truthy
      expect(File.exists?(public_path('uploads/old.jpeg'))).to be_truthy
    end

    after do
      FileUtils.rm_rf(public_path("uploads"))
    end

    describe 'normally' do

      it "should remove old file if old file had a different path" do
        @doc.image = stub_file('new.jpeg')
        expect(@doc.save).to be_truthy
        expect(File.exists?(public_path('uploads/new.jpeg'))).to be_truthy
        expect(File.exists?(public_path('uploads/old.jpeg'))).to be_falsey
      end

      it "should not remove old file if old file had a different path but config is false" do
        @doc.image.class.remove_previously_stored_files_after_update = false
        @doc.image = stub_file('new.jpeg')
        expect(@doc.save).to be_truthy
        expect(File.exists?(public_path('uploads/new.jpeg'))).to be_truthy
        expect(File.exists?(public_path('uploads/old.jpeg'))).to be_truthy
      end

      it "should not remove file if old file had the same path" do
        @doc.image = stub_file('old.jpeg')
        expect(@doc.save).to be_truthy
        expect(File.exists?(public_path('uploads/old.jpeg'))).to be_truthy
      end

      it "should not remove file if validations fail on save" do
        @class.validate { |r| r.errors.add :textfile, "FAIL!" }
        @doc.image = stub_file('new.jpeg')
        expect(@doc.save).to be_falsey
        expect(File.exists?(public_path('uploads/old.jpeg'))).to be_truthy
      end
    end

    describe 'with an overridden filename' do
      before do
        @uploader.class_eval do
          def filename
            model.foo + File.extname(super)
          end
        end

        @doc.image = stub_file('old.jpeg')
        @doc.foo = "test"
        expect(@doc.save).to be_truthy
        expect(File.exists?(public_path('uploads/test.jpeg'))).to be_truthy
        expect(@doc.image.read).to eq "this is stuff"
      end

      it "should not remove file if old file had the same dynamic path" do
        @doc.image = stub_file('test.jpeg')
        expect(@doc.save).to be_truthy
        expect(File.exists?(public_path('uploads/test.jpeg'))).to be_truthy
      end

      it "should remove old file if old file had a different dynamic path" do
        @doc.foo = "new"
        @doc.image = stub_file('test.jpeg')
        expect(@doc.save).to be_truthy
        expect(File.exists?(public_path('uploads/new.jpeg'))).to be_truthy
        expect(File.exists?(public_path('uploads/test.jpeg'))).to be_falsey
      end
    end

    shared_examples "embedded documents" do
      it "should remove old file if old file had a different path" do
        @embedded_doc.image = stub_file('new.jpeg')
        expect(@embedded_doc.save).to be_truthy
        expect(File.exists?(public_path('uploads/new.jpeg'))).to be_truthy
        expect(File.exists?(public_path('uploads/old.jpeg'))).to be_falsey
      end

      it "should not remove old file if old file had a different path but config is false" do
        @embedded_doc.image.class.remove_previously_stored_files_after_update = false
        @embedded_doc.image = stub_file('new.jpeg')
        expect(@embedded_doc.save).to be_truthy
        expect(File.exists?(public_path('uploads/new.jpeg'))).to be_truthy
        expect(File.exists?(public_path('uploads/old.jpeg'))).to be_truthy
      end

      it "should not remove file if old file had the same path" do
        @embedded_doc.image = stub_file('old.jpeg')
        expect(@embedded_doc.save).to be_truthy
        expect(File.exists?(public_path('uploads/old.jpeg'))).to be_truthy
      end

      it "should not remove file if validations fail on save" do
        @embedded_doc_class.validate { |r| r.errors.add :textfile, "FAIL!" }
        @embedded_doc.image = stub_file('new.jpeg')
        expect(@embedded_doc.save).to be_falsey
        expect(File.exists?(public_path('uploads/old.jpeg'))).to be_truthy
      end

      it "should not touch parent's dirty attributes" do
        @class.field :title
        @doc.title = "Title"
        @embedded_doc.image = stub_file('new.jpeg')
        expect(@embedded_doc.save).to be_truthy
        expect(@doc.title).to eq "Title"
      end
    end

    shared_examples "double embedded documents" do
      it "should remove old file if old file had a different path" do
        @double_embedded_doc.image = stub_file('new.jpeg')
        expect(@double_embedded_doc.save).to be_truthy
        expect(File.exists?(public_path('uploads/new.jpeg'))).to be_truthy
        expect(File.exists?(public_path('uploads/old.jpeg'))).to be_falsey
      end

      it "should not remove old file if old file had a different path but config is false" do
        @double_embedded_doc.image.class.remove_previously_stored_files_after_update = false
        @double_embedded_doc.image = stub_file('new.jpeg')
        expect(@double_embedded_doc.save).to be_truthy
        expect(File.exists?(public_path('uploads/new.jpeg'))).to be_truthy
        expect(File.exists?(public_path('uploads/old.jpeg'))).to be_truthy
      end

      it "should not remove file if old file had the same path" do
        @double_embedded_doc.image = stub_file('old.jpeg')
        expect(@double_embedded_doc.save).to be_truthy
        expect(File.exists?(public_path('uploads/old.jpeg'))).to be_truthy
      end

      it "should not remove file if validations fail on save" do
        @double_embedded_doc_class.validate { |r| r.errors.add :textfile, "FAIL!" }
        @double_embedded_doc.image = stub_file('new.jpeg')
        expect(@double_embedded_doc.save).to be_falsey
        expect(File.exists?(public_path('uploads/old.jpeg'))).to be_truthy
      end

    end

    describe 'with document embedded as embeds_one' do
      before do
        @embedded_doc_class = define_mongo_class('MongoLocation') do
          include Mongoid::Document
          mount_uploader :image, @uploader
          embedded_in :mongo_user
        end

        @class.class_eval do
          embeds_one :mongo_location
        end

        @doc = @class.new
        @embedded_doc = @doc.build_mongo_location
        @embedded_doc.image = stub_file('old.jpeg')
        expect(@embedded_doc.save).to be_truthy
      end

      include_examples "embedded documents"
    end

    describe 'with document embedded as embeds_one and parent document not matched the default scope' do
      before do
        @embedded_doc_class = define_mongo_class('MongoLocation') do
          include Mongoid::Document
          mount_uploader :image, @uploader
          embedded_in :mongo_user
        end

        @class.class_eval do
          embeds_one :mongo_location
          default_scope ->{ where(:always_false => false) }
        end

        @doc = @class.new
        @embedded_doc = @doc.build_mongo_location
        @embedded_doc.image = stub_file('old.jpeg')
        expect(@embedded_doc.save).to be_truthy
      end

      include_examples "embedded documents"
    end

    describe 'with embedded documents' do
      before do
        @embedded_doc_class = define_mongo_class('MongoLocation') do
          include Mongoid::Document
          mount_uploader :image, @uploader
          embedded_in :mongo_user
        end

        @class.class_eval do
          embeds_many :mongo_locations, cascade_callbacks: true
          accepts_nested_attributes_for :mongo_locations
        end

        @doc = @class.new
        @embedded_doc = @doc.mongo_locations.build
        @embedded_doc.image = stub_file('old.jpeg')
        expect(@embedded_doc.save).to be_truthy
      end

      include_examples "embedded documents"

      it "attaches a new file to an existing document that had no file at first" do
        doc = @class.new
        doc.mongo_locations.build
        expect(doc.save).to be_truthy
        doc.reload

        doc.mongo_locations.first.image = stub_file('test.jpeg')
        expect(doc.save).to be_truthy
        doc.reload

        expect(doc.mongo_locations.first[:image]).to eq 'test.jpeg'
      end

      it "changes the file" do
        @doc.update_attributes mongo_locations_attributes: { '0' => { _id: @embedded_doc._id, image: stub_file('test.jpeg') } }
        @doc.reload
        expect(@doc.mongo_locations.first[:image]).to eq 'test.jpeg'
      end

      it "removes a file" do
        @doc.update_attributes mongo_locations_attributes: { '0' => { _id: @embedded_doc._id, remove_image: "1" } }
        @doc.reload
        expect(@doc.mongo_locations.first[:image]).to_not be_present
      end

      describe 'with double embedded documents' do

        before do
          @double_embedded_doc_class = define_mongo_class('MongoItem') do
            include Mongoid::Document
            mount_uploader :image, @uploader
            embedded_in :mongo_location
          end

          @embedded_doc_class.class_eval do
            embeds_many :mongo_items
          end

          @doc = @class.new
          @embedded_doc = @doc.mongo_locations.build
          @embedded_doc.image = stub_file('old.jpeg')
          expect(@embedded_doc.save).to be_truthy

          @double_embedded_doc = @embedded_doc.mongo_items.build
          @double_embedded_doc.image = stub_file('old.jpeg')
          expect(@double_embedded_doc.save).to be_truthy
        end

        include_examples "double embedded documents"
      end
    end

    describe 'with embedded documents and parent document not matched the default scope' do
      before do
        @embedded_doc_class = define_mongo_class('MongoLocation') do
          include Mongoid::Document
          mount_uploader :image, @uploader
          embedded_in :mongo_user
        end

        @class.class_eval do
          embeds_many :mongo_locations
          default_scope ->{ where(:always_false => false) }
        end

        @doc = @class.new
        @embedded_doc = @doc.mongo_locations.build
        @embedded_doc.image = stub_file('old.jpeg')
        expect(@embedded_doc.save).to be_truthy
      end

      include_examples "embedded documents"

      describe 'with double embedded documents' do

        before do
          @double_embedded_doc_class = define_mongo_class('MongoItem') do
            include Mongoid::Document
            mount_uploader :image, @uploader
            embedded_in :mongo_location
          end

          @embedded_doc_class.class_eval do
            embeds_many :mongo_items
          end

          @doc = @class.new
          @embedded_doc = @doc.mongo_locations.build
          @embedded_doc.image = stub_file('old.jpeg')
          expect(@embedded_doc.save).to be_truthy

          @double_embedded_doc = @embedded_doc.mongo_items.build
          @double_embedded_doc.image = stub_file('old.jpeg')
          expect(@double_embedded_doc.save).to be_truthy
        end

        include_examples "double embedded documents"
      end
    end

    describe 'with embedded documents and nested attributes' do
      before do
        @embedded_doc_class = define_mongo_class('MongoLocation') do
          include Mongoid::Document
          mount_uploader :image, @uploader
          embedded_in :mongo_user
        end

        @class.class_eval do
          embeds_many :mongo_locations, cascade_callbacks: true
          accepts_nested_attributes_for :mongo_locations
        end

        @doc = @class.new(mongo_locations_attributes: [{image: stub_file("old.jpeg")}])
        expect(@doc.save).to be_truthy
        @embedded_doc = @doc.mongo_locations.first
      end

      it "should set the image on a save" do
        @doc.reload
        expect(@doc.mongo_locations.first.image.path).to match(/old\.jpeg$/)
        expect(@embedded_doc.image.path).to match(/old\.jpeg$/)
      end

      it "should update the image on update_attributes" do
        expect(@doc.update_attributes(mongo_locations_attributes: [{id: @embedded_doc.id, image: stub_file("new.jpeg")}])).to be_truthy
        @doc.reload
        expect(@doc.mongo_locations.first.image.path).to match(/new\.jpeg$/)
        expect(@embedded_doc.image.path).to match(/new\.jpeg$/)
      end
    end
  end

  describe '#mount_uploader removing old files with versions' do

    before do
      @uploader = Class.new(MongoUploader)
      @uploader.version :thumb
      @class = reset_mongo_class(@uploader)
      @doc = @class.new
      @doc.image = stub_file('old.jpeg')
      expect(@doc.save).to be_truthy
      expect(File.exists?(public_path('uploads/old.jpeg'))).to be_truthy
      expect(File.exists?(public_path('uploads/thumb_old.jpeg'))).to be_truthy
    end

    after do
      FileUtils.rm_rf(file_path("uploads"))
    end

    it "should remove old file if old file had a different path" do
      @doc.image = stub_file('new.jpeg')
      expect(@doc.save).to be_truthy
      expect(File.exists?(public_path('uploads/new.jpeg'))).to be_truthy
      expect(File.exists?(public_path('uploads/thumb_new.jpeg'))).to be_truthy
      expect(File.exists?(public_path('uploads/old.jpeg'))).to be_falsey
      expect(File.exists?(public_path('uploads/thumb_old.jpeg'))).to be_falsey
    end

    it "should not remove file if old file had the same path" do
      @doc.image = stub_file('old.jpeg')
      expect(@doc.save).to be_truthy
      expect(File.exists?(public_path('uploads/old.jpeg'))).to be_truthy
      expect(File.exists?(public_path('uploads/thumb_old.jpeg'))).to be_truthy
    end
  end

  describe '#mount_uploader removing old files with multiple uploaders' do

    before do
      @uploader = Class.new(MongoUploader)
      @class = reset_mongo_class(@uploader)
      @uploader1 = Class.new(CarrierWave::Uploader::Base)
      @class.mount_uploader(:textfile, @uploader1)
      @doc = @class.new
      @doc.image = stub_file('old.jpeg')
      @doc.textfile = stub_file('old.txt')
      expect(@doc.save).to be_truthy
      expect(File.exists?(public_path('uploads/old.jpeg'))).to be_truthy
      expect(File.exists?(public_path('uploads/old.txt'))).to be_truthy
    end

    after do
      FileUtils.rm_rf(file_path("uploads"))
    end

    it "should remove old file1 and file2 if old file1 and file2 had a different paths" do
      @doc.image = stub_file('new.jpeg')
      @doc.textfile = stub_file('new.txt')
      expect(@doc.save).to be_truthy
      expect(File.exists?(public_path('uploads/new.jpeg'))).to be_truthy
      expect(File.exists?(public_path('uploads/old.jpeg'))).to be_falsey
      expect(File.exists?(public_path('uploads/new.txt'))).to be_truthy
      expect(File.exists?(public_path('uploads/old.txt'))).to be_falsey
    end

    it "should remove old file1 but not file2 if old file1 had a different path but old file2 has the same path" do
      @doc.image = stub_file('new.jpeg')
      @doc.textfile = stub_file('old.txt')
      expect(@doc.save).to be_truthy
      expect(File.exists?(public_path('uploads/new.jpeg'))).to be_truthy
      expect(File.exists?(public_path('uploads/old.jpeg'))).to be_falsey
      expect(File.exists?(public_path('uploads/old.txt'))).to be_truthy
    end

    it "should not remove file1 or file2 if file1 and file2 have the same paths" do
      @doc.image = stub_file('old.jpeg')
      @doc.textfile = stub_file('old.txt')
      expect(@doc.save).to be_truthy
      expect(File.exists?(public_path('uploads/old.jpeg'))).to be_truthy
      expect(File.exists?(public_path('uploads/old.txt'))).to be_truthy
    end
  end

  describe '#mount_uploader removing old files with mount_on' do

    before do
      @class = reset_mongo_class
      @uploader1 = Class.new(CarrierWave::Uploader::Base)
      @class.mount_uploader(:avatar, @uploader1, :mount_on => :another_image)
      @doc = @class.new
      @doc.avatar = stub_file('old.jpeg')
      expect(@doc.save).to be_truthy
      expect(File.exists?(public_path('uploads/old.jpeg'))).to be_truthy
    end

    after do
      FileUtils.rm_rf(file_path("uploads"))
    end

    it "should remove old file if old file had a different path" do
      @doc.avatar = stub_file('new.jpeg')
      expect(@doc.save).to be_truthy
      expect(File.exists?(public_path('uploads/new.jpeg'))).to be_truthy
      expect(File.exists?(public_path('uploads/old.jpeg'))).to be_falsey
    end

    it "should not remove file if old file had the same path" do
      @doc.avatar = stub_file('old.jpeg')
      expect(@doc.save).to be_truthy
      expect(File.exists?(public_path('uploads/old.jpeg'))).to be_truthy
    end
  end

  # Mongoid::Paranoia support is only part of Mongoid 3.x. It was removed from
  # Mongoid 4.x.
  if defined?(Mongoid::Paranoia)
    describe "with paranoia enabled" do
      before do
        @class = reset_mongo_class
        @class.collection.drop
        @class.class_eval do
          include Mongoid::Paranoia
        end

        @doc = @class.new(image: stub_file("old.jpeg"))
        expect(@doc.save).to be_truthy
      end

      it "should not remove underlying image after #destroy" do
        expect(@doc.destroy).to be_truthy
        expect(@class.count).to eql(0)
        expect(@class.deleted.count).to eql(1)
        expect(File.exist?(public_path('uploads/old.jpeg'))).to be_truthy
      end

      it "should remove underlying image after #destroy!" do
        expect(@doc.destroy!).to be_truthy
        expect(@class.count).to eql(0)
        expect(@class.deleted.count).to eql(0)
        expect(File.exist?(public_path('uploads/old.jpeg'))).to be_falsey
      end
    end
  end

  context "JSON serialization with multiple uploaders" do
    before do
      @class = reset_mongo_class
      @class.send(:mount_uploader, :textfile,AnotherMongoUploader)
      @event = @class.new
      @event.image = stub_file('old.jpeg')
      @event.textfile = stub_file('old.txt')
    end

    it "serializes the correct values" do
      expect(@event.serializable_hash["image"]["url"]).to match(/old\.jpeg$/)
      expect(@event.serializable_hash["textfile"]["url"]).to match(/old\.txt$/)
    end

    it "should have JSON for each uploader" do
      parsed = JSON.parse(@event.to_json)
      expect(parsed["image"]["url"]).to match(/old\.jpeg$/)
      expect(parsed["textfile"]["url"]).to match(/old\.txt$/)
    end
  end

end


text:
const service = require('feathers-sequelize');
const hooks = require('./hooks');

module.exports = function () {
  const app = this;

  const options = {
    Model: app.get('models').event,
  };

  // Initialize our service with any options it requires
  app.use('/api/events', service(options));

  // Get our initialize service to that we can bind hooks
  const eventService = app.service('/api/events');

  // Set up our before hooks
  eventService.before(hooks.before);

  // Set up our after hooks
  eventService.after(hooks.after);
};

redpajama_set_name: RedPajamaGithub


text:
%EDGE_ORIENT  Calculate edge filter responses at any orientation
%
%   [R, O, G] = edge_orient(I, sigma, [mcm])
%
% Returns a handle to a function that generates an edge filter response
% image using angularly adaptive filtering, and also outputs the angle that
% gives maximal edge response. The implementation uses separable, steerable
% filters, hence is fast.
%
% For multi-channel images, the gradient is computed in the colour
% direction of greatest change.
%
% IN:
%   I - HxWxC input image.
%   sigma - Scalar value determing the scale of the edge filter
%           (essentially the amount of pre-smoothing to apply).
%   mcm - multi-channel method: 'dizenzo' (default), 'norm', 'pca',
%                               'rgb2gray'.
%
% OUT:
%   R - @(theta) anonymous function, which, when given a scalar angle (in
%       radians), or HxW angle array, returns an HxW edge filter response
%       image for the angle(s) given. R(O) is the maximal edge filter
%       response for each pixel.
%   O - HxW edge orientation image, returning the angle, in radians, of the
%       maximal filter response at each pixel.
%   G - HxWx2 array of gradient images in x and y directions, along third
%       dimension.

function [R, O, G] = edge_orient(I, sigma, mcm)

% Set the default method
if nargin < 3
    mcm = 'dizenzo';
end

% Compute the image gradients
[Ix, Iy] = imgrad(I, sigma, mcm);

% Output function that generates response at any angle
R = @(theta) cos(theta) .* Ix + sin(theta) .* Iy;

if nargout > 1
    % Evaluate the orientation, in radians
    O = atan2(Iy, Ix);
    if nargout > 2
        G = cat(3, Ix, Iy);
    end
end
return


text:
function cleanup() {
    kill ${SERVER_PID} ${CLIENT_PID}
    rm -f cp.txt
}

trap cleanup EXIT

mvn test dependency:build-classpath -Dmdep.outputFile=cp.txt
CLASSPATH=$(cat cp.txt):target/classes
java -classpath ${CLASSPATH} com.crossover.trial.weather.WeatherServer &
SERVER_PID=$$

while ! nc localhost 9090 > /dev/null 2>&1 < /dev/null; do
    echo "$(date) - waiting for server at localhost:9090..."
    sleep 1
done

java -classpath ${CLASSPATH} com.crossover.trial.weather.WeatherClient
CLIENT_PID=$$
cleanup


text:
package com.zerodes.bta.services.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zerodes.bta.domain.User;
import com.zerodes.bta.dto.CategoryDto;
import com.zerodes.bta.dto.SummaryCategoryDto;
import com.zerodes.bta.dto.SummaryDto;
import com.zerodes.bta.dto.TransactionDto;
import com.zerodes.bta.enums.CategoryTypeEnum;
import com.zerodes.bta.services.SummaryService;
import com.zerodes.bta.services.TransactionService;

@Service
public class SummaryServiceImpl implements SummaryService {
	@Autowired
	private TransactionService transactionService;

	@Override
	public SummaryDto getSummary(User user, int year, int month) {
		List<String> yearMonthListForPastYear = generateYearMonthListForPastYear(year, month);
		return summarize(transactionService.findTransactions(user, yearMonthListForPastYear), month);
	}

	protected List<String> generateYearMonthListForPastYear(int year, int month) {
		int currentYear = year;
		int currentMonth = month;
		List<String> yearMonthList = new ArrayList<String>();
		for (int index = 0; index < 12; index++) {
			yearMonthList.add(String.valueOf(currentYear) + "-" + String.valueOf(currentMonth));
			currentMonth--;
			if (currentMonth == 0) {
				currentMonth = 12;
				currentYear--;
			}
		}
		return yearMonthList;
	}

	private SummaryDto summarize(final List<TransactionDto> transactions, final int month) {
		SummaryDto result = new SummaryDto();
		Map<String, SummaryCategoryDto> categoriesMap = new HashMap<String, SummaryCategoryDto>();
		for (TransactionDto transaction : transactions) {
			CategoryDto category = transaction.getCategory();
			if (category == null) {
				category = new CategoryDto();
				category.setName("UNASSIGNED");
				category.setType(CategoryTypeEnum.VARIABLE);
			}
			SummaryCategoryDto summaryCategoryDto = categoriesMap.get(category.getName());
			if (summaryCategoryDto == null) {
				summaryCategoryDto = new SummaryCategoryDto(category);
				categoriesMap.put(category.getName(), summaryCategoryDto);
			}
			summaryCategoryDto.addToAmount(transaction.getAmount(), transaction.getTransactionMonth() == month);
		}
		result.getCategories().addAll(categoriesMap.values());
		return result;
	}
}


text:
// Package vagrant_cloud is an implementation of Interface, TCPLoadBalancer
// and Instances for developer managed Vagrant cluster.
package vagrant_cloud


text:
import Component from '@ember/component';
import ComputedProperty, { equal, bool, mapBy } from '@ember/object/computed';
import { get, getWithDefault, getProperties, computed } from '@ember/object';
import { action } from '@ember-decorators/object';
import {
  IComplianceChangeSet,
  IdentifierFieldWithFieldChangeSetTuple,
  ISuggestedFieldTypeValues
} from 'wherehows-web/typings/app/dataset-compliance';
import {
  changeSetReviewableAttributeTriggers,
  ComplianceFieldIdValue,
  complianceFieldChangeSetItemFactory,
  SuggestionIntent,
  fieldTagsRequiringReview,
  tagsHaveNoneAndNotNoneType,
  tagsHaveNoneType,
  suggestedIdentifierTypesInList
} from 'wherehows-web/constants';
import { getTagSuggestions } from 'wherehows-web/utils/datasets/compliance-suggestions';
import { IColumnFieldProps } from 'wherehows-web/typings/app/dataset-columns';
import { fieldTagsHaveIdentifierType } from 'wherehows-web/constants/dataset-compliance';
import { IComplianceDataType } from 'wherehows-web/typings/api/list/compliance-datatypes';
import { arrayEach, arrayReduce } from 'wherehows-web/utils/array';
import { IComplianceEntity } from 'wherehows-web/typings/api/datasets/compliance';
import { alias } from '@ember-decorators/object/computed';

export default class DatasetComplianceRollupRow extends Component.extend({
  tagName: ''
}) {
  /**
   * References the parent external action to handle double click events on the field name
   * @memberof DatasetComplianceRollupRow
   */
  onFieldDblClick: () => void;
  /**
   * References the parent external action to add a tag to the list of change sets
   * @memberof DatasetComplianceRollupRow
   */
  onFieldTagAdded: (tag: IComplianceChangeSet) => void;

  /**
   * References the parent external action to add a tag to the list of change sets
   * @memberof DatasetComplianceRollupRow
   */
  onFieldTagRemoved: (tag: IComplianceChangeSet) => void;

  /**
   * References the parent external action to remove the readonly property on a tag
   * @memberof DatasetComplianceRollupRow
   */
  onTagReadOnlyDisable: (tag: IComplianceChangeSet) => void;

  /**
   * Describes action interface for `onSuggestionIntent` action
   * @memberof DatasetComplianceRollupRow
   */
  onSuggestionIntent: (tag: IComplianceChangeSet, intent?: SuggestionIntent) => void;

  /**
   * Describes action interface for `onTagIdentifierTypeChange` action
   * @memberof DatasetComplianceRollupRow
   */
  onTagIdentifierTypeChange: (tag: IComplianceChangeSet, option: { value: ComplianceFieldIdValue | null }) => void;

  /**
   * Reference to the compliance data types
   * @type {Array<IComplianceDataType>}
   * @memberof DatasetComplianceRollupRow
   */
  complianceDataTypes: Array<IComplianceDataType>;

  /**
   * Confidence percentage number used to filter high quality suggestions versus lower quality
   * @type {number}
   * @memberof DatasetComplianceRollupRow
   */
  suggestionConfidenceThreshold: number;

  /**
   * Flag indicating the field has a readonly attribute
   * @type ComputedProperty<boolean>
   * @memberof DatasetComplianceRollupRow
   */
  isReadonlyField: ComputedProperty<boolean> = bool('fieldProps.readonly');

  /**
   * Checks that the field requires user attention
   * @type {ComputedProperty<boolean>}
   * @memberof DatasetComplianceRollupRow
   */
  isReviewRequested = computed(
    `fieldChangeSet.@each.{${changeSetReviewableAttributeTriggers}}`,
    'complianceDataTypes',
    'suggestionConfidenceThreshold',
    function(this: DatasetComplianceRollupRow): boolean {
      const { fieldChangeSet: tags, suggestionConfidenceThreshold } = getProperties(this, [
        'fieldChangeSet',
        'suggestionConfidenceThreshold'
      ]);
      const { length } = fieldTagsRequiringReview(get(this, 'complianceDataTypes'), {
        checkSuggestions: true,
        suggestionConfidenceThreshold
      })(get(this, 'identifierField'))(tags);

      return !!length || tagsHaveNoneAndNotNoneType(tags);
    }
  );

  /**
   * References the compliance field tuple containing the field name and the field change set properties
   * @type {IdentifierFieldWithFieldChangeSetTuple}
   * @memberof DatasetComplianceRollupRow
   */
  field: IdentifierFieldWithFieldChangeSetTuple;

  /**
   * References the first item in the IdentifierFieldWithFieldChangeSetTuple tuple, which is the field name
   * @type {ComputedProperty<string>}
   * @memberof DatasetComplianceRollupRow
   */
  @alias('field.firstObject')
  identifierField: string;

  /**
   * References the second item in the IdentifierFieldWithFieldChangeSetTuple type, this is the list of tags
   * for this field
   * @type {ComputedProperty<Array<IComplianceChangeSet>>}
   * @memberof DatasetComplianceRollupRow
   */
  @alias('field.1')
  fieldChangeSet: Array<IComplianceChangeSet>;

  /**
   * References the first tag in the change set, this is the primary tag for the field and should not be deleted
   * from the changeSet, contains the default properties for the field
   * @type {ComputedProperty<IComplianceChangeSet>}
   * @memberof DatasetComplianceRollupRow
   */
  @alias('fieldChangeSet.firstObject')
  fieldProps: IComplianceChangeSet;

  /**
   * Aliases the dataType property on the first item in the field change set, this should available
   * regardless of if the field already exists on the compliance policy or otherwise
   * @type {ComputedProperty<string>}
   * @memberof DatasetComplianceRollupRow
   */
  @alias('fieldProps.dataType')
  dataType: string;

  /**
   * Checks if the field has only one tag
   * @type {ComputedProperty<boolean>}
   * @memberof DatasetComplianceRollupRow
   */
  hasSingleTag: ComputedProperty<boolean> = equal('fieldChangeSet.length', 1);

  /**
   * Checks if any of the tags on this field have a ComplianceFieldIdValue.None identifierType
   * @type {ComputedProperty<boolean>}
   */
  hasNoneTag: ComputedProperty<boolean> = computed('fieldChangeSet.@each.identifierType', function(
    this: DatasetComplianceRollupRow
  ): boolean {
    return tagsHaveNoneType(get(this, 'fieldChangeSet'));
  });

  /**
   * Checks if any of the field tags for this row are dirty
   * @type {ComputedProperty<boolean>}
   * @memberof DatasetComplianceRollupRow
   */
  isRowDirty: ComputedProperty<boolean> = computed('fieldChangeSet', function(
    this: DatasetComplianceRollupRow
  ): boolean {
    return get(this, 'fieldChangeSet').some(tag => tag.isDirty);
  });

  /**
   * Reference to the current value of the field's SuggestionIntent if present
   * indicates that the provided suggestion is either accepted or ignored
   * @type {(ComputedProperty<SuggestionIntent | void>)}
   * @memberof DatasetComplianceRollupRow
   */
  @alias('fieldProps.suggestionAuthority')
  suggestionAuthority: IComplianceChangeSet['suggestionAuthority'];

  /**
   * Extracts the field suggestions into a cached computed property, if a suggestion exists
   * @type {(ComputedProperty<{ identifierType: ComplianceFieldIdValue; logicalType: string; confidence: number } | void>)}
   * @memberof DatasetComplianceRollupRow
   */
  suggestion = computed('fieldProps.suggestion', 'suggestionAuthority', 'suggestionConfidenceThreshold', function(
    this: DatasetComplianceRollupRow
  ): ISuggestedFieldTypeValues | void {
    const fieldProps = getWithDefault(this, 'fieldProps', <IComplianceChangeSet>{});

    return getTagSuggestions({ suggestionConfidenceThreshold: get(this, 'suggestionConfidenceThreshold') })(fieldProps);
  });

  /**
   * Maps the suggestion response, if present, to a string resolution
   * @type ComputedProperty<string | void>
   * @memberof DatasetComplianceRollupRow
   */
  suggestionResolution = computed('suggestionAuthority', function(this: DatasetComplianceRollupRow): string | void {
    const suggestionAuthority = get(this, 'suggestionAuthority');

    if (suggestionAuthority) {
      return {
        [SuggestionIntent.accept]: 'Accepted',
        [SuggestionIntent.ignore]: 'Discarded'
      }[suggestionAuthority];
    }
  });

  /**
   * Lists the ComplianceFieldIdValue values this field is currently tagged with
   * @type {ComputedProperty<Array<ComplianceFieldIdValue>>}
   * @memberof DatasetComplianceRollupRow
   */
  taggedIdentifiers: ComputedProperty<Array<IComplianceEntity['identifierType']>> = mapBy(
    'fieldChangeSet',
    'identifierType'
  );

  /**
   * Lists the identifierTypes that are suggested values but are currently in the fields tags
   * @type {ComputedProperty<Array<string>>}
   * @memberof DatasetComplianceRollupRow
   * TODO: multi valued suggestions
   */
  suggestedValuesInChangeSet = computed('taggedIdentifiers', 'suggestion', function(
    this: DatasetComplianceRollupRow
  ): Array<IComplianceEntity['identifierType']> {
    const { taggedIdentifiers, suggestion } = getProperties(this, ['taggedIdentifiers', 'suggestion']);

    return arrayReduce(suggestedIdentifierTypesInList(suggestion), [])(taggedIdentifiers);
  });

  /**
   * Checks the a suggested value for this field matches a value currently set in a field tag
   * @type ComputedProperty<boolean>
   * @memberof DatasetComplianceRollupRow
   */
  suggestionMatchesCurrentValue = computed('suggestedValuesInChangeSet', function(
    this: DatasetComplianceRollupRow
  ): boolean {
    const { suggestedValuesInChangeSet, suggestion } = getProperties(this, [
      'suggestedValuesInChangeSet',
      'suggestion'
    ]);

    if (suggestion) {
      const { identifierType } = suggestion;
      return !!identifierType && suggestedValuesInChangeSet.includes(identifierType);
    }

    return false;
  });

  /**
   * Mouse double click event handler invokes parent action
   * @memberof DatasetComplianceRollupRow
   */
  @action
  onFragmentDblClick() {
    get(this, 'onFieldDblClick')();
  }

  /**
   * Invokes the external action to edit the compliance policy and expands the clicked row
   * for editing
   * @param {() => void} externalEditAction
   */
  @action
  onEditPolicy(this: DatasetComplianceRollupRow, externalEditAction: () => void) {
    externalEditAction();
  }

  /**
   * Handles adding a field tag when the user indicates the action through the UI
   * @memberof DatasetComplianceRollupRow
   */
  @action
  onAddFieldTag(this: DatasetComplianceRollupRow, { identifierType, logicalType }: Partial<IColumnFieldProps>) {
    const { identifierField, dataType, onFieldTagAdded, fieldChangeSet, fieldProps } = getProperties(this, [
      'identifierField',
      'dataType',
      'onFieldTagAdded',
      'fieldChangeSet',
      'fieldProps'
    ]);

    if (fieldTagsHaveIdentifierType(fieldChangeSet)) {
      onFieldTagAdded(
        complianceFieldChangeSetItemFactory({
          identifierField,
          dataType,
          identifierType,
          logicalType,
          suggestion: fieldProps.suggestion,
          suggestionAuthority: fieldProps.suggestionAuthority
        })
      );
    }
  }

  /**
   * Handles the removal of a field tag from the list of change set items
   * @param {IComplianceChangeSet} tag
   * @memberof DatasetComplianceRollupRow
   */
  @action
  onRemoveFieldTag(this: DatasetComplianceRollupRow, tag: IComplianceChangeSet) {
    const onFieldTagRemoved = get(this, 'onFieldTagRemoved');

    if (typeof onFieldTagRemoved === 'function' && !get(this, 'hasSingleTag')) {
      onFieldTagRemoved(tag);
    }
  }

  /**
   * Handles the falsifying of a field's readonly attribute
   * @param {IComplianceChangeSet} tag
   * @memberof DatasetComplianceRollupRow
   */
  @action
  onEditReadonlyTag(tag: IComplianceChangeSet) {
    const onTagReadOnlyDisable = get(this, 'onTagReadOnlyDisable');

    if (typeof onTagReadOnlyDisable === 'function') {
      onTagReadOnlyDisable(tag);
    }
  }

  /**
   * Handler for user interactions with a suggested value. Applies / ignores the suggestion
   * Then invokes the parent supplied suggestion handler
   * @param {SuggestionIntent} intent a binary indicator to accept or ignore suggestion
   * @memberof DatasetComplianceRollupRow
   */
  @action
  onSuggestionClick(this: DatasetComplianceRollupRow, intent: SuggestionIntent = SuggestionIntent.ignore) {
    const { onSuggestionIntent, suggestedValuesInChangeSet, suggestion, hasSingleTag } = getProperties(this, [
      'onSuggestionIntent',
      'suggestedValuesInChangeSet',
      'suggestion',
      'hasSingleTag'
    ]);

    // Accept the suggestion for either identifierType and/or logicalType
    if (suggestion && intent === SuggestionIntent.accept) {
      const { identifierType, logicalType } = suggestion;
      // Field has only one tag, that tag has an identifierType
      const updateDefault = hasSingleTag && fieldTagsHaveIdentifierType(get(this, 'fieldChangeSet'));

      // Suggested identifierType exists but changeSet does not already have the suggested type
      if (identifierType && !suggestedValuesInChangeSet.includes(identifierType)) {
        if (updateDefault) {
          get(this, 'onTagIdentifierTypeChange')(get(this, 'fieldProps'), {
            value: <ComplianceFieldIdValue>identifierType
          });
        } else {
          // If suggested value is ComplianceFieldIdValue.None, remove all other annotations first before tagging field as none
          if (identifierType === ComplianceFieldIdValue.None) {
            arrayEach(this.actions.onRemoveFieldTag.bind(this))(this.fieldChangeSet);
          }

          this.actions.onAddFieldTag.call(this, { identifierType, logicalType });
        }
      }
    }

    // Invokes parent handle to ignore future revisits of this suggestion
    if (typeof onSuggestionIntent === 'function') {
      onSuggestionIntent(get(this, 'fieldProps'), intent);
    }
  }
}


text:
import { Column, ExcelCell, ExcelDataType, ExcelOOXMLDataType, ExcelWorksheet, RowNode } from '@ag-grid-community/core';
import { ExcelXmlSerializingSession } from './excelXmlSerializingSession';
import { RowSpanningAccumulator } from "@ag-grid-community/csv-export";
export declare class ExcelXlsxSerializingSession extends ExcelXmlSerializingSession {
    private stringList;
    private stringMap;
    onNewHeaderGroupingRow(): RowSpanningAccumulator;
    onNewHeaderColumn(rowIndex: number, currentCells: ExcelCell[]): (column: Column, index: number, node?: RowNode) => void;
    protected createExcel(data: ExcelWorksheet[]): string;
    protected getDataTypeForValue(valueForCell: any): ExcelOOXMLDataType | ExcelDataType;
    private getStringPosition;
    protected createCell(styleId: string | undefined, type: ExcelOOXMLDataType, value: string): ExcelCell;
    protected createMergedCell(styleId: string | undefined, type: ExcelDataType | ExcelOOXMLDataType, value: string, numOfCells: number): ExcelCell;
}


text:
from .sub_resource import SubResource

class InboundNatPool(SubResource):
    """Inbound NAT pool of the load balancer.

    All required parameters must be populated in order to send to Azure.

    :param id: Resource ID.
    :type id: str
    :param frontend_ip_configuration: A reference to frontend IP addresses.
    :type frontend_ip_configuration:
     ~azure.mgmt.network.v2017_11_01.models.SubResource
    :param protocol: Required. Possible values include: 'Udp', 'Tcp', 'All'
    :type protocol: str or
     ~azure.mgmt.network.v2017_11_01.models.TransportProtocol
    :param frontend_port_range_start: Required. The first port number in the
     range of external ports that will be used to provide Inbound Nat to NICs
     associated with a load balancer. Acceptable values range between 1 and
     65534.
    :type frontend_port_range_start: int
    :param frontend_port_range_end: Required. The last port number in the
     range of external ports that will be used to provide Inbound Nat to NICs
     associated with a load balancer. Acceptable values range between 1 and
     65535.
    :type frontend_port_range_end: int
    :param backend_port: Required. The port used for internal connections on
     the endpoint. Acceptable values are between 1 and 65535.
    :type backend_port: int
    :param idle_timeout_in_minutes: The timeout for the TCP idle connection.
     The value can be set between 4 and 30 minutes. The default value is 4
     minutes. This element is only used when the protocol is set to TCP.
    :type idle_timeout_in_minutes: int
    :param enable_floating_ip: Configures a virtual machine's endpoint for the
     floating IP capability required to configure a SQL AlwaysOn Availability
     Group. This setting is required when using the SQL AlwaysOn Availability
     Groups in SQL server. This setting can't be changed after you create the
     endpoint.
    :type enable_floating_ip: bool
    :param provisioning_state: Gets the provisioning state of the PublicIP
     resource. Possible values are: 'Updating', 'Deleting', and 'Failed'.
    :type provisioning_state: str
    :param name: The name of the resource that is unique within a resource
     group. This name can be used to access the resource.
    :type name: str
    :param etag: A unique read-only string that changes whenever the resource
     is updated.
    :type etag: str
    """

    _validation = {
        'protocol': {'required': True},
        'frontend_port_range_start': {'required': True},
        'frontend_port_range_end': {'required': True},
        'backend_port': {'required': True},
    }

    _attribute_map = {
        'id': {'key': 'id', 'type': 'str'},
        'frontend_ip_configuration': {'key': 'properties.frontendIPConfiguration', 'type': 'SubResource'},
        'protocol': {'key': 'properties.protocol', 'type': 'str'},
        'frontend_port_range_start': {'key': 'properties.frontendPortRangeStart', 'type': 'int'},
        'frontend_port_range_end': {'key': 'properties.frontendPortRangeEnd', 'type': 'int'},
        'backend_port': {'key': 'properties.backendPort', 'type': 'int'},
        'idle_timeout_in_minutes': {'key': 'properties.idleTimeoutInMinutes', 'type': 'int'},
        'enable_floating_ip': {'key': 'properties.enableFloatingIP', 'type': 'bool'},
        'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
        'name': {'key': 'name', 'type': 'str'},
        'etag': {'key': 'etag', 'type': 'str'},
    }

    def __init__(self, **kwargs):
        super(InboundNatPool, self).__init__(**kwargs)
        self.frontend_ip_configuration = kwargs.get('frontend_ip_configuration', None)
        self.protocol = kwargs.get('protocol', None)
        self.frontend_port_range_start = kwargs.get('frontend_port_range_start', None)
        self.frontend_port_range_end = kwargs.get('frontend_port_range_end', None)
        self.backend_port = kwargs.get('backend_port', None)
        self.idle_timeout_in_minutes = kwargs.get('idle_timeout_in_minutes', None)
        self.enable_floating_ip = kwargs.get('enable_floating_ip', None)
        self.provisioning_state = kwargs.get('provisioning_state', None)
        self.name = kwargs.get('name', None)
        self.etag = kwargs.get('etag', None)


text:
<!doctype html>

  <title>jGrader - Home</title>
  <meta name="viewport" content="width=device-width">

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

  <link href="../../../res/css/triangles.css" rel="stylesheet" >

Home

Alice

About

Help

Sign out

            Current courses

            Previous courses

Upcoming Assignments

Apr.22

              Python Lab Homework 5

Apr.23

                C Lab Homework 4

Apr.29

              Calculus 1 Homework 6

          Welcome to jGrader!

          On this page you can get an overview of current assignments and their completion.

          For a full list, please select a course from the course list here or the complete course list on the "course" tab.

          Learn more


text:
package org.twuni.xmppt.xml;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.junit.Assert;
import org.junit.Test;

public class XMLElementParserTest extends Assert {

	private static XMLElement parse( String in ) {
		return new XMLElementParser().parse( in ).get( 0 );
	}

	@Test
	public void parse_shouldDiscardTopLevelText() {
		List<XMLElement> entities = new XMLElementParser().parse( "Ignore this." );
		assertTrue( entities.isEmpty() );
	}

	@Test
	public void parse_shouldParseElementWithChildElement() {
		Collection<XMLEntity> children = new ArrayList<XMLEntity>();
		children.add( new XMLElement( "child" ) );
		XMLElement expected = new XMLElement( "parent", null, children );
		XMLElement actual = parse( "<parent><child/></parent>" );
		assertEquals( expected.name, actual.name );
		assertEquals( expected.children.size(), actual.children.size() );
	}

	@Test
	public void parse_shouldParseMultipleTopLevelElements() {
		List<XMLElement> entities = new XMLElementParser().parse( "<a/><b/><c/>" );
		assertEquals( 3, entities.size() );
	}

	@Test
	public void parse_shouldParseSimpleElement() {
		XMLElement expected = new XMLElement( "test" );
		XMLElement actual = parse( "<test/>" );
		assertEquals( expected.name, actual.name );
	}

	@Test
	public void parse_shouldParseSimpleElementWithOneAttribute() {
		Map<String, String> attributes = new HashMap<String, String>();
		attributes.put( "a", "1" );
		XMLElement expected = new XMLElement( "test", attributes );
		XMLElement actual = parse( "<test a=\"1\"/>" );
		assertEquals( expected.name, actual.name );
		assertEquals( "1", expected.attribute( "a" ) );
	}

	@Test
	public void parse_shouldParseSimpleElementWithTwoAttributes() {
		Map<String, String> attributes = new HashMap<String, String>();
		attributes.put( "a", "1" );
		attributes.put( "z", "9" );
		XMLElement expected = new XMLElement( "test", attributes );
		XMLElement actual = parse( "<test z=\"9\" a=\"1\"/>" );
		assertEquals( expected.name, actual.name );
		assertEquals( expected.attribute( "a" ), actual.attribute( "a" ) );
		assertEquals( expected.attribute( "z" ), actual.attribute( "z" ) );
	}

	@Test
	public void parse_shouldParseTopLevelElementsWithIgnoredSiblings() {
		List<XMLElement> entities = new XMLElementParser().parse( "Ignore <test/>, please." );
		assertEquals( 1, entities.size() );
	}

	@Test
	public void parse_xmppStream() {
		List<XMLElement> entities = new XMLElementParser().parse( "<stream:stream xmlns:stream=\"http://etherx.jabber.org/streams\" to=\"example.com\" xmlns=\"jabber:client\" version=\"1.0\"/>" );
		assertEquals( 1, entities.size() );
		System.out.println( entities );
	}

}


text:
package openperipheral.integration.vanilla;

import com.google.common.base.Preconditions;
import net.minecraft.tileentity.TileEntityDaylightDetector;
import net.minecraft.world.EnumSkyBlock;
import net.minecraft.world.World;
import openperipheral.api.adapter.IPeripheralAdapter;
import openperipheral.api.adapter.method.ReturnType;
import openperipheral.api.adapter.method.ScriptCallable;

public class AdapterDaylightSensor implements IPeripheralAdapter {

	@Override
	public Class<?> getTargetClass() {
		return TileEntityDaylightDetector.class;
	}

	@Override
	public String getSourceId() {
		return "vanilla_daylight_sensor";
	}

	@ScriptCallable(returnTypes = ReturnType.BOOLEAN, description = "Get true if age has normal sky")
	public boolean hasSky(TileEntityDaylightDetector target) {
		World world = target.getWorldObj();
		return !world.provider.hasNoSky;
	}

	@ScriptCallable(returnTypes = ReturnType.NUMBER, description = "Get level of natural light (sky)")
	public int getSkyLight(TileEntityDaylightDetector target) {
		World world = target.getWorldObj();
		Preconditions.checkArgument(!world.provider.hasNoSky, "World has no sky");
		return world.getSavedLightValue(EnumSkyBlock.Sky, target.xCoord, target.yCoord, target.zCoord) - world.skylightSubtracted;
	}

	@ScriptCallable(returnTypes = ReturnType.NUMBER, description = "Get level of block light")
	public int getBlockLight(TileEntityDaylightDetector target) {
		World world = target.getWorldObj();
		return world.getSavedLightValue(EnumSkyBlock.Block, target.xCoord, target.yCoord, target.zCoord);
	}

	@ScriptCallable(returnTypes = ReturnType.NUMBER, description = "Get angle of sun (in degrees, 0 is zenith)")
	public float getCelestialAngle(TileEntityDaylightDetector target) {
		World world = target.getWorldObj();
		return world.getCelestialAngle(1) * 360;
	}
}


text:
package org.apache.cassandra.io.sstable;

import java.io.Closeable;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;

import org.apache.cassandra.db.DecoratedKey;
import org.apache.cassandra.db.RowPosition;
import org.apache.cassandra.dht.IPartitioner;
import org.apache.cassandra.io.util.Memory;
import org.apache.cassandra.io.util.MemoryInputStream;
import org.apache.cassandra.io.util.MemoryOutputStream;
import org.apache.cassandra.utils.FBUtilities;

public class IndexSummary implements Closeable
{
    public static final IndexSummarySerializer serializer = new IndexSummarySerializer();
    private final int indexInterval;
    private final IPartitioner partitioner;
    private final int summary_size;
    private final Memory bytes;

    public IndexSummary(IPartitioner partitioner, Memory memory, int summary_size, int indexInterval)
    {
        this.partitioner = partitioner;
        this.indexInterval = indexInterval;
        this.summary_size = summary_size;
        this.bytes = memory;
    }

    // binary search is notoriously more difficult to get right than it looks; this is lifted from
    // Harmony's Collections implementation
    public int binarySearch(RowPosition key)
    {
        int low = 0, mid = summary_size, high = mid - 1, result = -1;
        while (low <= high)
        {
            mid = (low + high) >> 1;
            result = -DecoratedKey.compareTo(partitioner, ByteBuffer.wrap(getKey(mid)), key);
            if (result > 0)
            {
                low = mid + 1;
            }
            else if (result == 0)
            {
                return mid;
            }
            else
            {
                high = mid - 1;
            }
        }

        return -mid - (result < 0 ? 1 : 2);
    }

    public int getIndex(int index)
    {
        // multiply by 4.
        return bytes.getInt(index << 2);
    }

    public byte[] getKey(int index)
    {
        long start = getIndex(index);
        int keySize = (int) (caclculateEnd(index) - start - 8L);
        byte[] key = new byte[keySize];
        bytes.getBytes(start, key, 0, keySize);
        return key;
    }

    public long getPosition(int index)
    {
        return bytes.getLong(caclculateEnd(index) - 8);
    }

    private long caclculateEnd(int index)
    {
        return index == (summary_size - 1) ? bytes.size() : getIndex(index + 1);
    }

    public int getIndexInterval()
    {
        return indexInterval;
    }

    public int size()
    {
        return summary_size;
    }

    public static class IndexSummarySerializer
    {
        public void serialize(IndexSummary t, DataOutputStream out) throws IOException
        {
            out.writeInt(t.indexInterval);
            out.writeInt(t.summary_size);
            out.writeLong(t.bytes.size());
            FBUtilities.copy(new MemoryInputStream(t.bytes), out, t.bytes.size());
        }

        public IndexSummary deserialize(DataInputStream in, IPartitioner partitioner) throws IOException
        {
            int indexInterval = in.readInt();
            int summary_size = in.readInt();
            long offheap_size = in.readLong();
            Memory memory = Memory.allocate(offheap_size);
            FBUtilities.copy(in, new MemoryOutputStream(memory), offheap_size);
            return new IndexSummary(partitioner, memory, summary_size, indexInterval);
        }
    }

    @Override
    public void close() throws IOException
    {
        bytes.free();
    }
}


text:
package com.alibaba.json.bvt.issue_1300;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.annotation.JSONCreator;
import junit.framework.TestCase;

/**
 * Created by wenshao on 26/07/2017.
 */
public class Issue1344 extends TestCase {
    public void test_for_issue() throws Exception {
        TestException testException = new TestException("aaa");
        System.out.println("before:" + testException.getMessage());
        String json = JSONObject.toJSONString(testException);
        System.out.println(json);
        TestException o = JSONObject.parseObject(json, TestException.class);
        System.out.println("after:" + o.getMessage());
    }

    public static class TestException extends Exception {

        @JSONCreator
        public TestException() {

        }

        public TestException(String data) {
            super("Data : " + data);
        }

    }
}


text:
package oglematchers_test

import (
	. "github.com/smartystreets/assertions/internal/oglematchers"
	. "github.com/smartystreets/assertions/internal/ogletest"
)

////////////////////////////////////////////////////////////////////////
// Helpers
////////////////////////////////////////////////////////////////////////

type ContainsTest struct {}
func init() { RegisterTestSuite(&ContainsTest{}) }

////////////////////////////////////////////////////////////////////////
// Tests
////////////////////////////////////////////////////////////////////////

func (t *ContainsTest) WrongTypeCandidates() {
	m := Contains("")
	ExpectEq("contains: ", m.Description())

	var err error

	// Nil candidate
	err = m.Matches(nil)
	ExpectTrue(isFatal(err))
	ExpectThat(err, Error(HasSubstr("array")))
	ExpectThat(err, Error(HasSubstr("slice")))

	// String candidate
	err = m.Matches("")
	ExpectTrue(isFatal(err))
	ExpectThat(err, Error(HasSubstr("array")))
	ExpectThat(err, Error(HasSubstr("slice")))

	// Map candidate
	err = m.Matches(make(map[string]string))
	ExpectTrue(isFatal(err))
	ExpectThat(err, Error(HasSubstr("array")))
	ExpectThat(err, Error(HasSubstr("slice")))
}

func (t *ContainsTest) NilArgument() {
	m := Contains(nil)
	ExpectEq("contains: is nil", m.Description())

	var c interface{}
	var err error

	// Empty array of pointers
	c = [...]*int{}
	err = m.Matches(c)
	ExpectThat(err, Error(Equals("")))

	// Empty slice of pointers
	c = []*int{}
	err = m.Matches(c)
	ExpectThat(err, Error(Equals("")))

	// Non-empty array of integers
	c = [...]int{17, 0, 19}
	err = m.Matches(c)
	ExpectThat(err, Error(Equals("")))

	// Non-empty slice of integers
	c = []int{17, 0, 19}
	err = m.Matches(c)
	ExpectThat(err, Error(Equals("")))

	// Non-matching array of pointers
	c = [...]*int{new(int), new(int)}
	err = m.Matches(c)
	ExpectThat(err, Error(Equals("")))

	// Non-matching slice of pointers
	c = []*int{new(int), new(int)}
	err = m.Matches(c)
	ExpectThat(err, Error(Equals("")))

	// Matching array of pointers
	c = [...]*int{new(int), nil, new(int)}
	err = m.Matches(c)
	ExpectEq(nil, err)

	// Matching slice of pointers
	c = []*int{new(int), nil, new(int)}
	err = m.Matches(c)
	ExpectEq(nil, err)

	// Non-matching slice of pointers from matching array
	someArray := [...]*int{new(int), nil, new(int)}
	c = someArray[0:1]
	err = m.Matches(c)
	ExpectThat(err, Error(Equals("")))
}

func (t *ContainsTest) StringArgument() {
	m := Contains("taco")
	ExpectEq("contains: taco", m.Description())

	var c interface{}
	var err error

	// Non-matching array of strings
	c = [...]string{"burrito", "enchilada"}
	err = m.Matches(c)
	ExpectThat(err, Error(Equals("")))

	// Non-matching slice of strings
	c = []string{"burrito", "enchilada"}
	err = m.Matches(c)
	ExpectThat(err, Error(Equals("")))

	// Matching array of strings
	c = [...]string{"burrito", "taco", "enchilada"}
	err = m.Matches(c)
	ExpectEq(nil, err)

	// Matching slice of strings
	c = []string{"burrito", "taco", "enchilada"}
	err = m.Matches(c)
	ExpectEq(nil, err)

	// Non-matching slice of strings from matching array
	someArray := [...]string{"burrito", "taco", "enchilada"}
	c = someArray[0:1]
	err = m.Matches(c)
	ExpectThat(err, Error(Equals("")))
}

func (t *ContainsTest) IntegerArgument() {
	m := Contains(int(17))
	ExpectEq("contains: 17", m.Description())

	var c interface{}
	var err error

	// Non-matching array of integers
	c = [...]int{13, 19}
	err = m.Matches(c)
	ExpectThat(err, Error(Equals("")))

	// Non-matching slice of integers
	c = []int{13, 19}
	err = m.Matches(c)
	ExpectThat(err, Error(Equals("")))

	// Matching array of integers
	c = [...]int{13, 17, 19}
	err = m.Matches(c)
	ExpectEq(nil, err)

	// Matching slice of integers
	c = []int{13, 17, 19}
	err = m.Matches(c)
	ExpectEq(nil, err)

	// Non-matching slice of integers from matching array
	someArray := [...]int{13, 17, 19}
	c = someArray[0:1]
	err = m.Matches(c)
	ExpectThat(err, Error(Equals("")))

	// Non-matching array of floats
	c = [...]float32{13, 17.5, 19}
	err = m.Matches(c)
	ExpectThat(err, Error(Equals("")))

	// Non-matching slice of floats
	c = []float32{13, 17.5, 19}
	err = m.Matches(c)
	ExpectThat(err, Error(Equals("")))

	// Matching array of floats
	c = [...]float32{13, 17, 19}
	err = m.Matches(c)
	ExpectEq(nil, err)

	// Matching slice of floats
	c = []float32{13, 17, 19}
	err = m.Matches(c)
	ExpectEq(nil, err)
}

func (t *ContainsTest) MatcherArgument() {
	m := Contains(HasSubstr("ac"))
	ExpectEq("contains: has substring \"ac\"", m.Description())

	var c interface{}
	var err error

	// Non-matching array of strings
	c = [...]string{"burrito", "enchilada"}
	err = m.Matches(c)
	ExpectThat(err, Error(Equals("")))

	// Non-matching slice of strings
	c = []string{"burrito", "enchilada"}
	err = m.Matches(c)
	ExpectThat(err, Error(Equals("")))

	// Matching array of strings
	c = [...]string{"burrito", "taco", "enchilada"}
	err = m.Matches(c)
	ExpectEq(nil, err)

	// Matching slice of strings
	c = []string{"burrito", "taco", "enchilada"}
	err = m.Matches(c)
	ExpectEq(nil, err)

	// Non-matching slice of strings from matching array
	someArray := [...]string{"burrito", "taco", "enchilada"}
	c = someArray[0:1]
	err = m.Matches(c)
	ExpectThat(err, Error(Equals("")))
}


text:
/*
	Based on the FS Import classes:
	Copyright (C) 2005-2006 Feeling Software Inc
	Copyright (C) 2005-2006 Autodesk Media Entertainment
	MIT License: http://www.opensource.org/licenses/mit-license.php
*/

#include "StdAfx.h"
#include "FCDocument/FCDocument.h"
#include "FCDocument/FCDGeometry.h"
#include "FCDocument/FCDGeometryMesh.h"
#include "FCDocument/FCDGeometryPolygons.h"
#include "FCDocument/FCDGeometryPolygonsInput.h"
#include "FCDocument/FCDGeometrySource.h"
#include "FCDocument/FCDLibrary.h"
#include "FUtils/FUStringConversion.h"

//
// FCDGeometryMesh
//

ImplementObjectType(FCDGeometryMesh);
ImplementParameterObject(FCDGeometryMesh, FCDGeometrySource, sources, new FCDGeometrySource(parent->GetDocument()));
ImplementParameterObject(FCDGeometryMesh, FCDGeometryPolygons, polygons, new FCDGeometryPolygons(parent->GetDocument(), parent));
ImplementParameterObjectNoCtr(FCDGeometryMesh, FCDGeometrySource, vertexSources);

FCDGeometryMesh::FCDGeometryMesh(FCDocument* document, FCDGeometry* _parent)
    : FCDObject(document)
    , parent(_parent)
    , InitializeParameterNoArg(sources)
    , InitializeParameterNoArg(polygons)
    , InitializeParameterNoArg(vertexSources)
    , faceCount(0)
    , holeCount(0)
    , faceVertexCount(0)
    , isConvex(true)
    , convexify(false)
    , InitializeParameterNoArg(convexHullOf)
{
}

FCDGeometryMesh::~FCDGeometryMesh()
{
    polygons.clear();
    sources.clear();
    faceVertexCount = faceCount = holeCount = 0;
    parent = NULL;
}

// Retrieve the parent's id
const fm::string& FCDGeometryMesh::GetDaeId() const
{
    return parent->GetDaeId();
}

void FCDGeometryMesh::SetConvexHullOf(FCDGeometry* _geom)
{
    convexHullOf = _geom->GetDaeId();
    SetDirtyFlag();
}

const FCDGeometryMesh* FCDGeometryMesh::FindConvexHullOfMesh() const
{
    const FCDGeometryMesh* mesh = this;
    while ((mesh != NULL) && !mesh->GetConvexHullOf().empty())
    {
        const FCDocument* document = mesh->GetDocument();
        const FCDGeometry* geometry = document->GetGeometryLibrary()->
                                      FindDaeId(mesh->GetConvexHullOf());
        if (geometry == NULL)
            return NULL;
        mesh = geometry->GetMesh();
    }
    return mesh;
}

// Search for a data source in the geometry node
const FCDGeometrySource* FCDGeometryMesh::FindSourceById(const fm::string& id) const
{
    const char* localId = id.c_str();
    if (localId[0] == '#')
        ++localId;
    for (const FCDGeometrySource** it = sources.begin(); it != sources.end(); ++it)
    {
        if ((*it)->GetDaeId() == localId)
            return (*it);
    }
    return NULL;
}

// Retrieve the source for the given type
const FCDGeometrySource* FCDGeometryMesh::FindSourceByType(FUDaeGeometryInput::Semantic type) const
{
    for (const FCDGeometrySource** itS = sources.begin(); itS != sources.end(); ++itS)
    {
        if ((*itS)->GetType() == type)
            return (*itS);
    }
    return NULL;
}

void FCDGeometryMesh::FindSourcesByType(FUDaeGeometryInput::Semantic type, FCDGeometrySourceConstList& _sources) const
{
    for (const FCDGeometrySource** itS = sources.begin(); itS != sources.end(); ++itS)
    {
        if ((*itS)->GetType() == type)
            _sources.push_back(*itS);
    }
}

const FCDGeometrySource* FCDGeometryMesh::FindSourceByName(const fstring& name) const
{
    for (const FCDGeometrySource** itS = sources.begin(); itS != sources.end(); ++itS)
    {
        if ((*itS)->GetName() == name)
            return (*itS);
    }
    return NULL;
}

// Creates a new polygon group.
FCDGeometryPolygons* FCDGeometryMesh::AddPolygons()
{
    FCDGeometryPolygons* polys = new FCDGeometryPolygons(GetDocument(), this);
    polygons.push_back(polys);

    // Add to this new polygons all the per-vertex sources.
    size_t vertexSourceCount = vertexSources.size();
    for (size_t v = 0; v < vertexSourceCount; ++v)
    {
        polys->AddInput(vertexSources[v], 0);
    }

    SetNewChildFlag();
    if (parent != NULL)
        parent->SetNewChildFlag();
    return polys;
}

bool FCDGeometryMesh::IsTriangles() const
{
    bool isTriangles = true;
    for (size_t i = 0; i < polygons.size() && isTriangles; ++i)
    {
        isTriangles = (polygons[i]->TestPolyType() == 3);
    }
    return isTriangles;
}

// Retrieves the polygon sets that use a given material semantic
void FCDGeometryMesh::FindPolygonsByMaterial(const fstring& semantic, FCDGeometryPolygonsList& sets)
{
    size_t polygonCount = polygons.size();
    for (size_t p = 0; p < polygonCount; ++p)
    {
        if (polygons[p]->GetMaterialSemantic() == semantic)
            sets.push_back(polygons[p]);
    }
}

// Creates a new per-vertex data source
FCDGeometrySource* FCDGeometryMesh::AddVertexSource(FUDaeGeometryInput::Semantic type)
{
    FCDGeometrySource* vertexSource = AddSource(type);
    vertexSources.push_back(vertexSource);

    // Add this new per-vertex data source to all the existing polygon groups, at offset 0.
    size_t polygonsCount = polygons.size();
    for (size_t p = 0; p < polygonsCount; ++p)
    {
        polygons[p]->AddInput(vertexSource, 0);
    }

    SetNewChildFlag();
    return vertexSource;
}

// Sets a source as per-vertex data.
void FCDGeometryMesh::AddVertexSource(FCDGeometrySource* source)
{
    FUAssert(source != NULL, return );
    FUAssert(!vertexSources.contains(source), return );

    // Add the source to the list of per-vertex sources.
    vertexSources.push_back(source);

    // Remove any polygon set input that uses the source.
    size_t polygonsCount = polygons.size();
    for (size_t p = 0; p < polygonsCount; ++p)
    {
        FCDGeometryPolygonsInput* input = polygons[p]->FindInput(source);
        int32 set = (input != NULL) ? input->GetSet() : -1;
        SAFE_RELEASE(input);
        input = polygons[p]->AddInput(source, 0);
        if (set > -1)
            input->SetSet(set);
    }

    SetNewChildFlag();
}

void FCDGeometryMesh::RemoveVertexSource(FCDGeometrySource* source)
{
    FUAssert(source != NULL, return );
    if (!vertexSources.contains(source))
        return;

    // Add the source to the list of per-vertex sources.
    vertexSources.erase(source);
    SetDirtyFlag();
}

// Creates a new data source
FCDGeometrySource* FCDGeometryMesh::AddSource(FUDaeGeometryInput::Semantic type)
{
    FCDGeometrySource* source = new FCDGeometrySource(GetDocument());
    source->SetType(type);
    sources.push_back(source);
    SetNewChildFlag();
    return source;
}

// Recalculates all the hole/vertex/face-vertex counts and offsets within the mesh and its polygons
void FCDGeometryMesh::Recalculate()
{
    faceCount = holeCount = faceVertexCount = 0;
    size_t polygonsCount = polygons.size();
    for (size_t p = 0; p < polygonsCount; ++p)
    {
        FCDGeometryPolygons* polys = polygons[p];
        polys->Recalculate();

        polys->SetFaceOffset(faceCount);
        polys->SetHoleOffset(holeCount);
        polys->SetFaceVertexOffset(faceVertexCount);
        faceCount += polys->GetFaceCount();
        holeCount += polys->GetHoleCount();
        faceVertexCount += polys->GetFaceVertexCount();
    }
    SetDirtyFlag();
}

FCDGeometryMesh* FCDGeometryMesh::Clone(FCDGeometryMesh* clone) const
{
    if (clone == NULL)
        clone = new FCDGeometryMesh(const_cast<FCDocument*>(GetDocument()), NULL);

    // Copy the miscellaneous information
    clone->convexHullOf = convexHullOf;
    clone->isConvex = isConvex;
    clone->convexify = convexify;
    clone->faceCount = faceCount;
    clone->holeCount = holeCount;
    clone->faceVertexCount = faceVertexCount;

    // Clone the sources
    FCDGeometrySourceCloneMap cloneMap;
    for (const FCDGeometrySource** itS = sources.begin(); itS != sources.end(); ++itS)
    {
        FCDGeometrySource* clonedSource = (IsVertexSource(*itS)) ? clone->AddVertexSource() : clone->AddSource();
        (*itS)->Clone(clonedSource);
        cloneMap.insert(*itS, clonedSource);
    }

    // Clone the polygon sets.
    for (const FCDGeometryPolygons** itP = polygons.begin(); itP != polygons.end(); ++itP)
    {
        FCDGeometryPolygons* clonedPolys = clone->AddPolygons();
        (*itP)->Clone(clonedPolys, cloneMap);
    }

    return clone;
}


text:
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'therapeutor'


text:
ApiDescGenerator
================

生成Api的定义Java文件


text:
(function() {

  'use strict';

  angular
    .module('devPortal')
    .factory('UserRegisterService', UserRegisterService);

  /* @ngInject */
  function UserRegisterService($resource, IfStudioClient) {
    return $resource(IfStudioClient.apiBase + 'register/:orgId/accounts/:accountId', {
      orgId: '@orgId',
      accountId: '@accountId'
    }, {
      'update': { method: 'PUT' }
    });
  }
})();


text:
all:
	javac Jeffrey241/*.java
clean:
	rm Jeffrey241/*.class
run:
	java Jeffrey241.Main


text:
/*	$NetBSD: print_p.h,v 1.3 2012/06/05 00:43:05 christos Exp $	*/

/*
 * Copyright (C) 2004, 2007, 2010  Internet Systems Consortium, Inc. ("ISC")
 * Copyright (C) 1999-2001, 2003  Internet Software Consortium.
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
 * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
 * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
 * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
 * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 * PERFORMANCE OF THIS SOFTWARE.
 */

/* Id: print_p.h,v 1.6 2010/08/16 23:46:52 tbox Exp  */

#ifndef LWRES_PRINT_P_H
#define LWRES_PRINT_P_H 1

/***
 *** Imports
 ***/

#include <lwres/lang.h>
#include <lwres/platform.h>

/*
 * This block allows lib/lwres/print.c to be cleanly compiled even if
 * the platform does not need it.  The standard Makefile will still
 * not compile print.c or archive print.o, so this is just to make test
 * compilation ("make print.o") easier.
 */
#if !defined(LWRES_PLATFORM_NEEDVSNPRINTF) && defined(LWRES__PRINT_SOURCE)
#define LWRES_PLATFORM_NEEDVSNPRINTF
#endif

#if !defined(LWRES_PLATFORM_NEEDSPRINTF) && defined(LWRES__PRINT_SOURCE)
#define LWRES_PLATFORM_NEEDSPRINTF
#endif

/***
 *** Macros.
 ***/

#ifdef __GNUC__
#define LWRES_FORMAT_PRINTF(fmt, args) \
	__attribute__((__format__(__printf__, fmt, args)))
#else
#define LWRES_FORMAT_PRINTF(fmt, args)
#endif

/***
 *** Functions
 ***/

#ifdef LWRES_PLATFORM_NEEDVSNPRINTF
#include <stdarg.h>
#include <stddef.h>
#endif

LWRES_LANG_BEGINDECLS

#ifdef LWRES_PLATFORM_NEEDVSNPRINTF
int
lwres__print_vsnprintf(char *str, size_t size, const char *format, va_list ap)
     LWRES_FORMAT_PRINTF(3, 0);
#ifdef vsnprintf
#undef vsnprintf
#endif
#define vsnprintf lwres__print_vsnprintf

int
lwres__print_snprintf(char *str, size_t size, const char *format, ...)
     LWRES_FORMAT_PRINTF(3, 4);
#ifdef snprintf
#undef snprintf
#endif
#define snprintf lwres__print_snprintf
#endif /* LWRES_PLATFORM_NEEDVSNPRINTF */

#ifdef LWRES_PLATFORM_NEEDSPRINTF
int
lwres__print_sprintf(char *str, const char *format, ...) LWRES_FORMAT_PRINTF(2, 3);
#ifdef sprintf
#undef sprintf
#endif
#define sprintf lwres__print_sprintf
#endif

LWRES_LANG_ENDDECLS

#endif /* LWRES_PRINT_P_H */


text:
// -*- mode: c++; c-basic-offset: 4 -*-

#include <click/config.h>
#include "fromdagdump.hh"
#include <click/args.hh>
#include <click/router.hh>
#include <click/standard/scheduleinfo.hh>
#include <click/error.hh>
#include <click/glue.hh>
#include <click/handlercall.hh>
#include <click/packet_anno.hh>
#include <clicknet/rfc1483.h>
#include <click/userutils.hh>
#include "elements/userlevel/fakepcap.hh"
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#ifdef ALLOW_MMAP
# include <sys/mman.h>
#endif
CLICK_DECLS

#define	SWAPLONG(y) \
	((((y)&0xff)<<24) | (((y)&0xff00)<<8) | (((y)&0xff0000)>>8) | (((y)>>24)&0xff))
#define	SWAPSHORT(y) \
	( (((y)&0xff)<<8) | ((u_short)((y)&0xff00)>>8) )

FromDAGDump::FromDAGDump()
    : _packet(0), _end_h(0), _task(this)
{
    static_assert(sizeof(DAGCell) == 64 && DAGCell::CELL_SIZE == 64, "DAGCell must be exactly 64 bytes long.");
}

FromDAGDump::~FromDAGDump()
{
    delete _end_h;
}

int
FromDAGDump::configure(Vector<String> &conf, ErrorHandler *errh)
{
    bool timing = false, stop = false, active = true, force_ip = false;
    Timestamp first_time, first_time_off, last_time, last_time_off, interval;
    HandlerCall end_h;
    String encap;
    _sampling_prob = (1 << SAMPLING_SHIFT);

    if (_ff.configure_keywords(conf, this, errh) < 0)
	return -1;
    if (Args(conf, this, errh)
	.read_mp("FILENAME", FilenameArg(), _ff.filename())
	.read("STOP", stop)
	.read("ACTIVE", active)
	.read("FORCE_IP", force_ip)
	.read("START", first_time)
	.read("START_AFTER", first_time_off)
	.read("END", last_time)
	.read("END_AFTER", last_time_off)
	.read("INTERVAL", interval)
	.read("END_CALL", HandlerCallArg(HandlerCall::writable), end_h)
	.read("SAMPLE", FixedPointArg(SAMPLING_SHIFT), _sampling_prob)
	.read("TIMING", timing)
	.read("ENCAP", WordArg(), encap)
	.complete() < 0)
	return -1;

    // check sampling rate
    if (_sampling_prob > (1 << SAMPLING_SHIFT)) {
	errh->warning("SAMPLE probability reduced to 1");
	_sampling_prob = (1 << SAMPLING_SHIFT);
    } else if (_sampling_prob == 0)
	errh->warning("SAMPLE probability is 0; emitting no packets");

    // check times
    _have_first_time = _have_last_time = true;
    _first_time_relative = _last_time_relative = _last_time_interval = false;

    if ((bool) first_time + (bool) first_time_off > 1)
	return errh->error("'START' and 'START_AFTER' are mutually exclusive");
    else if ((bool) first_time)
	_first_time = first_time;
    else if ((bool) first_time_off)
	_first_time = first_time_off, _first_time_relative = true;
    else
	_have_first_time = false, _first_time_relative = true;

    if ((bool) last_time + (bool) last_time_off + (bool) interval > 1)
	return errh->error("END, END_AFTER, and INTERVAL are mutually exclusive");
    else if ((bool) last_time)
	_last_time = last_time;
    else if ((bool) last_time_off)
	_last_time = last_time_off, _last_time_relative = true;
    else if ((bool) interval)
	_last_time = interval, _last_time_interval = true;
    else
	_have_last_time = false;

    if (stop && end_h)
	return errh->error("END_CALL and STOP are mutually exclusive");
    else if (end_h)
	_end_h = new HandlerCall(end_h);
    else if (stop)
	_end_h = new HandlerCall(name() + ".stop");
    else if (_have_last_time)
	_end_h = new HandlerCall(name() + ".active false");

    // default linktype
    if (!encap)
	_base_linktype = FAKE_DLT_NONE;
    else if ((_base_linktype = fake_pcap_parse_dlt(encap)) < 0
	     || (_base_linktype != FAKE_DLT_SUNATM
		 && _base_linktype != FAKE_DLT_C_HDLC
		 && _base_linktype != FAKE_DLT_EN10MB
		 && _base_linktype != FAKE_DLT_ATM_RFC1483
		 && _base_linktype != FAKE_DLT_PPP
		 && _base_linktype != FAKE_DLT_PPP_HDLC
		 && _base_linktype != FAKE_DLT_RAW))
	return errh->error("bad encapsulation type");

    // set other variables
    _have_any_times = false;
    _timing = timing;
    _force_ip = force_ip;
    _linktype = FAKE_DLT_NONE;
    _active = active;
    return 0;
}

int
FromDAGDump::initialize(ErrorHandler *errh)
{
    if (_ff.initialize(errh) < 0)
	return -1;

    // if forcing IP packets, check we're not running TIMING
    if (_force_ip && _timing)
	return errh->error("FORCE_IP and TIMING options are incompatible");

    // check handler call
    if (_end_h && _end_h->initialize_write(this, errh) < 0)
	return -1;

    // try reading a packet
    if (read_packet(errh))
	_time_offset = Timestamp::now() - _packet->timestamp_anno();

    if (output_is_push(0))
	ScheduleInfo::initialize_task(this, &_task, _active, errh);
    return 0;
}

void
FromDAGDump::cleanup(CleanupStage)
{
    _ff.cleanup();
    if (_packet)
	_packet->kill();
    _packet = 0;
}

void
FromDAGDump::set_active(bool active)
{
    if (_active != active) {
	_active = active;
	if (active && output_is_push(0) && !_task.scheduled())
	    _task.reschedule();
    }
}

static inline uint64_t
swapq(uint64_t q)
{
#if CLICK_BYTE_ORDER == CLICK_BIG_ENDIAN
    return ((q & 0xff00000000000000LL) >> 56)
	| ((q & 0x00ff000000000000LL) >> 40)
	| ((q & 0x0000ff0000000000LL) >> 24)
	| ((q & 0x000000ff00000000LL) >>  8)
	| ((q & 0x00000000ff000000LL) <<  8)
	| ((q & 0x0000000000ff0000LL) << 24)
	| ((q & 0x000000000000ff00LL) << 40)
	| ((q & 0x00000000000000ffLL) << 56);
#elif CLICK_BYTE_ORDER == CLICK_LITTLE_ENDIAN
    return q;
#else
#error "neither big nor little endian"
#endif
}

void
FromDAGDump::stamp_to_time(uint64_t stamp, Timestamp &tv) const
{
    uint32_t sec = (uint32_t) (stamp >> 32);
    // based on a code description in an Endace document
    stamp = (stamp & 0xFFFFFFFFULL) * 1000000000;
    stamp += (stamp & 0x80000000ULL) << 1; // rounding
    uint32_t nsec = (uint32_t) (stamp >> 32);
    if (nsec >= 1000000000) {
	nsec -= 1000000000;
	sec += 1;
    }
    tv = Timestamp::make_nsec(sec, nsec);
}

void
FromDAGDump::prepare_times(const Timestamp &tv)
{
    if (_first_time_relative)
	_first_time += tv;
    if (_last_time_relative)
	_last_time += tv;
    else if (_last_time_interval)
	_last_time += _first_time;
    _have_any_times = true;
}

bool
FromDAGDump::read_packet(ErrorHandler *errh)
{
    const DAGCell *cell;
    static DAGCell static_cell;
    Timestamp tv;
    Packet *p;
    bool more = true;
    _packet = 0;

  retry:
    // quit if we sampled or force_ip failed, but we are no longer active
    if (!more)
	return false;

    // we may need to read bits of the file
    cell = reinterpret_cast<const DAGCell *>(_ff.get_aligned(DAGCell::HEADER_SIZE, &static_cell, errh));
    if (!cell)
	return false;

    // check times
  check_times:
    stamp_to_time(swapq(cell->timestamp), tv);
    if (!_have_any_times)
	prepare_times(tv);
    if (_have_first_time) {
	if (tv < _first_time)
	    goto retry;
	else
	    _have_first_time = false;
    }
    if (_have_last_time && tv >= _last_time) {
	_have_last_time = false;
	(void) _end_h->call_write(errh);
	if (!_active)
	    more = false;
	// retry _last_time in case someone changed it
	goto check_times;
    }

    // checking sampling probability
    if (_sampling_prob < (1 << SAMPLING_SHIFT)
	&& (click_random() & ((1<<SAMPLING_SHIFT)-1)) >= _sampling_prob)
	goto retry;

    // determine read length and wire length
    uint32_t wire_length = 0;
    if (cell->type == DAGCell::TYPE_LEGACY || _base_linktype >= 0) {
      use_base_linktype:
	_linktype = _base_linktype;
	switch (_base_linktype) {

	  cell:
	  case FAKE_DLT_ATM_RFC1483:
	  case FAKE_DLT_PPP:
	  case FAKE_DLT_PPP_HDLC:
	    p = _ff.get_packet(DAGCell::CELL_SIZE - DAGCell::HEADER_SIZE, tv.sec(), tv.subsec(), errh);
	    break;

	  case FAKE_DLT_C_HDLC:
	    wire_length = htons(*(reinterpret_cast<const uint16_t*>(cell) + 5));
	    goto cell;

	  case FAKE_DLT_NONE:
	    _linktype = FAKE_DLT_ATM_RFC1483;
	    goto cell;

	  case FAKE_DLT_SUNATM:
	    p = _ff.get_packet_from_data(reinterpret_cast<const uint8_t*>(cell) + 12, 4, DAGCell::CELL_SIZE - 12, tv.sec(), tv.subsec(), errh);
	    break;

	  case FAKE_DLT_EN10MB:
	    wire_length = htons(*(reinterpret_cast<const uint16_t*>(cell) + 4));
	    p = _ff.get_packet_from_data(reinterpret_cast<const uint8_t*>(cell) + 10, 6, DAGCell::CELL_SIZE - 10, tv.sec(), tv.subsec(), errh);
	    break;

	  default:
	    p = _ff.get_packet_from_data(reinterpret_cast<const uint8_t*>(cell) + 8, 8, DAGCell::CELL_SIZE - 8, tv.sec(), tv.subsec(), errh);
	    break;
	}

    } else {
	int read_length = htons(cell->rlen);
	wire_length = htons(cell->wlen);
	switch (cell->type) {
	  case DAGCell::TYPE_ATM:
	  case DAGCell::TYPE_AAL5:
	    _linktype = FAKE_DLT_SUNATM;
	    break;
	  case DAGCell::TYPE_ETH:
	    _ff.shift_pos(2);
	    read_length -= 2;
	    wire_length -= 4;	// XXX DAG 'wlen' includes CRC
	    _linktype = FAKE_DLT_EN10MB;
	    break;
	  case DAGCell::TYPE_HDLC_POS:
	    _linktype = FAKE_DLT_C_HDLC;
	    break;
	  default:		// indicates an old-format dump
	    if (_base_linktype == FAKE_DLT_NONE)
		_base_linktype = FAKE_DLT_ATM_RFC1483;
	    if (errh) {
		errh->warning("odd DAG cell type %d, assuming old-style ATM encapsulation", cell->type);
		errh->message("(To avoid this warning, specify an explicit ENCAP.)");
	    } else
		click_chatter("%p{element}: DAG cell with odd type %d, assuming old-style\n  ATM encapsulation for rest of dump.  Packets may have been read incorrectly!\n  (To avoid this warning, specify an explicit ENCAP.)", this, cell->type);
	    goto use_base_linktype;
	}
	if (read_length < DAGCell::HEADER_SIZE)
	    return false;
	p = _ff.get_packet(read_length - DAGCell::HEADER_SIZE, tv.sec(), tv.subsec(), errh);
    }

    // check packet
    if (!p)
	return false;
    if (wire_length)
	SET_EXTRA_LENGTH_ANNO(p, wire_length - p->length());

    if (_force_ip && !fake_pcap_force_ip(p, _linktype)) {
	checked_output_push(1, p);
	goto retry;
    }

    _packet = p;
    return more;
}

bool
FromDAGDump::run_task(Task *)
{
    if (!_active)
	return false;

    bool more;
    if (_packet || read_packet(0)) {
	if (_timing
	    && _packet->timestamp_anno() > Timestamp::now() - _time_offset) {
	    _task.fast_reschedule();
	    return false;
	}
	output(0).push(_packet);
	more = read_packet(0);
    } else
	more = false;

    if (more)
	_task.fast_reschedule();
    else if (_end_h)
	_end_h->call_write(ErrorHandler::default_handler());
    return true;
}

Packet *
FromDAGDump::pull(int)
{
    if (!_active)
	return 0;

    bool more;
    Packet *p;
    if (_packet || read_packet(0)) {
	if (_timing
	    && _packet->timestamp_anno() > Timestamp::now() - _time_offset)
	    return 0;
	p = _packet;
	more = read_packet(0);
    } else {
	p = 0;
	more = false;
    }

    if (!more && _end_h)
	_end_h->call_write(ErrorHandler::default_handler());
    return p;
}

enum {
    H_SAMPLING_PROB, H_ACTIVE, H_ENCAP, H_STOP, H_EXTEND_INTERVAL
};

String
FromDAGDump::read_handler(Element *e, void *thunk)
{
    FromDAGDump *fd = static_cast<FromDAGDump *>(e);
    switch ((intptr_t)thunk) {
      case H_SAMPLING_PROB:
	return cp_unparse_real2(fd->_sampling_prob, SAMPLING_SHIFT);
      case H_ENCAP:
	return String(fake_pcap_unparse_dlt(fd->_linktype));
      default:
	return "<error>";
    }
}

int
FromDAGDump::write_handler(const String &s_in, Element *e, void *thunk, ErrorHandler *errh)
{
    FromDAGDump *fd = static_cast<FromDAGDump *>(e);
    String s = cp_uncomment(s_in);
    switch ((intptr_t)thunk) {
      case H_ACTIVE: {
	  bool active;
	  if (BoolArg().parse(s, active)) {
	      fd->set_active(active);
	      return 0;
	  } else
	      return errh->error("type mismatch");
      }
      case H_STOP:
	fd->set_active(false);
	fd->router()->please_stop_driver();
	return 0;
      case H_EXTEND_INTERVAL: {
	  Timestamp tv;
	  if (cp_time(s, &tv)) {
	      fd->_last_time += tv;
	      if (fd->_end_h)
		  fd->_have_last_time = true, fd->set_active(true);
	      return 0;
	  } else
	      return errh->error("'extend_interval' takes a time interval");
      }
      default:
	return -EINVAL;
    }
}

void
FromDAGDump::add_handlers()
{
    add_read_handler("sampling_prob", read_handler, H_SAMPLING_PROB);
    add_data_handlers("active", Handler::f_read | Handler::f_checkbox, &_active);
    add_write_handler("active", write_handler, H_ACTIVE);
    add_read_handler("encap", read_handler, H_ENCAP);
    add_write_handler("stop", write_handler, H_STOP);
    add_write_handler("extend_interval", write_handler, H_EXTEND_INTERVAL);
    _ff.add_handlers(this);
    if (output_is_push(0))
	add_task_handlers(&_task);
}

CLICK_ENDDECLS
ELEMENT_REQUIRES(userlevel int64 FakePcap)
EXPORT_ELEMENT(FromDAGDump)


text:
namespace Microsoft.Graph
{
    /// <summary>
    /// The type DriveItemDeltaCollectionPage.
    /// </summary>
    public partial class DriveItemDeltaCollectionPage : CollectionPage<DriveItem>, IDriveItemDeltaCollectionPage
    {
        /// <summary>
        /// Gets the next page <see cref="IDriveItemDeltaRequest"/> instance.
        /// </summary>
        public IDriveItemDeltaRequest NextPageRequest { get; private set; }

        /// <summary>
        /// Initializes the NextPageRequest property.
        /// </summary>
        public void InitializeNextPageRequest(IBaseClient client, string nextPageLinkString)
        {
            if (!string.IsNullOrEmpty(nextPageLinkString))
            {
                this.NextPageRequest = new DriveItemDeltaRequest(
                    nextPageLinkString,
                    client,
                    null);
            }
        }
    }
}


text:
package best.purchase.interfaces;

public interface OrderResponse {

    int getQuantity();

}


text:
<!doctype html>

    <base href="./" />
    <title>JSDoc: controller:MapController</title>
    <link type="text/css" rel="stylesheet" href="css/jsdoc-default.css" />
    <link href="css/prettify-tomorrow.css" type="text/css" rel="stylesheet" />

Index

service

Attr2Options

GeoCoder

NavigatorGeolocation

StreetView

directive

bicycling-layer

cloud-layer

custom-control

directions

drawing-manager

dynamic-maps-engine-layer

fusion-tables-layer

heatmap-layer

info-window

kml-layer

map-data

map-lazy-load

map-type

maps-engine-layer

marker

overlay-map-type

places-auto-complete

shape

streetview-panorama

traffic-layer

transit-layer

weather-layer

controller

MapController

module: ngMap

directive

ngMap.map

      controller:MapController
        source

Dependencies:

Name	Type	Description

                $scope

                  service

                $q

                  service

promise Q

                NavigatorGeolocation

                  service

                GeoCoder

                  service

                Attr2Options

                  service

convert html attribute to Gogole map api options

Properties:

Name	Type	Description

                controls

                  Hash

collection of Controls initiated within map directive

                markers

                  Hash

collection of Markers initiated within map directive

                shapes

                  Hash

collection of shapes initiated within map directive

Methods

                addObject(groupName, obj)

Add an object to the collection of group

Parameters:

Name	Type	Description

                    groupName

the name of collection that object belongs to

                    obj

an object to add into a collection, i.e. marker, shape

                addObjects(objects)

Add collected objects to map

Parameters:

Name	Type	Description

                    objects

                      Array

the collection of objects. i.e., map.markers

                deleteObject(objs, obj)

Delete an object from the collection and remove from map

Parameters:

Name	Type	Description

                    objs

                      Array

the collection of objects. i.e., map.markers

                    obj

                      Object

the object to be removed. i.e., marker

                getGeoLocation(string)

                    -> Promise

returns the location of an address or 'current-location'

Parameters:

Name	Type	Description

                    string

                      String

an address to find the location

Returns:

latlng the location of the address

                observeAttrSetObj(orgAttrs, attrs, obj)

watch changes of attribute values and do appropriate action based on attribute name

Parameters:

Name	Type	Description

                    orgAttrs

                      Hash

attributes before its initialization

                    attrs

                      Hash

attributes after its initialization

                    obj

                      Object

map object that an action is to be done

      Documentation generated by
      JSDoc 3.3.2
      using
      Angular-JSDoc template


text:
require 'bundler/setup'
require 'json'
require 'sinatra'
require 'sass'
require 'erb'
require 'sinatra/assetpack'
require 'tilt/erb'

class App < Sinatra::Application
	def initialize(app=nil)
		super(app)
	end

	register Sinatra::AssetPack
	assets do
		js :application, [
			'js/*.js'
		]

		css :application, [
			'css/*.css'
		]

		js_compression :jsmin
		css_compression :sass
	end

	# 404 Error!
	not_found do
		status 404
		erb :not_found, :layout => :layout
	end

	error do
		erb :error, :layout => :layout
	end

	get '/' do
		erb :index, :layout => :layout
	end
end