text:
require File.dirname(__FILE__) + '/../spec_helper'

def build_secondary_iucn_hierarchy_and_resource
  another_iucn_resource  = Resource.gen(:title  => 'Another IUCN')
  another_iucn_hierarchy = Hierarchy.gen(:label => 'Another IUCN')
  AgentsResource.gen(:agent => Agent.iucn, :resource => another_iucn_resource)
  return [another_iucn_hierarchy, another_iucn_resource]
end

describe TaxonConcept do

  # Why am I loading scenarios in a model spec?  ...Because TaxonConcept is unlike other models: there is
  # really nothing to it: just an ID and a wee bit of ancillary data. At the same time, TC is *so* vital to
  # everything we do, that I wanted to construct tests that really jog the model through all of its
  # relationships.
  #
  # If you want to think of this as more of a "black-box" test, that's fine.  I chose to put it in the
  # models directory because, well, it isn't testing a website, and it IS testing a *model*, so it seemed a
  # "better" fit here, even if it isn't perfect.

  before :all do
    Scenario.load :foundation
    @overview        = TocItem.overview
    @overview_text   = 'This is a test Overview, in all its glory'
    @toc_item_2      = TocItem.gen(:view_order => 2)
    @toc_item_3      = TocItem.gen(:view_order => 3)
    @canonical_form  = Factory.next(:species)
    @attribution     = Faker::Eol.attribution
    @common_name     = Faker::Eol.common_name.firstcap
    @scientific_name = "#{@canonical_form} #{@attribution}"
    @italicized      = "#{@canonical_form} #{@attribution}"
    @gbif_map_id     = '424242'
    @image_1         = Factory.next(:image)
    @image_2         = Factory.next(:image)
    @image_3         = Factory.next(:image)
    @image_unknown_trust = Factory.next(:image)
    @image_untrusted = Factory.next(:image)
    @video_1_text    = 'First Test Video'
    @video_2_text    = 'Second Test Video'
    @video_3_text    = 'YouTube Test Video'
    @comment_1       = 'This is totally awesome'
    @comment_bad     = 'This is totally inappropriate'
    @comment_2       = 'And I can comment multiple times'
    tc = build_taxon_concept(
      :rank            => 'species',
      :canonical_form  => @canonical_form,
      :attribution     => @attribution,
      :scientific_name => @scientific_name,
      :italicized      => @italicized,
      :gbif_map_id     => @gbif_map_id,
      :flash           => [{:description => @video_1_text}, {:description => @video_2_text}],
      :youtube         => [{:description => @video_3_text}],
      :comments        => [{:body => @comment_1}, {:body => @comment_bad}, {:body => @comment_2}],
      :images          => [{:object_cache_url => @image_1, :data_rating => 2},
                           {:object_cache_url => @image_2, :data_rating => 3},
                           {:object_cache_url => @image_untrusted, :vetted => Vetted.untrusted},
                           {:object_cache_url => @image_3, :data_rating => 4},
                           {:object_cache_url => @image_unknown_trust, :vetted => Vetted.unknown}],
      :toc             => [{:toc_item => @overview, :description => @overview_text},
                           {:toc_item => @toc_item_2}, {:toc_item => @toc_item_3}]
    )
    @id            = tc.id
    @taxon_concept = TaxonConcept.find(@id)
    # The curator factory cleverly hides a lot of stuff that User.gen can't handle:
    @curator       = build_curator(@taxon_concept)
    # TODO - I am slowly trying to convert all of the above options to methods to make testing clearer:
    (@common_name_obj, @synonym_for_common_name, @tcn_for_common_name) =
      tc.add_common_name_synonym(@common_name, @curator.agent, :language => Language.english)
    # Curators aren't recognized until they actually DO something, which is here:
    LastCuratedDate.gen(:user => @curator, :taxon_concept => @taxon_concept)
    # And we want one comment that the world cannot see:
    Comment.find_by_body(@comment_bad).hide! User.last
    @user = User.gen
  end
  after :all do
    truncate_all_tables
  end

  it 'should capitalize the title (even if the name starts with a quote)' do
    good_title = %Q{"Good title"}
    bad_title = good_title.downcase
    tc = build_taxon_concept(:canonical_form => bad_title)
    tc.title.should =~ /#{good_title}/
  end

  it 'should have curators' do
    @taxon_concept.curators.map(&:id).should include(@curator.id)
  end

  it 'should have a scientific name (italicized for species)' do
    @taxon_concept.scientific_name.should == @italicized
  end

  it 'should have a common name' do
    @taxon_concept.common_name.should == @common_name
  end

  it 'should show the common name from the current users language' do
    lang = Language.gen(:label => 'Ancient Egyptian')
    user = User.gen(:language => lang)
    str  = 'Frebblebup'
    @taxon_concept.add_common_name_synonym(str, user.agent, :language => lang)
    @taxon_concept.current_user = user
    @taxon_concept.common_name.should == str
  end

  it 'should let you get/set the current user' do
    user = User.gen
    @taxon_concept.current_user = user
    @taxon_concept.current_user.should == user
  end

  it 'should have a default IUCN conservation status of NOT EVALUATED' do
    @taxon_concept.iucn_conservation_status.should == 'NOT EVALUATED'
  end

  it 'should have an IUCN conservation status' do
    tc = build_taxon_concept()
    iucn_status = Factory.next(:iucn)
    build_iucn_entry(tc, iucn_status)
    tc.iucn_conservation_status.should == iucn_status
  end

  it 'should have an IUCN conservation status even if it comes from another IUCN resource' do
    tc = build_taxon_concept()
    iucn_status = Factory.next(:iucn)
    (hierarchy, resource) = build_secondary_iucn_hierarchy_and_resource
    build_iucn_entry(tc, iucn_status, :hierarchy => hierarchy,
                                                  :event => HarvestEvent.gen(:resource => resource))
    tc.iucn_conservation_status.should == iucn_status
  end

  it 'should have only one IUCN conservation status when there could have been many (doesnt matter which)' do
    build_iucn_entry(@taxon_concept, Factory.next(:iucn))
    build_iucn_entry(@taxon_concept, Factory.next(:iucn))
    result = @taxon_concept.iucn
    result.should be_an_instance_of DataObject # (not an Array, mind you.)
  end

  it 'should not use an unpublished IUCN status' do
    tc = build_taxon_concept()
    bad_iucn = build_iucn_entry(tc, 'bad value')
    tc.iucn_conservation_status.should == 'bad value'

    # We *must* know that it would have worked if it *were* published, otherwise the test proves nothing:
    tc2 = build_taxon_concept()
    bad_iucn2 = build_iucn_entry(tc2, 'bad value')
    bad_iucn2.published = 0
    bad_iucn2.save
    tc2.iucn_conservation_status.should == 'NOT EVALUATED'
  end

  it 'should be able to list its ancestors (by convention, ending with itself)' do
    @kingdom = build_taxon_concept(:rank => 'kingdom', :depth => 0)
    @phylum  = build_taxon_concept(:rank => 'phylum',  :depth => 1, :parent_hierarchy_entry_id => @kingdom.entry.id)
    @order   = build_taxon_concept(:rank => 'order',   :depth => 2, :parent_hierarchy_entry_id => @phylum.entry.id)
    # Now we attach our TC to those:
    he = @taxon_concept.entry
    he.parent_id = @order.entry.id
    he.save
    @taxon_concept.ancestors.map(&:id).should == [@kingdom.id, @phylum.id, @order.id, @taxon_concept.id]
  end

  it 'should be able to list its children (NOT descendants, JUST children--animalia would be a disaster!)' do
    @subspecies1  = build_taxon_concept(:rank => 'subspecies', :depth => 4,
                                        :parent_hierarchy_entry_id => @taxon_concept.entry.id)
    @subspecies2  = build_taxon_concept(:rank => 'subspecies', :depth => 4,
                                        :parent_hierarchy_entry_id => @taxon_concept.entry.id)
    @subspecies3  = build_taxon_concept(:rank => 'subspecies', :depth => 4,
                                        :parent_hierarchy_entry_id => @taxon_concept.entry.id)
    @infraspecies = build_taxon_concept(:rank => 'infraspecies', :depth => 4,
                                        :parent_hierarchy_entry_id => @subspecies1.entry.id)
    @taxon_concept.children.map(&:id).should only_include @subspecies1.id, @subspecies2.id, @subspecies3.id
  end

  it 'should find its GBIF map ID' do
    @taxon_concept.gbif_map_id.should == @gbif_map_id
  end

  it 'should be able to show videos' do
    @taxon_concept.videos.should_not be_nil
    @taxon_concept.videos.map(&:description).should only_include @video_1_text, @video_2_text, @video_3_text
  end

  it 'should have visible comments that don\'t show invisible comments' do
    user = User.gen
    @taxon_concept.visible_comments.should_not be_nil
    @taxon_concept.visible_comments.map(&:body).should == [@comment_1, @comment_2] # Order DOES matter, now.
  end

  it 'should be able to show a table of contents' do
    # Tricky, tricky. See, we add special things to the TOC like "Common Names" and "Search the Web", when they are appropriate.  I
    # could test for those here, but that seems the perview of TocItem.  So, I'm only checking the first three elements:
    @taxon_concept.toc[0..2].should == [@overview, @toc_item_2, @toc_item_3]
  end

  # TODO - this is failing, but low-priority, I added a bug for it: EOLINFRASTRUCTURE-657
  # This was related to a bug (EOLINFRASTRUCTURE-598)
  #it 'should return the table of contents with unpublished items when a content partner is specified' do
    #cp   = ContentPartner.gen
    #toci = TocItem.gen
    #dato = build_data_object('Text', 'This is our target text',
                             #:hierarchy_entry => @taxon_concept.hierarchy_entries.first, :content_partner => cp,
                             #:published => false, :vetted => Vetted.unknown, :toc_item => toci)
    #@taxon_concept.toc.map(&:id).should_not include(toci.id)
    #@taxon_concept.current_agent = cp.agent
    #@taxon_concept.toc.map(&:id).should include(toci.id)
  #end

  it 'should show its untrusted images, by default' do
    @taxon_concept.current_user = User.create_new # It's okay if this one "sticks", so no cleanup code
    @taxon_concept.images.map(&:object_cache_url).should include(@image_unknown_trust)
  end

  it 'should show only trusted images if the user prefers' do
    old_user = @taxon_concept.current_user
    @taxon_concept.current_user = User.gen(:vetted => true)
    @taxon_concept.images.map(&:object_cache_url).should only_include(@image_1, @image_2, @image_3)
    @taxon_concept.current_user = old_user  # Cleaning up so as not to affect other tests
  end

  it 'should be able to get an overview' do
    results = @taxon_concept.overview
    results.length.should == 1
    results.first.description.should == @overview_text
  end

  # TODO - creating the CP -> Dato relationship is tricky. This should be made available elsewhere:
  it 'should show content partners THEIR preview items, but not OTHER content partner\'s preview items' do

    original_cp    = Agent.gen
    another_cp     = Agent.gen
    resource       = Resource.gen
    # Note this doesn't work without the ResourceAgentRole setting.  :\
    agent_resource = AgentsResource.gen(:agent_id => original_cp.id, :resource_id => resource.id,
                       :resource_agent_role_id => ResourceAgentRole.content_partner_upload_role.id)
    event          = HarvestEvent.gen(:resource => resource)
    # Note this *totally* doesn't work if you don't add it to top_unpublished_images!
    TopUnpublishedImage.gen(:hierarchy_entry => @taxon_concept.entry,
                            :data_object     => @taxon_concept.images.last)
    TopUnpublishedConceptImage.gen(:taxon_concept => @taxon_concept,
                            :data_object     => @taxon_concept.images.last)
    how_many = @taxon_concept.images.length
    how_many.should > 2
    dato            = @taxon_concept.images.last  # Let's grab the last one...
    # ... And remove it from top images:
    TopImage.delete_all(:hierarchy_entry_id => @taxon_concept.entry.id,
                        :data_object_id => @taxon_concept.images.last.id)
    TopConceptImage.delete_all(:taxon_concept_id => @taxon_concept.id,
                        :data_object_id => @taxon_concept.images.last.id)

    Rails.cache.delete("data_object/cached_images_for/#{@taxon_concept.id}")  # deleting the concept image cache
    @taxon_concept.current_user = @taxon_concept.current_user #hack to expire cached images
    @taxon_concept.images.length.should == how_many - 1 # Ensuring that we removed it...

    dato.visibility = Visibility.preview
    dato.save!

    DataObjectsHarvestEvent.delete_all(:data_object_id => dato.id)
    dohe           = DataObjectsHarvestEvent.gen(:harvest_event => event, :data_object => dato)

    # puts 'okok'
    # pp @taxon_concept.top_concept_images
    # pp @taxon_concept.top_unpublished_concept_images
    # pp @taxon_concept.entry.top_unpublished_images
    # Original should see it:
    @taxon_concept.current_agent = original_cp
    # pp @taxon_concept.images
    @taxon_concept.images.map {|i| i.id }.should include(dato.id)

    # Another CP should not:
    tc = TaxonConcept.find(@taxon_concept.id) # hack to reload the object and delete instance variables
    tc.current_agent = another_cp
    tc.images.map {|i| i.id }.should_not include(dato.id)

  end

  it "should have common names" do
    TaxonConcept.common_names_for?(@taxon_concept.id).should == true
  end

  it "should not have common names" do
    tc = build_taxon_concept(:toc=> [
      {:toc_item => TocItem.common_names}
    ])
    TaxonConcept.common_names_for?(tc.id).should == false
  end

  it 'should return images sorted by trusted, unknown, untrusted' do
    @taxon_concept.current_user = @user
    trusted   = Vetted.trusted.id
    unknown   = Vetted.unknown.id
    untrusted = Vetted.untrusted.id
    @taxon_concept.images.map {|i| i.vetted_id }.should == [trusted, trusted, trusted, unknown, untrusted]
  end

  it 'should sort the vetted images by data rating' do
    @taxon_concept.current_user = @user
    @taxon_concept.images[0..2].map(&:object_cache_url).should == [@image_3, @image_2, @image_1]
  end

  it 'should create a common name as a preferred common name, if there are no other common names for the taxon' do
    tc = build_taxon_concept(:common_names => [])
    agent = Agent.last # TODO - I don't like this.  We shouldn't need it for tests.  Overload the method for testing?
    tc.add_common_name_synonym('A name', agent, :language => Language.english)
    tc.quick_common_name.should == "A name"
    tc.add_common_name_synonym("Another name", agent, :language => Language.english)
    tc.quick_common_name.should == "A name"
  end

  it 'should determine and cache curation authorization' do
    @curator.can_curate?(@taxon_concept).should == true
    @curator.should_receive('can_curate?').and_return(true)
    @taxon_concept.show_curator_controls?(@curator).should == true
    @curator.should_not_receive('can_curate?')
    @taxon_concept.show_curator_controls?(@curator).should == true
  end

  it 'should return a toc item which accepts user submitted text' do
    @taxon_concept.tocitem_for_new_text.class.should == TocItem
    tc = build_taxon_concept(:images => [], :toc => [], :flash => [], :youtube => [], :comments => [], :bhl => [])
    tc.tocitem_for_new_text.class.should == TocItem
  end

  it 'should return description as first toc item which accepts user submitted text' do
    description_toc = TocItem.find_by_label('Description')
    InfoItem.gen(:toc_id => @overview.id)
    InfoItem.gen(:toc_id => description_toc.id)
    tc = build_taxon_concept(:images => [], :flash => [], :youtube => [], :comments => [], :bhl => [],
                             :toc => [{:toc_item => description_toc, :description => 'huh?'}])
    tc.tocitem_for_new_text.label.should == description_toc.label
  end

  it 'should include the LigerCat TocItem when the TaxonConcept has one'

  it 'should NOT include the LigerCat TocItem when the TaxonConcept does NOT have one'

  it 'should have a canonical form' do
    @taxon_concept.canonical_form.should == @canonical_form
  end

  it 'should cite a vetted source for the page when there are both vetted and unvetted sources' do
    h_vetted = Hierarchy.gen()
    h_unvetted = Hierarchy.gen()
    concept = TaxonConcept.gen(:published => 1, :vetted => Vetted.trusted)
    concept.entry.should be_nil

    # adding an unvetted name and testing
    unvetted_name = Name.gen(:canonical_form => cf = CanonicalForm.gen(:string => 'Annnvettedname'),
                      :string => 'Annnvettedname',
                      :italicized => 'Annnvettedname')
    he_unvetted = build_hierarchy_entry(0, concept, unvetted_name,
                                :hierarchy => h_unvetted,
                                :vetted_id => Vetted.unknown.id,
                                :published => 1)
    concept = TaxonConcept.find(concept.id) # cheating so I can flush all the instance variables
    concept.entry.should_not be_nil
    concept.entry.id.should == he_unvetted.id
    concept.name.should == unvetted_name.italicized

    # adding a vetted name and testing
    vetted_name = Name.gen(:canonical_form => cf = CanonicalForm.gen(:string => 'Avettedname'),
                      :string => 'Avettedname',
                      :italicized => 'Avettedname')
    he_vetted = build_hierarchy_entry(0, concept, vetted_name,
                                :hierarchy => h_vetted,
                                :vetted_id => Vetted.trusted.id,
                                :published => 1)
    concept = TaxonConcept.find(concept.id) # cheating so I can flush all the instance variables
    concept.entry.id.should == he_vetted.id
    concept.name.should == vetted_name.italicized

    # adding another unvetted name to test the vetted name remains
    another_unvetted_name = Name.gen(:canonical_form => cf = CanonicalForm.gen(:string => 'Anotherunvettedname'),
                      :string => 'Anotherunvettedname',
                      :italicized => 'Anotherunvettedname')
    he_anotherunvetted = build_hierarchy_entry(0, concept, another_unvetted_name,
                                :hierarchy => h_vetted,
                                :vetted_id => Vetted.unknown.id,
                                :published => 1)
    concept = TaxonConcept.find(concept.id) # cheating so I can flush all the instance variables
    concept.entry.id.should == he_vetted.id
    concept.name.should == vetted_name.italicized

    # now remove the vetted hierarchy entry and make sure the first entry is the chosen one
    he_vetted.destroy
    concept = TaxonConcept.find(concept.id) # cheating so I can flush all the instance variables
    concept.entry.id.should == he_unvetted.id
    concept.name.should == unvetted_name.italicized
  end

  # TODO - this is failing, but low-priority, I added a bug for it: EOLINFRASTRUCTURE-657
  # This was related to a bug (EOLINFRASTRUCTURE-598)
  #it 'should return the table of contents with unpublished items when a content partner is specified' do
    #cp   = ContentPartner.gen
    #toci = TocItem.gen
    #dato = build_data_object('Text', 'This is our target text',
                             #:hierarchy_entry => @taxon_concept.hierarchy_entries.first, :content_partner => cp,
                             #:published => false, :vetted => Vetted.unknown, :toc_item => toci)
    #@taxon_concept.toc.map(&:id).should_not include(toci.id)
    #@taxon_concept.current_agent = cp.agent
    #@taxon_concept.toc.map(&:id).should include(toci.id)
  #end

  describe "#add_common_name" do
    before(:all) do
      @tcn_count = TaxonConceptName.count
      @syn_count = Synonym.count
      @name_count = Name.count
      @name_string = "Piping plover"
      @agent = Agent.find(@curator.agent_id)
      @language = Language.english
      @synonym = @taxon_concept.add_common_name_synonym(@name_string, @agent, :language => @language)
      @name = @synonym.name
      @tcn = @synonym.taxon_concept_name
    end

    it "should increase name count, taxon name count, synonym count" do
      TaxonConceptName.count.should == @tcn_count + 1
      Synonym.count.should == @syn_count + 1
      Name.count.should == @name_count + 1
    end

    it "should mark first created name for a language as preferred automatically" do
      language = Language.gen(:label => "Russian")
      s= @taxon_concept.add_common_name_synonym("Саблезубая сосиска", @agent, :language => language)
      TaxonConceptName.find_all_by_taxon_concept_id_and_language_id(@taxon_concept, language).size.should == 1
      TaxonConceptName.find_by_synonym_id(s.id).preferred?.should be_true
      s = @taxon_concept.add_common_name_synonym("Голый землекоп", @agent, :language => language)
      TaxonConceptName.find_all_by_taxon_concept_id_and_language_id(@taxon_concept, language).size.should == 2
      TaxonConceptName.find_by_synonym_id(s.id).preferred?.should be_false
    end

    it "should not mark first created name as preffered for unknown language" do
      language = Language.unknown
      s = @taxon_concept.add_common_name_synonym("Саблезубая сосиска", @agent, :language => language)
      TaxonConceptName.find_all_by_taxon_concept_id_and_language_id(@taxon_concept, language).size.should == 1
      TaxonConceptName.find_by_synonym_id(s.id).preferred?.should be_false
    end

    it "should create new name object" do
      @name.class.should == Name
      @name.string.should == @name_string
    end

    it "should create synonym" do
      @synonym.class.should == Synonym
      @synonym.name.should == @name
      @synonym.agents.should == [@curator.agent]
    end

    it "should create taxon_concept_name" do
      @tcn.should_not be_nil
    end

    it "should be able to create a common name with the same name string but different language" do
      @taxon_concept.add_common_name_synonym(@name_string, Agent.find(@curator.agent_id), :language => Language.find_by_label("French"))
      TaxonConceptName.count.should == @tcn_count + 2
      Synonym.count.should == @syn_count + 2
      Name.count.should == @name_count + 1
    end
  end

  describe "#delete_common_name" do
    before(:all) do
      @synonym = @taxon_concept.add_common_name_synonym("Piping plover", Agent.find(@curator.agent_id), :language => Language.english)
      @tc_name = @synonym.taxon_concept_name
      @tcn_count = TaxonConceptName.count
      @syn_count = Synonym.count
      @name_count = Name.count
    end

    it "should delete a common name" do
      @taxon_concept.delete_common_name(@tc_name)
      TaxonConceptName.count.should == @tcn_count - 1
      Synonym.count.should == @syn_count - 1
      Name.count.should == @name_count #name is not deleted
    end

    it "should delete preffered common names, should mark last common name for a language as preferred" do
      pref_en_name = TaxonConceptName.find_by_taxon_concept_id_and_language_id_and_preferred(@taxon_concept, Language.english, true)
      all_en_names = TaxonConceptName.find_all_by_taxon_concept_id_and_language_id(@taxon_concept, Language.english)
      all_en_names.size.should == 2
      @tc_name.preferred?.should be_false
      @taxon_concept.delete_common_name(pref_en_name) #it should work now because it is the only name left
      TaxonConceptName.count.should == @tcn_count - 1
      Synonym.count.should == @syn_count - 1
      Name.count.should == @name_count
      TaxonConceptName.find_by_synonym_id(@tc_name.synonym.id).preferred?.should be_true
      @taxon_concept.delete_common_name(@tc_name)
      TaxonConceptName.count.should == @tcn_count - 2
      Synonym.count.should == @syn_count - 2
      Name.count.should == @name_count
    end

  end

  #
  # I'm all for pending tests, but in this case, they run SLOWLY, so it's best to comment them out:
  #

  # Medium Priority:
  #
  # it 'should be able to list whom the species is recognized by' do
  # it 'should be able to add a comment' do
  # it 'should be able to list exemplars' do
  #
  # Lower priority (at least for me!)
  #
  # it 'should know which hosts to ping' do
  # it 'should be able to set a current agent' # This is only worthwhile if we know what it should change... do
  # it 'should follow supercedure' do
  # it 'should be able to show a thumbnail' do
  # it 'should be able to show a single image' do

end


text:
<?php declare(strict_types = 1);

declare(strict_types=1);

namespace DrdPlus\Tests\Properties;

use Granam\Tests\ExceptionsHierarchy\Exceptions\AbstractExceptionsHierarchyTest;

class PropertiesExceptionsHierarchyTest extends AbstractExceptionsHierarchyTest
{
    protected function getTestedNamespace(): string
    {
        return $this->getRootNamespace();
    }

    protected function getRootNamespace(): string
    {
        return str_replace('\Tests', '', __NAMESPACE__);
    }

}

redpajama_set_name: RedPajamaGithub


text:
START_ATF_NAMESPACE
    typedef unsigned __int16 PROPVAR_PAD2;
END_ATF_NAMESPACE


text:
<?php

require_once dirname(__FILE__).'/../lib/Basesympal_defaultComponents.class.php';

class sympal_defaultComponents extends Basesympal_defaultComponents
{
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>de.huxhorn.sulky</groupId>
	<artifactId>de.huxhorn.sulky.conditions</artifactId>
	<version><!-- SV -->0.9.14-SNAPSHOT</version>
	<packaging>jar</packaging>
	<name>Sulky Conditions</name>
	<description>This file is part of the sulky modules. It contains the definition of conditions and the implementation of some purpose conditions.</description>
	<url>http://sulky.huxhorn.de/projects/${project.artifactId}/</url>

	<parent>
		<groupId>de.huxhorn.sulky</groupId>
		<artifactId>de.huxhorn.sulky.parent</artifactId>
		<version><!-- SV -->0.9.14-SNAPSHOT</version>
		<relativePath>../sulky-parent/pom.xml</relativePath>
	</parent>

	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>
</project>


text:
'use strict';

/* Invoice Controllers */

angular.module('cartApp.checkout.controllers', []).
	controller('CheckoutController',
	['$scope', '$state', '$rootScope', 'servQuantity', 'formData', '$locale',
		function ($scope, $state, $rootScope, servQuantity, formData, $locale) {
			$scope.date = new Date();
			$rootScope.billSameAsShip = true;

			if($rootScope.billSameAsShip){
				$scope.billingAddress = true;
			}

			$scope.toggleBillAddressView = function(){
				//console.log('$rootScope.billSameAsShip: '+$rootScope.billSameAsShip);
				if($rootScope.billSameAsShip){
					$rootScope.bool = true;
					$scope.billingAddress = true;
				} else {
					$scope.billingAddress = false;
					$rootScope.bool = false;
				}
			}

			$scope.subtotal = $rootScope.grandTotal;

			if($scope.subtotal < 1000){
				$scope.shippingcost = 60;
			} else {
				$scope.shippingcost = 0;
			}

			$scope.ordertotal = $scope.subtotal + $scope.shippingcost;

			$scope.couponCode = function(){
				if($scope.coupon.toUpperCase() == 'FIRSTBUY'){
					$scope.discountedPrice = false;
					$scope.strikePrice = true;
					$scope.discountPrice = $scope.ordertotal - (($scope.ordertotal*25)/100);
				} else if($scope.coupon.toUpperCase() == 'SECONDBUY'){
					$scope.discountedPrice = false;
					$scope.strikePrice = true;
					$scope.discountPrice = $scope.ordertotal - (($scope.ordertotal*15)/100);
				} else {
					$scope.discountedPrice = true;
					$scope.strikePrice = false;
				}
			}

			$scope.gotoInvoice = function(){
				//console.log('discountPrice: '+$scope.discountPrice + ' ::ordertotal: '+$scope.ordertotal);
				$scope.shipAddressData = {
					'country': $scope.shipCountry,
					'fullName': $scope.shipFullName,
					'address': $scope.shipAddress,
					'city': $scope.shipCity,
					'state': $scope.shipState,
					'zip': $scope.shipPostal,
					'phone': $scope.shipPhone,
					'email': $scope.shipEmail
				}
				$scope.billAddressData = {
					'country': $scope.billCountry,
					'fullName': $scope.billFullName,
					'address': $scope.billAddress,
					'city': $scope.billCity,
					'state': $scope.billState,
					'zip': $scope.billPostal,
					'phone': $scope.billPhone,
					'email': $scope.billEmail
				}

				formData.setAddress($scope.shipAddressData);
				formData.setBillingAddress($scope.billAddressData);

				/*if(!$rootScope.billSameAsShip){
					formData.setBillingAddress($scope.billAddressData);
				} */

				if($scope.discountPrice == undefined){
					$rootScope.finalPrice = $scope.ordertotal;
				} else {
					$rootScope.finalPrice = $scope.discountPrice;
				}
				//$state.go('invoice');
			}

			// CC validation
			$scope.currentYear = new Date().getFullYear();
			$scope.currentMonth = new Date().getMonth() + 1;
			$scope.months = $locale.DATETIME_FORMATS.MONTH;
			$scope.ccinfo = {type:undefined};
			$scope.save = function(data){
				if ($scope.paymentType == 'card' && $scope.paymentForm.$valid){
					console.log('data: '+data) // valid data saving stuff here
					$state.go('invoice');
				} else if($scope.paymentType == 'cash' && $scope.paymentForm.$valid){
					$state.go('invoice');
				}
			}

		}
	]);


text:
import mm = require('mm');
import {expect} from 'chai';
import {Hub} from '../../src/hub/Hub';
import {HubClient} from '../../src/hub/HubClient';
import {EventEmitter} from 'events';
import {PANDORA_HUB_ACTION_MSG_DOWN, PANDORA_HUB_ACTION_MSG_UP} from '../../src/const';

describe('HubClient', () => {

  describe('start and stop', () => {

    let hub: Hub;
    before(async () => {
      hub = new Hub();
      await hub.start();
    });

    after(async () => {
      await hub.stop();
    });

    it('should start() and stop() be ok', async () => {
      const client = new HubClient({
        location: {
          appName: 'testApp'
        }
      });
      await client.start();
      await client.stop();
    });

    it('should throw an error when start twice and stop twice', async () => {
      const client = new HubClient({
        location: {
          appName: 'testApp'
        }
      });
      await client.start();
      await expect(client.start()).to.be.rejectedWith('HubClient already started');
      await client.stop();
      await expect(client.stop()).to.be.rejectedWith('HubClient has not started yet');
    });

  });

  describe('dispatch', () => {

    it('should pushDispatchHandler and handleHubDispatch be ok', async () => {

      const client = new HubClient({
        location: {
          appName: 'testApp'
        }
      });

      client.pushDispatchHandler({
        dispatch(message) {
          if(message.action === 'custom') {
            return {
              test: true
            };
          }
        }
      });

      // case 1 : hit dispatchHandler
      let gotEvent1 = false;
      client.once('custom', () => {
        gotEvent1 = true;

      });
      const res1 = await client.handleHubDispatch({
        action: 'custom'
      });
      await new Promise(resolve => setTimeout(resolve, 100));
      expect(res1.test).to.be.true;
      expect(gotEvent1).to.be.false;

      // case 2 : emit event if not hit dispatchHandler
      let gotEvent2 = false;
      client.once('lala', () => {
        gotEvent2 = true;

      });
      await client.handleHubDispatch({
        action: 'lala'
      });
      await new Promise(resolve => setTimeout(resolve, 100));
      expect(gotEvent2).to.be.true;

    });

    it('should handing PANDORA_HUB_ACTION_ONLINE_UP be ok', async () => {

      const fakeClient = {
        logger: console,
        messengerClient: new EventEmitter,
        startListen: HubClient.prototype.startListen,
        handleHubDispatch: function () {
          return {test: true};
        }
      };

      fakeClient.startListen();
      const res = await <Promise<any>> new Promise((resolve, reject) => {
        fakeClient.messengerClient.emit(PANDORA_HUB_ACTION_MSG_DOWN, {needReply: true}, (resp) => {
          if(!resp.success) {
            return reject(resp.error);
          }
          resolve(resp.data);
        });
      });

      expect(res.test).to.be.true;

    });

    it('should handing PANDORA_HUB_ACTION_ONLINE_UP without reply be ok', async () => {

      let called = false;
      const fakeClient = {
        logger: console,
        messengerClient: new EventEmitter,
        startListen: HubClient.prototype.startListen,
        handleHubDispatch: function () {
          called = true;
          return {test: true};
        }
      };

      fakeClient.startListen();
      fakeClient.messengerClient.emit(PANDORA_HUB_ACTION_MSG_DOWN, {needReply: false}, null);
      expect(called).to.be.true;
    });

    it('should get an error when handing PANDORA_HUB_ACTION_ONLINE_UP got an error from dispatchHandler', async () => {

      const fakeClient = {
        logger: console,
        messengerClient: new EventEmitter,
        startListen: HubClient.prototype.startListen,
        handleHubDispatch: function () {
          throw new Error('fake error');
        }
      };

      fakeClient.startListen();
      expect(new Promise((resolve, reject) => {
        fakeClient.messengerClient.emit(PANDORA_HUB_ACTION_MSG_DOWN, {needReply: true}, (resp) => {
          if(!resp.success) {
            return reject(resp.error);
          }
          resolve(resp.data);
        });
      })).to.be.rejectedWith('fake error');

    });

    it('should log error when handing PANDORA_HUB_ACTION_ONLINE_UP got an error from unknown place', async () => {

      const errorLogs = [];
      const fakeClient = {
        logger: {
          error: function (msg) {
            errorLogs.push(msg);
          }
        },
        messengerClient: new EventEmitter,
        startListen: HubClient.prototype.startListen,
        handleHubDispatch: function () {
          return {test: true};
        }
      };

      fakeClient.startListen();
      await new Promise((resolve) => {
        fakeClient.messengerClient.emit(PANDORA_HUB_ACTION_MSG_DOWN, {needReply: true}, () => {
          resolve();
          throw new Error('fake error');
        });
      });

      expect(errorLogs.length).to.equal(2);
      expect(errorLogs[0].toString()).to.includes('fake error');
      expect(errorLogs[1]).to.includes('Handing PANDORA_HUB_ACTION_MSG_DOWN went wrong');

    });

  });

  describe('publish and unpulibsh', () => {

    const hubClient: HubClient = new HubClient({
      location: {
        appName: 'fake'
      }
    });

    it('should publish be ok', async () => {
      let calledSendPublishToHub = false;
      mm(hubClient, 'sendPublishToHub', () => {
        calledSendPublishToHub = true;
      });
      await hubClient.publish({
        appName: 'fake',
        objectName: 'theName'
      });
      expect(calledSendPublishToHub).to.be.true;
      expect((<any> hubClient).publishedSelectors.length).to.equal(1);
      mm.restore();
    });

    it('should get an error when publish same one again', async () => {
      await expect(hubClient.publish({
        appName: 'fake',
        objectName: 'theName'
      })).to.be.rejectedWith('already exist');
    });

    it('should unpublish be ok', async () => {
      let calledSendToHubAndWaitReply = false;
      mm(hubClient, 'sendPublishToHub', () => {
      });
      mm(hubClient, 'sendToHubAndWaitReply', () => {
        calledSendToHubAndWaitReply = true;
        return {
          success: true
        };
      });
      await hubClient.publish({
        appName: 'fake',
        objectName: 'theName2'
      });
      await hubClient.unpublish({
        appName: 'fake',
        objectName: 'theName'
      });
      expect(calledSendToHubAndWaitReply).to.be.true;
      expect((<any> hubClient).publishedSelectors.length).to.equal(1);
      await hubClient.unpublish({
        appName: 'fake',
        objectName: 'theName2'
      });
      expect((<any> hubClient).publishedSelectors.length).to.equal(0);
      mm.restore();
    });

    it('should get an error when unpublish() got an error from Hub', async () => {

      mm(hubClient, 'sendPublishToHub', () => {
      });
      mm(hubClient, 'sendToHubAndWaitReply', () => {
        return {
          success: false,
          error: new Error('fake error')
        };
      });

      await hubClient.publish({
        appName: 'fake',
        objectName: 'theName'
      });
      await expect(hubClient.unpublish({
        appName: 'fake',
        objectName: 'theName'
      })).to.be.rejectedWith('fake error');

      mm.restore();

    });

    it('should get an error when sendPublishToHub() got an error from Hub', async () => {

      const fakeHubClient = {
        sendPublishToHub: (<any> HubClient.prototype).sendPublishToHub,
        sendToHubAndWaitReply: function () {
          return {
            success: false,
            error: new Error('fake error')
          };
        }
      };
      await expect(fakeHubClient.sendPublishToHub({
        appName: 'fakeApp'
      })).to.be.rejectedWith('fake error');

    });

  });

  describe('send and multipleSend', () => {

    it('should send() be ok', async () => {

      let msg = null;
      let action = null;
      const fakeHubClient = {
        send: HubClient.prototype.send,
        sendToHub: function (ownAction, ownMsg) {
          msg = ownMsg;
          action = ownAction;
        }
      };

      fakeHubClient.send({objectName: 'nope'}, 'anAction', {
        test: true
      });

      expect(action).to.equal(PANDORA_HUB_ACTION_MSG_UP);
      expect(msg.broadcast).to.be.false;
      expect(msg.remote).to.deep.equal({
        objectName: 'nope'
      });

    });

    it('should multipleSend() be ok', async () => {

      let msg = null;
      let action = null;
      const fakeHubClient = {
        multipleSend: HubClient.prototype.multipleSend,
        sendToHub: function (ownAction, ownMsg) {
          msg = ownMsg;
          action = ownAction;
        }
      };

      fakeHubClient.multipleSend({objectName: 'nope'}, 'anAction', {
        test: true
      });

      expect(action).to.equal(PANDORA_HUB_ACTION_MSG_UP);
      expect(msg.broadcast).to.be.true;
      expect(msg.remote).to.deep.equal({
        objectName: 'nope'
      });

    });

    it('should sendToHub() be ok', async () => {

      let msg = null;
      let action = null;
      const fakeHubClient = {
        location: { appName: 'fake' },
        messengerClient: {
          send: function (ownAction, ownMsg) {
            action = ownAction;
            msg = ownMsg;
          }
        },
        sendToHub: (<any> HubClient.prototype).sendToHub
      };
      fakeHubClient.sendToHub('anAction');
      expect(action).to.deep.equal('anAction');
      expect(msg.host).to.deep.equal(fakeHubClient.location);

    });

  });

  describe('invoke and multipleInvoke', () => {

    it('should invoke() be ok', async () => {

      let msg = null;
      let action = null;
      const fakeHubClient = {
        location: { appName: 'fake' },
        invoke: HubClient.prototype.invoke,
        sendToHubAndWaitReply: (ownAction, ownMsg) => {
          msg = ownMsg;
          action = ownAction;
          return {
            success: true
          };
        }
      };

      const res = await fakeHubClient.invoke({objectName: 'nope'}, 'anAction', { test: true });
      expect(res.success).to.be.true;

      expect(action).to.deep.equal(PANDORA_HUB_ACTION_MSG_UP);
      expect(msg.broadcast).to.be.false;
      expect(msg.remote).to.deep.equal({
        objectName: 'nope'
      });

    });

    it('should multipleInvoke() be ok', async () => {

      let msg = null;
      let action = null;
      const fakeHubClient = {
        location: { appName: 'fake' },
        multipleInvoke: HubClient.prototype.multipleInvoke,
        sendToHubAndWaitReply: (ownAction, ownMsg) => {
          msg = ownMsg;
          action = ownAction;
          return {
            batchReply: [
              {
                success: true
              }
            ]
          };
        }
      };

      const res = await fakeHubClient.multipleInvoke({objectName: 'nope'}, 'anAction', { test: true });

      expect(res[0].success).to.be.true;
      expect(action).to.deep.equal(PANDORA_HUB_ACTION_MSG_UP);
      expect(msg.broadcast).to.be.true;
      expect(msg.remote).to.deep.equal({
        objectName: 'nope'
      });

    });

    it('should get an error when sendToHubAndWaitReply() got an error from Hub', async () => {

      const fakeHubClient = {
        sendToHubAndWaitReply: (<any> HubClient.prototype).sendToHubAndWaitReply,
        messengerClient: {
          send (action, message, reply) {
            reply(new Error('fake error'));
          }
        }
      };

      await expect(fakeHubClient.sendToHubAndWaitReply('anAction', {test: true})).to.be.rejectedWith('fake error');

    });

  });

});


text:
namespace Microsoft.OData.Client
{
    using System;

    /// Represents the error thrown if the data service returns a response code less than 200 or greater than 299, or the top-level element in the response is <error>. This class cannot be inherited.
#if !PORTABLELIB
    [Serializable]
#endif
    [System.Diagnostics.DebuggerDisplay("{Message}")]
    public sealed class DataServiceRequestException : InvalidOperationException
    {
        /// Actual response object.
#if !PORTABLELIB
        [NonSerialized]
#endif
        private readonly DataServiceResponse response;

        #region Constructors

        /// Initializes a new instance of the <see cref="T:Microsoft.OData.Client.DataServiceRequestException" /> class with a system-supplied message that describes the error.
        public DataServiceRequestException()
            : base(Strings.DataServiceException_GeneralError)
        {
        }

        /// Initializes a new instance of the <see cref="T:Microsoft.OData.Client.DataServiceRequestException" /> class with a specified message that describes the error.
        /// <param name="message">The message that describes the exception. The caller of this constructor is required to ensure that this string has been localized for the current system culture.The error message text.</param>
        public DataServiceRequestException(string message)
            : base(message)
        {
        }

        /// Initializes a new instance of the <see cref="T:Microsoft.OData.Client.DataServiceRequestException" /> class with a specified error message and a reference to the inner exception that is the cause of this exception.
        /// <param name="message">The message that describes the exception. The caller of this constructor is required to ensure that this string has been localized for the current system culture. </param>
        /// <param name="innerException">The exception that is the cause of the current exception. If the <paramref name="innerException" /> parameter is not null, the current exception is raised in a catch block that handles the inner exception. </param>
        public DataServiceRequestException(string message, Exception innerException)
            : base(message, innerException)
        {
        }

        /// Initializes a new instance of the <see cref="T:Microsoft.OData.Client.DataServiceRequestException" /> class.
        /// <param name="message">Error message text.</param>
        /// <param name="innerException">Exception object that contains the inner exception.</param>
        /// <param name="response"><see cref="T:Microsoft.OData.Client.DataServiceResponse" /> object.</param>
        public DataServiceRequestException(string message, Exception innerException, DataServiceResponse response)
            : base(message, innerException)
        {
            this.response = response;
        }

#if !PORTABLELIB
#pragma warning disable 0628
        ///
        /// Initializes a new instance of the DataServiceQueryException class from the
        /// specified SerializationInfo and StreamingContext instances.
        ///
        /// <param name="info">
        /// A SerializationInfo containing the information required to serialize
        /// the new DataServiceException.</param>
        /// <param name="context">
        /// A StreamingContext containing the source of the serialized stream
        /// associated with the new DataServiceException.</param>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1047", Justification = "Follows serialization info pattern.")]
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1032", Justification = "Follows serialization info pattern.")]
        protected DataServiceRequestException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
            : base(info, context)
        {
        }
#pragma warning restore 0628
#endif

        #endregion Constructors

        #region Public properties

        /// Gets the response as a <see cref="T:Microsoft.OData.Client.DataServiceResponse" /> object.
        /// <returns>A <see cref="T:Microsoft.OData.Client.DataServiceResponse" /> object.</returns>
        public DataServiceResponse Response
        {
            get { return this.response; }
        }

        #endregion Public properties
    }
}


text:
class JobModel;
//------------------------------------------------------------------------------
class ViewModel : public QObject {
	Q_OBJECT
//------------------------------------------------------------------------------
// Constructors/Destructor
//------------------------------------------------------------------------------
	private:
		ViewModel() = delete;
		ViewModel(const ViewModel &) = delete;
		ViewModel & operator=(const ViewModel &) = delete;

	public:
		explicit ViewModel(const QString &name, const QString &url, QObject *parent=nullptr);
		~ViewModel();

//------------------------------------------------------------------------------
// Typedefs
//------------------------------------------------------------------------------
	public:
		typedef QList<JobModel*>				JobsList;
		typedef QMap<QString, JobModel*>		JobsMap;

//------------------------------------------------------------------------------
// Signals
//------------------------------------------------------------------------------
	signals:
		void jobsListLoaded();

//------------------------------------------------------------------------------
// Public slots
//------------------------------------------------------------------------------
	public slots:
		void setName(const QString &name);
		void setUrl(const QString &url);
		void loadJobs();

//------------------------------------------------------------------------------
// Public functions
//------------------------------------------------------------------------------
	public:
		const QString &	getName() const;
		const QString &	getUrl() const;
		bool					isJobsListLoaded() const;
		JobsList				getJobs() const;

		void http_finished(const QString &content, QNetworkReply::NetworkError errCode, const QString &error);

//------------------------------------------------------------------------------
// Private slots
//------------------------------------------------------------------------------
	private slots:
		void job_loaded();
//------------------------------------------------------------------------------
// Private functions
//------------------------------------------------------------------------------
	private:
		void clearJobs();
//------------------------------------------------------------------------------
// Members
//------------------------------------------------------------------------------
	private:
		QString			m_name;
		QString			m_url;
		bool			m_jobsListLoaded;
		JobsMap			m_jobs;
//------------------------------------------------------------------------------
};
//------------------------------------------------------------------------------
#endif // VIEWMODEL_H
//------------------------------------------------------------------------------


text:
/**
 * @name $.ui.simplicityMapQuestMapBoundsCoordinator
 * @namespace A MapQuest map
 *

 * An invisible jquery ui widget which coordinates the updating of a MapQuest Map's bounds after a discovery search
 * response is parsed and dispatched (the simplicitySearchResponseHandled event from the simplicityDiscoverySearch
 * widget. Triggers a simplicitymapquestmapboundscoordinatorcalculatebounds event which other components can use to
 * modify the map bounds.
 *
 * @example
 *   <div id="map" style="width: 300px; height: 300px;"></div>
 *   <script type="text/javascript">
 *     $('#map').simplicityMapQuestMap();
 *   </script>
 *
 * @see MapQuest JavaScript SDK v6 documentation.
 */
(function ($) {
  $.widget("ui.simplicityMapQuestMapBoundsCoordinator", $.ui.simplicityWidget, {
    /**
     * Widget options.
     *
     *

     *
searchElement

     *

     *     The simplicityDiscoverySearch widget that this widget binds it's events to. Defaults to 'body'.
     *

     *
map

     *

     *     Optional map instance, if not provided one will be created. Defaults to ''.
     *

     *

     * @name $.ui.simplicityMapQuestMapBoundsCoordinator.options
     */
    options : {
      searchElement: 'body',
      map: ''
    },
    _create: function () {
      this._addClass('ui-simplicity-mapquest-map-bounds-coordinator');
      this._map = this.options.map !== '' ? this.options.map : this.element.simplicityMapQuestMap('map');
      this._bind(this.options.searchElement, 'simplicitySearchResponseHandled', function () {
        this.updateBounds();
      });
    },
    /**
     * Return the actual map object.
     *
     * @name $.ui.simplicityMapQuestMapBoundsCoordinator.map
     * @function
     */
    map: function () {
      return this._map;
    },
    updateBounds: function () {
      var ui = {
        locations: []
      };
      this._trigger('calculateBounds', {}, ui);
      if ('undefined' !== typeof ui.locations && 0 !== ui.locations.length) {
        var bounds;
        $.each(ui.locations, function (idx, loc) {
          if (typeof bounds === 'undefined') {
            bounds = new MQA.RectLL(loc, loc);
          } else {
            bounds.extend(loc);
          }
        });
        if (typeof bounds !== 'undefined') {
          this._map.zoomToRect(bounds);
        }
      }
    }
  });
}(jQuery));


text:
package org.elasticsearch.search.fetch.version;

import com.google.common.collect.ImmutableMap;
import org.apache.lucene.index.Term;
import org.apache.lucene.util.BytesRef;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.common.lucene.uid.Versions;
import org.elasticsearch.index.mapper.Uid;
import org.elasticsearch.index.mapper.internal.UidFieldMapper;
import org.elasticsearch.search.SearchParseElement;
import org.elasticsearch.search.fetch.FetchSubPhase;
import org.elasticsearch.search.internal.InternalSearchHit;
import org.elasticsearch.search.internal.SearchContext;

import java.io.IOException;
import java.util.Map;

/**
 *
 */
public class VersionFetchSubPhase implements FetchSubPhase {

    @Override
    public Map<String, ? extends SearchParseElement> parseElements() {
        return ImmutableMap.of("version", new VersionParseElement());
    }

    @Override
    public boolean hitsExecutionNeeded(SearchContext context) {
        return false;
    }

    @Override
    public void hitsExecute(SearchContext context, InternalSearchHit[] hits) throws ElasticsearchException {
    }

    @Override
    public boolean hitExecutionNeeded(SearchContext context) {
        return context.version();
    }

    @Override
    public void hitExecute(SearchContext context, HitContext hitContext) throws ElasticsearchException {
        // it might make sense to cache the TermDocs on a shared fetch context and just skip here)
        // it is going to mean we work on the high level multi reader and not the lower level reader as is
        // the case below...
        long version;
        try {
            BytesRef uid = Uid.createUidAsBytes(hitContext.hit().type(), hitContext.hit().id());
            version = Versions.loadVersion(
                    hitContext.readerContext().reader(),
                    new Term(UidFieldMapper.NAME, uid)
            );
        } catch (IOException e) {
            throw new ElasticsearchException("Could not query index for _version", e);
        }

        if (version < 0) {
            version = -1;
        }
        hitContext.hit().version(version);
    }
}


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.usfirst.frc2877.UltimateAscent2013Robot.commands;

import edu.wpi.first.wpilibj.command.Command;
import org.usfirst.frc2877.UltimateAscent2013Robot.Robot;
import org.usfirst.frc2877.UltimateAscent2013Robot.RobotMap;
/**
 *
 * @author Administrator
 */
public class AcquisitionScrewControl extends Command {

    // save the requested number of turns
    private int m_requestedTurns = 0;
    // keep track of how many turns
    private int m_turns;
    // keep track of how many iterations we've done
    private int m_numCycles = 0;
    // This constant is used to define how many cycles we need to go to make
    // sure that the cam has cleared the limit switch
    private final int MIN_CYCLES_TO_CLEAR = 20;
    // In case the switch can be set for multiple iterations
    // It's initialized to false because we won't check it until after we have
    // run MIN_CYCLLES_TO_CLEAR iterations.
    private boolean m_switchContacted = false;
    // The default speed for the screws
    double run = Robot.acquisition.ACQUISITIONSPEED;
    boolean limitSwitchTriggered;
    int m_count = 10;
    public AcquisitionScrewControl(int turns) {
        setInterruptible(false);
        m_requestedTurns = turns;

        // Use requires() here to declare subsystem dependencies
        // eg. requires(chassis);
        requires (Robot.acquisition);
        System.out.println("AcquisitionOverride constructor called");
    }

    // Called just before this Command runs the first time
    protected void initialize() {
        // if M-requested turns is less than zero, then we have to move the
        // screws down, so make the speed negative.
        if (m_requestedTurns < 0) {
            run = -1 * run;
        }
        System.out.println("Initialize AcquisitionOverride " + m_requestedTurns);
    }

    // Called repeatedly when this Command is scheduled to run
    protected void execute() {
        boolean limit = Robot.getRotaryLimitSwitch();

        if (--m_count==0)
        {
            m_count = 10;
            Robot.debugOut("Rotary Limit Switch: ", limit ? "true" : "false" );
        }
        // We need to run a few cycles before we check for the switch or else
        // it migh stop immediately.
        // If the switch state has changed, then if it is now true that means
        // we just finished a rotation.
        if (m_numCycles > MIN_CYCLES_TO_CLEAR &&
                limit != m_switchContacted &&
                m_switchContacted) {
                    m_turns++;
                    // if we have completed the requested number of turns,
                    // we can go straight to end.
                    if (m_turns == m_requestedTurns) {
                        end();
                    }
                } else {
                    // Since the switch is not contacted, we have not completed
                    // the current turn, so keep going.
                    Robot.acquisition.acquisitionTurnScrews(run);
                }
        // Save the current state of the switch to check against next iteration
        m_switchContacted = limit;
        // increment the number of cycles
        m_numCycles++;
    }

    // Make this return true when this Command no longer needs to run execute()
    protected boolean isFinished() {
        // It si finished it we have completed the right number of turns.
        // So the switch must be contacted and m_turns must be equal to the
        // requested number. I made it >= just in case.
       return (m_turns >= m_requestedTurns);
    }

    // Called once after isFinished returns true
    protected void end() {
        Robot.acquisition.acquisitionTurnScrews(0);
    }

    // Called when another command which requires one or more of the same
    // subsystems is scheduled to run
    protected void interrupted() {
    }
}


text:
Memcached安装非常简单:

Debian/Ubuntu: apt-get install libevent-dev Redhat/Centos: yum install libevent-devel

```bash
wget http://memcached.org/latest
tar -zxvf memcached-1.x.x.tar.gz
cd memcached-1.x.x
./configure && make && make test && sudo make install
```

### Memcached客户端使用

满怀热情的看完Memcached及Memcached Client各实现版本,本来想用Memcached做缓存服务器使用的。但具体实用时,发现Memcached做得事情非常有限,归咎于它的设计适用于简单的key - value存储,并没有namespace/group这一说法。只能继续找其他的缓存方案,下面贴出使用例子:

客户端使用xmemcached,并使用simple-spring-memcached的注解形式

1. pom文件配置

	```xml
	<simple.spring.memcached.version>3.6.0</simple.spring.memcached.version>
	....
	<dependency>
		<groupId>com.google.code.simple-spring-memcached</groupId>
		<artifactId>simple-spring-memcached</artifactId>
		<version>${simple.spring.memcached.version}</version>
	</dependency>
	<dependency>
		<groupId>com.google.code.simple-spring-memcached</groupId>
		<artifactId>xmemcached-provider</artifactId>
		<version>${simple.spring.memcached.version}</version>
	</dependency>
	```
2. spring配置文件

	```xml
	<import resource="simplesm-context.xml" />

	<bean name="defaultMemcachedClient" class="com.google.code.ssm.CacheFactory">
		<property name="cacheClientFactory">
			<bean class="com.google.code.ssm.providers.xmemcached.MemcacheClientFactoryImpl" />
		</property>
		<property name="addressProvider">
			<bean class="com.google.code.ssm.config.DefaultAddressProvider">
				<property name="address" value="10.0.11.135:11211" />
			</bean>
		</property>
		<property name="configuration">
			<bean class="com.google.code.ssm.providers.CacheConfiguration">
				<!-- 使用一致性HASH算法 -->
				<property name="consistentHashing" value="true" />
				<!-- 使用二进制协议,比文本协议好 -->
				<property name="useBinaryProtocol" value="true" />
			</bean>
		</property>
	</bean>
	```
3. JAVA注解

	```java
	@Override
	@ReadThroughSingleCache(namespace = GlobalConstants.CACHE_KEY_ROLE)
	public Role load(@ParameterValueKeyProvider Integer id) {
		return super.get(id, OpenClose.OPEN, OpenClose.CLOSE);
	}
	```

	```java
	//测试代码    ======= 显示Memcached所有的key - value
	public void listCacheObjs() throws Exception {
		final String ip = "10.0.11.135:11211";

		MemcachedClientBuilder builder = new XMemcachedClientBuilder(AddrUtil.getAddresses(ip));
		MemcachedClient client = builder.build();
		KeyIterator it = client.getKeyIterator(AddrUtil.getOneAddress(ip));
		while (it.hasNext()) {
			String key = it.next();
			LOG.info("====== Key/value : {0} / {1}", key, client.get(key));
		}
    }
	```

使用就是这么简单,但功能也比较单一,适合简单的key-value场景。

> 注意事项:
> 1.`@ReadThroughSingleCache` 作为一个cache存储,即不管你返回值是List还是int,统统转成字符窜后存储。`@ReadThroughMultiCache` list数据是作为多个cache存储,且方法的参数必须包含list的参数。`@ReadThroughAssignCache` 自定义cache的KEY值。
> 2. 如果方法的参数为一个Entity对象,则需要在主键的get方法上加上`@CacheKeyMethod`注解,表明此Entity生成key的方法为此主键的get方法。如果对象为联合主键,则自己建一个`public String cacheKey() { ... }`,在此方法上加上`@CacheKeyMethod`就可以了。如果没有`@CacheKeyMethod`注解,则使用此对象的`toString`方法生成KEY。标记`@CacheKeyMethod`注解的方法必须返回`String`。


text:
<?php defined('SYSPATH') or die('No direct script access.');

class Storage_Connection_Local extends Kohana_Storage_Connection_Local {}


text:
@interface HsBottomView : UIView

@end


text:
require "rails_helper"

describe Everett::Subject do
  describe "::CALLBACKS" do
    subject { described_class::CALLBACKS }

    let(:expectation) do
      %i(
          after_initialize
          after_find
          after_touch
          before_validation
          after_validation
          before_save
          around_save
          after_save
          before_create
          around_create
          after_create
          before_update
          around_update
          after_update
          before_destroy
          around_destroy
          after_destroy
          after_commit
          after_create_commit
          after_update_commit
          after_destroy_commit
          after_rollback
        )
    end

    it { is_expected.to contain_exactly(*expectation) }
  end

  describe ".new" do
    subject { -> { described_class.new(Class.new) } }
    it { is_expected.to raise_error(NoMethodError) }
  end

  describe ".[]" do
    subject { -> { described_class[model_class] } }
    let(:model_class) { Class.new }

    it { expect(subject.call).to eq subject.call }
  end

  describe "#add_observer" do
    subject { described_method.call }

    let(:described_method) { -> { described_class[model_class].add_observer(observer) } }
    let(:model_class) { class_double("Model") }
    let(:observer) { double(:observer) }

    before do
      allow(observer).to receive(defined_method)
      described_class::CALLBACKS.each { |callback| allow(model_class).to receive(callback) }
    end

    context "when the observer defines no ActiveRecord callbacks" do
      let(:defined_method) { :foo }
      it { is_expected.to eq false }
    end

    context "when the observer defines ActiveRecord callbacks" do
      let(:defined_method) { described_class::CALLBACKS.first }

      context "when the observer is already added" do
        before do
          described_method.call
        end

        it "should return false, and the instance isn't used to set callbacks" do
          expect(model_class).not_to receive(defined_method)
          expect(subject).to eq false
        end
      end

      context "when the observer isn't added yet" do
        it "should return true, and the instance is used to set callbacks" do
          expect(model_class).to receive(defined_method).and_yield.once
          expect(subject).to eq true
        end
      end
    end
  end
end


text:
/* $Id: setjmp.h,v 1.10.2.1 2008/03/24 11:29:53 dmix Exp $ */

#ifndef __SETJMP_H_
#define __SETJMP_H_ 1

#ifdef __cplusplus
extern "C" {
#endif

/*
   jmp_buf:
	offset	size	description
	 0	16	call-saved registers (r2-r17)
	16	 2	frame pointer (r29:r28)
	18	 2	stack pointer (SPH:SPL)
	20	 1	status register (SREG)
	21	 2/3	return address (PC) (2 bytes used for <=128Kw flash)
	23/24 = total size
 */

#if !defined(__DOXYGEN__)

#if	defined(__AVR_3_BYTE_PC__) && __AVR_3_BYTE_PC__
# define _JBLEN  24
#else
# define _JBLEN  23
#endif
typedef struct _jmp_buf { unsigned char _jb[_JBLEN]; } jmp_buf[1];

#endif /* not __DOXYGEN__ */

/** \file */
/** \defgroup setjmp <setjmp.h>: Non-local goto

    While the C language has the dreaded \c goto statement, it can only be
    used to jump to a label in the same (local) function.  In order to jump
    directly to another (non-local) function, the C library provides the
    setjmp() and longjmp() functions.  setjmp() and longjmp() are useful for
    dealing with errors and interrupts encountered in a low-level subroutine
    of a program.

    \note setjmp() and longjmp() make programs hard to understand and maintain.
    If possible, an alternative should be used.

    \note longjmp() can destroy changes made to global register
    variables (see \ref faq_regbind).

    For a very detailed discussion of setjmp()/longjmp(), see Chapter 7 of
    Advanced Programming in the UNIX Environment, by W. Richard
    Stevens.

    Example:

    \code
    #include <setjmp.h>

    jmp_buf env;

    int main (void)
    {
        if (setjmp (env))
        {
            ... handle error ...
        }

        while (1)
        {
           ... main processing loop which calls foo() some where ...
        }
    }

    ...

    void foo (void)
    {
        ... blah, blah, blah ...

        if (err)
        {
            longjmp (env, 1);
        }
    }
    \endcode */

#ifndef __ATTR_NORETURN__
#define __ATTR_NORETURN__ __attribute__((__noreturn__))
#endif

/** \ingroup setjmp
    \brief Save stack context for non-local goto.

    \code #include <setjmp.h>\endcode

    setjmp() saves the stack context/environment in \e __jmpb for later use by
    longjmp().  The stack context will be invalidated if the function which
    called setjmp() returns.

    \param __jmpb Variable of type \c jmp_buf which holds the stack
    information such that the environment can be restored.

    \returns setjmp() returns 0 if returning directly, and
    non-zero when returning from longjmp() using the saved context. */

extern int setjmp(jmp_buf __jmpb);

/** \ingroup setjmp
    \brief Non-local jump to a saved stack context.

    \code #include <setjmp.h>\endcode

    longjmp() restores the environment saved by the last call of setjmp() with
    the corresponding \e __jmpb argument.  After longjmp() is completed,
    program execution continues as if the corresponding call of setjmp() had
    just returned the value \e __ret.

    \note longjmp() cannot cause 0 to be returned.  If longjmp() is invoked
    with a second argument of 0, 1 will be returned instead.

    \param __jmpb Information saved by a previous call to setjmp().
    \param __ret  Value to return to the caller of setjmp().

    \returns This function never returns. */

extern void longjmp(jmp_buf __jmpb, int __ret) __ATTR_NORETURN__;

#ifdef __cplusplus
}
#endif

#endif  /* !__SETJMP_H_ */


text:
package org.spongepowered.mod.mixin.core.forge.fluids;

import net.minecraft.block.state.IBlockState;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.common.util.Constants;
import net.minecraftforge.fluids.BlockFluidBase;
import net.minecraftforge.fluids.BlockFluidClassic;
import org.spongepowered.api.block.BlockSnapshot;
import org.spongepowered.api.data.Transaction;
import org.spongepowered.api.event.CauseStackManager;
import org.spongepowered.api.event.block.ChangeBlockEvent;
import org.spongepowered.api.event.cause.EventContextKeys;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.Redirect;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.common.bridge.world.WorldServerBridge;
import org.spongepowered.common.bridge.world.WorldBridge;
import org.spongepowered.common.event.ShouldFire;
import org.spongepowered.common.event.SpongeCommonEventFactory;
import org.spongepowered.common.event.tracking.IPhaseState;
import org.spongepowered.common.event.tracking.PhaseContext;
import org.spongepowered.common.event.tracking.PhaseTracker;

import java.util.Random;
import java.util.function.BiConsumer;

import javax.annotation.Nullable;

@Mixin(value = BlockFluidClassic.class)
public abstract class BlockFluidClassicMixin_Forge extends BlockFluidBaseMixin_Forge {

    @Override
    public BiConsumer<CauseStackManager.StackFrame, WorldServerBridge> bridge$getTickFrameModifier() {
        return (frame, world) -> frame.addContext(EventContextKeys.LIQUID_FLOW, (org.spongepowered.api.world.World) world);
    }

    @Inject(method = "updateTick",
        at = @At("HEAD"),
        cancellable = true
    )
    private void onUpdateTickCheckSpongePre(final World world, final BlockPos pos, final IBlockState state, final Random rand, final CallbackInfo ci) {
        if (!((WorldBridge) world).bridge$isFake() && ShouldFire.CHANGE_BLOCK_EVENT_PRE) {
            if (SpongeCommonEventFactory.callChangeBlockEventPre((WorldServerBridge) world, pos).isCancelled()) {
                ci.cancel();
            }
        }
    }

    @Nullable private Boolean isPreCancelled;

    /**
     * @author gabizou - June 4th, 2019 - 1.12.2
     * @reason In the event the injection above does cancel, we need to duck out of the rest of the method.
     * Otherwise, the above injection never went through, the {@link BlockFluidBase#canDisplace(IBlockAccess, BlockPos)}
     * ends up getting it's injection thrown anyways.
     *
     * @param world The world
     * @param pos the position being flown into
     * @param state The state
     * @param rand The rando
     * @param ci The callback info
     */
    @Inject(
        method = "updateTick",
        at = @At(
            value = "INVOKE",
            target = "Lnet/minecraftforge/fluids/BlockFluidClassic;canDisplace(Lnet/minecraft/world/IBlockAccess;Lnet/minecraft/util/math/BlockPos;)Z",
            remap = false
        ),
        cancellable = true
    )
    private void onCheckDisplaceIfPreAlreadyCancelled(
        final World world, final BlockPos pos, final IBlockState state, final Random rand, final CallbackInfo ci) {
        if (this.isPreCancelled == Boolean.TRUE) {
            ci.cancel();
            // And reset the field so we don't leak...
            this.isPreCancelled = null;
        }
    }

    // Capture Fluids flowing into other blocks
    @SuppressWarnings({"unchecked", "rawtypes"})
    @Redirect(
        method = "flowIntoBlock",
        at = @At(
            value = "INVOKE",
            target = "Lnet/minecraft/world/World;setBlockState(Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/block/state/IBlockState;)Z"
        ),
        constraints = "FORGE(2821+)"
    )
    private boolean afterCanFlowInto(
        final World targetWorld, final BlockPos targetPos, final IBlockState newLiquidState, final World world, final BlockPos pos, final int meta) {
        if (((WorldBridge) targetWorld).bridge$isFake() || !ShouldFire.CHANGE_BLOCK_EVENT_BREAK) { // Check if we even need to fire.
            return world.setBlockState(targetPos, newLiquidState, Constants.BlockFlags.DEFAULT);
        }

        final IBlockState existing = targetWorld.getBlockState(targetPos);
        // Do not call events when just flowing into air or same liquid
        //noinspection RedundantCast
        if (!existing.getBlock().isAir(existing, targetWorld, targetPos) && !(existing.getMaterial().isLiquid() || existing.getBlock() == (BlockFluidClassic) (Object) this)) {
            final ChangeBlockEvent.Break event = SpongeCommonEventFactory.callChangeBlockEventModifyLiquidBreak(world, pos, newLiquidState);

            final Transaction<BlockSnapshot> transaction = event.getTransactions().get(0);
            if (event.isCancelled() || !transaction.isValid()) {
                // We need to clear any drops here because this is called after {@link #displaceIfPossible} and since it was true, well
                // there's the likelyhood that there's a dropped item
                final PhaseContext<?> currentContext = PhaseTracker.getInstance().getCurrentContext();
                ((IPhaseState) currentContext.state).processCancelledTransaction(currentContext, transaction, transaction.getOriginal());
                return false;
            }

            // Transaction modified?
            if (transaction.getCustom().isPresent()) {
                return targetWorld.setBlockState(targetPos, (IBlockState) transaction.getFinal().getState(), Constants.BlockFlags.DEFAULT);
            }
        }

        return targetWorld.setBlockState(targetPos, newLiquidState, Constants.BlockFlags.DEFAULT);
    }

}


text:
from pandac.PandaModules import *
from toontown.toonbase.ToonBaseGlobal import *
from direct.interval.IntervalGlobal import *
from toontown.toonbase.ToontownGlobals import *
from direct.directnotify import DirectNotifyGlobal
from direct.fsm import StateData
from direct.fsm import ClassicFSM, State
from direct.fsm import State
import ToonBlitzGlobals
from otp.otpbase import OTPGlobals
from direct.task.Task import Task
from toontown.minigame import TwoDBattleMgr
from toontown.racing import RaceHeadFrame
COLOR_RED = VBase4(1, 0, 0, 0.3)

class TwoDGameToonSD(StateData.StateData):
    notify = DirectNotifyGlobal.directNotify.newCategory('TwoDGameToonSD')
    FallBackAnim = 'slip-backward'
    NeutralAnim = 'neutral'
    RunAnim = 'run'
    ShootGun = 'water-gun'
    Victory = 'victory'
    animList = [FallBackAnim,
     NeutralAnim,
     RunAnim,
     ShootGun,
     Victory]
    ScoreTextGenerator = TextNode('ScoreTextGenerator')

    def __init__(self, avId, game):
        self.avId = avId
        self.game = game
        self.isLocal = avId == base.localAvatar.doId
        self.toon = self.game.getAvatar(self.avId)
        self.unexpectedExit = False
        self.fallBackIval = None
        self.fallDownIval = None
        self.victoryIval = None
        self.squishIval = None
        self.fsm = ClassicFSM.ClassicFSM('TwoDGameAnimFSM-%s' % self.avId, [State.State('init', self.enterInit, self.exitInit, ['normal']),
         State.State('normal', self.enterNormal, self.exitNormal, ['shootGun',
          'fallBack',
          'fallDown',
          'victory',
          'squish']),
         State.State('shootGun', self.enterShootGun, self.exitShootGun, ['normal',
          'fallBack',
          'fallDown',
          'victory',
          'squish']),
         State.State('fallBack', self.enterFallBack, self.exitFallBack, ['normal', 'fallDown', 'squish']),
         State.State('fallDown', self.enterFallDown, self.exitFallDown, ['normal']),
         State.State('squish', self.enterSquish, self.exitSquish, ['normal']),
         State.State('victory', self.enterVictory, self.exitVictory, ['normal', 'fallDown']),
         State.State('cleanup', self.enterCleanup, self.exitCleanup, [])], 'init', 'cleanup')
        self.scoreText = None
        self.load()
        self.progressLineLength = self.game.assetMgr.faceEndPos[0] - self.game.assetMgr.faceStartPos[0]
        self.conversionRatio = self.progressLineLength / self.game.gameLength
        return

    def load(self):
        for anim in self.animList:
            self.toon.pose(anim, 0)

        self.battleMgr = TwoDBattleMgr.TwoDBattleMgr(self.game, self.toon)
        self.squishSound = base.loadSfx('phase_3.5/audio/dial/AV_' + self.toon.style.getAnimal() + '_exclaim.ogg')

    def destroy(self):
        if self.fallBackIval != None:
            self.fallBackIval.finish()
            self.fallBackIval = None
        if self.fallDownIval != None:
            self.fallDownIval.finish()
            self.fallDownIval = None
        if self.squishIval != None:
            self.squishIval.finish()
            self.squishIval = None
        if self.victoryIval != None:
            self.victoryIval.finish()
            self.victoryIval = None
        self.hideScoreText()
        self.headFrame.destroy()
        self.battleMgr.destroy()
        del self.battleMgr
        del self.fsm
        return

    def enter(self):
        self.fsm.enterInitialState()

    def exit(self, unexpectedExit = False):
        self.unexpectedExit = unexpectedExit
        self.fsm.requestFinalState()

    def enterInit(self):
        self.notify.debug('enterInit')
        self.toon.startBlink()
        self.toon.stopLookAround()
        self.toon.useLOD(1000)
        self.toon.dropShadow.hide()

    def exitInit(self):
        pass

    def enterNormal(self):
        self.notify.debug('enterNormal')

    def exitNormal(self):
        pass

    def enterFallBack(self):
        self.notify.debug('enterFallBack')
        fallBackDist = 9
        self.blinkRed = self.blinkColor(COLOR_RED, 2)
        duration = 4
        animName = self.FallBackAnim
        startFrame = 1
        endFrame = 22
        totalFrames = self.toon.getNumFrames(animName)
        frames = totalFrames - 1 - startFrame
        frameRate = self.toon.getFrameRate(animName)
        newRate = frames / duration
        playRate = newRate / frameRate
        fallBackAnim = Sequence(ActorInterval(self.toon, animName, startTime=startFrame / newRate, endTime=endFrame / newRate, playRate=playRate), ActorInterval(self.toon, animName, startFrame=23, playRate=1), FunctionInterval(self.resume))
        self.fallBackIval = Parallel(self.blinkRed, fallBackAnim)
        if self.isLocal:
            self.game.ignoreInputs()
            self.toon.controlManager.currentControls.lifter.setVelocity(12)
            if self.toon.getH() == 90:
                endPoint = Point3(self.toon.getX() + fallBackDist, self.toon.getY(), self.toon.getZ())
            else:
                endPoint = Point3(self.toon.getX() - fallBackDist, self.toon.getY(), self.toon.getZ())
            enemyHitTrajectory = LerpFunc(self.toon.setX, fromData=self.toon.getX(), toData=endPoint.getX(), duration=0.75, name='enemyHitTrajectory')
            self.fallBackIval.append(enemyHitTrajectory)
            base.playSfx(self.game.assetMgr.sndOof)
        self.fallBackIval.start()

    def exitFallBack(self):
        self.fallBackIval.pause()
        self.blinkRed.finish()
        if self.isLocal:
            if self.game.gameFSM.getCurrentState().getName() == 'play':
                self.game.acceptInputs()

    def shootGun(self):
        if self.fsm.getCurrentState().getName() == 'shootGun':
            self.fsm.request('normal')
        self.fsm.request('shootGun')

    def enterShootGun(self):
        self.battleMgr.shoot()
        self.fsm.request('normal')

    def exitShootGun(self):
        pass

    def enterFallDown(self):
        self.notify.debug('enterFallDown')
        self.fallDownIval = Sequence()
        self.blinkRed = self.blinkColor(COLOR_RED, 2)
        if self.isLocal:
            self.game.ignoreInputs()
            base.playSfx(self.game.assetMgr.fallSound)
            pos = self.game.sectionMgr.getLastSpawnPoint()
            toonRespawnIval = Sequence(Wait(1), Func(base.localAvatar.setPos, pos))
            self.fallDownIval.append(toonRespawnIval)
        self.fallDownIval.append(Func(self.resume))
        self.fallDownIval.append(self.blinkRed)
        self.fallDownIval.start()

    def exitFallDown(self):
        if self.isLocal:
            if self.game.gameFSM.getCurrentState().getName() == 'play':
                self.game.acceptInputs()

    def enterSquish(self):
        self.notify.debug('enterSquish')
        if self.isLocal:
            self.game.ignoreInputs()
        self.toon.setAnimState('Squish')
        self.toon.stunToon()
        base.playSfx(self.squishSound, node=self.toon, volume=2)
        self.blinkRed = self.blinkColor(COLOR_RED, 3)
        self.squishIval = Parallel(self.blinkRed, Sequence(Wait(2.5), Func(self.resume)))
        self.squishIval.start()

    def exitSquish(self):
        if self.isLocal:
            if self.game.gameFSM.getCurrentState().getName() == 'play':
                self.game.acceptInputs()

    def enterVictory(self):
        self.notify.debug('enterVictory')
        outsideElevatorPos = self.game.sectionMgr.exitElevator.find('**/loc_elevator_front').getPos(render)
        insideElevatorPos = self.game.sectionMgr.exitElevator.find('**/loc_elevator_inside').getPos(render)
        runToElevator = Parallel(LerpPosInterval(self.toon, self.game.timeToRunToElevator, outsideElevatorPos), ActorInterval(self.toon, self.RunAnim, loop=1, duration=self.game.timeToRunToElevator))
        danceIval = Parallel(LerpPosInterval(self.toon, 2, insideElevatorPos), ActorInterval(self.toon, self.Victory, loop=1, duration=ToonBlitzGlobals.GameDuration[self.game.getSafezoneId()]))
        waitToLand = 0.0
        if self.toon.getZ(render) > 13:
            waitToLand = 1
        self.victoryIval = Sequence(Wait(waitToLand), runToElevator, danceIval)
        self.victoryIval.start()

    def exitVictory(self):
        pass

    def enterCleanup(self):
        self.notify.debug('enterCleanup')
        self.toon.stopBlink()
        self.toon.startLookAround()
        self.toon.resetLOD()
        self.toon.dropShadow.show()

    def exitCleanup(self):
        pass

    def resume(self):
        self.fsm.request('normal')
        messenger.send('jumpLand')

    def blinkColor(self, color, duration):
        blink = Sequence(LerpColorScaleInterval(self.toon, 0.5, color, startColorScale=VBase4(1, 1, 1, 1)), LerpColorScaleInterval(self.toon, 0.5, VBase4(1, 1, 1, 1), startColorScale=color))
        track = Sequence(Func(blink.loop), Wait(duration), Func(blink.finish))
        return track

    def setAnimState(self, newState, playRate):
        if not self.unexpectedExit:
            self.toon.setAnimState(newState, playRate)

    def createHeadFrame(self, drawNum):
        toon = base.cr.doId2do.get(self.avId, None)
        self.headFrame = RaceHeadFrame.RaceHeadFrame(av=toon)
        eyes = self.headFrame.head.find('**/eyes*')
        eyes.setDepthTest(1)
        eyes.setDepthWrite(1)
        self.headFrame.configure(geom_scale=(0.5, 0.5, 0.5))
        self.headFrame.setZ(self.game.assetMgr.faceStartPos[2])
        self.headFrame.setDepthWrite(True)
        self.headFrame.setDepthTest(True)
        self.headFrame.reparentTo(self.game.assetMgr.aspect2dRoot)
        self.headFrame.setY(-drawNum)
        if self.isLocal:
            self.headFrame.setScale(0.2)
        else:
            self.headFrame.setScale(0.15)
        self.headFrame.setX(self.game.assetMgr.faceStartPos[0])
        return

    def update(self):
        toonCurrX = self.toon.getX(render)
        progress = toonCurrX - self.game.gameStartX
        headFrameProgress = progress * self.conversionRatio
        headFrameX = self.game.assetMgr.faceStartPos[0] + headFrameProgress
        headFrameX = max(self.game.assetMgr.faceStartPos[0], headFrameX)
        headFrameX = min(self.game.assetMgr.faceEndPos[0], headFrameX)
        self.headFrame.setX(headFrameX)

    def showScoreText(self, number, scale = 1.25):
        if not number == 0:
            if self.scoreText:
                self.hideScoreText()
            self.ScoreTextGenerator.setFont(OTPGlobals.getSignFont())
            if number < 0:
                self.ScoreTextGenerator.setText(str(number))
            else:
                self.ScoreTextGenerator.setText('+' + str(number))
            self.ScoreTextGenerator.clearShadow()
            self.ScoreTextGenerator.setAlign(TextNode.ACenter)
            if number < 0:
                r, g, b, a = (0.9, 0, 0, 1)
            else:
                r, g, b, a = (0.9, 0.9, 0, 1)
            self.scoreTextNode = self.ScoreTextGenerator.generate()
            self.scoreText = self.toon.attachNewNode(self.scoreTextNode)
            self.scoreText.setScale(scale)
            self.scoreText.setBillboardPointEye()
            self.scoreText.setBin('fixed', 100)
            self.scoreText.setPos(0, 0, self.toon.height / 2)
            self.scoreText.setTransparency(1)
            self.scoreText.setColor(r, g, b, a)
            self.scoreText.setDepthTest(0)
            self.scoreText.setDepthWrite(0)
            seq = Sequence(self.scoreText.posInterval(0.5, Point3(0, 0, self.toon.height + 2), blendType='easeOut'), self.scoreText.colorInterval(0.25, Vec4(r, g, b, 0)), Func(self.hideScoreText))
            seq.start()

    def hideScoreText(self):
        if self.scoreText:
            taskMgr.remove(self.game.uniqueName('scoreText'))
            self.scoreText.removeNode()
            self.scoreText = None
        return


text:
FOUNDATION_EXPORT double Pods_LaraCrypt_TestsVersionNumber;
FOUNDATION_EXPORT const unsigned char Pods_LaraCrypt_TestsVersionString[];


text:
using System;
using biz.dfch.CS.Web.Utilities.Contracts.Endpoint;

namespace biz.dfch.CS.Web.Utilities.Tests.Contracts.Endpoint
{
    public class HttpApplicationEventsDataWithPriority : IHttpApplicationEventsData
    {
        public HttpApplicationEventsDataWithPriority()
        {
            // N/A
        }

        public HttpApplicationEventsDataWithPriority(int priority)
        {
            _priority = priority;
        }

        private int _priority = 0;
        public int Priority
        {
            get
            {
                return _priority;
            }
        }
        public string Data
        {
            get
            {
                // not needed in this test
                throw new NotImplementedException();
            }
        }
    }
}


text:
const baseConfig = require('./jest.base.config');

module.exports = {
  ...baseConfig,
  roots: ['<rootDir>/demo'],
  modulePaths: ['<rootDir>/dist'],
  moduleNameMapper: {
      'ngx-jsonapi': '<rootDir>/dist'
  },
  coveragePathIgnorePatterns: [
      '/node_modules/',
      '/src/*.*/'
  ],

  globals: {
      'ts-jest': {
          tsConfigFile: 'demo/tsconfig.spec.json'
      },
      stringifyContentPathRegex: true
  },
};


text:
package org.springframework.aop.interceptor;

import com.jamonapi.MonitorFactory;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.logging.Log;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.*;
import static org.mockito.BDDMockito.*;

/**
 * @author Steve Souza
 * @since 4.1
 */
public class JamonPerformanceMonitorInterceptorTests {

	private final JamonPerformanceMonitorInterceptor interceptor = new JamonPerformanceMonitorInterceptor();

	private final MethodInvocation mi = mock(MethodInvocation.class);

	private final Log log = mock(Log.class);

	@Before
	public void setUp() {
		MonitorFactory.reset();
	}

	@After
	public void tearDown() {
		MonitorFactory.reset();
	}

	@Test
	public void testInvokeUnderTraceWithNormalProcessing() throws Throwable {
		given(mi.getMethod()).willReturn(String.class.getMethod("toString"));

		interceptor.invokeUnderTrace(mi, log);

		assertTrue("jamon must track the method being invoked", MonitorFactory.getNumRows() > 0);
		assertTrue("The jamon report must contain the toString method that was invoked",
				MonitorFactory.getReport().contains("toString"));
	}

	@Test
	public void testInvokeUnderTraceWithExceptionTracking() throws Throwable {
		given(mi.getMethod()).willReturn(String.class.getMethod("toString"));
		given(mi.proceed()).willThrow(new IllegalArgumentException());

		try {
			interceptor.invokeUnderTrace(mi, log);
			fail("Must have propagated the IllegalArgumentException");
		}
		catch (IllegalArgumentException expected) {
		}

		assertEquals("Monitors must exist for the method invocation and 2 exceptions",
				3, MonitorFactory.getNumRows());
		assertTrue("The jamon report must contain the toString method that was invoked",
				MonitorFactory.getReport().contains("toString"));
		assertTrue("The jamon report must contain the generic exception: " + MonitorFactory.EXCEPTIONS_LABEL,
				MonitorFactory.getReport().contains(MonitorFactory.EXCEPTIONS_LABEL));
		assertTrue("The jamon report must contain the specific exception: IllegalArgumentException'",
				MonitorFactory.getReport().contains("IllegalArgumentException"));
	}

}


text:
namespace Google.Cloud.Security.PrivateCA.V1.Snippets
{
    // [START privateca_v1_generated_CertificateAuthorityService_ListCertificateTemplates_sync]
    using Google.Api.Gax;
    using Google.Api.Gax.ResourceNames;
    using Google.Cloud.Security.PrivateCA.V1;
    using System;

    public sealed partial class GeneratedCertificateAuthorityServiceClientSnippets
    {
        /// <summary>Snippet for ListCertificateTemplates</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public void ListCertificateTemplatesRequestObject()
        {
            // Create client
            CertificateAuthorityServiceClient certificateAuthorityServiceClient = CertificateAuthorityServiceClient.Create();
            // Initialize request argument(s)
            ListCertificateTemplatesRequest request = new ListCertificateTemplatesRequest
            {
                ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
                Filter = "",
                OrderBy = "",
            };
            // Make the request
            PagedEnumerable<ListCertificateTemplatesResponse, CertificateTemplate> response = certificateAuthorityServiceClient.ListCertificateTemplates(request);

            // Iterate over all response items, lazily performing RPCs as required
            foreach (CertificateTemplate item in response)
            {
                // Do something with each item
                Console.WriteLine(item);
            }

            // Or iterate over pages (of server-defined size), performing one RPC per page
            foreach (ListCertificateTemplatesResponse page in response.AsRawResponses())
            {
                // Do something with each page of items
                Console.WriteLine("A page of results:");
                foreach (CertificateTemplate item in page)
                {
                    // Do something with each item
                    Console.WriteLine(item);
                }
            }

            // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
            int pageSize = 10;
            Page<CertificateTemplate> singlePage = response.ReadPage(pageSize);
            // Do something with the page of items
            Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
            foreach (CertificateTemplate item in singlePage)
            {
                // Do something with each item
                Console.WriteLine(item);
            }
            // Store the pageToken, for when the next page is required.
            string nextPageToken = singlePage.NextPageToken;
        }
    }
    // [END privateca_v1_generated_CertificateAuthorityService_ListCertificateTemplates_sync]
}


text:
using System;
using System.Net;

using ASC.Mail.Exceptions;

using Newtonsoft.Json.Linq;

using RestSharp;

namespace ASC.Mail.Extensions
{
    static class RestClientExtensions
    {
        public static IRestResponse ExecuteSafe(this RestClient client, RestRequest request)
        {
            IRestResponse response;
            try
            {
                response = client.Execute(request);

                if (response.StatusCode == HttpStatusCode.InternalServerError &&
                    response.ErrorException == null &&
                    !string.IsNullOrEmpty(response.Content))
                {
                    try
                    {
                        var json = JObject.Parse(response.Content);
                        if (json == null || json["error"] == null || json["error"]["message"] == null)
                            return response;

                        response.ErrorException = new ApiHelperException(json["error"]["message"].ToString(), response.StatusCode, response.Content);
                    }
                    catch
                    {
                        // ignored
                    }
                }
            }
            catch (Exception ex)
            {
                response = new RestResponse { ErrorException = ex };
            }

            return response;
        }
    }
}


text:
exports.assertion = function elementCount(selector, count) {
  this.message = `Testing if element <${selector}> has count: ${count}`;
  this.expected = count;
  this.pass = (val) => val === count;
  this.value = (res) => res.value;
  function evaluator(_selector) {
    return document.querySelectorAll(_selector).length;
  }
  this.command = (cb) => this.api.execute(evaluator, [selector], cb);
};


text:
const assert = require('yeoman-assert');
const utils = require('../generators/utils');

describe('JHipster Utils', () => {
    describe('::getJavadoc', () => {
        describe('when passing a negative or nil increment', () => {
            it('returns the comment with no increment', () => {
                assert.textEqual(utils.getJavadoc('whatever', -42), '/**\n * whatever\n */');
                assert.textEqual(utils.getJavadoc('whatever', 0), '/**\n * whatever\n */');
            });
        });
        describe('when passing a positive increment', () => {
            it('returns the comment with the increment', () => {
                assert.textEqual(utils.getJavadoc('whatever', 1), ' /**\n  * whatever\n  */');
            });
        });
        describe('when passing a nil comment', () => {
            it('inserts an empty comment instead of failing', () => {
                assert.textEqual(utils.getJavadoc(null, 1), ' /**\n  * \n  */');
            });
        });
        describe('when passing a comment containing double quotes', () => {
            it('escapes the quotes', () => {
                assert.textEqual(utils.getJavadoc('Comment="KO"', 1), ' /**\n  * Comment=\\"KO\\"\n  */');
            });
        });
    });
    describe('::escapeRegExp', () => {
        describe('when the string is not a java class name', () => {
            it('converts string into proper java class name', () => {
                assert.textEqual(utils.classify('class name'), 'ClassName');
            });
        });
        describe('when the string is already a java class name', () => {
            it('will not convert the string', () => {
                assert.textEqual(utils.classify('ClassName'), 'ClassName');
            });
        });
    });
    describe('::copyObjectProps', () => {
        it('expects all the pairs (key, value) of the source to be in destination', () => {
            const src = { foo: 'foo', foo2: 'foo2' };
            const dst = { foo3: 'foo3' };
            utils.copyObjectProps(dst, src);
            assert.objectContent(dst, src);
        });
    });
    describe('::buildEnumFunction', () => {
        it('describes all the properties of the entity', () => {
            const packageName = 'com.package';
            const angularAppName = 'myApp';
            const clientRootFolder = 'root';
            const entity = { enumName: 'entityName', fieldValues: 'field1, field2' };
            const infos = utils.buildEnumInfo(entity, angularAppName, packageName, clientRootFolder);
            assert.objectContent(infos, { packageName, angularAppName, clientRootFolder: `${clientRootFolder}-` });
        });
    });
    describe('::deepFind function', () => {
        const jsonData = {
            foo11: 'foo11value',
            fooNested: { foo21: 'foo21value' },
            foo21: 'foo21value'
        };
        describe('the key is found in the object that is searched', () => {
            it('returns the value associated to the key', () => {
                const value = utils.deepFind(jsonData, 'foo21');
                assert.textEqual(value, 'foo21value');
            });
        });
        describe('the key is not found in the object that is searched', () => {
            it('returns undefined', () => {
                const value = utils.deepFind(jsonData, 'foo123');
                assert.textEqual(`${value}`, 'undefined');
            });
        });
    });
});


text:
ACCEPTED

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

#### Published in
Can. J. Bot. 57(7): 783 (1979)

#### Original name
Ramakrishnania Ramachar & Bhagyan., 1979

### Remarks
null