text:
namespace boost{
namespace intrusive{
namespace test{

static const std::size_t BucketSize = 8;

template<class ContainerDefiner>
struct test_unordered
{
   typedef typename ContainerDefiner::value_cont_type value_cont_type;

   static void test_all(value_cont_type& values);
   private:
   static void test_sort(value_cont_type& values);
   static void test_insert(value_cont_type& values, detail::true_);
   static void test_insert(value_cont_type& values, detail::false_);
   static void test_swap(value_cont_type& values);
   static void test_rehash(value_cont_type& values, detail::true_);
   static void test_rehash(value_cont_type& values, detail::false_);
   static void test_find(value_cont_type& values);
   static void test_impl();
   static void test_clone(value_cont_type& values);
};

template<class ContainerDefiner>
void test_unordered<ContainerDefiner>::test_all (value_cont_type& values)
{
   typedef typename ContainerDefiner::template container
      <>::type unordered_type;
   typedef typename unordered_type::bucket_traits bucket_traits;
   typedef typename unordered_type::bucket_ptr    bucket_ptr;
   {
      typename unordered_type::bucket_type buckets [BucketSize];
      unordered_type testset
         (bucket_traits(pointer_traits<bucket_ptr>::pointer_to(buckets[0]), BucketSize));
      testset.insert(values.begin(), values.end());
      test::test_container(testset);
      testset.clear();
      testset.insert(values.begin(), values.end());
      test::test_common_unordered_and_associative_container(testset, values);
      testset.clear();
      testset.insert(values.begin(), values.end());
      test::test_unordered_associative_container(testset, values);
      testset.clear();
      testset.insert(values.begin(), values.end());
      typedef detail::bool_<boost::intrusive::test::is_multikey_true
         <unordered_type>::value> select_t;
      test::test_maybe_unique_container(testset, values, select_t());
   }
   {
      value_cont_type vals(BucketSize);
      for (int i = 0; i < (int)BucketSize; ++i)
         (&vals[i])->value_ = i;
      typename unordered_type::bucket_type buckets [BucketSize];
      unordered_type testset(bucket_traits(
         pointer_traits<bucket_ptr>::pointer_to(buckets[0]), BucketSize));
      testset.insert(vals.begin(), vals.end());
      test::test_iterator_forward(testset);
   }
   test_sort(values);
   test_insert(values, detail::bool_<boost::intrusive::test::is_multikey_true<unordered_type>::value>());
   test_swap(values);
   test_rehash(values, detail::bool_<unordered_type::incremental>());
   test_find(values);
   test_impl();
   test_clone(values);
}

//test case due to an error in tree implementation:
template<class ContainerDefiner>
void test_unordered<ContainerDefiner>::test_impl()
{
   typedef typename ContainerDefiner::template container
      <>::type unordered_type;
   typedef typename unordered_type::bucket_traits bucket_traits;
   typedef typename unordered_type::bucket_ptr    bucket_ptr;

   value_cont_type values (5);
   for (int i = 0; i < 5; ++i)
      values[i].value_ = i;

   typename unordered_type::bucket_type buckets [BucketSize];
   unordered_type testset(bucket_traits(
      pointer_traits<bucket_ptr>::pointer_to(buckets[0]), BucketSize));

   for (int i = 0; i < 5; ++i)
      testset.insert (values[i]);

   testset.erase (testset.iterator_to (values[0]));
   testset.erase (testset.iterator_to (values[1]));
   testset.insert (values[1]);

   testset.erase (testset.iterator_to (values[2]));
   testset.erase (testset.iterator_to (values[3]));
}

//test: constructor, iterator, clear, reverse_iterator, front, back, size:
template<class ContainerDefiner>
void test_unordered<ContainerDefiner>::test_sort(value_cont_type& values)
{
   typedef typename ContainerDefiner::template container
      <>::type unordered_type;
   typedef typename unordered_type::bucket_traits bucket_traits;
   typedef typename unordered_type::bucket_ptr    bucket_ptr;

   typename unordered_type::bucket_type buckets [BucketSize];
   unordered_type testset1
      (values.begin(), values.end(), bucket_traits
         (pointer_traits<bucket_ptr>::pointer_to(buckets[0]), BucketSize));

   if(unordered_type::incremental){
      {  int init_values [] = { 4, 5, 1, 2, 2, 3 };
         TEST_INTRUSIVE_SEQUENCE_MAYBEUNIQUE( init_values, testset1 );  }
   }
   else{
      {  int init_values [] = { 1, 2, 2, 3, 4, 5 };
         TEST_INTRUSIVE_SEQUENCE_MAYBEUNIQUE( init_values, testset1 );  }
   }
   testset1.clear();
   BOOST_TEST (testset1.empty());
}

//test: insert, const_iterator, const_reverse_iterator, erase, iterator_to:
template<class ContainerDefiner>
void test_unordered<ContainerDefiner>::test_insert(value_cont_type& values, detail::false_) //not multikey
{

   typedef typename ContainerDefiner::template container
      <>::type unordered_set_type;
   typedef typename unordered_set_type::bucket_traits bucket_traits;
   typedef typename unordered_set_type::key_of_value  key_of_value;

   typename unordered_set_type::bucket_type buckets [BucketSize];
   unordered_set_type testset(bucket_traits(
      pointer_traits<typename unordered_set_type::bucket_ptr>::
         pointer_to(buckets[0]), BucketSize));
   testset.insert(&values[0] + 2, &values[0] + 5);

   typename unordered_set_type::insert_commit_data commit_data;
   BOOST_TEST ((!testset.insert_check(key_of_value()(values[2]), commit_data).second));
   BOOST_TEST (( testset.insert_check(key_of_value()(values[0]), commit_data).second));

   const unordered_set_type& const_testset = testset;
   if(unordered_set_type::incremental)
   {
      {  int init_values [] = { 4, 5, 1 };
         TEST_INTRUSIVE_SEQUENCE_MAYBEUNIQUE( init_values, const_testset );  }
      typename unordered_set_type::iterator i = testset.begin();
      BOOST_TEST (i->value_ == 4);

      i = testset.insert(values[0]).first;
      BOOST_TEST (&*i == &values[0]);

      i = testset.iterator_to (values[2]);
      BOOST_TEST (&*i == &values[2]);

      testset.erase (i);

      {  int init_values [] = { 5, 1, 3 };
         TEST_INTRUSIVE_SEQUENCE_MAYBEUNIQUE( init_values, const_testset );  }
   }
   else{
      {  int init_values [] = { 1, 4, 5 };
         TEST_INTRUSIVE_SEQUENCE_MAYBEUNIQUE( init_values, const_testset );  }
      typename unordered_set_type::iterator i = testset.begin();
      BOOST_TEST (i->value_ == 1);

      i = testset.insert(values[0]).first;
      BOOST_TEST (&*i == &values[0]);

      i = testset.iterator_to (values[2]);
      BOOST_TEST (&*i == &values[2]);

      testset.erase (i);

      {  int init_values [] = { 1, 3, 5 };
         TEST_INTRUSIVE_SEQUENCE_MAYBEUNIQUE( init_values, const_testset );  }
   }
}

template<class ContainerDefiner>
void test_unordered<ContainerDefiner>::test_insert(value_cont_type& values, detail::true_) //is multikey
{
   typedef typename ContainerDefiner::template container
      <>::type unordered_type;

   typedef typename unordered_type::bucket_traits bucket_traits;
   typedef typename unordered_type::bucket_ptr bucket_ptr;
   typedef typename unordered_type::iterator iterator;
   typedef typename unordered_type::key_type key_type;
   {
      typename unordered_type::bucket_type buckets [BucketSize];
      unordered_type testset(bucket_traits(
         pointer_traits<bucket_ptr>::pointer_to(buckets[0]), BucketSize));

      testset.insert(&values[0] + 2, &values[0] + 5);

      const unordered_type& const_testset = testset;

      if(unordered_type::incremental){
         {
            {  int init_values [] = { 4, 5, 1 };
               TEST_INTRUSIVE_SEQUENCE_MAYBEUNIQUE( init_values, const_testset );  }

            typename unordered_type::iterator i = testset.begin();
            BOOST_TEST (i->value_ == 4);

            i = testset.insert (values[0]);
            BOOST_TEST (&*i == &values[0]);

            i = testset.iterator_to (values[2]);
            BOOST_TEST (&*i == &values[2]);
            testset.erase(i);

            {  int init_values [] = { 5, 1, 3 };
               TEST_INTRUSIVE_SEQUENCE_MAYBEUNIQUE( init_values, const_testset );  }
            testset.clear();
            testset.insert(&values[0], &values[0] + values.size());

            {  int init_values [] = { 4, 5, 1, 2, 2, 3 };
               TEST_INTRUSIVE_SEQUENCE_MAYBEUNIQUE( init_values, const_testset );  }

            BOOST_TEST (testset.erase(key_type(1)) == 1);
            BOOST_TEST (testset.erase(key_type(2)) == 2);
            BOOST_TEST (testset.erase(key_type(3)) == 1);
            BOOST_TEST (testset.erase(key_type(4)) == 1);
            BOOST_TEST (testset.erase(key_type(5)) == 1);
            BOOST_TEST (testset.empty() == true);

            //Now with a single bucket
            typename unordered_type::bucket_type single_bucket[1];
            unordered_type testset2(bucket_traits(
               pointer_traits<bucket_ptr>::pointer_to(single_bucket[0]), 1));
            testset2.insert(&values[0], &values[0] + values.size());
            BOOST_TEST (testset2.erase(key_type(5)) == 1);
            BOOST_TEST (testset2.erase(key_type(2)) == 2);
            BOOST_TEST (testset2.erase(key_type(1)) == 1);
            BOOST_TEST (testset2.erase(key_type(4)) == 1);
            BOOST_TEST (testset2.erase(key_type(3)) == 1);
            BOOST_TEST (testset2.empty() == true);
         }
      }
      else{
         {
            {  int init_values [] = { 1, 4, 5 };
               TEST_INTRUSIVE_SEQUENCE_MAYBEUNIQUE( init_values, const_testset );  }

            typename unordered_type::iterator i = testset.begin();
            BOOST_TEST (i->value_ == 1);

            i = testset.insert (values[0]);
            BOOST_TEST (&*i == &values[0]);

            i = testset.iterator_to (values[2]);
            BOOST_TEST (&*i == &values[2]);
            testset.erase(i);

            {  int init_values [] = { 1, 3, 5 };
               TEST_INTRUSIVE_SEQUENCE_MAYBEUNIQUE( init_values, const_testset );  }
            testset.clear();
            testset.insert(&values[0], &values[0] + values.size());

            {  int init_values [] = { 1, 2, 2, 3, 4, 5 };
               TEST_INTRUSIVE_SEQUENCE_MAYBEUNIQUE( init_values, const_testset );  }

            BOOST_TEST (testset.erase(key_type(1)) == 1);
            BOOST_TEST (testset.erase(key_type(2)) == 2);
            BOOST_TEST (testset.erase(key_type(3)) == 1);
            BOOST_TEST (testset.erase(key_type(4)) == 1);
            BOOST_TEST (testset.erase(key_type(5)) == 1);
            BOOST_TEST (testset.empty() == true);

            //Now with a single bucket
            typename unordered_type::bucket_type single_bucket[1];
            unordered_type testset2(bucket_traits(
               pointer_traits<bucket_ptr>::pointer_to(single_bucket[0]), 1));
            testset2.insert(&values[0], &values[0] + values.size());
            BOOST_TEST (testset2.erase(key_type(5)) == 1);
            BOOST_TEST (testset2.erase(key_type(2)) == 2);
            BOOST_TEST (testset2.erase(key_type(1)) == 1);
            BOOST_TEST (testset2.erase(key_type(4)) == 1);
            BOOST_TEST (testset2.erase(key_type(3)) == 1);
            BOOST_TEST (testset2.empty() == true);
         }
      }
      {
         //Now erase just one per loop
         const int random_init[] = { 3, 2, 4, 1, 5, 2, 2 };
         const unsigned int random_size = sizeof(random_init)/sizeof(random_init[0]);
         typename unordered_type::bucket_type single_bucket[1];
         for(unsigned int i = 0, max = random_size; i != max; ++i){
            value_cont_type data (random_size);
            for (unsigned int j = 0; j < random_size; ++j)
               data[j].value_ = random_init[j];
            unordered_type testset_new(bucket_traits(
               pointer_traits<bucket_ptr>::pointer_to(single_bucket[0]), 1));
            testset_new.insert(&data[0], &data[0]+max);
            testset_new.erase(testset_new.iterator_to(data[i]));
            BOOST_TEST (testset_new.size() == (max -1));
         }
      }
   }
   {
      const unsigned int LoadFactor    = 3;
      const unsigned int NumIterations = BucketSize*LoadFactor;
      value_cont_type random_init(NumIterations);//Preserve memory
      value_cont_type set_tester;
      set_tester.reserve(NumIterations);

      //Initialize values
      for (unsigned int i = 0; i < NumIterations; ++i){
         random_init[i].value_ = i*2;//(i/LoadFactor)*LoadFactor;
      }

      typename unordered_type::bucket_type buckets [BucketSize];
      bucket_traits btraits(pointer_traits<bucket_ptr>::pointer_to(buckets[0]), BucketSize);

      for(unsigned int initial_pos = 0; initial_pos != (NumIterations+1); ++initial_pos){
         for(unsigned int final_pos = initial_pos; final_pos != (NumIterations+1); ++final_pos){

            //Create intrusive container inserting values
            unordered_type testset
               ( random_init.data()
               , random_init.data() + random_init.size()
               , btraits);

            BOOST_TEST (testset.size() == random_init.size());

            //Obtain the iterator range to erase
            iterator it_beg_pos = testset.begin();
            for(unsigned int it_beg_pos_num = 0; it_beg_pos_num != initial_pos; ++it_beg_pos_num){
               ++it_beg_pos;
            }
            iterator it_end_pos(it_beg_pos);
            for(unsigned int it_end_pos_num = 0; it_end_pos_num != (final_pos - initial_pos); ++it_end_pos_num){
               ++it_end_pos;
            }

            //Erase the same values in both the intrusive and original vector
            std::size_t erased_cnt = boost::intrusive::iterator_distance(it_beg_pos, it_end_pos);

            //Erase values from the intrusive container
            testset.erase(it_beg_pos, it_end_pos);

            BOOST_TEST (testset.size() == (random_init.size()-(final_pos - initial_pos)));

            //Now test...
            BOOST_TEST ((random_init.size() - erased_cnt) == testset.size());

            //Create an ordered copy of the intrusive container
            set_tester.insert(set_tester.end(), testset.begin(), testset.end());
            std::sort(set_tester.begin(), set_tester.end());
            {
               typename value_cont_type::iterator it = set_tester.begin(), itend = set_tester.end();
               typename value_cont_type::iterator random_init_it(random_init.begin());
               for( ; it != itend; ++it){
                  while(!random_init_it->is_linked())
                     ++random_init_it;
                  BOOST_TEST(*it == *random_init_it);
                  ++random_init_it;
               }
            }
            set_tester.clear();
         }
      }
   }
}

//test: insert (seq-version), swap, erase (seq-version), size:
template<class ContainerDefiner>
void test_unordered<ContainerDefiner>::test_swap(value_cont_type& values)
{
   typedef typename ContainerDefiner::template container
      <>::type unordered_type;

   typedef typename unordered_type::bucket_traits bucket_traits;
   typedef typename unordered_type::bucket_ptr    bucket_ptr;
   typename unordered_type::bucket_type buckets [BucketSize];

   typename unordered_type::bucket_type buckets2 [BucketSize];
   unordered_type testset1(&values[0], &values[0] + 2,
      bucket_traits(pointer_traits<bucket_ptr>::pointer_to(buckets[0]), BucketSize));
   unordered_type testset2(bucket_traits(
      pointer_traits<bucket_ptr>::pointer_to(buckets2[0]), BucketSize));

   testset2.insert (&values[0] + 2, &values[0] + 6);
   testset1.swap (testset2);

   if(unordered_type::incremental){
      {  int init_values [] = { 4, 5, 1, 2 };
         TEST_INTRUSIVE_SEQUENCE_MAYBEUNIQUE( init_values, testset1 );  }

      {  int init_values [] = { 2, 3 };
         TEST_INTRUSIVE_SEQUENCE_MAYBEUNIQUE( init_values, testset2 );  }
      testset1.erase (testset1.iterator_to(values[4]), testset1.end());
      BOOST_TEST (testset1.size() == 1);
      //  BOOST_TEST (&testset1.front() == &values[3]);
      BOOST_TEST (&*testset1.begin() == &values[2]);
   }
   else{
      {  int init_values [] = { 1, 2, 4, 5 };
         TEST_INTRUSIVE_SEQUENCE_MAYBEUNIQUE( init_values, testset1 );  }

      {  int init_values [] = { 2, 3 };
         TEST_INTRUSIVE_SEQUENCE_MAYBEUNIQUE( init_values, testset2 );  }
      testset1.erase (testset1.iterator_to(values[5]), testset1.end());
      BOOST_TEST (testset1.size() == 1);
      //  BOOST_TEST (&testset1.front() == &values[3]);
      BOOST_TEST (&*testset1.begin() == &values[3]);
   }
}

//test: rehash:

template<class ContainerDefiner>
void test_unordered<ContainerDefiner>::test_rehash(value_cont_type& values, detail::true_)
{
   typedef typename ContainerDefiner::template container
      <>::type unordered_type;

   typedef typename unordered_type::bucket_traits bucket_traits;
   typedef typename unordered_type::bucket_ptr bucket_ptr;
   //Build a uset
   typename unordered_type::bucket_type buckets1 [BucketSize];
   typename unordered_type::bucket_type buckets2 [BucketSize*2];
   unordered_type testset1(&values[0], &values[0] + values.size(),
      bucket_traits(pointer_traits<bucket_ptr>::
         pointer_to(buckets1[0]), BucketSize));
   //Test current state
   BOOST_TEST(testset1.split_count() == BucketSize/2);
   {  int init_values [] = { 4, 5, 1, 2, 2, 3 };
      TEST_INTRUSIVE_SEQUENCE_MAYBEUNIQUE( init_values, testset1 );  }
   //Incremental rehash step
   BOOST_TEST (testset1.incremental_rehash() == true);
   BOOST_TEST(testset1.split_count() == (BucketSize/2+1));
   {  int init_values [] = { 5, 1, 2, 2, 3, 4 };
      TEST_INTRUSIVE_SEQUENCE_MAYBEUNIQUE( init_values, testset1 );  }
   //Rest of incremental rehashes should lead to the same sequence
   for(std::size_t split_bucket = testset1.split_count(); split_bucket != BucketSize; ++split_bucket){
      BOOST_TEST (testset1.incremental_rehash() == true);
      BOOST_TEST(testset1.split_count() == (split_bucket+1));
      {  int init_values [] = { 1, 2, 2, 3, 4, 5 };
      TEST_INTRUSIVE_SEQUENCE_MAYBEUNIQUE( init_values, testset1 );  }
   }
   //This incremental rehash should fail because we've reached the end of the bucket array
   BOOST_TEST (testset1.incremental_rehash() == false);
   BOOST_TEST(testset1.split_count() == BucketSize);
   {  int init_values [] = { 1, 2, 2, 3, 4, 5 };
   TEST_INTRUSIVE_SEQUENCE_MAYBEUNIQUE( init_values, testset1 );  }

   //
   //Try incremental hashing specifying a new bucket traits pointing to the same array
   //
   //This incremental rehash should fail because the new size is not twice the original
   BOOST_TEST(testset1.incremental_rehash(bucket_traits(
      pointer_traits<bucket_ptr>::
                              pointer_to(buckets1[0]), BucketSize)) == false);
   BOOST_TEST(testset1.split_count() == BucketSize);
   {  int init_values [] = { 1, 2, 2, 3, 4, 5 };
   TEST_INTRUSIVE_SEQUENCE_MAYBEUNIQUE( init_values, testset1 );  }

   //
   //Try incremental hashing specifying a new bucket traits pointing to the same array
   //
   //This incremental rehash should fail because the new size is not twice the original
   BOOST_TEST(testset1.incremental_rehash(bucket_traits(
      pointer_traits<bucket_ptr>::
               pointer_to(buckets2[0]), BucketSize)) == false);
   BOOST_TEST(testset1.split_count() == BucketSize);
   {  int init_values [] = { 1, 2, 2, 3, 4, 5 };
   TEST_INTRUSIVE_SEQUENCE_MAYBEUNIQUE( init_values, testset1 );  }

   //This incremental rehash should success because the new size is twice the original
   //and split_count is the same as the old bucket count
   BOOST_TEST(testset1.incremental_rehash(bucket_traits(
      pointer_traits<bucket_ptr>::
                     pointer_to(buckets2[0]), BucketSize*2)) == true);
   BOOST_TEST(testset1.split_count() == BucketSize);
   {  int init_values [] = { 1, 2, 2, 3, 4, 5 };
   TEST_INTRUSIVE_SEQUENCE_MAYBEUNIQUE( init_values, testset1 );  }

   //This incremental rehash should also success because the new size is half the original
   //and split_count is the same as the new bucket count
   BOOST_TEST(testset1.incremental_rehash(bucket_traits(
      pointer_traits<bucket_ptr>::
                           pointer_to(buckets1[0]), BucketSize)) == true);
   BOOST_TEST(testset1.split_count() == BucketSize);
   {  int init_values [] = { 1, 2, 2, 3, 4, 5 };
   TEST_INTRUSIVE_SEQUENCE_MAYBEUNIQUE( init_values, testset1 );  }

   //Shrink rehash
   testset1.rehash(bucket_traits(
      pointer_traits<bucket_ptr>::
         pointer_to(buckets1[0]), 4));
   BOOST_TEST (testset1.incremental_rehash() == false);
   {  int init_values [] = { 4, 5, 1, 2, 2, 3 };
      TEST_INTRUSIVE_SEQUENCE_MAYBEUNIQUE( init_values, testset1 );  }

   //Shrink rehash again
   testset1.rehash(bucket_traits(
      pointer_traits<bucket_ptr>::
         pointer_to(buckets1[0]), 2));
   BOOST_TEST (testset1.incremental_rehash() == false);
   {  int init_values [] = { 2, 2, 4, 3, 5, 1 };
      TEST_INTRUSIVE_SEQUENCE_MAYBEUNIQUE( init_values, testset1 );  }

   //Growing rehash
   testset1.rehash(bucket_traits(
      pointer_traits<bucket_ptr>::
         pointer_to(buckets1[0]), BucketSize));

   //Full rehash (no effects)
   testset1.full_rehash();
   {  int init_values [] = { 1, 2, 2, 3, 4, 5 };
      TEST_INTRUSIVE_SEQUENCE_MAYBEUNIQUE( init_values, testset1 );  }

   //Incremental rehash shrinking
   //First incremental rehashes should lead to the same sequence
   for(std::size_t split_bucket = testset1.split_count(); split_bucket > 6; --split_bucket){
      BOOST_TEST (testset1.incremental_rehash(false) == true);
      BOOST_TEST(testset1.split_count() == (split_bucket-1));
      {  int init_values [] = { 1, 2, 2, 3, 4, 5 };
      TEST_INTRUSIVE_SEQUENCE_MAYBEUNIQUE( init_values, testset1 );  }
   }

   //Incremental rehash step
   BOOST_TEST (testset1.incremental_rehash(false) == true);
   BOOST_TEST(testset1.split_count() == (BucketSize/2+1));
   {  int init_values [] = { 5, 1, 2, 2, 3, 4 };
      TEST_INTRUSIVE_SEQUENCE_MAYBEUNIQUE( init_values, testset1 );  }

   //Incremental rehash step 2
   BOOST_TEST (testset1.incremental_rehash(false) == true);
   BOOST_TEST(testset1.split_count() == (BucketSize/2));
   {  int init_values [] = { 4, 5, 1, 2, 2, 3 };
      TEST_INTRUSIVE_SEQUENCE_MAYBEUNIQUE( init_values, testset1 );  }

   //This incremental rehash should fail because we've reached the half of the bucket array
   BOOST_TEST(testset1.incremental_rehash(false) == false);
   BOOST_TEST(testset1.split_count() == BucketSize/2);
   {  int init_values [] = { 4, 5, 1, 2, 2, 3 };
   TEST_INTRUSIVE_SEQUENCE_MAYBEUNIQUE( init_values, testset1 );  }
}
template<class ContainerDefiner>
void test_unordered<ContainerDefiner>::test_rehash(value_cont_type& values, detail::false_)
{
   typedef typename ContainerDefiner::template container
      <>::type unordered_type;

   typedef typename unordered_type::bucket_traits bucket_traits;
   typedef typename unordered_type::bucket_ptr    bucket_ptr;

   typename unordered_type::bucket_type buckets1 [BucketSize];
   typename unordered_type::bucket_type buckets2 [2];
   typename unordered_type::bucket_type buckets3 [BucketSize*2];

   unordered_type testset1(&values[0], &values[0] + 6, bucket_traits(
      pointer_traits<bucket_ptr>::
         pointer_to(buckets1[0]), BucketSize));
   {  int init_values [] = { 1, 2, 2, 3, 4, 5 };
      TEST_INTRUSIVE_SEQUENCE_MAYBEUNIQUE( init_values, testset1 );  }

   testset1.rehash(bucket_traits(
      pointer_traits<bucket_ptr>::pointer_to(buckets2[0]), 2));
   {  int init_values [] = { 4, 2, 2, 5, 3, 1 };
      TEST_INTRUSIVE_SEQUENCE_MAYBEUNIQUE( init_values, testset1 );  }

   testset1.rehash(bucket_traits(
      pointer_traits<bucket_ptr>::pointer_to(buckets3[0]), BucketSize*2));
   {  int init_values [] = { 1, 2, 2, 3, 4, 5 };
      TEST_INTRUSIVE_SEQUENCE_MAYBEUNIQUE( init_values, testset1 );  }

   //Now rehash reducing the buckets
   testset1.rehash(bucket_traits(
      pointer_traits<bucket_ptr>::pointer_to(buckets3[0]), 2));
   {  int init_values [] = { 4, 2, 2, 5, 3, 1 };
      TEST_INTRUSIVE_SEQUENCE_MAYBEUNIQUE( init_values, testset1 );  }

   //Now rehash increasing the buckets
   testset1.rehash(bucket_traits(
      pointer_traits<bucket_ptr>::pointer_to(buckets3[0]), BucketSize*2));
   {  int init_values [] = { 1, 2, 2, 3, 4, 5 };
      TEST_INTRUSIVE_SEQUENCE_MAYBEUNIQUE( init_values, testset1 );  }

   //Full rehash (no effects)
   testset1.full_rehash();
   {  int init_values [] = { 1, 2, 2, 3, 4, 5 };
      TEST_INTRUSIVE_SEQUENCE_MAYBEUNIQUE( init_values, testset1 );  }
}

//test: find, equal_range (lower_bound, upper_bound):
template<class ContainerDefiner>
void test_unordered<ContainerDefiner>::test_find(value_cont_type& values)
{
   typedef typename ContainerDefiner::template container
      <>::type unordered_type;
   typedef typename unordered_type::value_type value_type;

   typedef typename unordered_type::bucket_traits  bucket_traits;
   typedef typename unordered_type::bucket_ptr     bucket_ptr;
   typedef typename unordered_type::key_of_value   key_of_value;
   const bool is_multikey = boost::intrusive::test::is_multikey_true<unordered_type>::value;

   typename unordered_type::bucket_type buckets[BucketSize];
   unordered_type testset(values.begin(), values.end(), bucket_traits(
      pointer_traits<bucket_ptr>::pointer_to(buckets[0]), BucketSize));

   typedef typename unordered_type::iterator iterator;

   value_type cmp_val;
   cmp_val.value_ = 2;
   BOOST_TEST (testset.count(key_of_value()(cmp_val)) == (is_multikey ? 2 : 1));
   iterator i = testset.find (key_of_value()(cmp_val));
   BOOST_TEST (i->value_ == 2);
   if(is_multikey)
      BOOST_TEST ((++i)->value_ == 2);
   else
      BOOST_TEST ((++i)->value_ != 2);
   std::pair<iterator,iterator> range = testset.equal_range (key_of_value()(cmp_val));

   BOOST_TEST (range.first->value_ == 2);
   BOOST_TEST (range.second->value_ == 3);
   BOOST_TEST (boost::intrusive::iterator_distance (range.first, range.second) == (is_multikey ? 2 : 1));
   cmp_val.value_ = 7;
   BOOST_TEST (testset.find (key_of_value()(cmp_val)) == testset.end());
   BOOST_TEST (testset.count(key_of_value()(cmp_val)) == 0);
}

template<class ContainerDefiner>
void test_unordered<ContainerDefiner>::test_clone(value_cont_type& values)
{
   typedef typename ContainerDefiner::template container
      <>::type unordered_type;
   typedef typename unordered_type::value_type value_type;
   typedef std::multiset<value_type> std_multiset_t;

   typedef typename unordered_type::bucket_traits bucket_traits;
   typedef typename unordered_type::bucket_ptr    bucket_ptr;

   {
      //Test with equal bucket arrays
      typename unordered_type::bucket_type buckets1 [BucketSize];
      typename unordered_type::bucket_type buckets2 [BucketSize];
      unordered_type testset1 (values.begin(), values.end(), bucket_traits(
         pointer_traits<bucket_ptr>::pointer_to(buckets1[0]), BucketSize));
      unordered_type testset2 (bucket_traits(
         pointer_traits<bucket_ptr>::pointer_to(buckets2[0]), BucketSize));

      testset2.clone_from(testset1, test::new_cloner<value_type>(), test::delete_disposer<value_type>());
      BOOST_TEST(testset1 == testset2);
      //Ordering is not guarantee in the cloning so insert data in a set and test
      std_multiset_t src(testset1.begin(), testset1.end());
      std_multiset_t dst(testset2.begin(), testset2.end());
      BOOST_TEST (src.size() == dst.size() && std::equal(src.begin(), src.end(), dst.begin()));
      testset2.clear_and_dispose(test::delete_disposer<value_type>());
      BOOST_TEST (testset2.empty());

      testset2.clone_from(boost::move(testset1), test::new_nonconst_cloner<value_type>(), test::delete_disposer<value_type>());
      BOOST_TEST(testset1 == testset2);
      //Ordering is not guarantee in the cloning so insert data in a set and test
      std_multiset_t(testset1.begin(), testset1.end()).swap(src);
      std_multiset_t(testset2.begin(), testset2.end()).swap(dst);
      BOOST_TEST(src.size() == dst.size() && std::equal(src.begin(), src.end(), dst.begin()));
      testset2.clear_and_dispose(test::delete_disposer<value_type>());
      BOOST_TEST (testset2.empty());
   }
   {
      //Test with bigger source bucket arrays
      typename unordered_type::bucket_type buckets1 [BucketSize*2];
      typename unordered_type::bucket_type buckets2 [BucketSize];
      unordered_type testset1 (values.begin(), values.end(), bucket_traits(
         pointer_traits<bucket_ptr>::pointer_to(buckets1[0]), BucketSize*2));
      unordered_type testset2 (bucket_traits(
         pointer_traits<bucket_ptr>::pointer_to(buckets2[0]), BucketSize));

      testset2.clone_from(testset1, test::new_cloner<value_type>(), test::delete_disposer<value_type>());
      BOOST_TEST(testset1 == testset2);
      //Ordering is not guarantee in the cloning so insert data in a set and test
      std_multiset_t src(testset1.begin(), testset1.end());
      std_multiset_t dst(testset2.begin(), testset2.end());
      BOOST_TEST (src.size() == dst.size() && std::equal(src.begin(), src.end(), dst.begin()));
      testset2.clear_and_dispose(test::delete_disposer<value_type>());
      BOOST_TEST (testset2.empty());

      testset2.clone_from(boost::move(testset1), test::new_nonconst_cloner<value_type>(), test::delete_disposer<value_type>());
      BOOST_TEST(testset1 == testset2);
      //Ordering is not guarantee in the cloning so insert data in a set and test
      std_multiset_t(testset1.begin(), testset1.end()).swap(src);
      std_multiset_t(testset2.begin(), testset2.end()).swap(dst);
      BOOST_TEST (src.size() == dst.size() && std::equal(src.begin(), src.end(), dst.begin()));
      testset2.clear_and_dispose(test::delete_disposer<value_type>());
      BOOST_TEST (testset2.empty());
   }
   {
      //Test with smaller source bucket arrays
      typename unordered_type::bucket_type buckets1 [BucketSize];
      typename unordered_type::bucket_type buckets2 [BucketSize*2];
      unordered_type testset1 (values.begin(), values.end(), bucket_traits(
         pointer_traits<bucket_ptr>::pointer_to(buckets1[0]), BucketSize));
      unordered_type testset2 (bucket_traits(
         pointer_traits<bucket_ptr>::pointer_to(buckets2[0]), BucketSize*2));

      testset2.clone_from(testset1, test::new_cloner<value_type>(), test::delete_disposer<value_type>());
      BOOST_TEST(testset1 == testset2);
      //Ordering is not guaranteed in the cloning so insert data in a set and test
      std_multiset_t src(testset1.begin(), testset1.end());
      std_multiset_t dst(testset2.begin(), testset2.end());
      BOOST_TEST (src.size() == dst.size() && std::equal(src.begin(), src.end(), dst.begin()));
      testset2.clear_and_dispose(test::delete_disposer<value_type>());
      BOOST_TEST (testset2.empty());

      testset2.clone_from(boost::move(testset1), test::new_nonconst_cloner<value_type>(), test::delete_disposer<value_type>());
      BOOST_TEST(testset1 == testset2);
      //Ordering is not guaranteed in the cloning so insert data in a set and test
      std_multiset_t(testset1.begin(), testset1.end()).swap(src);
      std_multiset_t(testset2.begin(), testset2.end()).swap(dst);
      BOOST_TEST (src.size() == dst.size() && std::equal(src.begin(), src.end(), dst.begin()));
      testset2.clear_and_dispose(test::delete_disposer<value_type>());
      BOOST_TEST (testset2.empty());
   }
}

}  //namespace test{
}  //namespace intrusive{
}  //namespace boost{


text:
import http.client
import json
from sys import argv
import os

HOST_NAME = 'localhost:8080'
HEADER = {'Content-type': 'application/json'}

method = argv[1]
data = ""
url = ""
if method == 'put':
	data = '{"instances": '+ argv[3] +'}'
	url = '/v2/apps/' + argv[2]
else:
	f = open(argv[2]+'.json', 'r')
	data = json.load(f)
	data = json.dumps(data)
	url = '/v2/apps'

connect = http.client.HTTPConnection(HOST_NAME)
connect.request(method,url,data,HEADER)

response = connect.getresponse()
print(response.read().decode())
os.system("sudo ./servicerouter.py --marathon http://localhost:8080 --haproxy-config /etc/haproxy/haproxy.cfg")

redpajama_set_name: RedPajamaGithub


text:
module Console.Draw
  ( drawUI
  , attributes
  ) where

import Console.AppState
import GameState
import Console.MovesAdapter (Tile(..), labelBoardMoves, labelBoardPieces, viewBoard)

import Brick
  ( Widget
  , AttrMap
  , hBox
  , vBox
  , AttrMap
  , attrMap
  , str
  , fill
  , (<=>)
  , (<+>)
  )
import Brick.Widgets.Core
  ( vLimit
  , hLimit
  , joinBorders
  )
import Brick.Widgets.Border
  ( border
  , vBorder
  , hBorder
  , borderAttr
  , borderWithLabel
  , hBorderWithLabel
  )
import Brick.Util (fg)
import Control.Lens ((&), (^.))
import Data.List (intersperse)
import Graphics.Vty (brightBlack, defAttr)

-------------------------------------------------------------------------------

divBoard :: [a] -> [[a]]
divBoard [] = []
divBoard xs = splitAt 11 xs & \(x, y) -> x : divBoard y

drawBoard :: [Tile] -> Widget ()
drawBoard
  = vLimit 23     -- limit widget height
  . hLimit 45     -- limit widget width
  . joinBorders   -- Join the border glyphs where they meet
  . border        -- Put a border around the whole board
  . mkRows        -- transform list of rows widgets into single board widget
  . (map mkRow)   -- transform each row-list into a row widget
  . divBoard      -- turn list of tiles into list of row-lists
 where
  drawTile t = case t of
    Symbol c -> str [' ', c, ' ']
    Label c  -> str ['<', c, '>']
  mkRow  = hBox . intersperse vBorder . map drawTile
  mkRows = vBox . intersperse hBorder

attributes :: AttrMap
attributes =
  attrMap
    defAttr
    [ (borderAttr, fg brightBlack)
    ]

drawUI :: AppState -> [Widget Name]
drawUI a = [(boardWidget a <+> playersWidget a) <=> logWidget a]

playersWidget :: AppState -> Widget Name
playersWidget a = blackPlayerWidget a <=> whitePlayerWidget a

playerWidget
  :: (AppState -> Bool)
  -> String
  -> (AppState -> PlayerType)
  -> AppState
  -> Widget Name
playerWidget turnFunc playerLabel playerFunc a =
  hBox
  [ currentSymbol
  , str $ playerLabel ++ ": " ++ (playerFunc a & show)
  , str status
  ]
  where
    currentSymbol = str $ case turnFunc a of
      True -> " > "
      False -> "   "
    status = if not (turnFunc a) then "" else " - " ++ a ^. selectionStatus

whitePlayerWidget :: AppState -> Widget Name
whitePlayerWidget a = playerWidget (\a -> a ^. gameState . whiteTurn) "White" (\a -> a ^. gameOptions . whitePlayer) a

blackPlayerWidget :: AppState -> Widget Name
blackPlayerWidget a = playerWidget (\a -> a ^. gameState . whiteTurn & not) "Black" (\a -> a ^. gameOptions . blackPlayer) a

logWidget :: AppState -> Widget Name
logWidget a = (hBorderWithLabel $ str "Logs") <=> (vBox $ map str $ _logMessages a)

boardWidget :: AppState -> Widget Name
boardWidget a = case a ^. phase of
  ChoosePiece m -> a ^. gameState . board & (labelBoardPieces m) & drawBoard
  ChooseMove _ m -> a ^. gameState . board & (labelBoardMoves m) & drawBoard
  View m -> a ^. gameState . board & viewBoard & drawBoard
  _ -> str "Nothing to see here..."


text:
<?xml version="1.0" encoding="UTF-8"?>
<refentry xmlns="http://docbook.org/ns/docbook" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:svg="http://www.w3.org/2000/svg" xmlns:ns5="http://www.w3.org/1999/xhtml" xmlns:mml="http://www.w3.org/1998/Math/MathML" xmlns:db="http://docbook.org/ns/docbook" version="5.0-subset Scilab" xml:id="int_example">
	<refnamediv>
		<refname>Custom 'My step' Xcos block for MicroDAQ</refname>
		<refpurpose>This guide shows how to build custom Xcos block which can be used for code generation and host simulation mode</refpurpose>
	</refnamediv>

	<refsection id="Description_block_introduction">
		<para></para><emphasis role="bold">Defining block functionality</emphasis>

		<para>
			Before MicroDAQ Xcos block creation a requirements defining functionality and block interface has to be defined. Our new block will be described by the following properties:
			<simplelist type="inline">
				<member>name - describes block function, should be unique, created block macro will have provided name with prefix 'mdaq_'</member>
				<member>description - help for user, should provided (if needed) short description of block properties</member>
				<member>parameter name - names of block parameters which can be modified during Xcos diagram creation</member>
				<member>parameter size - size of block parameters</member>
				<member>parameter default value - default values of block parameters</member>
				<member>inputs - definition of block inputs</member>
				<member>outputs - definition of block outputs</member>
                <member>use_sim_script - defines how simulation mode will be performed (from C source or Scilab _sim.sci script)</member>
			</simplelist>

			<para> Our custom block will be named 'My_step', it has three parameters 'Step time', 'Initial value', 'Final value' and 'Terminate value'. All block parameters are scalars, and has default values:
			'Step time' - 1, 'Initial value' - 0, 'Final value' - 1, 'Terminate value' - 0. Block shall have one output port, output port size is 1. Block doesn't have input ports.</para>

			<para></para><emphasis role="bold">Custom 'Step' block step by step</emphasis>

			<simplelist type="inline">
				<member>Initialize MicroDAQ block structure with mdaqBlock() function</member>
				<programlisting role="example">
					<![CDATA[ block = mdaqBlock()
   // block  =
   //    name: "new_block"
   //    desc: "Set new_block parameters"
   //    param_name: [2x1 string]
   //    param_size: [2x1 constant]
   //    param_def_val: list
   //    in: 1
   //    out: 1
   //    use_sim_script: %T
   ]]>
				</programlisting>
				<member>
					<para>Set block properties:</para>
					<simplelist type="inline">
						<member>name - our block will have 'My_step', toolbox defines Step function (mdaq_step macro already defined), block name length is limited to 24 signs</member>
						<member>desc - if not provided 'new_block' in default description string will be replaced with block name</member>
						<member>param_name  - this parameter holds block parameters names, it should be provided as an array of strings. Provided names will be used in generated block C code</member>
						<member>param_size - our block will have four scalar parameters, have to be defined in the same order as 'param_name' </member>
						<member>param_def_val - default block parameters values are organized as a list and have to be defined in the same order as 'param_name' </member>
						<member>in - in case of our block we should provide an empty array - block doesn't have input ports</member>
						<member>out - our block will have one output port and its size will be 1 - scalar</member>
                        <member>use_sim_script - if false (%T - by default), our block will use compiled C source in simulation mode. It guarantees the same code on host (simulation mode) and target (code generation) side.
                        If parameter is set to true (%T) then (block.name)_sim.sci script will be executed during simulation mode.
                        </member>
						<programlisting role="example">
							<![CDATA[
	block.name = "My_step";
	block.param_name = ['Step time' 'Initial value' 'Final value' 'Terminate value'];
	block.param_size = [ 1 1 1 1 ];
	block.param_def_val(1) = 1; // 'Step time' default value
	block.param_def_val(2) = 0; // 'Initial value' default value
	block.param_def_val(3) = 1; // 'Final value' default value
	block.param_def_val(4) = 0; // 'Terminate value' default value
	block.in = []; // block doesnt'have input port
	block.out = [ 1 ]; // one output port - size 1
	block.use_sim_script = %T; // Use Scilab script instead of compiled C source in simulation mode
   ]]>
						</programlisting>

					</simplelist>

				</member>
				<para/>
				<member>Generate and add block to MicroDAQ User palette</member>
				<programlisting role="example">
					<![CDATA[ mdaqBlockAdd(block);    ]]>
				</programlisting>
				<para>This step will generate block C code. Also block macros defining block properties and block behaviour in simulation mode ()'_sim' postfix) are generated.
						Functions generate following files:
				</para>
				<simplelist type="inline">
					<member>mdaq_my_step.sci - defines block properties and block appearance </member>
					<member>mdaq_my_step_sim.sci - Scilab code which can be used in simulation mode (not for code generation)</member>
					<member>mdaq_my_step.c - C code containing DSP code used for code generation</member>

				</simplelist>
				<para> Generated C code file is compiled, resulting DSP library will be used to build DSP executable created from Xcos diagram containing 'My_step' block.</para>
				<member>Open for edit mdaq_my_step.c file</member>
				<member>Add your C code.
					<para>Generated C source code contains 'init', 'inout' and 'end' functions. Function 'init' is executed when model is loaded on target.
					This function can initialize peripherals, allocate resources for block etc. The 'inout' function contains code which will be executed on every model step.
					The 'end' function is executed when model execution is done or it is stopped with Xcos 'Stop' button</para>

					<programlisting role="example">
						<![CDATA[
					    if (get_scicos_time() > step_time)
							*y1 = final_value;
						else
							*y1 = initial_value;
												]]>
					</programlisting>
					<para>The code uses get_scicos_time() function to get current simulation time. Depending on step_time block parameter block output (*y1) is set to final_value or initial_value.</para>
					<para></para>
				</member>

				<member>Build modified C code. First parameter is for enable/disable debug compilation, second parameter is for setting up compilation on host machine (need a supported compiler):
					<para></para>
					<programlisting role="example">
						<![CDATA[
						mdaqBlockBuild(%F, %F);
						]]>
					</programlisting>
					<para>If errors found during compilation correct them and run mdaqBlockBuild() again.</para>
				</member>
				<member>Restart Scilab - in order to reload 'MicroDAQ User' palette MicroDAQ toolbox for Scilab has to be reloaded.</member>
				<member>Start Xcos and open palette browser and locate 'MicroDAQ User' block category.
					<para></para>
					<imagedata align="center" fileref="../images/my_step.png" valign="middle"/>
					<para/>
				</member>
				<member>Create Xcos diagram containing newly created 'My_step' Xcos block
					<para></para>
					<imagedata align="center" fileref="../images/my_step_test.png" valign="middle"/>
					<para/>
				</member>

				<member>Create 'Superblock' by selecting 'My_step', 'SIGNAL' and Scope block.</member>
				<member>Change model sample rate to 0.01 by editing 'Period' Clock block parameter. Set 'Initialisation Time' to 0</member>
				<member>Save model and build and load model by selecting Tools->MicroDAQ build and load model from Xcos menu</member>

				<member>
							Start model with Xcos 'Start' simulation button
					<imagedata align="center" fileref="../images/my_step_test_result.png" valign="middle"/>
					<para/>
				</member>

				<member>
					    Check different block parameters
				</member>

			</simplelist>

		</para>

		<emphasis role="bold">'My_step' block in simulation mode</emphasis>
        <para>
        If block.use_sim_script is set to false (%T - by default) then C source will be compiled to shared library which will be used in simulation mode. It guarantees the same code on host (simulation mode) and target (code generation) side.
        In order to use this option the external C compiler is required. List of supported compilers can be found at:
        <ulink url="https://help.scilab.org/doc/5.5.2/en_US/supported_compilers.html">https://help.scilab.org/doc/5.5.2/en_US/supported_compilers.html. </ulink>
        If compiler cannot be provided or user want to have different behaviour in simulation mode, the _sim.sci script can be used instead.
        </para>

		<para>
		Generated block files can be used to implement block code for standard simulation mode.
		In order to add code for simulation mode generated mdaq_my_step_sim.sci file needs to be edited. The mdaq_my_step_sim.sci
		file contains code which will be executed in simulation mode. Function mdaqBlockAdd() generates file which contains
		block parameters variables which has to be used to change block output.
		</para>

		<para>Generated mdaq_my_step.sci file: </para>
		<para></para>

		<programlisting role="example">
			<![CDATA[
// Generated with MicroDAQ toolbox ver: 1.1.
function block=mdaq_my_step_sim(block,flag)

    global %microdaq
    if %microdaq.dsp_loaded == %F then

        step_time = block.rpar(1);
        initial_value = block.rpar(2);
        final_value = block.rpar(3);
        terminate_value = block.rpar(4);
        select flag
        case -5 // Error
        case 0 // Derivative State Update
        case 1 // Output Update
        case 2 // State Update
        case 3 // OutputEventTiming
        case 4 // Initialization
        case 5 // Ending
        case 6 // Re-Initialisation
        case 9 // ZeroCrossing
        else // Unknown flag
            break
        end
    end
endfunction

	]]>
		</programlisting>

		<para>Similar to C source file we have to add Scilab code which will be performing 'step' function.</para>

		<simplelist type="inline">
			<member>Locate and open generated mdaq_my_step_sim.sci file</member>
			<member>
				<para>Add the following code to 'Output Update' case in generated mdaq_my_step_sim.sci file

					<para></para>

					<programlisting role="example">
						<![CDATA[
					    if scicos_time() > step_time then
							block.outptr(1) = final_value;
						else
							block.outptr(1) = initial_value;
						end
						 						]]>
					</programlisting>

				</para>
			</member>
			<member>In order to use modified code clear old mdaq_my_step_sim function:
				<para>
					<programlisting role="example">
						<![CDATA[ clear mdaq_my_step_sim;    ]]>
					</programlisting>
				</para>
			</member>
			<member>Compile modified file with:
				<para>
					<programlisting role="example">
						<![CDATA[ mdaqBlockBuild();    ]]>
					</programlisting>
				</para>
			</member>
			<member>Go back to Xcos and run simulation (don't generated DSP application)</member>
		</simplelist>

	</refsection>
</refentry>


text:
require_relative "../name.rb"

module RandomPerson
  module Names

    class EnglishPrefix < Name

      # @private
      Names = %w(Mr Dr Mrs Ms Miss )

      def initialize
        @names = Names
        @formats_ratiod = [ 0..47, 48..49, 50..70, 71..87, 88..99]
        @possibles = Hash[ @formats_ratiod.zip @names ]
        @on_execute = for_prefixes( 'Miss', 'Mr' )
        super
      end

    end
  end
end


text:
.class Lcom/google/common/primitives/Floats$FloatArrayAsList;
.super Ljava/util/AbstractList;
.source "Floats.java"

# interfaces
.implements Ljava/io/Serializable;
.implements Ljava/util/RandomAccess;

# annotations
.annotation build Lcom/google/common/annotations/GwtCompatible;
.end annotation

.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/google/common/primitives/Floats;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0xa
    name = "FloatArrayAsList"
.end annotation

.annotation system Ldalvik/annotation/Signature;
    value = {
        "Ljava/util/AbstractList",
        "<",
        "Ljava/lang/Float;",
        ">;",
        "Ljava/util/RandomAccess;",
        "Ljava/io/Serializable;"
    }
.end annotation

# static fields
.field private static final serialVersionUID:J

# instance fields
.field final array:[F

.field final end:I

.field final start:I

# direct methods
.method constructor <init>([F)V
    .locals 2
    .param p1, "array"    # [F

    .prologue
    .line 386
    const/4 v0, 0x0

    array-length v1, p1

    invoke-direct {p0, p1, v0, v1}, Lcom/google/common/primitives/Floats$FloatArrayAsList;-><init>([FII)V

    .line 387
    return-void
.end method

.method constructor <init>([FII)V
    .locals 0
    .param p1, "array"    # [F
    .param p2, "start"    # I
    .param p3, "end"    # I

    .prologue
    .line 389
    invoke-direct {p0}, Ljava/util/AbstractList;-><init>()V

    .line 390
    iput-object p1, p0, Lcom/google/common/primitives/Floats$FloatArrayAsList;->array:[F

    .line 391
    iput p2, p0, Lcom/google/common/primitives/Floats$FloatArrayAsList;->start:I

    .line 392
    iput p3, p0, Lcom/google/common/primitives/Floats$FloatArrayAsList;->end:I

    .line 393
    return-void
.end method

# virtual methods
.method public contains(Ljava/lang/Object;)Z
    .locals 4
    .param p1, "target"    # Ljava/lang/Object;

    .prologue
    .line 410
    instance-of v0, p1, Ljava/lang/Float;

    if-eqz v0, :cond_0

    iget-object v0, p0, Lcom/google/common/primitives/Floats$FloatArrayAsList;->array:[F

    check-cast p1, Ljava/lang/Float;

    .end local p1    # "target":Ljava/lang/Object;
    invoke-virtual {p1}, Ljava/lang/Float;->floatValue()F

    move-result v1

    iget v2, p0, Lcom/google/common/primitives/Floats$FloatArrayAsList;->start:I

    iget v3, p0, Lcom/google/common/primitives/Floats$FloatArrayAsList;->end:I

    # invokes: Lcom/google/common/primitives/Floats;->indexOf([FFII)I
    invoke-static {v0, v1, v2, v3}, Lcom/google/common/primitives/Floats;->access$000([FFII)I

    move-result v0

    const/4 v1, -0x1

    if-eq v0, v1, :cond_0

    const/4 v0, 0x1

    :goto_0
    return v0

    :cond_0
    const/4 v0, 0x0

    goto :goto_0
.end method

.method public equals(Ljava/lang/Object;)Z
    .locals 8
    .param p1, "object"    # Ljava/lang/Object;

    .prologue
    const/4 v3, 0x1

    const/4 v4, 0x0

    .line 453
    if-ne p1, p0, :cond_1

    .line 469
    :cond_0
    :goto_0
    return v3

    .line 456
    :cond_1
    instance-of v5, p1, Lcom/google/common/primitives/Floats$FloatArrayAsList;

    if-eqz v5, :cond_4

    move-object v2, p1

    .line 457
    check-cast v2, Lcom/google/common/primitives/Floats$FloatArrayAsList;

    .line 458
    .local v2, "that":Lcom/google/common/primitives/Floats$FloatArrayAsList;
    invoke-virtual {p0}, Lcom/google/common/primitives/Floats$FloatArrayAsList;->size()I

    move-result v1

    .line 459
    .local v1, "size":I
    invoke-virtual {v2}, Lcom/google/common/primitives/Floats$FloatArrayAsList;->size()I

    move-result v5

    if-eq v5, v1, :cond_2

    move v3, v4

    .line 460
    goto :goto_0

    .line 462
    :cond_2
    const/4 v0, 0x0

    .local v0, "i":I
    :goto_1
    if-ge v0, v1, :cond_0

    .line 463
    iget-object v5, p0, Lcom/google/common/primitives/Floats$FloatArrayAsList;->array:[F

    iget v6, p0, Lcom/google/common/primitives/Floats$FloatArrayAsList;->start:I

    add-int/2addr v6, v0

    aget v5, v5, v6

    iget-object v6, v2, Lcom/google/common/primitives/Floats$FloatArrayAsList;->array:[F

    iget v7, v2, Lcom/google/common/primitives/Floats$FloatArrayAsList;->start:I

    add-int/2addr v7, v0

    aget v6, v6, v7

    cmpl-float v5, v5, v6

    if-eqz v5, :cond_3

    move v3, v4

    .line 464
    goto :goto_0

    .line 462
    :cond_3
    add-int/lit8 v0, v0, 0x1

    goto :goto_1

    .line 469
    .end local v0    # "i":I
    .end local v1    # "size":I
    .end local v2    # "that":Lcom/google/common/primitives/Floats$FloatArrayAsList;
    :cond_4
    invoke-super {p0, p1}, Ljava/util/AbstractList;->equals(Ljava/lang/Object;)Z

    move-result v3

    goto :goto_0
.end method

.method public get(I)Ljava/lang/Float;
    .locals 2
    .param p1, "index"    # I

    .prologue
    .line 404
    invoke-virtual {p0}, Lcom/google/common/primitives/Floats$FloatArrayAsList;->size()I

    move-result v0

    invoke-static {p1, v0}, Lcom/google/common/base/Preconditions;->checkElementIndex(II)I

    .line 405
    iget-object v0, p0, Lcom/google/common/primitives/Floats$FloatArrayAsList;->array:[F

    iget v1, p0, Lcom/google/common/primitives/Floats$FloatArrayAsList;->start:I

    add-int/2addr v1, p1

    aget v0, v0, v1

    invoke-static {v0}, Ljava/lang/Float;->valueOf(F)Ljava/lang/Float;

    move-result-object v0

    return-object v0
.end method

.method public bridge synthetic get(I)Ljava/lang/Object;
    .locals 1
    .param p1, "x0"    # I

    .prologue
    .line 378
    invoke-virtual {p0, p1}, Lcom/google/common/primitives/Floats$FloatArrayAsList;->get(I)Ljava/lang/Float;

    move-result-object v0

    return-object v0
.end method

.method public hashCode()I
    .locals 4

    .prologue
    .line 473
    const/4 v1, 0x1

    .line 474
    .local v1, "result":I
    iget v0, p0, Lcom/google/common/primitives/Floats$FloatArrayAsList;->start:I

    .local v0, "i":I
    :goto_0
    iget v2, p0, Lcom/google/common/primitives/Floats$FloatArrayAsList;->end:I

    if-ge v0, v2, :cond_0

    .line 475
    mul-int/lit8 v2, v1, 0x1f

    iget-object v3, p0, Lcom/google/common/primitives/Floats$FloatArrayAsList;->array:[F

    aget v3, v3, v0

    invoke-static {v3}, Lcom/google/common/primitives/Floats;->hashCode(F)I

    move-result v3

    add-int v1, v2, v3

    .line 474
    add-int/lit8 v0, v0, 0x1

    goto :goto_0

    .line 477
    :cond_0
    return v1
.end method

.method public indexOf(Ljava/lang/Object;)I
    .locals 5
    .param p1, "target"    # Ljava/lang/Object;

    .prologue
    .line 416
    instance-of v1, p1, Ljava/lang/Float;

    if-eqz v1, :cond_0

    .line 417
    iget-object v1, p0, Lcom/google/common/primitives/Floats$FloatArrayAsList;->array:[F

    check-cast p1, Ljava/lang/Float;

    .end local p1    # "target":Ljava/lang/Object;
    invoke-virtual {p1}, Ljava/lang/Float;->floatValue()F

    move-result v2

    iget v3, p0, Lcom/google/common/primitives/Floats$FloatArrayAsList;->start:I

    iget v4, p0, Lcom/google/common/primitives/Floats$FloatArrayAsList;->end:I

    # invokes: Lcom/google/common/primitives/Floats;->indexOf([FFII)I
    invoke-static {v1, v2, v3, v4}, Lcom/google/common/primitives/Floats;->access$000([FFII)I

    move-result v0

    .line 418
    .local v0, "i":I
    if-ltz v0, :cond_0

    .line 419
    iget v1, p0, Lcom/google/common/primitives/Floats$FloatArrayAsList;->start:I

    sub-int v1, v0, v1

    .line 422
    .end local v0    # "i":I
    :goto_0
    return v1

    :cond_0
    const/4 v1, -0x1

    goto :goto_0
.end method

.method public isEmpty()Z
    .locals 1

    .prologue
    .line 400
    const/4 v0, 0x0

    return v0
.end method

.method public lastIndexOf(Ljava/lang/Object;)I
    .locals 5
    .param p1, "target"    # Ljava/lang/Object;

    .prologue
    .line 427
    instance-of v1, p1, Ljava/lang/Float;

    if-eqz v1, :cond_0

    .line 428
    iget-object v1, p0, Lcom/google/common/primitives/Floats$FloatArrayAsList;->array:[F

    check-cast p1, Ljava/lang/Float;

    .end local p1    # "target":Ljava/lang/Object;
    invoke-virtual {p1}, Ljava/lang/Float;->floatValue()F

    move-result v2

    iget v3, p0, Lcom/google/common/primitives/Floats$FloatArrayAsList;->start:I

    iget v4, p0, Lcom/google/common/primitives/Floats$FloatArrayAsList;->end:I

    # invokes: Lcom/google/common/primitives/Floats;->lastIndexOf([FFII)I
    invoke-static {v1, v2, v3, v4}, Lcom/google/common/primitives/Floats;->access$100([FFII)I

    move-result v0

    .line 429
    .local v0, "i":I
    if-ltz v0, :cond_0

    .line 430
    iget v1, p0, Lcom/google/common/primitives/Floats$FloatArrayAsList;->start:I

    sub-int v1, v0, v1

    .line 433
    .end local v0    # "i":I
    :goto_0
    return v1

    :cond_0
    const/4 v1, -0x1

    goto :goto_0
.end method

.method public set(ILjava/lang/Float;)Ljava/lang/Float;
    .locals 4
    .param p1, "index"    # I
    .param p2, "element"    # Ljava/lang/Float;

    .prologue
    .line 437
    invoke-virtual {p0}, Lcom/google/common/primitives/Floats$FloatArrayAsList;->size()I

    move-result v1

    invoke-static {p1, v1}, Lcom/google/common/base/Preconditions;->checkElementIndex(II)I

    .line 438
    iget-object v1, p0, Lcom/google/common/primitives/Floats$FloatArrayAsList;->array:[F

    iget v2, p0, Lcom/google/common/primitives/Floats$FloatArrayAsList;->start:I

    add-int/2addr v2, p1

    aget v0, v1, v2

    .line 439
    .local v0, "oldValue":F
    iget-object v1, p0, Lcom/google/common/primitives/Floats$FloatArrayAsList;->array:[F

    iget v2, p0, Lcom/google/common/primitives/Floats$FloatArrayAsList;->start:I

    add-int/2addr v2, p1

    invoke-virtual {p2}, Ljava/lang/Float;->floatValue()F

    move-result v3

    aput v3, v1, v2

    .line 440
    invoke-static {v0}, Ljava/lang/Float;->valueOf(F)Ljava/lang/Float;

    move-result-object v1

    return-object v1
.end method

.method public bridge synthetic set(ILjava/lang/Object;)Ljava/lang/Object;
    .locals 1
    .param p1, "x0"    # I
    .param p2, "x1"    # Ljava/lang/Object;

    .prologue
    .line 378
    check-cast p2, Ljava/lang/Float;

    .end local p2    # "x1":Ljava/lang/Object;
    invoke-virtual {p0, p1, p2}, Lcom/google/common/primitives/Floats$FloatArrayAsList;->set(ILjava/lang/Float;)Ljava/lang/Float;

    move-result-object v0

    return-object v0
.end method

.method public size()I
    .locals 2

    .prologue
    .line 396
    iget v0, p0, Lcom/google/common/primitives/Floats$FloatArrayAsList;->end:I

    iget v1, p0, Lcom/google/common/primitives/Floats$FloatArrayAsList;->start:I

    sub-int/2addr v0, v1

    return v0
.end method

.method public subList(II)Ljava/util/List;
    .locals 5
    .param p1, "fromIndex"    # I
    .param p2, "toIndex"    # I
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "(II)",
            "Ljava/util/List",
            "<",
            "Ljava/lang/Float;",
            ">;"
        }
    .end annotation

    .prologue
    .line 444
    invoke-virtual {p0}, Lcom/google/common/primitives/Floats$FloatArrayAsList;->size()I

    move-result v0

    .line 445
    .local v0, "size":I
    invoke-static {p1, p2, v0}, Lcom/google/common/base/Preconditions;->checkPositionIndexes(III)V

    .line 446
    if-ne p1, p2, :cond_0

    .line 447
    invoke-static {}, Ljava/util/Collections;->emptyList()Ljava/util/List;

    move-result-object v1

    .line 449
    :goto_0
    return-object v1

    :cond_0
    new-instance v1, Lcom/google/common/primitives/Floats$FloatArrayAsList;

    iget-object v2, p0, Lcom/google/common/primitives/Floats$FloatArrayAsList;->array:[F

    iget v3, p0, Lcom/google/common/primitives/Floats$FloatArrayAsList;->start:I

    add-int/2addr v3, p1

    iget v4, p0, Lcom/google/common/primitives/Floats$FloatArrayAsList;->start:I

    add-int/2addr v4, p2

    invoke-direct {v1, v2, v3, v4}, Lcom/google/common/primitives/Floats$FloatArrayAsList;-><init>([FII)V

    goto :goto_0
.end method

.method toFloatArray()[F
    .locals 5

    .prologue
    .line 491
    invoke-virtual {p0}, Lcom/google/common/primitives/Floats$FloatArrayAsList;->size()I

    move-result v1

    .line 492
    .local v1, "size":I
    new-array v0, v1, [F

    .line 493
    .local v0, "result":[F
    iget-object v2, p0, Lcom/google/common/primitives/Floats$FloatArrayAsList;->array:[F

    iget v3, p0, Lcom/google/common/primitives/Floats$FloatArrayAsList;->start:I

    const/4 v4, 0x0

    invoke-static {v2, v3, v0, v4, v1}, Ljava/lang/System;->arraycopy(Ljava/lang/Object;ILjava/lang/Object;II)V

    .line 494
    return-object v0
.end method

.method public toString()Ljava/lang/String;
    .locals 5

    .prologue
    .line 481
    new-instance v0, Ljava/lang/StringBuilder;

    invoke-virtual {p0}, Lcom/google/common/primitives/Floats$FloatArrayAsList;->size()I

    move-result v2

    mul-int/lit8 v2, v2, 0xc

    invoke-direct {v0, v2}, Ljava/lang/StringBuilder;-><init>(I)V

    .line 482
    .local v0, "builder":Ljava/lang/StringBuilder;
    const/16 v2, 0x5b

    invoke-virtual {v0, v2}, Ljava/lang/StringBuilder;->append(C)Ljava/lang/StringBuilder;

    move-result-object v2

    iget-object v3, p0, Lcom/google/common/primitives/Floats$FloatArrayAsList;->array:[F

    iget v4, p0, Lcom/google/common/primitives/Floats$FloatArrayAsList;->start:I

    aget v3, v3, v4

    invoke-virtual {v2, v3}, Ljava/lang/StringBuilder;->append(F)Ljava/lang/StringBuilder;

    .line 483
    iget v2, p0, Lcom/google/common/primitives/Floats$FloatArrayAsList;->start:I

    add-int/lit8 v1, v2, 0x1

    .local v1, "i":I
    :goto_0
    iget v2, p0, Lcom/google/common/primitives/Floats$FloatArrayAsList;->end:I

    if-ge v1, v2, :cond_0

    .line 484
    const-string v2, ", "

    invoke-virtual {v0, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v2

    iget-object v3, p0, Lcom/google/common/primitives/Floats$FloatArrayAsList;->array:[F

    aget v3, v3, v1

    invoke-virtual {v2, v3}, Ljava/lang/StringBuilder;->append(F)Ljava/lang/StringBuilder;

    .line 483
    add-int/lit8 v1, v1, 0x1

    goto :goto_0

    .line 486
    :cond_0
    const/16 v2, 0x5d

    invoke-virtual {v0, v2}, Ljava/lang/StringBuilder;->append(C)Ljava/lang/StringBuilder;

    move-result-object v2

    invoke-virtual {v2}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v2

    return-object v2
.end method


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Lecidea rufococcinea Zenk.

### Remarks
null


text:
'use strict';
var printError = function(x) { console.log('\x1b[31mERROR: %s\x1b[0m', x);};
module.exports = printError;


text:
const authFilter = require('../auth-filter');
const jwtUtils = require('../../utils/jwt-utils');

jest.mock('../../utils/jwt-utils')

describe('auth-filter.js', () => {

  beforeEach(() => jest.clearAllMocks());

  test('Auth-filter returns 401 for requests without token in the header', () => {
    const req = { headers: {} };
    const res = {
      status: jest.fn(() => res),
      send: jest.fn(() => res)
    };
    const next = jest.fn();
    jwtUtils.decodeToken.mockReturnValue(null);

    authFilter(req, res, next);
    expect(res.status).toBeCalledWith(401);
    expect(res.send).toBeCalledTimes(1);
  });

  test('Auth-filter returns 401 for missing tokens in the header', () => {
    const req = { headers: { authorization: 'TOKEN' } };
    const res = {
      status: jest.fn(() => res),
      send: jest.fn(() => res)
    };
    const next = jest.fn();
    const UID = 1234;
    jwtUtils.decodeToken.mockReturnValue(UID);

    authFilter(req, res, next);
    expect(req.uid).toEqual(UID);
    expect(next).toBeCalledTimes(1);
  });

});


text:
package org.hisp.dhis.icon;

import java.util.Arrays;
import java.util.Collection;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;

/**
 * @author Kristian Wærstad
 */
@Service( "org.hisp.dhis.icon.IconService" )
public class DefaultIconService
    implements IconService
{
    private static final String ICON_PATH = "SVGs";

    private Map<String, IconData> icons = Arrays.stream( Icon.values() )
        .map( Icon::getVariants )
        .flatMap( Collection::stream )
        .collect( Collectors.toMap( IconData::getKey, Function.identity() ) );

    @Override
    public Collection<IconData> getIcons()
    {
        return icons.values();
    }

    @Override
    public Collection<IconData> getIcons( Collection<String> keywords )
    {
        return icons.values().stream()
            .filter( icon -> Arrays.asList( icon.getKeywords() ).containsAll( keywords ) )
            .collect( Collectors.toList() );
    }

    @Override
    public Optional<IconData> getIcon( String key )
    {
        return Optional.ofNullable( icons.get( key ) );
    }

    @Override
    public Optional<Resource> getIconResource( String key )
    {
        return Optional.ofNullable( new ClassPathResource( String.format( "%s/%s.%s", ICON_PATH, key, Icon.SUFFIX ) ) );
    }

    @Override
    public Collection<String> getKeywords()
    {
        return icons.values().stream()
            .map( IconData::getKeywords )
            .flatMap( Arrays::stream )
            .collect( Collectors.toSet() );
    }
}


text:
#region License

#endregion

using System.Collections.Generic;
using System.Threading.Tasks;
using Gremlin.Net.Driver;
using Gremlin.Net.Driver.Remote;
using static Gremlin.Net.Process.Traversal.AnonymousTraversalSource;
using Xunit;

namespace Gremlin.Net.IntegrationTest.Docs.Reference
{
    public class GremlinApplicationsTests
    {
        [Fact(Skip="No Server under localhost")]
        public async Task ConnectingViaDriversTest()
        {
// tag::connectingViaDrivers[]
// script
var gremlinServer = new GremlinServer("localhost", 8182);
using (var gremlinClient = new GremlinClient(gremlinServer))
{
    var bindings = new Dictionary<string, object>
    {
        {"name", "marko"}
    };

    var response =
        await gremlinClient.SubmitWithSingleResultAsync<object>("g.V().has('person','name',name).out('knows')",
            bindings);
}

// bytecode
using (var gremlinClient = new GremlinClient(new GremlinServer("localhost", 8182)))
{
    var g = Traversal().WithRemote(new DriverRemoteConnection(gremlinClient));
    var list = g.V().Has("person", "name", "marko").Out("knows").ToList();
}
// end::connectingViaDrivers[]
        }
    }
}


text:
package io.github.mzmine.gui.chartbasics.simplechart.providers.impl.series;

import io.github.mzmine.datamodel.Scan;
import io.github.mzmine.datamodel.featuredata.IonMobilogramTimeSeries;
import io.github.mzmine.datamodel.featuredata.IonTimeSeries;
import io.github.mzmine.datamodel.featuredata.impl.SummedIntensityMobilitySeries;
import io.github.mzmine.datamodel.features.Feature;
import io.github.mzmine.gui.chartbasics.simplechart.providers.PlotXYDataProvider;
import io.github.mzmine.main.MZmineCore;
import io.github.mzmine.taskcontrol.TaskStatus;
import io.github.mzmine.util.javafx.FxColorUtil;
import java.text.NumberFormat;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.scene.paint.Color;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

/**
 * Used to plot a {@link SummedIntensityMobilitySeries} in an XY chart.
 *
 * @author https://github.com/SteffenHeu
 */
public class SummedMobilogramXYProvider implements PlotXYDataProvider {

  private static NumberFormat mzFormat = MZmineCore.getConfiguration().getMZFormat();
  private final SummedIntensityMobilitySeries data;
  private final String seriesKey;
  private final ObjectProperty<Color> color;
  private final boolean swapAxes;

  public SummedMobilogramXYProvider(final Feature f) {
    this(f, false);
  }

  public SummedMobilogramXYProvider(final Feature f, boolean swapAxes) {
    IonTimeSeries<? extends Scan> series = f.getFeatureData();
    if (!(series instanceof IonMobilogramTimeSeries)) {
      throw new IllegalArgumentException(
          "Feature does not possess an IonMobilogramTimeSeries, cannot create mobilogram chart");
    }
    data = ((IonMobilogramTimeSeries) series).getSummedMobilogram();
    color = new SimpleObjectProperty<>(f.getRawDataFile().getColor());
    seriesKey = "m/z " + mzFormat.format(f.getMZ());
    this.swapAxes = swapAxes;
  }

  public SummedMobilogramXYProvider(SummedIntensityMobilitySeries summedMobilogram,
      ObjectProperty<Color> color, String seriesKey) {
    this(summedMobilogram, color, seriesKey, false);
  }

  public SummedMobilogramXYProvider(SummedIntensityMobilitySeries summedMobilogram,
      ObjectProperty<Color> color, String seriesKey, boolean swapAxes) {
    this.seriesKey = seriesKey;
    this.color = color;
    this.data = summedMobilogram;
    this.swapAxes = swapAxes;
  }

  @NotNull
  @Override
  public java.awt.Color getAWTColor() {
    return FxColorUtil.fxColorToAWT(color.get());
  }

  @NotNull
  @Override
  public javafx.scene.paint.Color getFXColor() {
    return color.get();
  }

  @Nullable
  @Override
  public String getLabel(int index) {
    return null;
  }

  @NotNull
  @Override
  public Comparable<?> getSeriesKey() {
    return seriesKey;
  }

  @Nullable
  @Override
  public String getToolTipText(int itemIndex) {
    return null;
  }

  @Override
  public void computeValues(SimpleObjectProperty<TaskStatus> status) {
    // no computation needed, all data is taken from the double buffers in the feature data.
  }

  @Override
  public double getDomainValue(int index) {
    if (swapAxes) {
      return data.getIntensity(index);
    }
    return data.getMobility(index);
  }

  @Override
  public double getRangeValue(int index) {
    if (swapAxes) {
      return data.getMobility(index);
    }
    return data.getIntensity(index);
  }

  @Override
  public int getValueCount() {
    return data.getNumberOfDataPoints();
  }

  @Override
  public double getComputationFinishedPercentage() {
    return 0;
  }
}


text:
require_relative '../command'
require_relative '../../app/util'

# up command. Like 'down' but the direction (set by DIRECTION) is different.
#
# NOTE: The down command  subclasses this, so beware when changing!
class Trepan::Command::UpCommand < Trepan::Command

  Trepan::Util.suppress_warnings {
    NAME        = File.basename(__FILE__, '.rb')
    HELP        = <<-HELP
**#{NAME}** [*count*]

Move the current frame up in the stack trace (to an older frame). 0 is
the most-recent frame. If no count is given, move up 1.

A negative number moves in the opposite direction.

See also:
---------

`down`, `frame`.
  HELP

    CATEGORY      = 'stack'
    MAX_ARGS      = 1  # Need at most this many
    NEED_STACK    = true
    SHORT_HELP    = 'Move frame in the direction of the caller of the last-selected frame'
  }

  require_relative '../../app/frame'
  include Trepan::Frame

  def complete(prefix)
    @proc.frame_complete(prefix, @direction)
  end

  def initialize(proc)
    super
    @direction = +1 # -1 for down.
  end

  # Run 'up' command.
  def run(args)

    # FIXME: move into @proc and test based on NEED_STACK.
    if not @proc.top_frame
      errmsg('No frames recorded.')
      return false
    end

    if args.size == 1
      # Form is: "down" which means "down 1"
      count = 1
    else
      low, high = @proc.frame_low_high(@direction)
      count_str = args[1]
      name_or_id = args[1]
      opts = {
        :msg_on_error =>
        "The '#{NAME}' command argument requires a frame number. Got: %s" % count_str,
        :min_value => low, :max_value => high
      }
      count = @proc.get_an_int(count_str, opts)
      return false unless count
    end
    @proc.adjust_frame(@direction * count, false)
  end
end

if __FILE__ == $0
  # Demo it.
  require 'thread_frame'
  require_relative '../mock'
  dbgr, cmd = MockDebugger::setup

  def sep ; puts '=' * 40 end
  cmd.run [cmd.name]
  %w(-1 0 1 -2).each do |count|
    puts "#{cmd.name} #{count}"
    cmd.run([cmd.name, count])
    sep
  end
  def foo(cmd, name)
    cmd.proc.frame_setup(RubyVM::Frame::current)
    puts "#{name}"
    cmd.run([name])
    sep
    %w(-2 -1).each do |count|
      puts "#{name} #{count}"
      cmd.run([name, count])
      sep
    end
  end
  foo(cmd, cmd.name)
end


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

feature "Credits Feature" do

  before do
    fake_login
    user.update_attribute :credits, 60
    @backers = [
      Factory(:backer, user: user, confirmed: true, can_refund: true, requested_refund: false, refunded: false, value: 10, created_at: 8.days.ago),
    ]
    user.reload

    click_link "Olá, #{user.display_name.split(' ').first}"
    verify_translations
    click_link 'Meus créditos'
    verify_translations
    current_path.should == user_path(user)

    within 'head title' do
      page.should have_content("#{user.display_name} · #{I18n.t('site.name')}")
    end
  end

  scenario "I have backs to refund but not enough credits" do
    user.stubs(:credits).returns(5)
    rows = all("#user_credits table tbody tr")
    # And now I try to request refund for the fourth row, but don't have enough credits
    within rows[0] do
      rows[0].find(".status").find('a').click
      verify_translations
      column = rows[0].all("td")[4]
      # Needed this sleep because have_content is not returning the right value and thus capybara does not know it has to way for the AJAX to finish
      sleep 1
      column.text.should == "Você não possui créditos suficientes para realizar este estorno."
    end
    click_on "OK"
    verify_translations
    find("#current_credits").should have_content(user.display_credits)
  end

  scenario "I have credits and backs to refund" do
    User.any_instance.stubs(:credits).returns(500)

    rows = all("#user_credits table tbody tr")
    rows.should have(1).items

    # Testing the content of the whole table
    rows.each do |row|
      columns = row.all("td")
      id = row[:id].split("_").last
      backer = @backers.first

      columns[0].find("a")[:href].should match(/\/projects\/#{backer.project.to_param}/)
      columns[1].text.should == I18n.l(backer.created_at.to_date)
      columns[2].text.should == backer.display_value
      columns[3].text.should == I18n.l(backer.refund_deadline.to_date)
      columns[4].text.should == "Solicitar estorno."
    end

    # Disabling javascript confirm, because we cannot test it with Capybara
    page.evaluate_script('window.confirm = function() { return true; }')

    # Requesting refund for the third row
    within rows[0] do
      rows[0].find(".status").find('a').click
      verify_translations
      column = rows[0].all("td")[4]
      # Needed this sleep because have_content is not returning the right value and thus capybara does not know it has to way for the AJAX to finish
      sleep 1
      column.text.should == "Pedido enviado com sucesso"
    end
    click_on "OK"
    verify_translations
  end
end


text:
package models

import (
	"fmt"

	"code.gitea.io/gitea/modules/setting"
	"code.gitea.io/gitea/modules/timeutil"
)

// RepoWatchMode specifies what kind of watch the user has on a repository
type RepoWatchMode int8

const (
	// RepoWatchModeNone don't watch
	RepoWatchModeNone RepoWatchMode = iota // 0
	// RepoWatchModeNormal watch repository (from other sources)
	RepoWatchModeNormal // 1
	// RepoWatchModeDont explicit don't auto-watch
	RepoWatchModeDont // 2
	// RepoWatchModeAuto watch repository (from AutoWatchOnChanges)
	RepoWatchModeAuto // 3
)

// Watch is connection request for receiving repository notification.
type Watch struct {
	ID          int64              `xorm:"pk autoincr"`
	UserID      int64              `xorm:"UNIQUE(watch)"`
	RepoID      int64              `xorm:"UNIQUE(watch)"`
	Mode        RepoWatchMode      `xorm:"SMALLINT NOT NULL DEFAULT 1"`
	CreatedUnix timeutil.TimeStamp `xorm:"INDEX created"`
	UpdatedUnix timeutil.TimeStamp `xorm:"INDEX updated"`
}

// getWatch gets what kind of subscription a user has on a given repository; returns dummy record if none found
func getWatch(e Engine, userID, repoID int64) (Watch, error) {
	watch := Watch{UserID: userID, RepoID: repoID}
	has, err := e.Get(&watch)
	if err != nil {
		return watch, err
	}
	if !has {
		watch.Mode = RepoWatchModeNone
	}
	return watch, nil
}

// Decodes watchability of RepoWatchMode
func isWatchMode(mode RepoWatchMode) bool {
	return mode != RepoWatchModeNone && mode != RepoWatchModeDont
}

// IsWatching checks if user has watched given repository.
func IsWatching(userID, repoID int64) bool {
	watch, err := getWatch(x, userID, repoID)
	return err == nil && isWatchMode(watch.Mode)
}

func watchRepoMode(e Engine, watch Watch, mode RepoWatchMode) (err error) {
	if watch.Mode == mode {
		return nil
	}
	if mode == RepoWatchModeAuto && (watch.Mode == RepoWatchModeDont || isWatchMode(watch.Mode)) {
		// Don't auto watch if already watching or deliberately not watching
		return nil
	}

	hadrec := watch.Mode != RepoWatchModeNone
	needsrec := mode != RepoWatchModeNone
	repodiff := 0

	if isWatchMode(mode) && !isWatchMode(watch.Mode) {
		repodiff = 1
	} else if !isWatchMode(mode) && isWatchMode(watch.Mode) {
		repodiff = -1
	}

	watch.Mode = mode

	if !hadrec && needsrec {
		watch.Mode = mode
		if _, err = e.Insert(watch); err != nil {
			return err
		}
	} else if needsrec {
		watch.Mode = mode
		if _, err := e.ID(watch.ID).AllCols().Update(watch); err != nil {
			return err
		}
	} else if _, err = e.Delete(Watch{ID: watch.ID}); err != nil {
		return err
	}
	if repodiff != 0 {
		_, err = e.Exec("UPDATE `repository` SET num_watches = num_watches + ? WHERE id = ?", repodiff, watch.RepoID)
	}
	return err
}

// WatchRepoMode watch repository in specific mode.
func WatchRepoMode(userID, repoID int64, mode RepoWatchMode) (err error) {
	var watch Watch
	if watch, err = getWatch(x, userID, repoID); err != nil {
		return err
	}
	return watchRepoMode(x, watch, mode)
}

func watchRepo(e Engine, userID, repoID int64, doWatch bool) (err error) {
	var watch Watch
	if watch, err = getWatch(e, userID, repoID); err != nil {
		return err
	}
	if !doWatch && watch.Mode == RepoWatchModeAuto {
		err = watchRepoMode(e, watch, RepoWatchModeDont)
	} else if !doWatch {
		err = watchRepoMode(e, watch, RepoWatchModeNone)
	} else {
		err = watchRepoMode(e, watch, RepoWatchModeNormal)
	}
	return err
}

// WatchRepo watch or unwatch repository.
func WatchRepo(userID, repoID int64, watch bool) (err error) {
	return watchRepo(x, userID, repoID, watch)
}

func getWatchers(e Engine, repoID int64) ([]*Watch, error) {
	watches := make([]*Watch, 0, 10)
	return watches, e.Where("`watch`.repo_id=?", repoID).
		And("`watch`.mode<>?", RepoWatchModeDont).
		And("`user`.is_active=?", true).
		And("`user`.prohibit_login=?", false).
		Join("INNER", "`user`", "`user`.id = `watch`.user_id").
		Find(&watches)
}

// GetWatchers returns all watchers of given repository.
func GetWatchers(repoID int64) ([]*Watch, error) {
	return getWatchers(x, repoID)
}

// GetRepoWatchersIDs returns IDs of watchers for a given repo ID
// but avoids joining with `user` for performance reasons
// User permissions must be verified elsewhere if required
func GetRepoWatchersIDs(repoID int64) ([]int64, error) {
	return getRepoWatchersIDs(x, repoID)
}

func getRepoWatchersIDs(e Engine, repoID int64) ([]int64, error) {
	ids := make([]int64, 0, 64)
	return ids, e.Table("watch").
		Where("watch.repo_id=?", repoID).
		And("watch.mode<>?", RepoWatchModeDont).
		Select("user_id").
		Find(&ids)
}

// GetWatchers returns range of users watching given repository.
func (repo *Repository) GetWatchers(opts ListOptions) ([]*User, error) {
	sess := x.Where("watch.repo_id=?", repo.ID).
		Join("LEFT", "watch", "`user`.id=`watch`.user_id").
		And("`watch`.mode<>?", RepoWatchModeDont)
	if opts.Page > 0 {
		sess = opts.setSessionPagination(sess)
		users := make([]*User, 0, opts.PageSize)

		return users, sess.Find(&users)
	}

	users := make([]*User, 0, 8)
	return users, sess.Find(&users)
}

func notifyWatchers(e Engine, actions ...*Action) error {
	var watchers []*Watch
	var repo *Repository
	var err error
	var permCode []bool
	var permIssue []bool
	var permPR []bool

	for _, act := range actions {
		repoChanged := repo == nil || repo.ID != act.RepoID

		if repoChanged {
			// Add feeds for user self and all watchers.
			watchers, err = getWatchers(e, act.RepoID)
			if err != nil {
				return fmt.Errorf("get watchers: %v", err)
			}
		}

		// Add feed for actioner.
		act.UserID = act.ActUserID
		if _, err = e.InsertOne(act); err != nil {
			return fmt.Errorf("insert new actioner: %v", err)
		}

		if repoChanged {
			act.loadRepo()
			repo = act.Repo

			// check repo owner exist.
			if err := act.Repo.getOwner(e); err != nil {
				return fmt.Errorf("can't get repo owner: %v", err)
			}
		} else if act.Repo == nil {
			act.Repo = repo
		}

		// Add feed for organization
		if act.Repo.Owner.IsOrganization() && act.ActUserID != act.Repo.Owner.ID {
			act.ID = 0
			act.UserID = act.Repo.Owner.ID
			if _, err = e.InsertOne(act); err != nil {
				return fmt.Errorf("insert new actioner: %v", err)
			}
		}

		if repoChanged {
			permCode = make([]bool, len(watchers))
			permIssue = make([]bool, len(watchers))
			permPR = make([]bool, len(watchers))
			for i, watcher := range watchers {
				user, err := getUserByID(e, watcher.UserID)
				if err != nil {
					permCode[i] = false
					permIssue[i] = false
					permPR[i] = false
					continue
				}
				perm, err := getUserRepoPermission(e, repo, user)
				if err != nil {
					permCode[i] = false
					permIssue[i] = false
					permPR[i] = false
					continue
				}
				permCode[i] = perm.CanRead(UnitTypeCode)
				permIssue[i] = perm.CanRead(UnitTypeIssues)
				permPR[i] = perm.CanRead(UnitTypePullRequests)
			}
		}

		for i, watcher := range watchers {
			if act.ActUserID == watcher.UserID {
				continue
			}
			act.ID = 0
			act.UserID = watcher.UserID
			act.Repo.Units = nil

			switch act.OpType {
			case ActionCommitRepo, ActionPushTag, ActionDeleteTag, ActionPublishRelease, ActionDeleteBranch:
				if !permCode[i] {
					continue
				}
			case ActionCreateIssue, ActionCommentIssue, ActionCloseIssue, ActionReopenIssue:
				if !permIssue[i] {
					continue
				}
			case ActionCreatePullRequest, ActionCommentPull, ActionMergePullRequest, ActionClosePullRequest, ActionReopenPullRequest:
				if !permPR[i] {
					continue
				}
			}

			if _, err = e.InsertOne(act); err != nil {
				return fmt.Errorf("insert new action: %v", err)
			}
		}
	}
	return nil
}

// NotifyWatchers creates batch of actions for every watcher.
func NotifyWatchers(actions ...*Action) error {
	return notifyWatchers(x, actions...)
}

// NotifyWatchersActions creates batch of actions for every watcher.
func NotifyWatchersActions(acts []*Action) error {
	sess := x.NewSession()
	defer sess.Close()
	if err := sess.Begin(); err != nil {
		return err
	}
	for _, act := range acts {
		if err := notifyWatchers(sess, act); err != nil {
			return err
		}
	}
	return sess.Commit()
}

func watchIfAuto(e Engine, userID, repoID int64, isWrite bool) error {
	if !isWrite || !setting.Service.AutoWatchOnChanges {
		return nil
	}
	watch, err := getWatch(e, userID, repoID)
	if err != nil {
		return err
	}
	if watch.Mode != RepoWatchModeNone {
		return nil
	}
	return watchRepoMode(e, watch, RepoWatchModeAuto)
}

// WatchIfAuto subscribes to repo if AutoWatchOnChanges is set
func WatchIfAuto(userID, repoID int64, isWrite bool) error {
	return watchIfAuto(x, userID, repoID, isWrite)
}


text:
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

package org.openqa.selenium;

import static org.assertj.core.api.Assertions.assertThat;
import static org.openqa.selenium.testing.drivers.Browser.IE;

import org.junit.Test;
import org.openqa.selenium.testing.Ignore;
import org.openqa.selenium.testing.JUnit4TestBase;

public class ErrorsTest extends JUnit4TestBase {

  /**
   * This will trivially pass on browsers that do not support the onerror handler (e.g. Internet
   * Explorer).
   */
  @Test
  @Ignore(value = IE, reason = "IE does not support onerror")
  public void testShouldNotGenerateErrorsWhenOpeningANewPage() {
    driver.get(pages.errorsPage);
    Object result = ((JavascriptExecutor) driver).
        executeScript("return window.ERRORS.join('\\n');");
    assertThat(result).isEqualTo("");
  }
}


text:
package me.yndy.basic.util;

import java.io.IOException;
import java.io.StringWriter;

import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

public class JsonJacksonUtil {
	private final static JsonJacksonUtil util = new JsonJacksonUtil();
	private final static JsonFactory factory = new JsonFactory();

	public static JsonJacksonUtil getInstance() {
		return util;
	}

	public String obj2json(Object obj) {
		//通过jsonFactory创建JsonGenerator,要传入相应的输出流
		StringWriter out = new StringWriter();
		JsonGenerator jg = null;
		try {
			jg = factory.createJsonGenerator(out);
			//创建对象mapper
			ObjectMapper mapper = new ObjectMapper();
			mapper.writeValue(jg, obj);
		} catch (IOException e) {
			e.printStackTrace();
		} finally{
			try {
				if(jg!=null) jg.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return out.getBuffer().toString();
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public Object json2obj(String json,Class clazz) {
		ObjectMapper mapper = new ObjectMapper();
		Object o = null;
		try {
			o = mapper.readValue(json, clazz);
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return o;
	}
}


text:
module M (module Mod171_A, h) where

import Mod171_A -- This isn't unused...
import Mod171_B -- even though this imports all the same stuff

h :: Int -> Int
h = g


text:
module Pageflow
  module Editor
    # @api private
    module FilesHelper
      include Pageflow::FilesHelper
      include AudioFilesHelper
      include VideoFilesHelper
      include RenderJsonHelper

      def editor_files_json_seed(entry)
        inner = Pageflow.config.file_types.map { |file_type|
          json = render_json_partial(partial: 'pageflow/editor/files/file',
                                     collection: entry.find_files(file_type.model),
                                     locals: {file_type: file_type},
                                     as: :file)

          %("#{file_type.collection_name}": #{json})
        }.join(',')

        "{#{inner}}".html_safe
      end
    end
  end
end


text:
package org.ietf.jgss;

/**
 *
This is a utility class used within the per-message {@link
 * GSSContext} methods to convey per-message properties.

 *
 *
When used with the GSSContext interface's {@link
 * GSSContext#wrap(byte[],int,int,org.ietf.jgss.MessageProp)} and {@link
 * GSSContext#getMIC(byte[],int,int,org.ietf.jgss.MessageProp)} methods, an
 * instance of this class is used to indicate the desired QOP and to
 * request if confidentiality services are to be applied to caller
 * supplied data (wrap only).  To request default QOP, the value of 0
 * should be used for QOP.

 *
 *
When used with the {@link
 * GSSContext#unwrap(byte[],int,int,org.ietf.jgss.MessageProp)} and {@link
 * GSSContext#verifyMIC(byte[],int,int,byte[],int,int,org.ietf.jgss.MessageProp)}
 * methods of the GSSContext interface, an instance of this class will be
 * used to indicate the applied QOP and confidentiality services over the
 * supplied message. In the case of verifyMIC, the confidentiality state
 * will always be "false".  Upon return from these methods, this object will
 * also contain any supplementary status values applicable to the processed
 * token.  The supplementary status values can indicate old tokens, out
 * of sequence tokens, gap tokens or duplicate tokens.

 */
public class MessageProp
{

  // Fields.
  // -------------------------------------------------------------------------

  private int qopVal;
  private boolean privState;
  private boolean duplicate;
  private boolean old;
  private boolean unseq;
  private boolean gap;
  private int minorStatus;
  private String minorString;

  // Constructors.
  // -------------------------------------------------------------------------

  /**
   *
Constructor which sets QOP to 0 indicating that the default QOP is
   * requested.

   *
   * @param privState The desired privacy state. "true" for privacy and
   *                  "false" for integrity only.
   */
  public MessageProp(boolean privState)
  {
    this(0, privState);
  }

  /**
   *
Constructor which sets the values for the qop and privacy state.

   *
   * @param qop       The desired QOP.  Use 0 to request a default QOP.
   * @param privState The desired privacy state. "true" for privacy and
   *                  "false" for integrity only.
   */
  public MessageProp(int qop, boolean privState)
  {
    this.qopVal = qop;
    this.privState = privState;
  }

  // Instance methods.
  // -------------------------------------------------------------------------

  /**
   * Retrieves the QOP value.
   *
   * @return The QOP value.
   */
  public int getQOP()
  {
    return qopVal;
  }

  /**
   * Retrieves the privacy state.
   *
   * @return The privacy state.
   */
  public boolean getPrivacy()
  {
    return privState;
  }

  /**
   * Retrieves the minor status that the underlying mechanism might have
   * set.
   *
   * @return The minor status.
   */
  public int getMinorStatus()
  {
    return minorStatus;
  }

  /**
   * Returns a string explaining the mechanism specific error code.
   * null will be returned when no mechanism error code has
   * been set.
   *
   * @return The minor status string.
   */
  public String getMinorString()
  {
    return minorString;
  }

  /**
   * Sets the QOP value.
   *
   * @param qopVal The QOP value to be set.  Use 0 to request a default
   *               QOP value.
   */
  public void setQOP(int qopVal)
  {
    this.qopVal = qopVal;
  }

  /**
   * Sets the privacy state.
   *
   * @param privState The privacy state to set.
   */
  public void setPrivacy(boolean privState)
  {
    this.privState = privState;
  }

  /**
   * Returns "true" if this is a duplicate of an earlier token.
   *
   * @return True if this is a duplicate of an earlier token.
   */
  public boolean isDuplicateToken()
  {
    return duplicate;
  }

  /**
   * Returns "true" if the token's validity period has expired.
   *
   * @return True if the token's validity period has expired.
   */
  public boolean isOldToken()
  {
    return old;
  }

  /**
   * Returns "true" if a later token has already been processed.
   *
   * @return True if a later token has already been processed.
   */
  public boolean isUnseqToken()
  {
    return unseq;
  }

  /**
   * Returns "true" if an expected per-message token was not received.
   *
   * @return True if an expected per-message token was not received.
   */
  public boolean isGapToken()
  {
    return gap;
  }

  /**
   * This method sets the state for the supplementary information flags
   * and the minor status in MessageProp.  It is not used by the
   * application but by the GSS implementation to return this information
   * to the caller of a per-message context method.
   *
   * @param duplicate   True if the token was a duplicate of an earlier
   *                    token, false otherwise.
   * @param old         True if the token's validity period has expired,
   *                    false otherwise.
   * @param unseq       True if a later token has already been processed,
   *                    false otherwise.
   * @param gap         True if one or more predecessor tokens have not yet
   *                    been successfully processed, false otherwise.
   * @param minorStatus The integer minor status code that the underlying
   *                    mechanism wants to set.
   * @param minorString The textual representation of the minorStatus
   *                    value.
   */
  public void setSupplementaryStates(boolean duplicate, boolean old,
                                     boolean unseq, boolean gap,
                                     int minorStatus, String minorString)
  {
    this.duplicate = duplicate;
    this.old = old;
    this.unseq = unseq;
    this.gap = gap;
    this.minorStatus = minorStatus;
    this.minorString = minorString;
  }
}


text:
  protected function getLanguage()
  {
    $this->language = $this->getDefaultLanguage();

    if (($this->getRequest()->isMethod(sfRequest::PUT) || $this->getRequest()->isMethod(sfRequest::POST)) && $this->getRequest()->getPostParameter('_language') != null)
    {
      $this->language = $this->getRequest()->getPostParameter('_language');
    }
    elseif ($this->getRequest()->getGetParameter('_language') != null)
    {
      $this->language = $this->getRequest()->getGetParameter('_language');
    }

    return $this->language;
  }

  protected function getDefaultLanguage()
  {
    return $this->configuration->getDefaultLanguage() !== false ? $this->configuration->getDefaultLanguage() : $this->getUser()->getCulture();
  }


text:
package org.apache.lucene.analysis.gl;

import java.io.IOException;
import java.io.Reader;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.BaseTokenStreamTestCase;
import org.apache.lucene.analysis.MockTokenizer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.Tokenizer;
import org.apache.lucene.analysis.core.KeywordTokenizer;
import org.apache.lucene.analysis.miscellaneous.SetKeywordMarkerFilter;
import org.apache.lucene.analysis.util.CharArraySet;

/**
 * Simple tests for {@link GalicianMinimalStemmer}
 */
public class TestGalicianMinimalStemFilter extends BaseTokenStreamTestCase {
  Analyzer a = new Analyzer() {
    @Override
    protected TokenStreamComponents createComponents(String fieldName, Reader reader) {
      Tokenizer tokenizer = new MockTokenizer(reader, MockTokenizer.WHITESPACE, false);
      return new TokenStreamComponents(tokenizer, new GalicianMinimalStemFilter(tokenizer));
    }
  };

  public void testPlural() throws Exception {
    checkOneTerm(a, "elefantes", "elefante");
    checkOneTerm(a, "elefante", "elefante");
    checkOneTerm(a, "kalóres", "kalór");
    checkOneTerm(a, "kalór", "kalór");
  }

  public void testExceptions() throws Exception {
    checkOneTerm(a, "mas", "mas");
    checkOneTerm(a, "barcelonês", "barcelonês");
  }

  public void testKeyword() throws IOException {
    final CharArraySet exclusionSet = new CharArraySet( asSet("elefantes"), false);
    Analyzer a = new Analyzer() {
      @Override
      protected TokenStreamComponents createComponents(String fieldName, Reader reader) {
        Tokenizer source = new MockTokenizer(reader, MockTokenizer.WHITESPACE, false);
        TokenStream sink = new SetKeywordMarkerFilter(source, exclusionSet);
        return new TokenStreamComponents(source, new GalicianMinimalStemFilter(sink));
      }
    };
    checkOneTerm(a, "elefantes", "elefantes");
  }

  /** blast some random strings through the analyzer */
  public void testRandomStrings() throws Exception {
    checkRandomData(random(), a, 1000*RANDOM_MULTIPLIER);
  }

  public void testEmptyTerm() throws IOException {
    Analyzer a = new Analyzer() {
      @Override
      protected TokenStreamComponents createComponents(String fieldName, Reader reader) {
        Tokenizer tokenizer = new KeywordTokenizer(reader);
        return new TokenStreamComponents(tokenizer, new GalicianMinimalStemFilter(tokenizer));
      }
    };
    checkOneTerm(a, "", "");
  }
}


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

package com.google.collide.client.testing;

import com.google.collide.client.collaboration.DocOpsSavedNotifier;

/**
 * Mock class for {@link DocOpsSavedNotifier}.
 *
 * <p>This will callback the client synchronously.
 */
public class MockDocOpsSavedNotifier extends DocOpsSavedNotifier {

  public MockDocOpsSavedNotifier() {
    super(null, null);
  }

  @Override
  public boolean notifyForWorkspace(Callback callback) {
    callback.onAllDocOpsSaved();
    return false;
  }

  @Override
  public boolean notifyForFiles(Callback callback, String... fileEditSessionKeys) {
    callback.onAllDocOpsSaved();
    return false;
  }

  @Override
  public boolean notifyForDocuments(Callback callback, int... documentIds) {
    callback.onAllDocOpsSaved();
    return false;
  }

}