text:
using Microsoft.Owin.Security;
using Moq;
using NUnit.Framework;
using SotnWiki.Auth.Contracts;
using SotnWiki.MvcClient.Controllers;
using System;

namespace SotnWiki.MvcClient.Tests.AccountControllerTests
{
    [TestFixture]
    public class ConstructorShould
    {
        [Test]
        public void ThrowArgumentNullException_WhenSignInServiceIsNull()
        {
            //Arrange
            var mockedSignInService = new Mock<ISignInService>();
            var mockedAuthenticationManager = new Mock<IAuthenticationManager>();
            string expectedExceptionMessage = "userService";

            //Act
            var exc = Assert.Throws<ArgumentNullException>(() => { new AccountController(mockedSignInService.Object, null, mockedAuthenticationManager.Object); });

            //Assert
            StringAssert.Contains(expectedExceptionMessage, exc.Message);
        }

        [Test]
        public void ThrowArgumentNullException_WhenUserServiceIsNull()
        {
            //Arrange
            var mockedUserService = new Mock<IUserService>();
            var mockedAuthenticationManager = new Mock<IAuthenticationManager>();
            string expectedExceptionMessage = "signInService";

            //Act
            var exc = Assert.Throws<ArgumentNullException>(() => { new AccountController(null, mockedUserService.Object, mockedAuthenticationManager.Object); });

            //Assert
            StringAssert.Contains(expectedExceptionMessage, exc.Message);
        }

        [Test]
        public void ThrowArgumentNullException_WhenAuthenticationManagerIsNull()
        {
            //Arrange
            var mockedUserService = new Mock<IUserService>();
            var mockedSignInService = new Mock<ISignInService>();
            string expectedExceptionMessage = "authenticationManager";

            //Act
            var exc = Assert.Throws<ArgumentNullException>(() => { new AccountController(mockedSignInService.Object, mockedUserService.Object, null); });

            //Assert
            StringAssert.Contains(expectedExceptionMessage, exc.Message);
        }

        [Test]
        public void ReturnsAnInstance_WhenParametersAreNotNull()
        {
            //Arrange
            var mockedUserService = new Mock<IUserService>();
            var mockedSignInService = new Mock<ISignInService>();
            var mockedAuthenticationManager = new Mock<IAuthenticationManager>();

            //Act
            var controllerUnderTest = new AccountController(mockedSignInService.Object, mockedUserService.Object, mockedAuthenticationManager.Object);

            //Assert
            Assert.IsNotNull(controllerUnderTest);
        }
    }
}


text:
#include <cstddef>                      // for size_t
#include <functional>                   // for bind, __bind, _1

#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>

#include <gmock/gmock-cardinalities.h>  // for AtLeast
#include <gmock/gmock-generated-function-mockers.h>  // for FunctionMocker, etc
#include <gmock/gmock-matchers.h>       // for AnythingMatcher, etc
#include <gmock/gmock-spec-builders.h>  // for EXPECT_CALL, etc
#include <gtest/gtest.h>                // for TEST_F, Test, Types, etc

#include <glm_ostream_operators.h>
#include <mathematical_model_matcher.h>
#include <ostream_point_operator.h>

#include <animation/geometry.h>
#include <animation/stepper/linear.h>
#include <animation/stepper/reverse.h>
#include <animation/magiclamp/magiclamp.h>

using ::testing::_;
using ::testing::AtLeast;
using ::testing::Eq;
using ::testing::Test;

namespace am = animation::matchers;
namespace aml = animation::magiclamp;
namespace as = animation::stepper;

namespace animation
{
    namespace matchers
    {
        template <>
        struct AlmostEqTrait <animation::Point>
        {
            typedef double ValueType;

            template <class Comparator>
            static bool apply (animation::Point const &lhs,
                               animation::Point const &rhs,
                               Comparator             &&comparator)
            {
                return comparator (agd::get <0> (lhs), agd::get <0> (rhs)) &&
                       comparator (agd::get <1> (lhs), agd::get <1> (rhs));
            }
        };
    }
}

namespace
{
    static animation::geometry::PointModel <size_t> const Resolution (4, 4);
    static double const BendFactor = 10;
    static double const OffsetFactor = 0.5;
    static double const StretchFactor = 0.45;
    static double const DeformationSpeedFactor = 2.3;

    TEST (MagicLampAnimation, AnimationIncompleteBeforeLengthTimesteps)
    {
        aml::MagicLampAnimation anim (animation::Box <animation::Point> (animation::Point (100, 100),
                                                                         animation::Point (150, 150)),
                                      animation::Box <animation::Point> (animation::Point (0, 0),
                                                                         animation::Point (100, 100)),
                                      Resolution,
                                      BendFactor,
                                      OffsetFactor,
                                      StretchFactor,
                                      DeformationSpeedFactor,
                                      as::Linear (200));

        EXPECT_TRUE (anim.Step (199));
    }

    TEST (MagicLampAnimation, AnimationCompleteAfterLengthTimesteps)
    {
        aml::MagicLampAnimation anim (animation::Box <animation::Point> (animation::Point (100, 100),
                                                                         animation::Point (150, 150)),
                                      animation::Box <animation::Point> (animation::Point (0, 0),
                                                                         animation::Point (100, 100)),
                                      Resolution,
                                      BendFactor,
                                      OffsetFactor,
                                      StretchFactor,
                                      DeformationSpeedFactor,
                                      as::Linear (200));

        EXPECT_FALSE (anim.Step (200));
    }

    TEST (MagicLampAnimation, StartsAtCorrectPosition)
    {
        aml::MagicLampAnimation anim (animation::Box <animation::Point> (animation::Point (100, 100),
                                                                         animation::Point (150, 150)),
                                      animation::Box <animation::Point> (animation::Point (0, 0),
                                                                         animation::Point (100, 100)),
                                      Resolution,
                                      BendFactor,
                                      OffsetFactor,
                                      StretchFactor,
                                      DeformationSpeedFactor,
                                      as::Linear (200));

        std::array <animation::Point, 4> corners = {{
            animation::Point (0, 0),
            animation::Point (100, 0),
            animation::Point (0, 100),
            animation::Point (100, 100)
        }};
        std::array <animation::Vector4D, 4> extremes = anim.Extremes (corners);

        EXPECT_THAT (extremes[0], am::Eq (animation::Vector4D (100, 100, 0, 1)));
        EXPECT_THAT (extremes[1], am::Eq (animation::Vector4D (150, 100, 0, 1)));
        EXPECT_THAT (extremes[2], am::Eq (animation::Vector4D (100, 150, 0, 1)));
        EXPECT_THAT (extremes[3], am::Eq (animation::Vector4D (150, 150, 0, 1)));
    }

    TEST (MagicLampAnimation, CorrectLinearInterpolatedVertexDeformation)
    {
        std::vector <animation::Point> clientGrid;
        clientGrid.reserve(128);

        double const x = 0;
        double const y = 0;
        double const width = 100;
        double const height = 100;

        double const iconX = 100;
        double const iconY = 100;
        double const iconWidth = 50;
        double const iconHeight = 50;

        aml::MagicLampAnimation anim (animation::Box <animation::Point> (animation::Point (iconX, iconY),
                                                                         animation::Point (iconX + iconWidth, iconY + iconHeight)),
                                      animation::Box <animation::Point> (animation::Point (x, y),
                                                                         animation::Point (width, height)),
                                      Resolution,
                                      BendFactor,
                                      OffsetFactor,
                                      StretchFactor,
                                      DeformationSpeedFactor,
                                      as::Linear (200));

        size_t const gridWidth = 4;
        size_t const gridHeight = 100;

        for (size_t i = 0; i < gridWidth; ++i)
        {
            for (size_t j = 0; j < gridHeight; ++j)
            {
                EXPECT_THAT (anim.DeformUVToModelSpace (animation::Point (i / static_cast <double> (gridWidth - 1),
                                                                          j / static_cast <double> (gridHeight - 1))),
                             am::AlmostEq (animation::Point (iconX + (iconWidth / (gridWidth - 1)) * i,
                                                             iconY + (iconHeight / (gridHeight - 1)) * j),
                                           0.002));
            }
        }
    }

    TEST (MagicLampAnimation, AnimatesToCorrectPositionAfterLengthTimesteps)
    {
        aml::MagicLampAnimation anim (animation::Box <animation::Point> (animation::Point (100, 100),
                                                                         animation::Point (150, 150)),
                                      animation::Box <animation::Point> (animation::Point (0, 0),
                                                                         animation::Point (100, 100)),
                                      Resolution,
                                      BendFactor,
                                      OffsetFactor,
                                      StretchFactor,
                                      DeformationSpeedFactor,
                                      as::Linear (200));
        anim.Step (200);

        std::array <animation::Point, 4> corners = {{
            animation::Point (0, 0),
            animation::Point (100, 0),
            animation::Point (0, 100),
            animation::Point (100, 100)
        }};
        std::array <animation::Vector4D, 4> extremes = anim.Extremes (corners);

        EXPECT_THAT (extremes[0], am::Eq (animation::Vector4D (0, 0, 0, 1)));
        EXPECT_THAT (extremes[1], am::Eq (animation::Vector4D (100, 0, 0, 1)));
        EXPECT_THAT (extremes[2], am::Eq (animation::Vector4D (0, 100, 0, 1)));
        EXPECT_THAT (extremes[3], am::Eq (animation::Vector4D (100, 100, 0, 1)));
    }

    TEST (MagicLampAnimation, AnimatesToCorrectPositionAfterLengthTimestepsReverse)
    {
        aml::MagicLampAnimation anim (animation::Box <animation::Point> (animation::Point (100, 100),
                                                                         animation::Point (150, 150)),
                                      animation::Box <animation::Point> (animation::Point (0, 0),
                                                                         animation::Point (100, 100)),
                                      Resolution,
                                      BendFactor,
                                      OffsetFactor,
                                      StretchFactor,
                                      DeformationSpeedFactor,
                                      as::Reverse (as::Linear (200)));
        anim.Step (200);

        std::array <animation::Point, 4> corners = {{
            animation::Point (0, 0),
            animation::Point (100, 0),
            animation::Point (0, 100),
            animation::Point (100, 100)
        }};
        std::array <animation::Vector4D, 4> extremes = anim.Extremes (corners);

        EXPECT_THAT (extremes[0], am::Eq (animation::Vector4D (100, 100, 0, 1)));
        EXPECT_THAT (extremes[1], am::Eq (animation::Vector4D (150, 100, 0, 1)));
        EXPECT_THAT (extremes[2], am::Eq (animation::Vector4D (100, 150, 0, 1)));
        EXPECT_THAT (extremes[3], am::Eq (animation::Vector4D (150, 150, 0, 1)));
    }
}

redpajama_set_name: RedPajamaGithub


text:
#include <mysql2_ext.h>

#ifdef HAVE_RUBY_ENCODING_H
rb_encoding *binaryEncoding;
#endif

VALUE cMysql2Result;
VALUE cBigDecimal, cDate, cDateTime;
VALUE opt_decimal_zero, opt_float_zero, opt_time_year, opt_time_month;
extern VALUE mMysql2, cMysql2Client, cMysql2Error;
static VALUE intern_encoding_from_charset;
static ID intern_new, intern_utc, intern_local, intern_encoding_from_charset_code,
          intern_localtime;
static ID sym_symbolize_keys, sym_as, sym_array, sym_database_timezone, sym_application_timezone,
          sym_local, sym_utc, sym_cast_booleans;
static ID intern_merge;

static void rb_mysql_result_mark(void * wrapper) {
  mysql2_result_wrapper * w = wrapper;
  if (w) {
    rb_gc_mark(w->fields);
    rb_gc_mark(w->rows);
  }
}

/* this may be called manually or during GC */
static void rb_mysql_result_free_result(mysql2_result_wrapper * wrapper) {
  if (wrapper && wrapper->resultFreed != 1) {
    mysql_free_result(wrapper->result);
    wrapper->resultFreed = 1;
  }
}

/* this is called during GC */
static void rb_mysql_result_free(void * wrapper) {
  mysql2_result_wrapper * w = wrapper;
  /* FIXME: this may call flush_use_result, which can hit the socket */
  rb_mysql_result_free_result(w);
  xfree(wrapper);
}

/*
 * for small results, this won't hit the network, but there's no
 * reliable way for us to tell this so we'll always release the GVL
 * to be safe
 */
static VALUE nogvl_fetch_row(void *ptr) {
  MYSQL_RES *result = ptr;

  return (VALUE)mysql_fetch_row(result);
}

static VALUE rb_mysql_result_fetch_field(VALUE self, unsigned int idx, short int symbolize_keys) {
  mysql2_result_wrapper * wrapper;

  GetMysql2Result(self, wrapper);

  if (wrapper->fields == Qnil) {
    wrapper->numberOfFields = mysql_num_fields(wrapper->result);
    wrapper->fields = rb_ary_new2(wrapper->numberOfFields);
  }

  VALUE rb_field = rb_ary_entry(wrapper->fields, idx);
  if (rb_field == Qnil) {
    MYSQL_FIELD *field = NULL;
#ifdef HAVE_RUBY_ENCODING_H
    rb_encoding *default_internal_enc = rb_default_internal_encoding();
    rb_encoding *conn_enc = rb_to_encoding(GET_ENCODING(self));
#endif

    field = mysql_fetch_field_direct(wrapper->result, idx);
    if (symbolize_keys) {
      char buf[field->name_length+1];
      memcpy(buf, field->name, field->name_length);
      buf[field->name_length] = 0;
      rb_field = ID2SYM(rb_intern(buf));
    } else {
      rb_field = rb_str_new(field->name, field->name_length);
#ifdef HAVE_RUBY_ENCODING_H
      rb_enc_associate(rb_field, conn_enc);
      if (default_internal_enc) {
        rb_field = rb_str_export_to_enc(rb_field, default_internal_enc);
      }
#endif
    }
    rb_ary_store(wrapper->fields, idx, rb_field);
  }

  return rb_field;
}

static VALUE rb_mysql_result_fetch_row(VALUE self, ID db_timezone, ID app_timezone, int symbolizeKeys, int asArray, int castBool) {
  VALUE rowVal;
  mysql2_result_wrapper * wrapper;
  MYSQL_ROW row;
  MYSQL_FIELD * fields = NULL;
  unsigned int i = 0;
  unsigned long * fieldLengths;
  void * ptr;
#ifdef HAVE_RUBY_ENCODING_H
  rb_encoding *default_internal_enc = rb_default_internal_encoding();
  rb_encoding *conn_enc = rb_to_encoding(GET_ENCODING(self));
#endif

  GetMysql2Result(self, wrapper);

  ptr = wrapper->result;
  row = (MYSQL_ROW)rb_thread_blocking_region(nogvl_fetch_row, ptr, RUBY_UBF_IO, 0);
  if (row == NULL) {
    return Qnil;
  }

  if (asArray) {
    rowVal = rb_ary_new2(wrapper->numberOfFields);
  } else {
    rowVal = rb_hash_new();
  }
  fields = mysql_fetch_fields(wrapper->result);
  fieldLengths = mysql_fetch_lengths(wrapper->result);
  if (wrapper->fields == Qnil) {
    wrapper->numberOfFields = mysql_num_fields(wrapper->result);
    wrapper->fields = rb_ary_new2(wrapper->numberOfFields);
  }

  for (i = 0; i < wrapper->numberOfFields; i++) {
    VALUE field = rb_mysql_result_fetch_field(self, i, symbolizeKeys);
    if (row[i]) {
      VALUE val;
      switch(fields[i].type) {
        case MYSQL_TYPE_NULL:       // NULL-type field
          val = Qnil;
          break;
        case MYSQL_TYPE_BIT:        // BIT field (MySQL 5.0.3 and up)
          val = rb_str_new(row[i], fieldLengths[i]);
          break;
        case MYSQL_TYPE_TINY:       // TINYINT field
          if (castBool && fields[i].length == 1) {
            val = *row[i] == '1' ? Qtrue : Qfalse;
            break;
          }
        case MYSQL_TYPE_SHORT:      // SMALLINT field
        case MYSQL_TYPE_LONG:       // INTEGER field
        case MYSQL_TYPE_INT24:      // MEDIUMINT field
        case MYSQL_TYPE_LONGLONG:   // BIGINT field
        case MYSQL_TYPE_YEAR:       // YEAR field
          val = rb_cstr2inum(row[i], 10);
          break;
        case MYSQL_TYPE_DECIMAL:    // DECIMAL or NUMERIC field
        case MYSQL_TYPE_NEWDECIMAL: // Precision math DECIMAL or NUMERIC field (MySQL 5.0.3 and up)
          if (strtod(row[i], NULL) == 0.000000){
            val = rb_funcall(cBigDecimal, intern_new, 1, opt_decimal_zero);
          }else{
            val = rb_funcall(cBigDecimal, intern_new, 1, rb_str_new(row[i], fieldLengths[i]));
          }
          break;
        case MYSQL_TYPE_FLOAT:      // FLOAT field
        case MYSQL_TYPE_DOUBLE: {     // DOUBLE or REAL field
          double column_to_double;
          column_to_double = strtod(row[i], NULL);
          if (column_to_double == 0.000000){
            val = opt_float_zero;
          }else{
            val = rb_float_new(column_to_double);
          }
          break;
        }
        case MYSQL_TYPE_TIME: {     // TIME field
          int hour, min, sec, tokens;
          tokens = sscanf(row[i], "%2d:%2d:%2d", &hour, &min, &sec);
          val = rb_funcall(rb_cTime, db_timezone, 6, opt_time_year, opt_time_month, opt_time_month, INT2NUM(hour), INT2NUM(min), INT2NUM(sec));
          if (!NIL_P(app_timezone)) {
            if (app_timezone == intern_local) {
              val = rb_funcall(val, intern_localtime, 0);
            } else { // utc
              val = rb_funcall(val, intern_utc, 0);
            }
          }
          break;
        }
        case MYSQL_TYPE_TIMESTAMP:  // TIMESTAMP field
        case MYSQL_TYPE_DATETIME: { // DATETIME field
          int year, month, day, hour, min, sec, tokens;
          tokens = sscanf(row[i], "%4d-%2d-%2d %2d:%2d:%2d", &year, &month, &day, &hour, &min, &sec);
          if (year+month+day+hour+min+sec == 0) {
            val = Qnil;
          } else {
            if (month < 1 || day < 1) {
              rb_raise(cMysql2Error, "Invalid date: %s", row[i]);
              val = Qnil;
            } else {
              val = rb_funcall(rb_cTime, db_timezone, 6, INT2NUM(year), INT2NUM(month), INT2NUM(day), INT2NUM(hour), INT2NUM(min), INT2NUM(sec));
              if (!NIL_P(app_timezone)) {
                if (app_timezone == intern_local) {
                  val = rb_funcall(val, intern_localtime, 0);
                } else { // utc
                  val = rb_funcall(val, intern_utc, 0);
                }
              }
            }
          }
          break;
        }
        case MYSQL_TYPE_DATE:       // DATE field
        case MYSQL_TYPE_NEWDATE: {  // Newer const used > 5.0
          int year, month, day, tokens;
          tokens = sscanf(row[i], "%4d-%2d-%2d", &year, &month, &day);
          if (year+month+day == 0) {
            val = Qnil;
          } else {
            if (month < 1 || day < 1) {
              rb_raise(cMysql2Error, "Invalid date: %s", row[i]);
              val = Qnil;
            } else {
              val = rb_funcall(cDate, intern_new, 3, INT2NUM(year), INT2NUM(month), INT2NUM(day));
            }
          }
          break;
        }
        case MYSQL_TYPE_TINY_BLOB:
        case MYSQL_TYPE_MEDIUM_BLOB:
        case MYSQL_TYPE_LONG_BLOB:
        case MYSQL_TYPE_BLOB:
        case MYSQL_TYPE_VAR_STRING:
        case MYSQL_TYPE_VARCHAR:
        case MYSQL_TYPE_STRING:     // CHAR or BINARY field
        case MYSQL_TYPE_SET:        // SET field
        case MYSQL_TYPE_ENUM:       // ENUM field
        case MYSQL_TYPE_GEOMETRY:   // Spatial fielda
        default:
          val = rb_str_new(row[i], fieldLengths[i]);
#ifdef HAVE_RUBY_ENCODING_H
          // if binary flag is set, respect it's wishes
          if (fields[i].flags & BINARY_FLAG) {
            rb_enc_associate(val, binaryEncoding);
          } else {
            // lookup the encoding configured on this field
            VALUE new_encoding = rb_funcall(cMysql2Client, intern_encoding_from_charset_code, 1, INT2NUM(fields[i].charsetnr));
            if (new_encoding != Qnil) {
              // use the field encoding we were able to match
              rb_encoding *enc = rb_to_encoding(new_encoding);
              rb_enc_associate(val, enc);
            } else {
              // otherwise fall-back to the connection's encoding
              rb_enc_associate(val, conn_enc);
            }
            if (default_internal_enc) {
              val = rb_str_export_to_enc(val, default_internal_enc);
            }
          }
#endif
          break;
      }
      if (asArray) {
        rb_ary_push(rowVal, val);
      } else {
        rb_hash_aset(rowVal, field, val);
      }
    } else {
      if (asArray) {
        rb_ary_push(rowVal, Qnil);
      } else {
        rb_hash_aset(rowVal, field, Qnil);
      }
    }
  }
  return rowVal;
}

static VALUE rb_mysql_result_fetch_fields(VALUE self) {
  mysql2_result_wrapper * wrapper;
  unsigned int i = 0;
  short int symbolizeKeys = 0;
  VALUE defaults;

  GetMysql2Result(self, wrapper);

  defaults = rb_iv_get(self, "@query_options");
  if (rb_hash_aref(defaults, sym_symbolize_keys) == Qtrue) {
    symbolizeKeys = 1;
  }

  if (wrapper->fields == Qnil) {
    wrapper->numberOfFields = mysql_num_fields(wrapper->result);
    wrapper->fields = rb_ary_new2(wrapper->numberOfFields);
  }

  if (RARRAY_LEN(wrapper->fields) != wrapper->numberOfFields) {
    for (i=0; i<wrapper->numberOfFields; i++) {
      rb_mysql_result_fetch_field(self, i, symbolizeKeys);
    }
  }

  return wrapper->fields;
}

static VALUE rb_mysql_result_each(int argc, VALUE * argv, VALUE self) {
  VALUE defaults, opts, block;
  ID db_timezone, app_timezone, dbTz, appTz;
  mysql2_result_wrapper * wrapper;
  unsigned long i;
  int symbolizeKeys = 0, asArray = 0, castBool = 0;

  GetMysql2Result(self, wrapper);

  defaults = rb_iv_get(self, "@query_options");
  if (rb_scan_args(argc, argv, "01&", &opts, &block) == 1) {
    opts = rb_funcall(defaults, intern_merge, 1, opts);
  } else {
    opts = defaults;
  }

  if (rb_hash_aref(opts, sym_symbolize_keys) == Qtrue) {
    symbolizeKeys = 1;
  }

  if (rb_hash_aref(opts, sym_as) == sym_array) {
    asArray = 1;
  }

  if (rb_hash_aref(opts, sym_cast_booleans) == Qtrue) {
    castBool = 1;
  }

  dbTz = rb_hash_aref(opts, sym_database_timezone);
  if (dbTz == sym_local) {
    db_timezone = intern_local;
  } else if (dbTz == sym_utc) {
    db_timezone = intern_utc;
  } else {
    if (!NIL_P(dbTz)) {
      rb_warn(":database_timezone option must be :utc or :local - defaulting to :local");
    }
    db_timezone = intern_local;
  }

  appTz = rb_hash_aref(opts, sym_application_timezone);
  if (appTz == sym_local) {
    app_timezone = intern_local;
  } else if (appTz == sym_utc) {
    app_timezone = intern_utc;
  } else {
    app_timezone = intern_local;
  }

  if (wrapper->lastRowProcessed == 0) {
    wrapper->numberOfRows = mysql_num_rows(wrapper->result);
    if (wrapper->numberOfRows == 0) {
      wrapper->rows = rb_ary_new();
      return wrapper->rows;
    }
    wrapper->rows = rb_ary_new2(wrapper->numberOfRows);
  }

  if (wrapper->lastRowProcessed == wrapper->numberOfRows) {
    // we've already read the entire dataset from the C result into our
    // internal array. Lets hand that over to the user since it's ready to go
    for (i = 0; i < wrapper->numberOfRows; i++) {
      rb_yield(rb_ary_entry(wrapper->rows, i));
    }
  } else {
    unsigned long rowsProcessed = 0;
    rowsProcessed = RARRAY_LEN(wrapper->rows);
    for (i = 0; i < wrapper->numberOfRows; i++) {
      VALUE row;
      if (i < rowsProcessed) {
        row = rb_ary_entry(wrapper->rows, i);
      } else {
        row = rb_mysql_result_fetch_row(self, db_timezone, app_timezone, symbolizeKeys, asArray, castBool);
        rb_ary_store(wrapper->rows, i, row);
        wrapper->lastRowProcessed++;
      }

      if (row == Qnil) {
        // we don't need the mysql C dataset around anymore, peace it
        rb_mysql_result_free_result(wrapper);
        return Qnil;
      }

      if (block != Qnil) {
        rb_yield(row);
      }
    }
    if (wrapper->lastRowProcessed == wrapper->numberOfRows) {
      // we don't need the mysql C dataset around anymore, peace it
      rb_mysql_result_free_result(wrapper);
    }
  }

  return wrapper->rows;
}

/* Mysql2::Result */
VALUE rb_mysql_result_to_obj(MYSQL_RES * r) {
  VALUE obj;
  mysql2_result_wrapper * wrapper;
  obj = Data_Make_Struct(cMysql2Result, mysql2_result_wrapper, rb_mysql_result_mark, rb_mysql_result_free, wrapper);
  wrapper->numberOfFields = 0;
  wrapper->numberOfRows = 0;
  wrapper->lastRowProcessed = 0;
  wrapper->resultFreed = 0;
  wrapper->result = r;
  wrapper->fields = Qnil;
  wrapper->rows = Qnil;
  rb_obj_call_init(obj, 0, NULL);
  return obj;
}

void init_mysql2_result() {
  cBigDecimal = rb_const_get(rb_cObject, rb_intern("BigDecimal"));
  cDate = rb_const_get(rb_cObject, rb_intern("Date"));
  cDateTime = rb_const_get(rb_cObject, rb_intern("DateTime"));

  cMysql2Result = rb_define_class_under(mMysql2, "Result", rb_cObject);
  rb_define_method(cMysql2Result, "each", rb_mysql_result_each, -1);
  rb_define_method(cMysql2Result, "fields", rb_mysql_result_fetch_fields, 0);

  intern_encoding_from_charset = rb_intern("encoding_from_charset");
  intern_encoding_from_charset_code = rb_intern("encoding_from_charset_code");

  intern_new        = rb_intern("new");
  intern_utc        = rb_intern("utc");
  intern_local      = rb_intern("local");
  intern_merge      = rb_intern("merge");
  intern_localtime  = rb_intern("localtime");

  sym_symbolize_keys  = ID2SYM(rb_intern("symbolize_keys"));
  sym_as              = ID2SYM(rb_intern("as"));
  sym_array           = ID2SYM(rb_intern("array"));
  sym_local           = ID2SYM(rb_intern("local"));
  sym_utc             = ID2SYM(rb_intern("utc"));
  sym_cast_booleans   = ID2SYM(rb_intern("cast_booleans"));
  sym_database_timezone     = ID2SYM(rb_intern("database_timezone"));
  sym_application_timezone  = ID2SYM(rb_intern("application_timezone"));

  rb_global_variable(&opt_decimal_zero); //never GC
  opt_decimal_zero = rb_str_new2("0.0");
  rb_global_variable(&opt_float_zero);
  opt_float_zero = rb_float_new((double)0);
  opt_time_year = INT2NUM(2000);
  opt_time_month = INT2NUM(1);

#ifdef HAVE_RUBY_ENCODING_H
  binaryEncoding = rb_enc_find("binary");
#endif
}


text:
describe('GGRC.Components.checkboxFormField', function () {
  'use strict';
  var viewModel;

  beforeEach(function () {
    viewModel = GGRC.Components
      .getViewModel('checkboxFormField');
    spyOn(viewModel, 'dispatch');
    viewModel.attr('fieldId', 'id');
  });

  it('does not fire valueChanged event on first value assignation', function () {
    viewModel.attr('value', true);
    expect(viewModel.dispatch).not.toHaveBeenCalled();
  });

  it('sets the value of the input', function () {
    viewModel.attr('value', true);
    expect(viewModel.attr('_value')).toEqual(true);
  });

  it('fires valueChanged event on input value change', function () {
    viewModel.attr('value', false);
    viewModel.attr('_value', true);
    expect(viewModel.dispatch).toHaveBeenCalledWith({
      type: 'valueChanged',
      fieldId: 'id',
      value: true
    });
    viewModel.attr('_value', false);
    expect(viewModel.dispatch).toHaveBeenCalledWith({
      type: 'valueChanged',
      fieldId: 'id',
      value: false
    });
  });
});


text:
using System.Threading;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
using Microsoft.CodeAnalysis.Editor.Implementation.AutomaticCompletion;
using Microsoft.VisualStudio.Text.BraceCompletion;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.Editor.CSharp.AutomaticCompletion.Sessions
{
    internal class InterpolatedStringCompletionSession : IEditorBraceCompletionSession
    {
        public InterpolatedStringCompletionSession()
        {
        }

        public void AfterReturn(IBraceCompletionSession session, CancellationToken cancellationToken)
        {
        }

        public void AfterStart(IBraceCompletionSession session, CancellationToken cancellationToken)
        {
        }

        public bool AllowOverType(IBraceCompletionSession session, CancellationToken cancellationToken)
        {
            return true;
        }

        public bool CheckOpeningPoint(IBraceCompletionSession session, CancellationToken cancellationToken)
        {
            var snapshot = session.SubjectBuffer.CurrentSnapshot;
            var position = session.OpeningPoint.GetPosition(snapshot);
            var token = snapshot.FindToken(position, cancellationToken);

            return token.IsKind(SyntaxKind.InterpolatedStringStartToken, SyntaxKind.InterpolatedVerbatimStringStartToken)
                && token.Span.End - 1 == position;
        }

        public static bool IsContext(Document document, int position, CancellationToken cancellationToken)
        {
            // Check to see if we're to the right of an $ or an @$
            var text = document.GetTextAsync(cancellationToken).WaitAndGetResult(cancellationToken);

            var start = position - 1;
            if (start < 0)
            {
                return false;
            }

            if (text[start] == '@')
            {
                start--;

                if (start < 0)
                {
                    return false;
                }
            }

            if (text[start] != '$')
            {
                return false;
            }

            var tree = document.GetSyntaxTreeAsync(cancellationToken).WaitAndGetResult(cancellationToken);
            var token = tree.GetRoot(cancellationToken).FindTokenOnLeftOfPosition(start);

            return tree.IsExpressionContext(start, token, attributes: false, cancellationToken: cancellationToken)
                || tree.IsStatementContext(start, token, cancellationToken);
        }
    }
}


text:
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://www.ehcache.org/ehcache.xsd" updateCheck="true">
    <diskStore path="java.io.tmpdir"/>

    <defaultCache
            maxEntriesLocalHeap="10000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            maxEntriesLocalDisk="10000000"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU">
    <persistence strategy="localTempSwap"/>
    </defaultCache>

    <cache name="user"
           maxElementsInMemory="180000"
           eternal="false"
           timeToIdleSeconds="80"
           timeToLiveSeconds="120">
        <persistence strategy="localTempSwap"/>
    </cache>

    <cache name="guild"
           maxElementsInMemory="180000"
           eternal="false"
           timeToIdleSeconds="80"
           timeToLiveSeconds="120">
        <persistence strategy="localTempSwap"/>
    </cache>

    <cache name="permission"
           maxElementsInMemory="180000"
           eternal="false"
           timeToIdleSeconds="80"
           timeToLiveSeconds="120">
        <persistence strategy="localTempSwap"/>
    </cache>

    <!-- Hibernate Caching -->

    <cache
            name="org.hibernate.cache.internal.StandardQueryCache"
            maxEntriesLocalHeap="5"
            eternal="false"
            timeToLiveSeconds="120">
        <persistence strategy="localTempSwap"/>
    </cache>

    <cache name="org.hibernate.cache.spi.UpdateTimestampsCache"
           maxEntriesLocalHeap="5000"
           eternal="true">
        <persistence strategy="localTempSwap"/>
    </cache>

</ehcache>


text:
wurstminestats
==============

Plotting the Wurstmineberg Minecraft Server

![Whitelist growth](http://i.wurstmineberg.de/wurstminestats/WhitelistGrowth.png)
![Play Time](http://i.wurstmineberg.de/wurstminestats/sessions/playedPerMonthYear.png)

## What this is
Primarily it's me playing around with [R](http://www.r-project.org).
Besides that, this is an addition to the [wurstmineberg](http://wurstminebger.de) player statistics page at our [stats page](http://wurstminebger.de/stats).

The public directory at [i.wurstmineberg.de/wurstminestats](http://i.wurstmineberg.de/wurstminestats/) is the place to go for up to date plots (hopefully).
For everything else, I'd like to build a [shiny](http://shiny.rstudio.com/) version of wurstminestats, which should serve as a more convenient place to scroll through the data. Also, interactive plot with actual text would be nice, but finding a plotting library for the web that's comparable to `ggplot2` is pretty hard. Yes, I know about `ggvis`. No, there's no feature parity yet.

## Deployment
The plots are now generated by executing `genAll.R`on wurstmineberg.de via the `fcrontab` entry

    30 0,3,6,9,12,15,18,21 * * * /opt/hub/wurstmineberg/wurstminestats/genAll.R

…which, in theory, should update the plots every 3 hours at 30m past the hour, to reduce load on full hours caused by backup compression and whatnot.

## Dependencies
Besides a recent version of R (duh), there are some things you need for this to be portable to any other Minecraft server. Let's go over the foreign data sources in this briefly.

### Packages
#### The biggie: wurstmineR
In an attempt to make this suck less, I moved most of the basic functionality from `functions.R`, along with the static `strings.*` data (see below) to it's own R package, primarily because I was curious how that would turn out.
As it turns out, it's pretty hard to do it right, but oh well.
See [wurstmineR](https://github.com/jemus42/wurstmineR) for details.
You need to install that via `devtools::install_github("jemus42/wurstmineR")`, which `dataPrep.R`does for you on startup. Or at least it should.
Note that `wurstmineR` has it's own list of dependencies.

#### Other packages
* [twitteR](https://github.com/geoffjentry/twitteR) (Only required if you intend to fill a twitter account with random stats, see [@wurstminedata](https://twitter.com/wurstminedata) – Used in `tweetstats.R`)

### Data sources
* http://api.wurstmineberg.de/server/playerstats/general.json
* http://api.wurstmineberg.de/server/playerstats/achievement.json
* http://api.wurstmineberg.de/server/playerstats/item.json
* http://api.wurstmineberg.de/server/playerstats/entity.json
* http://api.wurstmineberg.de/server/deaths/latest.json
* http://api.wurstmineberg.de/server/sessions/overview.json

These are [Minecraft API](http://api.wurstmineberg.de) endpoints, which expose the actual player statistics we're interested in visualising. If you have this set up for your own server, you're pretty much good to go. Almost.

### General information sources
* http://wurstmineberg.de/assets/serverstatus/people.json

This is our [people database](http://wiki.wurstmineberg.de/People_file), which holds metadata about the people on our server, such as join date, nickname (ID), minecraft username and what have you. This is required to sort and classify the datasets. It is required in many dataset transformations, because I substitute minecraft usernames with their nicknames (IDs), sort them by join dates and group by their join status, so… If you don't want to set up a people.json, you'd need to get rid of these parts manually.

* http://assets.wurstmineberg.de/json/achievements.json

Just some substitution-friendly strings to make achievements more human readable.

* http://assets.wurstmineberg.de/json/strings.json

Similar to achievements.json, this provides names and classification for player stats, as well as some mob name substitutions.

* http://assets.wurstmineberg.de/json/biomes.json

You guessed it. Contains biome ID, name if necessary and for this project the most relevant: Is the biome relevant to the [Adventuring Time](http://minecraft.gamepedia.com/Adventuring_Time#List_of_achievements) achievement or not. Used as a filter for the total amount of visited biomes per player and then put in [this](http://i.wurstmineberg.de/wurstminestats/achievements/exploreAllBiomesProgress.png).

* http://assets.wurstmineberg.de/json/items.json
  * also see http://assets.wurstmineberg.de/json/items.json.description.txt

Like the other files, this is also used to substitute internal IDs with nicer names. More importantly, it contains both numeric and new IDs for each biome, which allows us to merge old, still numerically indexed item stats with current item stats. This will no longer be necessary when all the inactive players have finally logged in for once, but it's nice to be backwards compatible.
Note that these files are already included in dataframe form in `wurstmineR`.

## Contribution
* If you're familiar with R or [ggplot2](http://docs.ggplot2.org/), I appreciate any hints on how to do something better, cleaner, more efficient or just more visually pleasing.
* Requests for graphs are appreciated, and if I figure out how to make them happen, I will
* Visual errors in graphs can be reported via the issue tracker, you know, to keep track
* Errors with the data itself are more or less out of my reach.


text:
layout: default
description: The "db" Object
---
The "db" Object
===============

The `db` object is available in [arangosh](programs-arangosh.html) by
default, and can also be imported and used in Foxx services.

*db.name* returns a [collection object](appendix-references-collection-object.html) for the collection *name*.

The following methods exist on the *_db* object:

*Database*

* [db._createDatabase(name, options, users)](data-modeling-databases-working-with.html#create-database)
* [db._databases()](data-modeling-databases-working-with.html#list-databases)
* [db._dropDatabase(name, options, users)](data-modeling-databases-working-with.html#drop-database)
* [db._useDatabase(name)](data-modeling-databases-working-with.html#use-database)

*Indexes*

* [db._index(index)](indexing-working-with-indexes.html#fetching-an-index-by-handle)
* [db._dropIndex(index)](indexing-working-with-indexes.html#dropping-an-index-via-a-database-handle)

*Properties*

* [db._id()](data-modeling-databases-working-with.html#id)
* [db._isSystem()](data-modeling-databases-working-with.html#issystem)
* [db._name()](data-modeling-databases-working-with.html#name)
* [db._path()](data-modeling-databases-working-with.html#path)
* [db._properties()](data-modeling-databases-working-with.html#properties)

*Collection*

* [db._collection(name)](data-modeling-collections-database-methods.html#collection)
* [db._collections()](data-modeling-collections-database-methods.html#all-collections)
* [db._create(name)](data-modeling-collections-database-methods.html#create)
* [db._drop(name)](data-modeling-collections-database-methods.html#drop)
* [db._truncate(name)](data-modeling-collections-database-methods.html#truncate)

*AQL*

* [db._createStatement(query)](aql/invocation-with-arangosh.html#with-_createstatement-arangostatement)
* [db._query(query)](aql/invocation-with-arangosh.html#with-db_query)
* [db._explain(query)](release-notes-new-features28.html#miscellaneous-improvements)
* [db._parse(query)](aql/invocation-with-arangosh.html#query-validation)

*Document*

* [db._document(object)](data-modeling-documents-database-methods.html#document)
* [db._exists(object)](data-modeling-documents-database-methods.html#exists)
* [db._remove(selector)](data-modeling-documents-database-methods.html#remove)
* [db._replace(selector,data)](data-modeling-documents-database-methods.html#replace)
* [db._update(selector,data)](data-modeling-documents-database-methods.html#update)

*Views*

* [db._view(name)](data-modeling-views-database-methods.html#view)
* [db._views()](data-modeling-views-database-methods.html#all-views)
* [db._createView(name, type, properties)](data-modeling-views-database-methods.html#create)
* [db._dropView(name)](data-modeling-views-database-methods.html#drop)

*Global*

* [db._compact()](data-modeling-databases-working-with.html#compact)
* [db._engine()](data-modeling-databases-working-with.html#engine)
* [db._engineStats()](data-modeling-databases-working-with.html#engine-statistics)
* [db._executeTransaction()](transactions-transaction-invocation.html)
* [db._version()](data-modeling-databases-working-with.html#get-the-version-of-arangodb)


text:
package radlab.rain.workloadtraits;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.LinkedList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import radlab.rain.LoadProfile;
import radlab.rain.LoadScheduleCreator;
import radlab.rain.util.storage.KeyGenerator;
import radlab.rain.util.storage.StorageLoadProfile;

/* Flat/steady hotspot workload
 */
public class FlatHotspotScheduleCreator extends LoadScheduleCreator
{
	private static NumberFormat FORMATTER = new DecimalFormat( "00000" );
	public static String CFG_INITIAL = "initialWorkload";
	public static String CFG_INCREMENT_SIZE = "incrementSize";
	public static String CFG_INCREMENTS_PER_INTERVAL = "incrementsPerInterval";

	private int _initialWorkload = 1;
	private double[] _relativeLoads = { 1,
			1,
			1,
			1,
			1,
			1,
			1,
			1,
			1,
			1,
			1,
			1,
			1,
			1,
			1,
			1,
			1,
			1,
			1,
			1,
			1,
			1,
			1,
			1,
	};

	private int[] _numHotObjects = { 100,
			100,
			100,
			100,
			100,
			100,
			100,
			100,
			100,
			100,
			100,
			100,
			100,
			100,
			100,
			100,
			100,
			100,
			100,
			100,
			100,
			100,
			100,
			100
	};

	private double[] _hotTrafficFraction = { 0.64,
			0.64,
			0.64,
			0.64,
			0.64,
			0.64,
			0.64,
			0.64,
			0.64,
			0.64,
			0.64,
			0.64,
			0.64,
			0.64,
			0.64,
			0.64,
			0.64,
			0.64,
			0.64,
			0.64,
			0.64,
			0.64,
			0.64,
			0.64
	};

	private int _incrementSize = 30; // 30 seconds per increment
	private int _incrementsPerInterval = 1; // this gives us 10 seconds per interval

	public FlatHotspotScheduleCreator()
	{}

	public int getInitialWorkload() { return this._initialWorkload; }
	public void setInitialWorkload( int val ){ this._initialWorkload = val; }

	public int getIncrementSize() { return this._incrementSize; }
	public void setIncrementSize( int val ){ this._incrementSize = val; }

	public int getIncrementsPerInterval() { return this._incrementsPerInterval; }
	public void setIncrementsPerInterval( int val ){ this._incrementsPerInterval = val; }

	@Override
	public LinkedList<LoadProfile> createSchedule(JSONObject config) throws JSONException
	{
		// The relative load, num hot object and hot traffic fraction arrays must all be the same size
		if( this._relativeLoads.length != this._numHotObjects.length )
			throw new JSONException( "Length of Number of hot objects array: " + this._numHotObjects.length + " is not the same as relative load array: " + this._relativeLoads.length );

		if( this._relativeLoads.length != this._hotTrafficFraction.length )
			throw new JSONException( "Length of hot traffic fraction array: " + this._hotTrafficFraction.length + " is not the same as relative load array: " + this._relativeLoads.length );

		// Pull out the base offset
		if( config.has( CFG_INITIAL ) )
			this._initialWorkload = config.getInt( CFG_INITIAL );

		if( config.has(CFG_INCREMENT_SIZE) )
			this._incrementSize = config.getInt( CFG_INCREMENT_SIZE );

		if( config.has( CFG_INCREMENTS_PER_INTERVAL) )
			this._incrementsPerInterval = config.getInt( CFG_INCREMENTS_PER_INTERVAL );

		// Accept parameters for the number min and max key and the object size

		/* Example storage load profile that we're creating programmatically

		 "interval": 20,
			"users": 100,
			"mix": "uniform50r/50w",

			"keyGenerator": "radlab.rain.util.storage.UniformKeyGenerator",
			"keyGeneratorConfig": {
				"rngSeed": 1,
				"minKey": 1,
				"maxKey": 100000,
				"a": 1.001,
				"r": 3.456
			},
			"size": 4096,
			"readPct": 0.50,
			"writePct": 0.50,
			"numHotObjects" : 10,
			"hotTrafficFraction": 0.0
		 */

		// Here are some default parameters
		String mixName = "uniform50r/50w";
		long objectSize = 4096;
		double readPct = 0.5;
		double writePct = 0.5;
		//long numHotObjects = 0;
		//double hotTrafficFraction = 0.0;
		JSONArray hotSet = null;
		int minKey = 1;
		int maxKey = 100000;

		// See whether our config contained any overrides
		if( config.has( StorageLoadProfile.CFG_LOAD_PROFILE_REQUEST_SIZE_KEY ) )
			objectSize = config.getInt( StorageLoadProfile.CFG_LOAD_PROFILE_REQUEST_SIZE_KEY );

		if( config.has( StorageLoadProfile.CFG_LOAD_PROFILE_READ_PCT_KEY ) )
			readPct = config.getDouble( StorageLoadProfile.CFG_LOAD_PROFILE_READ_PCT_KEY );

		if( config.has( StorageLoadProfile.CFG_LOAD_PROFILE_WRITE_PCT_KEY ) )
			writePct = config.getDouble( StorageLoadProfile.CFG_LOAD_PROFILE_WRITE_PCT_KEY );

		// Override the number of hot objects with a flat/steady signal based on the config file param
		if( config.has( StorageLoadProfile.CFG_NUM_HOT_OBJECTS_KEY ) )
		{
			int numHotObjects = config.getInt( StorageLoadProfile.CFG_NUM_HOT_OBJECTS_KEY );
			for( int i = 0; i < this._relativeLoads.length; i++ )
				this._numHotObjects[i] = numHotObjects;
		}

		// Override the hot traffic fraction with a flat/steady signal based on the config file param
		if( config.has( StorageLoadProfile.CFG_HOT_TRAFFIC_FRACTION_KEY ) )
		{
			double hotTrafficFraction = config.getDouble( StorageLoadProfile.CFG_HOT_TRAFFIC_FRACTION_KEY );
			for( int i = 0; i < this._relativeLoads.length; i++ )
				this._hotTrafficFraction[i] = hotTrafficFraction;
		}

		// Use a hot set if it's been pre-specified
		//if( config.has( StorageLoadProfile.CFG_HOT_SET_KEY ) )
		//{
		hotSet = config.getJSONArray( StorageLoadProfile.CFG_HOT_SET_KEY );
		//}

		if( config.has( KeyGenerator.MIN_KEY_CONFIG_KEY ) )
			minKey = config.getInt( KeyGenerator.MIN_KEY_CONFIG_KEY );

		if( config.has( KeyGenerator.MAX_KEY_CONFIG_KEY ) )
			maxKey = config.getInt( KeyGenerator.MAX_KEY_CONFIG_KEY );

		LinkedList<LoadProfile> loadSchedule = new LinkedList<LoadProfile>();

		// Specify the key generator parameters
		JSONObject keyGenConfig = new JSONObject();
		keyGenConfig.put( KeyGenerator.RNG_SEED_KEY, 1 );
		keyGenConfig.put( KeyGenerator.MIN_KEY_CONFIG_KEY, minKey );
		keyGenConfig.put( KeyGenerator.MAX_KEY_CONFIG_KEY, maxKey );
		keyGenConfig.put( KeyGenerator.A_CONFIG_KEY, 1.001 );
		keyGenConfig.put( KeyGenerator.R_CONFIG_KEY, 3.456 );

		for( int i = 0; i < this._relativeLoads.length; i++ )
		{
			long intervalLength = this._incrementSize * this._incrementsPerInterval;
			if( i == 0 )
			{
				JSONObject profileConfig = new JSONObject();
				// Set the basics: # interval, users, mix name
				profileConfig.put( LoadProfile.CFG_LOAD_PROFILE_INTERVAL_KEY, intervalLength );
				profileConfig.put( LoadProfile.CFG_LOAD_PROFILE_USERS_KEY, this._initialWorkload );
				profileConfig.put( LoadProfile.CFG_LOAD_PROFILE_MIX_KEY, mixName );
				// Set the Storage specific elements
				profileConfig.put( StorageLoadProfile.CFG_LOAD_PROFILE_KEY_GENERATOR_KEY, "radlab.rain.util.storage.UniformKeyGenerator" );
				profileConfig.put( StorageLoadProfile.CFG_LOAD_PROFILE_KEY_GENERATOR_CONFIG_KEY, keyGenConfig );
				profileConfig.put( StorageLoadProfile.CFG_LOAD_PROFILE_REQUEST_SIZE_KEY, objectSize );
				profileConfig.put( StorageLoadProfile.CFG_LOAD_PROFILE_READ_PCT_KEY, readPct );
				profileConfig.put( StorageLoadProfile.CFG_LOAD_PROFILE_WRITE_PCT_KEY, writePct );
				// We're going to let the first interval be hotspot free
				//profileConfig.put( StorageLoadProfile.CFG_HOT_SET_KEY, hotSet );
				profileConfig.put( StorageLoadProfile.CFG_HOT_TRAFFIC_FRACTION_KEY, 0.0 );

				StorageLoadProfile profile = new StorageLoadProfile( profileConfig );
				profile._name = FORMATTER.format(i);
				profile.setTransitionTime( 0 );

				loadSchedule.add( profile );
			}
			else
			{
				int users = 0;
				users = (int) Math.round( loadSchedule.getLast().getNumberOfUsers() * this._relativeLoads[i] );

				JSONObject profileConfig = new JSONObject();
				// Set the basics: # interval, users, mix name
				profileConfig.put( LoadProfile.CFG_LOAD_PROFILE_INTERVAL_KEY, intervalLength );
				profileConfig.put( LoadProfile.CFG_LOAD_PROFILE_USERS_KEY, users );
				profileConfig.put( LoadProfile.CFG_LOAD_PROFILE_MIX_KEY, mixName );
				// Set the Storage specific elements
				profileConfig.put( StorageLoadProfile.CFG_LOAD_PROFILE_KEY_GENERATOR_KEY, "radlab.rain.util.storage.UniformKeyGenerator" );
				profileConfig.put( StorageLoadProfile.CFG_LOAD_PROFILE_KEY_GENERATOR_CONFIG_KEY, keyGenConfig );
				profileConfig.put( StorageLoadProfile.CFG_LOAD_PROFILE_REQUEST_SIZE_KEY, objectSize );
				profileConfig.put( StorageLoadProfile.CFG_LOAD_PROFILE_READ_PCT_KEY, readPct );
				profileConfig.put( StorageLoadProfile.CFG_LOAD_PROFILE_WRITE_PCT_KEY, writePct );
				// Specify the hot set directly
				profileConfig.put( StorageLoadProfile.CFG_HOT_SET_KEY, hotSet );
				profileConfig.put( StorageLoadProfile.CFG_HOT_TRAFFIC_FRACTION_KEY, this._hotTrafficFraction[i] );

				StorageLoadProfile profile = new StorageLoadProfile( profileConfig );
				profile._name = FORMATTER.format(i);
				profile.setTransitionTime( 0 );

				loadSchedule.add( profile );
			}
		}

		int padIntervals = 5;

		// Pad the workload with 3 intervals back at the initial workload level
		for( int i = 0; i < padIntervals; i++ )
		{
			long intervalLength = this._incrementSize * this._incrementsPerInterval;
			JSONObject profileConfig = new JSONObject();
			// Set the basics: # interval, users, mix name
			profileConfig.put( LoadProfile.CFG_LOAD_PROFILE_INTERVAL_KEY, intervalLength );
			profileConfig.put( LoadProfile.CFG_LOAD_PROFILE_USERS_KEY, this._initialWorkload );
			profileConfig.put( LoadProfile.CFG_LOAD_PROFILE_MIX_KEY, mixName );
			// Set the Storage specific elements
			profileConfig.put( StorageLoadProfile.CFG_LOAD_PROFILE_KEY_GENERATOR_KEY, "radlab.rain.util.storage.UniformKeyGenerator" );
			profileConfig.put( StorageLoadProfile.CFG_LOAD_PROFILE_KEY_GENERATOR_CONFIG_KEY, keyGenConfig );
			profileConfig.put( StorageLoadProfile.CFG_LOAD_PROFILE_REQUEST_SIZE_KEY, objectSize );
			profileConfig.put( StorageLoadProfile.CFG_LOAD_PROFILE_READ_PCT_KEY, readPct );
			profileConfig.put( StorageLoadProfile.CFG_LOAD_PROFILE_WRITE_PCT_KEY, writePct );
			profileConfig.put( StorageLoadProfile.CFG_NUM_HOT_OBJECTS_KEY, this._numHotObjects[0] );
			profileConfig.put( StorageLoadProfile.CFG_HOT_TRAFFIC_FRACTION_KEY, this._hotTrafficFraction[0] );
			//profileConfig.put( StorageLoadProfile.CFG_NUM_HOT_OBJECTS_KEY, numHotObjects );
			//profileConfig.put( StorageLoadProfile.CFG_HOT_TRAFFIC_FRACTION_KEY, hotTrafficFraction );

			StorageLoadProfile profile = new StorageLoadProfile( profileConfig );
			profile._name = "pad-" + FORMATTER.format(i);
			profile.setTransitionTime( 0 );

			loadSchedule.add( profile );
		}

		return loadSchedule;
	}

	public static void main( String[] args ) throws JSONException
	{
		HotspotScheduleCreator creator = new HotspotScheduleCreator();

		creator.setInitialWorkload( 800 );

		// Would like to give a duration and have the workload stretched/compressed into that
		LinkedList<LoadProfile> profiles = creator.createSchedule( new JSONObject() );
		for( LoadProfile p : profiles )
		{
			if( p instanceof StorageLoadProfile )
			{
				StorageLoadProfile slp = (StorageLoadProfile) p;
				System.out.println( slp.getNumberOfUsers() + " " + slp.getNumHotObjects() + " " + slp.getHotTrafficFraction() );
			}
			else System.out.println( p.getNumberOfUsers() );
		}
	}
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>NUM</title>
    <link rel="root" href=""/>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
    <link rel="stylesheet" type="text/css" href="../../css/jquery-ui-redmond.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/style.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/style-vis.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/hint.css"/>

          home

          edit page
          issue tracker

          <gcse:search></gcse:search>

        This page pertains to UD version 2.

            It appears that you have Javascript disabled.
            Please consider enabling Javascript for this page to see the visualizations.

NUM: numeral

Definition

A numeral is a word, functioning most typically as a determiner,
adjective or pronoun, that expresses a number and a relation to the
number, such as quantity, sequence, frequency or fraction.

Cardinal numerals are covered by NUM whether they are used
as determiners or not (as in Windows Seven) and whether they
are expressed as words (four), or digits (4).

There are numerals belonging to other parts of speech in the universal
tagging scheme, based mainly on syntactic criteria: e.g. ordinal numerals
are tagged as adjectives or pronouns (first, second, third, …).
In Italian there are no adverbial numerals like [cs] poprvé "for the first time" nor multiplicative numerals such as [en] (once, twice).

Note that, since Roman numerals (IV) are only used as ordinal numerals in Italian (Enciclopedia Treccani), they are tagged ADJ for coherence with other ordinal numerals.
In this case we specify NumType=Ord as morphological feature.
A similar treatment is reserved to a cardinal with a suffix such as a, o, esimo, esima, or the symbol ° (similar to the English use of the suffix "th").

Other words functioning as determiners (including quantifiers such as many and few) are tagged DET.

Examples

Tagged as NUM:

0, 1, 2, 2014, 1000000, 3,14159265359

zero, uno, due, settantasette

Tagged as ADJ:

XX secolo

48esimo

primo, secondo, ultima

20°

Tagged as PRON:

il terzo ad arrivare "the third to arrive"

References

Enciclopedia Treccani

NUM in other languages:

[bej]

[bg]

[bm]

[cs]

[cy]

[da]

[el]

[en]

[ess]

[et]

[fi]

[fro]

[fr]

[ga]

[grc]

[hu]

[hy]

[it]

[ja]

[kk]

[kpv]

[myv]

[no]

[pcm]

[pt]

[qpm]

[ru]

[sl]

[sv]

[tr]

[tt]

[uk]

[u]

[urj]

[yue]

[zh]

© 2014–2021
            Universal Dependencies contributors.
            Site powered by Annodoc and brat
.


text:
package hackerRank.HourRank7;

import java.util.Arrays;
import java.util.Scanner;

public class _03TilePaintingRevisited {

	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		int T = in.nextInt();
		for (int i = 0; i < T; i++) {
			int elements=in.nextInt();
			System.out.println(findNumberOfArithSequences(elements));
		}
	}

	private static int findNumberOfArithSequences(int elements) {
		if(elements%5==0||elements>5)
		{
			return elements*(elements-1)+1+elements/5;
		}
		else
			return elements*(elements-1)+1;
	}

}


text:
{!! Form::select(
        'priority',
        $priorities,
        (isset($priority) ? $priority : null),
        array('class'=>'form-control select2', 'placeholder'=>'ex. Low / Lowest')
    )
!!}


text:
namespace {

struct FakePlaneInfo {
  uint32_t id;
  uint32_t allowed_crtc_mask;
};

const FakePlaneInfo kOnePlanePerCrtc[] = {{10, 1}, {20, 2}};
const FakePlaneInfo kTwoPlanesPerCrtc[] = {{10, 1}, {11, 1}, {20, 2}, {21, 2}};
const FakePlaneInfo kOnePlanePerCrtcWithShared[] = {{10, 1}, {20, 2}, {50, 3}};

class FakeScanoutBuffer : public ui::ScanoutBuffer {
 public:
  FakeScanoutBuffer() {}

  // ui::ScanoutBuffer:
  uint32_t GetFramebufferId() const override { return 1; }
  uint32_t GetHandle() const override { return 0; }
  gfx::Size GetSize() const override { return gfx::Size(1, 1); }

 protected:
  ~FakeScanoutBuffer() override {}
};

class FakePlaneManager : public ui::HardwareDisplayPlaneManager {
 public:
  FakePlaneManager() : plane_count_(0) {}
  ~FakePlaneManager() override {}

  // Normally we'd use DRM to figure out the controller configuration. But we
  // can't use DRM in unit tests, so we just create a fake configuration.
  void InitForTest(const FakePlaneInfo* planes,
                   size_t count,
                   const std::vector<uint32_t>& crtcs) {
    crtcs_ = crtcs;
    for (size_t i = 0; i < count; i++) {
      planes_.push_back(new ui::HardwareDisplayPlane(
          planes[i].id, planes[i].allowed_crtc_mask));
    }
    // The real HDPM uses sorted planes, so sort them for consistency.
    std::sort(planes_.begin(), planes_.end(),
              [](ui::HardwareDisplayPlane* l, ui::HardwareDisplayPlane* r) {
      return l->plane_id() < r->plane_id();
    });
  }

  bool Commit(ui::HardwareDisplayPlaneList* plane_list, bool is_sync) override {
    return false;
  }

  bool SetPlaneData(ui::HardwareDisplayPlaneList* plane_list,
                    ui::HardwareDisplayPlane* hw_plane,
                    const ui::OverlayPlane& overlay,
                    uint32_t crtc_id,
                    const gfx::Rect& src_rect,
                    ui::CrtcController* crtc) override {
    // Check that the chosen plane is a legal choice for the crtc.
    EXPECT_NE(-1, LookupCrtcIndex(crtc_id));
    EXPECT_TRUE(hw_plane->CanUseForCrtc(LookupCrtcIndex(crtc_id)));
    EXPECT_FALSE(hw_plane->in_use());
    plane_count_++;
    return true;
  }

  int plane_count() const { return plane_count_; }

 private:
  DISALLOW_COPY_AND_ASSIGN(FakePlaneManager);

  int plane_count_;
};

class HardwareDisplayPlaneManagerTest : public testing::Test {
 public:
  HardwareDisplayPlaneManagerTest() {}

  void SetUp() override;

 protected:
  scoped_ptr<FakePlaneManager> plane_manager_;
  ui::HardwareDisplayPlaneList state_;
  std::vector<uint32_t> default_crtcs_;
  scoped_refptr<ui::ScanoutBuffer> fake_buffer_;

 private:
  DISALLOW_COPY_AND_ASSIGN(HardwareDisplayPlaneManagerTest);
};

void HardwareDisplayPlaneManagerTest::SetUp() {
  fake_buffer_ = new FakeScanoutBuffer();
  plane_manager_.reset(new FakePlaneManager());
  default_crtcs_.push_back(100);
  default_crtcs_.push_back(200);
}

TEST_F(HardwareDisplayPlaneManagerTest, SinglePlaneAssignment) {
  ui::OverlayPlaneList assigns;
  assigns.push_back(ui::OverlayPlane(fake_buffer_));
  plane_manager_->InitForTest(kOnePlanePerCrtc, arraysize(kOnePlanePerCrtc),
                              default_crtcs_);
  EXPECT_TRUE(plane_manager_->AssignOverlayPlanes(&state_, assigns,
                                                  default_crtcs_[0], nullptr));
  EXPECT_EQ(1, plane_manager_->plane_count());
}

TEST_F(HardwareDisplayPlaneManagerTest, BadCrtc) {
  ui::OverlayPlaneList assigns;
  assigns.push_back(ui::OverlayPlane(fake_buffer_));
  plane_manager_->InitForTest(kOnePlanePerCrtc, arraysize(kOnePlanePerCrtc),
                              default_crtcs_);
  EXPECT_FALSE(
      plane_manager_->AssignOverlayPlanes(&state_, assigns, 1, nullptr));
}

TEST_F(HardwareDisplayPlaneManagerTest, MultiplePlaneAssignment) {
  ui::OverlayPlaneList assigns;
  assigns.push_back(ui::OverlayPlane(fake_buffer_));
  assigns.push_back(ui::OverlayPlane(fake_buffer_));
  plane_manager_->InitForTest(kTwoPlanesPerCrtc, arraysize(kTwoPlanesPerCrtc),
                              default_crtcs_);
  EXPECT_TRUE(plane_manager_->AssignOverlayPlanes(&state_, assigns,
                                                  default_crtcs_[0], nullptr));
  EXPECT_EQ(2, plane_manager_->plane_count());
}

TEST_F(HardwareDisplayPlaneManagerTest, NotEnoughPlanes) {
  ui::OverlayPlaneList assigns;
  assigns.push_back(ui::OverlayPlane(fake_buffer_));
  assigns.push_back(ui::OverlayPlane(fake_buffer_));
  plane_manager_->InitForTest(kOnePlanePerCrtc, arraysize(kOnePlanePerCrtc),
                              default_crtcs_);

  EXPECT_FALSE(plane_manager_->AssignOverlayPlanes(&state_, assigns,
                                                   default_crtcs_[0], nullptr));
}

TEST_F(HardwareDisplayPlaneManagerTest, MultipleCrtcs) {
  ui::OverlayPlaneList assigns;
  assigns.push_back(ui::OverlayPlane(fake_buffer_));
  plane_manager_->InitForTest(kOnePlanePerCrtc, arraysize(kOnePlanePerCrtc),
                              default_crtcs_);

  EXPECT_TRUE(plane_manager_->AssignOverlayPlanes(&state_, assigns,
                                                  default_crtcs_[0], nullptr));
  EXPECT_TRUE(plane_manager_->AssignOverlayPlanes(&state_, assigns,
                                                  default_crtcs_[1], nullptr));
  EXPECT_EQ(2, plane_manager_->plane_count());
}

TEST_F(HardwareDisplayPlaneManagerTest, MultiplePlanesAndCrtcs) {
  ui::OverlayPlaneList assigns;
  assigns.push_back(ui::OverlayPlane(fake_buffer_));
  assigns.push_back(ui::OverlayPlane(fake_buffer_));
  plane_manager_->InitForTest(kTwoPlanesPerCrtc, arraysize(kTwoPlanesPerCrtc),
                              default_crtcs_);
  EXPECT_TRUE(plane_manager_->AssignOverlayPlanes(&state_, assigns,
                                                  default_crtcs_[0], nullptr));
  EXPECT_TRUE(plane_manager_->AssignOverlayPlanes(&state_, assigns,
                                                  default_crtcs_[1], nullptr));
  EXPECT_EQ(4, plane_manager_->plane_count());
}

TEST_F(HardwareDisplayPlaneManagerTest, MultipleFrames) {
  ui::OverlayPlaneList assigns;
  assigns.push_back(ui::OverlayPlane(fake_buffer_));
  plane_manager_->InitForTest(kTwoPlanesPerCrtc, arraysize(kTwoPlanesPerCrtc),
                              default_crtcs_);

  EXPECT_TRUE(plane_manager_->AssignOverlayPlanes(&state_, assigns,
                                                  default_crtcs_[0], nullptr));
  EXPECT_EQ(1, plane_manager_->plane_count());
  // Pretend we committed the frame.
  state_.committed = true;
  state_.plane_list.swap(state_.old_plane_list);
  ui::HardwareDisplayPlane* old_plane = state_.old_plane_list[0];
  // The same plane should be used.
  EXPECT_TRUE(plane_manager_->AssignOverlayPlanes(&state_, assigns,
                                                  default_crtcs_[0], nullptr));
  EXPECT_EQ(2, plane_manager_->plane_count());
  EXPECT_EQ(state_.plane_list[0], old_plane);
}

TEST_F(HardwareDisplayPlaneManagerTest, MultipleFramesDifferentPlanes) {
  ui::OverlayPlaneList assigns;
  assigns.push_back(ui::OverlayPlane(fake_buffer_));
  plane_manager_->InitForTest(kTwoPlanesPerCrtc, arraysize(kTwoPlanesPerCrtc),
                              default_crtcs_);

  EXPECT_TRUE(plane_manager_->AssignOverlayPlanes(&state_, assigns,
                                                  default_crtcs_[0], nullptr));
  EXPECT_EQ(1, plane_manager_->plane_count());
  // The other plane should be used.
  EXPECT_TRUE(plane_manager_->AssignOverlayPlanes(&state_, assigns,
                                                  default_crtcs_[0], nullptr));
  EXPECT_EQ(2, plane_manager_->plane_count());
  EXPECT_NE(state_.plane_list[0], state_.plane_list[1]);
}

TEST_F(HardwareDisplayPlaneManagerTest, SharedPlanes) {
  ui::OverlayPlaneList assigns;
  assigns.push_back(ui::OverlayPlane(fake_buffer_));
  assigns.push_back(ui::OverlayPlane(fake_buffer_));
  plane_manager_->InitForTest(kOnePlanePerCrtcWithShared,
                              arraysize(kOnePlanePerCrtcWithShared),
                              default_crtcs_);

  EXPECT_TRUE(plane_manager_->AssignOverlayPlanes(&state_, assigns,
                                                  default_crtcs_[1], nullptr));
  EXPECT_EQ(2, plane_manager_->plane_count());
  // The shared plane is now unavailable for use by the other CRTC.
  EXPECT_FALSE(plane_manager_->AssignOverlayPlanes(&state_, assigns,
                                                   default_crtcs_[0], nullptr));
}

TEST(HardwareDisplayPlaneManagerLegacyTest, UnusedPlanesAreReleased) {
  std::vector<uint32_t> crtcs;
  crtcs.push_back(100);
  scoped_refptr<ui::MockDriWrapper> drm =
      new ui::MockDriWrapper(false, crtcs, 2);
  ui::OverlayPlaneList assigns;
  scoped_refptr<FakeScanoutBuffer> fake_buffer = new FakeScanoutBuffer();
  assigns.push_back(ui::OverlayPlane(fake_buffer));
  assigns.push_back(ui::OverlayPlane(fake_buffer));
  ui::HardwareDisplayPlaneList hdpl;
  ui::CrtcController crtc(drm, crtcs[0], 0);
  EXPECT_TRUE(drm->plane_manager()->AssignOverlayPlanes(&hdpl, assigns,
                                                        crtcs[0], &crtc));
  EXPECT_TRUE(drm->plane_manager()->Commit(&hdpl, false));
  assigns.clear();
  assigns.push_back(ui::OverlayPlane(fake_buffer));
  EXPECT_TRUE(drm->plane_manager()->AssignOverlayPlanes(&hdpl, assigns,
                                                        crtcs[0], &crtc));
  EXPECT_EQ(0, drm->get_overlay_clear_call_count());
  EXPECT_TRUE(drm->plane_manager()->Commit(&hdpl, false));
  EXPECT_EQ(1, drm->get_overlay_clear_call_count());
}

}  // namespace


text:
from django.contrib import admin
from wall.models import WallItem, Wall

class WallItemAdmin(admin.ModelAdmin):
    list_display = ('wall', 'author', 'created_at', 'body')

admin.site.register(WallItem, WallItemAdmin)

admin.site.register(Wall)


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

export abstract class UiComponent extends EventTarget {
  /**
   * A reference to the host itself.
   */
  protected readonly _host: UserScript;

  /**
   * The main DOM element for this component, in a JQuery wrapper.
   */
  abstract readonly element: JQuery<HTMLElement>;

  readonly children = new Set<UiComponent>();

  constructor(host: UserScript) {
    super();
    this._host = host;
  }

  refreshUi() {
    for (const child of this.children) {
      child.refreshUi();
    }
  }

  addChild(child: UiComponent) {
    this.children.add(child);
    this.element.append(child.element);
  }
  addChildren(children: Iterable<UiComponent>) {
    for (const child of children) {
      this.addChild(child);
    }
  }

  static promptLimit(text: string, defaultValue: string): number | null {
    const value = window.prompt(text, defaultValue);
    if (value === null) {
      return null;
    }

    const hasSuffix = /[KMGT]$/.test(value);
    const baseValue = value.substring(0, value.length - (hasSuffix ? 1 : 0));

    let numericValue =
      value.includes("e") || hasSuffix ? parseFloat(baseValue) : parseInt(baseValue);
    if (hasSuffix) {
      const suffix = value.substring(value.length - 1);
      numericValue = numericValue * Math.pow(1000, ["", "K", "M", "G", "T"].indexOf(suffix));
    }
    if (numericValue === Number.POSITIVE_INFINITY || numericValue < 0) {
      numericValue = -1;
    }

    return numericValue;
  }

  static promptPercentage(text: string, defaultValue: string): number | null {
    const value = window.prompt(text, defaultValue);
    if (value === null) {
      return null;
    }

    // Cap value between 0 and 1.
    return Math.max(0, Math.min(1, parseFloat(value)));
  }

  protected _renderLimit(value: number): string {
    return UiComponent.renderLimit(value, this._host);
  }

  static renderLimit(value: number, host: UserScript) {
    if (value < 0 || value === Number.POSITIVE_INFINITY) {
      return "∞";
    }

    return host.gamePage.getDisplayValueExt(value);
  }

  static renderPercentage(value: number): string {
    return value.toFixed(3);
  }
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.github.sakserv</groupId>
    <artifactId>lslock</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>lslock</name>
    <description>List locks for a given directory</description>
    <url>https://github.com/sakserv/lslock</url>

    <licenses>
        <license>
            <name>Apache License, Version 2.0</name>
            <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
            <distribution>repo</distribution>
        </license>
    </licenses>

    <scm>
        <connection>scm:git:git://github.com/sakserv/lslock.git</connection>
        <developerConnection>scm:git:git@github.com:sakserv/lslock.git</developerConnection>
        <url>http://github.com/sakserv/lslock</url>
        <tag>HEAD</tag>
    </scm>

    <developers>
        <developer>
            <name>Shane Kumpf</name>
            <email>sakserv@sakserv.org</email>
            <organization>Hortonworks</organization>
            <organizationUrl>http://www.hortonworks.com/</organizationUrl>
        </developer>
    </developers>

    <properties>

        <!-- Common Deps -->
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <slf4j.version>1.7.10</slf4j.version>
        <junit.version>4.11</junit.version>
        <commons-cli.version>1.3.1</commons-cli.version>
        <commons-io.version>2.4</commons-io.version>

        <!-- Maven Plugins -->
        <maven-surefire-plugin.version>2.19</maven-surefire-plugin.version>
        <maven-compiler-plugin.version>3.3</maven-compiler-plugin.version>
        <maven-release-plugin.version>2.5.3</maven-release-plugin.version>
        <maven-scm-api.version>1.9.2</maven-scm-api.version>
        <maven-scm-provider-gitexe.version>1.9.2</maven-scm-provider-gitexe.version>
        <maven-source-plugin.version>2.4</maven-source-plugin.version>
        <maven-javadoc-plugin.version>2.10.3</maven-javadoc-plugin.version>
        <docker-maven-plugin.version>0.3.4</docker-maven-plugin.version>

    </properties>

    <distributionManagement>
        <snapshotRepository>
            <id>sonatype-nexus-snapshots</id>
            <name>Sonatype Nexus snapshot repository</name>
            <url>https://oss.sonatype.org/content/repositories/snapshots</url>
        </snapshotRepository>
        <repository>
            <id>sonatype-nexus-staging</id>
            <name>Sonatype Nexus release repository</name>
            <url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url>
        </repository>
    </distributionManagement>

    <dependencies>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${slf4j.version}</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>${slf4j.version}</version>
        </dependency>
        <dependency>
            <groupId>commons-cli</groupId>
            <artifactId>commons-cli</artifactId>
            <version>${commons-cli.version}</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>${commons-io.version}</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <profiles>
        <!-- release signing profile -->
        <profile>
            <id>release-sign-artifacts</id>
            <activation>
                <property>
                    <name>performRelease</name>
                    <value>true</value>
                </property>
            </activation>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-gpg-plugin</artifactId>
                        <executions>
                            <execution>
                                <id>sign-artifacts</id>
                                <phase>verify</phase>
                                <goals>
                                    <goal>sign</goal>
                                </goals>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>${maven-surefire-plugin.version}</version>
                <configuration>
                    <forkMode>pertest</forkMode>
                    <argLine>-Xms512m -Xmx512m -XX:MaxPermSize=128M</argLine>
                    <testFailureIgnore>false</testFailureIgnore>
                    <skip>false</skip>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>${maven-compiler-plugin.version}</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-assembly-plugin</artifactId>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>single</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <descriptorRefs>
                        <descriptorRef>jar-with-dependencies</descriptorRef>
                    </descriptorRefs>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-release-plugin</artifactId>
                <version>${maven-release-plugin.version}</version>
                <configuration>
                    <autoVersionSubmodules>true</autoVersionSubmodules>
                </configuration>
                <dependencies>
                    <dependency>
                        <groupId>org.apache.maven.scm</groupId>
                        <artifactId>maven-scm-api</artifactId>
                        <version>${maven-scm-api.version}</version>
                    </dependency>
                    <dependency>
                        <groupId>org.apache.maven.scm</groupId>
                        <artifactId>maven-scm-provider-gitexe</artifactId>
                        <version>${maven-scm-provider-gitexe.version}</version>
                    </dependency>
                </dependencies>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-source-plugin</artifactId>
                <version>${maven-source-plugin.version}</version>
                <executions>
                    <execution>
                        <id>attach-sources</id>
                        <goals>
                            <goal>jar</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-javadoc-plugin</artifactId>
                <version>${maven-javadoc-plugin.version}</version>
                <executions>
                    <execution>
                        <id>attach-javadocs</id>
                        <goals>
                            <goal>jar</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

            <plugin>
                <groupId>com.spotify</groupId>
                <artifactId>docker-maven-plugin</artifactId>
                <version>${docker-maven-plugin.version}</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>build</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <imageName>${project.name}</imageName>
                    <baseImage>java</baseImage>
                    <entryPoint>["/entrypoint-wrapper.sh", "/${project.build.finalName}-jar-with-dependencies.jar" ]</entryPoint>
                    <runs>
                        <run>["/entrypoint-wrapper.sh", "/${project.build.finalName}-jar-with-dependencies.jar"]</run>
                    </runs>
                    <resources>
                        <resource>
                            <targetPath>/</targetPath>
                            <directory>${project.build.directory}</directory>
                            <include>${project.build.finalName}-jar-with-dependencies.jar</include>
                        </resource>
                        <resource>
                            <targetPath>/</targetPath>
                            <directory>${project.build.directory}/../bin</directory>
                            <include>lslock</include>
                        </resource>
                        <resource>
                            <targetPath>/</targetPath>
                            <directory>${project.build.directory}/../bin</directory>
                            <include>lslock-test</include>
                        </resource>
                        <resource>
                            <targetPath>/</targetPath>
                            <directory>${project.build.directory}/../bin</directory>
                            <include>entrypoint-wrapper.sh</include>
                        </resource>
                    </resources>
                </configuration>
            </plugin>

        </plugins>
    </build>
</project>


text:
namespace ash {

namespace {

using printing::proto::PrintJobInfo;

constexpr char kId1[] = "id1";
constexpr char kId2[] = "id2";

PrintJobInfo ConstructPrintJobInfo(const std::string& id,
                                   const base::Time& completion_time) {
  PrintJobInfo print_job_info;
  print_job_info.set_id(id);
  print_job_info.set_completion_time(
      static_cast<int64_t>(completion_time.ToJsTime()));
  return print_job_info;
}

}  // namespace

class PrintJobHistoryCleanerTest : public ::testing::Test {
 public:
  PrintJobHistoryCleanerTest() = default;

  void SetUp() override {
    test_prefs_.SetInitializationCompleted();

    print_job_database_ = std::make_unique<TestPrintJobDatabase>();
    print_job_history_cleaner_ = std::make_unique<PrintJobHistoryCleaner>(
        print_job_database_.get(), &test_prefs_);

    print_job_history_cleaner_->SetClockForTesting(
        task_environment_.GetMockClock());

    PrintJobHistoryService::RegisterProfilePrefs(test_prefs_.registry());
  }

  void TearDown() override {}

 protected:
  void SavePrintJob(const PrintJobInfo& print_job_info) {
    base::RunLoop run_loop;
    print_job_database_->SavePrintJob(
        print_job_info,
        base::BindOnce(&PrintJobHistoryCleanerTest::OnPrintJobSaved,
                       base::Unretained(this), run_loop.QuitClosure()));
    run_loop.Run();
  }

  void OnPrintJobSaved(base::RepeatingClosure run_loop_closure, bool success) {
    EXPECT_TRUE(success);
    run_loop_closure.Run();
  }

  std::vector<PrintJobInfo> GetPrintJobs() {
    base::RunLoop run_loop;
    print_job_database_->GetPrintJobs(
        base::BindOnce(&PrintJobHistoryCleanerTest::OnPrintJobsRetrieved,
                       base::Unretained(this), run_loop.QuitClosure()));
    run_loop.Run();
    return entries_;
  }

  void OnPrintJobsRetrieved(base::RepeatingClosure run_loop_closure,
                            bool success,
                            std::vector<PrintJobInfo> entries) {
    EXPECT_TRUE(success);
    entries_ = std::move(entries);
    run_loop_closure.Run();
  }

  base::test::TaskEnvironment task_environment_{
      base::test::TaskEnvironment::TimeSource::MOCK_TIME};
  TestingPrefServiceSimple test_prefs_;
  std::unique_ptr<PrintJobDatabase> print_job_database_;
  std::unique_ptr<PrintJobHistoryCleaner> print_job_history_cleaner_;

 private:
  std::vector<PrintJobInfo> entries_;
};

TEST_F(PrintJobHistoryCleanerTest, CleanExpiredPrintJobs) {
  // Set expiration period to 1 day.
  test_prefs_.SetInteger(prefs::kPrintJobHistoryExpirationPeriod, 1);
  print_job_database_->Initialize(base::DoNothing());

  task_environment_.FastForwardBy(base::Days(300));
  PrintJobInfo print_job_info1 =
      ConstructPrintJobInfo(kId1, task_environment_.GetMockClock()->Now());
  SavePrintJob(print_job_info1);

  task_environment_.FastForwardBy(base::Days(1));
  PrintJobInfo print_job_info2 =
      ConstructPrintJobInfo(kId2, task_environment_.GetMockClock()->Now());
  SavePrintJob(print_job_info2);

  task_environment_.FastForwardBy(base::Hours(12));
  base::RunLoop run_loop1;
  print_job_history_cleaner_->CleanUp(run_loop1.QuitClosure());
  run_loop1.Run();

  std::vector<PrintJobInfo> entries = GetPrintJobs();
  // CleanUp() call should clear the first entry which is expected to expire.
  ASSERT_EQ(1u, entries.size());
  EXPECT_EQ(kId2, entries[0].id());

  task_environment_.FastForwardBy(base::Days(1));
  base::RunLoop run_loop2;
  print_job_history_cleaner_->CleanUp(run_loop2.QuitClosure());
  run_loop2.Run();
  entries = GetPrintJobs();
  // The second entry is expected to be removed after cleaner ran again.
  EXPECT_TRUE(entries.empty());
}

TEST_F(PrintJobHistoryCleanerTest, CleanExpiredPrintJobsAfterPrefChanged) {
  // Set expiration period to 1 day.
  test_prefs_.SetInteger(prefs::kPrintJobHistoryExpirationPeriod, 3);
  print_job_database_->Initialize(base::DoNothing());

  task_environment_.FastForwardBy(base::Days(300));
  PrintJobInfo print_job_info =
      ConstructPrintJobInfo(kId1, task_environment_.GetMockClock()->Now());
  SavePrintJob(print_job_info);

  task_environment_.FastForwardBy(base::Hours(36));
  base::RunLoop run_loop1;
  print_job_history_cleaner_->CleanUp(run_loop1.QuitClosure());
  run_loop1.Run();

  std::vector<PrintJobInfo> entries = GetPrintJobs();
  // CleanUp() shouldn't clear anything.
  ASSERT_EQ(1u, entries.size());
  EXPECT_EQ(kId1, entries[0].id());

  test_prefs_.SetInteger(prefs::kPrintJobHistoryExpirationPeriod, 1);
  base::RunLoop run_loop2;
  print_job_history_cleaner_->CleanUp(run_loop2.QuitClosure());
  run_loop2.Run();
  entries = GetPrintJobs();
  // The entry is expected to be removed after pref has changed.
  EXPECT_TRUE(entries.empty());
}

TEST_F(PrintJobHistoryCleanerTest, StorePrintJobHistoryIndefinite) {
  // Set expiration period policy to store history indefinitely.
  test_prefs_.SetInteger(prefs::kPrintJobHistoryExpirationPeriod, -1);
  print_job_database_->Initialize(base::DoNothing());

  task_environment_.FastForwardBy(base::Days(300));
  PrintJobInfo print_job_info1 =
      ConstructPrintJobInfo(kId1, task_environment_.GetMockClock()->Now());
  SavePrintJob(print_job_info1);

  task_environment_.FastForwardBy(base::Days(300));

  base::RunLoop run_loop;
  print_job_history_cleaner_->CleanUp(run_loop.QuitClosure());
  run_loop.Run();

  std::vector<PrintJobInfo> entries = GetPrintJobs();
  // CleanUp() call shouldn't clear anything as according to pref we store
  // history indefinitely.
  ASSERT_EQ(1u, entries.size());
  EXPECT_EQ(kId1, entries[0].id());
}

}  // namespace ash


text:
module AnsibleTowerClient
  class Project < BaseModel
    def playbooks
      Collection.new(api).find_all_by_url(related['playbooks'])
    end

    def can_update?
      response  = api.get(related['update'].to_s).body
      updatable = JSON.parse(response)

      updatable['can_update']
    end

    def update
      response = api.post(related['update'].to_s).body
      update   = JSON.parse(response)

      api.project_updates.find(update['project_update'])
    end

    def last_update
      return @last_update if defined? @last_update
      return @last_update = nil unless related.raw_hash.key?('last_update')
      return @last_update = nil if (update_id = related.last_update).blank?

      if !numberish?(update_id)
        if raw_hash.key?('summary_fields') && summary_fields.raw_hash.key?('last_update')
          update_id = summary_fields.last_update.id
        else
          /\/(?'update_id'\d+)\/?\z/ =~ update_id
        end
      end

      @last_update = update_id && api.project_updates.find(update_id)
    end

    private

    def numberish?(value)
      value.kind_of?(Numeric) || value.to_s =~ /\A\d+\z/
    end
  end
end


text:
package com.example.tests;

import static com.example.tests.ContactDataGenerator.loadContactsFromCSVFile;
import static org.junit.Assert.assertThat;
import static org.hamcrest.Matchers.*;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import com.example.utils.SortedListOf;

public class NewContact extends BaseClass{

@DataProvider
public Iterator<Object[]> contactsFromFile() throws IOException {
	return wrapContactsForDataProvider(loadContactsFromCSVFile(new File("contacts.txt"))).iterator();
}

  @Test(dataProvider = "contactsFromFile")
  public void testNewUserCreation(ContactData contact) throws Exception {
	//get contacts
	  SortedListOf<ContactData> oldContactsList = app.getModel().getContacts();

	//action
	app.getContactHelper().createContact(contact);

	//save new contacts at list
	SortedListOf<ContactData> newContactsList = app.getModel().getContacts();

	//asserts
	assertThat(newContactsList, equalTo(oldContactsList.withAdded(contact)));
    //if (wantToCheck()) {
        if ("yes".equals(app.getProperty("check.db"))) {
            assertThat(app.getModel().getContacts(), equalTo(app.getHibernateHelper().listContacts()));
        }
        if ("yes".equals(app.getProperty("check.ui"))) {
            assertThat(app.getModel().getContacts(), equalTo(app.getContactHelper().getUiContacts()));
        }
    //}
  }

}


text:
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;

namespace VSToDoList.BL.Services.Converters

{
    /// <summary>
    /// Converts between a <see cref="Models.ITask"/> Status and a <seealso cref="TextDecorationCollection"/>
    /// </summary>
    internal class TaskStatusToTextDecorationConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (!(value is Models.TaskStatus)) throw new ArgumentException("Task Status");
            if ((Models.TaskStatus)value == Models.TaskStatus.Done) return TextDecorations.Strikethrough;
            return null;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException("Task status convert back");
        }
    }
}


text:
immutable ErrorBarGeometry <: Gadfly.GeometryElement
    tag::Symbol

    function ErrorBarGeometry(; tag::Symbol=empty_tag)
        new(tag)
    end
end

immutable XErrorBarGeometry <: Gadfly.GeometryElement
    tag::Symbol

    function XErrorBarGeometry(; tag::Symbol=empty_tag)
        new(tag)
    end
end

immutable YErrorBarGeometry <: Gadfly.GeometryElement
    tag::Symbol

    function YErrorBarGeometry(; tag::Symbol=empty_tag)
        new(tag)
    end
end

const errorbar = ErrorBarGeometry
const xerrorbar = XErrorBarGeometry
const yerrorbar = YErrorBarGeometry

function element_aesthetics(::ErrorBarGeometry)
    [:x, :y, :xmin, :xmax, :ymin, :ymax]
end

function element_aesthetics(::YErrorBarGeometry)
    [:x, :ymin, :ymax]
end

function element_aesthetics(::XErrorBarGeometry)
    [:y, :xmin, :xmax]
end

# Generate a form for the errorbar geometry.
#
# Args:
#   geom: errorbar geometry
#   theme: the plot's theme
#   aes: aesthetics
#
# Returns:
#   A compose Form.
#
function render(geom::ErrorBarGeometry, theme::Gadfly.Theme, aes::Gadfly.Aesthetics)
    # check for X and Y error bar aesthetics
    if isempty(Gadfly.undefined_aesthetics(aes, element_aesthetics(xerrorbar())...))
        xctx = render(xerrorbar(), theme, aes)
    else
        xctx = nothing
    end
    if isempty(Gadfly.undefined_aesthetics(aes, element_aesthetics(yerrorbar())...))
        yctx = render(yerrorbar(), theme, aes)
    else
        yctx = nothing
    end
    compose(context(order=3), xctx, yctx)
end

function render(geom::YErrorBarGeometry, theme::Gadfly.Theme, aes::Gadfly.Aesthetics)
    Gadfly.assert_aesthetics_defined("Geom.errorbar", aes,
                                     element_aesthetics(geom)...)
    Gadfly.assert_aesthetics_equal_length("Geom.errorbar", aes,
                                          element_aesthetics(geom)...)

    default_aes = Gadfly.Aesthetics()
    default_aes.color = PooledDataArray(RGB{Float32}[theme.default_color])
    aes = inherit(aes, default_aes)
    caplen = theme.errorbar_cap_length/2
    ttc, teb, tbc = subtags(geom.tag, :top_cap, :error_bar, :bottom_cap)

    return compose!(
        context(order=3; tag=geom.tag),

        # top cap
        Compose.line([[(x*cx - caplen, ymax), (x*cx + caplen, ymax)]
                      for (x, ymax) in zip(aes.x, aes.ymax)], ttc),

        # error bar
        Compose.line([[(x*cx, ymax), (x*cx, ymin)]
                      for (x, ymin, ymax) in zip(aes.x, aes.ymin, aes.ymax)], teb),

        # bottom cap
        Compose.line([[(x*cx - caplen, ymin), (x*cx + caplen, ymin)]
                      for (x, ymin) in zip(aes.x, aes.ymin)], tbc),

        stroke([theme.stroke_color(c) for c in aes.color]),
        linewidth(theme.line_width),
        aes.color_key_continuous == true ?
            svgclass("geometry") :
            svgclass([string("geometry ", svg_color_class_from_label(aes.color_label([c])[1]))
                      for c in aes.color]))
end

function render(geom::XErrorBarGeometry, theme::Gadfly.Theme, aes::Gadfly.Aesthetics)
    Gadfly.assert_aesthetics_defined("Geom.errorbar", aes,
                                     element_aesthetics(geom)...)
    Gadfly.assert_aesthetics_equal_length("Geom.errorbar", aes,
                                          element_aesthetics(geom)...)

    colored = aes.color != nothing
    default_aes = Gadfly.Aesthetics()
    default_aes.color = PooledDataArray(RGB{Float32}[theme.default_color])
    aes = inherit(aes, default_aes)
    caplen = theme.errorbar_cap_length/2
    tlc, teb, trc = subtags(geom.tag, :left_cap, :error_bar, :right_cap)

    return compose!(
        context(order=3, tag=geom.tag),

        # left cap
        Compose.line([[(xmin, y*cy - caplen), (xmin, y*cy + caplen)]
                      for (xmin, y) in zip(aes.xmin, aes.y)], tlc),

        # error bar
        Compose.line([[(xmin, y*cy), (xmax, y*cy)]
                      for (xmin, xmax, y) in zip(aes.xmin, aes.xmax, aes.y)], teb),

        # right cap
        Compose.line([[(xmax, y*cy - caplen), (xmax, y*cy + caplen)]
                      for (xmax, y) in zip(aes.xmax, aes.y)], trc),

        stroke([theme.stroke_color(c) for c in aes.color]),
        linewidth(theme.line_width),
        (aes.color_key_continuous == true || !colored) ?
            svgclass("geometry") :
            svgclass([string("geometry ", svg_color_class_from_label(aes.color_label([c])[1]))
                      for c in aes.color]))
end


text:
package org.springframework.aop.aspectj;

import java.io.Serializable;
import java.lang.reflect.Method;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

import org.springframework.aop.AfterAdvice;

/**
 * Spring AOP advice wrapping an AspectJ after-throwing advice method.
 *
 * @author Rod Johnson
 * @since 2.0
 */
@SuppressWarnings("serial")
public class AspectJAfterThrowingAdvice extends AbstractAspectJAdvice
		implements MethodInterceptor, AfterAdvice, Serializable {

	public AspectJAfterThrowingAdvice(
			Method aspectJBeforeAdviceMethod, AspectJExpressionPointcut pointcut, AspectInstanceFactory aif) {

		super(aspectJBeforeAdviceMethod, pointcut, aif);
	}

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

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

	@Override
	public void setThrowingName(String name) {
		setThrowingNameNoCheck(name);
	}

	@Override
	public Object invoke(MethodInvocation mi) throws Throwable {
		try {
			return mi.proceed();
		}
		catch (Throwable ex) {
			if (shouldInvokeOnThrowing(ex)) {
				invokeAdviceMethod(getJoinPointMatch(), null, ex);
			}
			throw ex;
		}
	}

	/**
	 * In AspectJ semantics, after throwing advice that specifies a throwing clause
	 * is only invoked if the thrown exception is a subtype of the given throwing type.
	 */
	private boolean shouldInvokeOnThrowing(Throwable ex) {
		return getDiscoveredThrowingType().isAssignableFrom(ex.getClass());
	}

}


text:
package org.molasdin.wbase.storage.cursor;

/**
 * Result of search
 * Intended to provide convenient pagination, sorting and filtering
 * @param <T>
 */
public interface BiDirectionalBatchCursor<T> extends BatchCursor<T> {
    long currentPage();
    void setCurrentPage(long page);
}


text:
using System;
using System.Collections.Generic;
using ATMobile.Objects;
using ATMobile.PickerForms;
using Xamarin.Forms;

namespace ATMobile.Controls
{
    public class ATArcherEntry : ContentView
    {
        private string m_strLongDescription;
        private string m_strShortDescription;
        private ATLabel m_lblTitle;
        private Grid m_gridLayout;
        private Button m_btnPick;
        private Archer m_Archer;
        private List<Guid> m_PossibleArchers = null;

        public ATArcherEntry (string _shortDescription, string _longDescription)
        {
            m_strShortDescription = _shortDescription;
            m_strLongDescription = _longDescription;

            //Setup grid to hold the controls
            m_gridLayout = new Grid {
                Padding = 5,
                HorizontalOptions = LayoutOptions.FillAndExpand,
                RowDefinitions = {
                    new RowDefinition {
                        Height = new GridLength (40, GridUnitType.Absolute) //Name
                    }
                },
                ColumnDefinitions = {
                    new ColumnDefinition {
                        Width = new GridLength(1, GridUnitType.Star)
                    },
                    new ColumnDefinition {
                        Width = new GridLength(80, GridUnitType.Absolute)
                    }
                }
            };

            m_lblTitle = new ATLabel {
                VerticalTextAlignment = TextAlignment.Center
            };

            if (Device.Idiom == TargetIdiom.Phone) {
                m_lblTitle.Text = m_strShortDescription;
            } else {
                m_lblTitle.Text = m_strLongDescription;
            }

            m_gridLayout.Children.Add (m_lblTitle, 0, 0);

            m_btnPick = new Button {
                Text = "Pick",
                WidthRequest = 80,
                HeightRequest = 40,
                BorderWidth = 1,
                HorizontalOptions = LayoutOptions.End
            };
            m_btnPick.Clicked += Pick;
            m_gridLayout.Children.Add (m_btnPick, 1, 0);

            Content = m_gridLayout;
        }

        async private void Pick (object sender, EventArgs e)
        {
            ArcherPicker picker = new ArcherPicker (m_PossibleArchers, false);
            picker.ItemPicked += Picked;

            await Navigation.PushModalAsync (picker);
        }

        private void Picked (Archer _archer)
        {
            m_Archer = _archer;
            SetText ();
        }

        private void SetText ()
        {
            if (m_Archer == null) {
                if (Device.Idiom == TargetIdiom.Phone) {
                    m_lblTitle.Text = m_strShortDescription;
                } else {
                    m_lblTitle.Text = m_strLongDescription;
                }

            } else {
                m_lblTitle.Text = string.Format (
                    "{0} : {1}",
                    m_strShortDescription,
                    m_Archer.FullName);
            }
        }

        public Archer Archer {
            get {
                return m_Archer;
            }

            set {
                m_Archer = value;
                SetText ();
            }
        }

        public new bool IsEnabled {
            get {
                return base.IsEnabled;
            }

            set {
                base.IsEnabled = value;
                m_btnPick.IsEnabled = value;
            }
        }

        public List<Guid> PossibleArchers {
            get {
                return m_PossibleArchers;
            }
            set {
                m_PossibleArchers = value;
            }
        }
    }
}