text:
#include "ecma-alloc.h"
#include "ecma-builtin-helpers.h"
#include "ecma-builtins.h"
#include "ecma-conversion.h"
#include "ecma-exceptions.h"
#include "ecma-gc.h"
#include "ecma-globals.h"
#include "ecma-helpers.h"
#include "ecma-objects.h"
#include "ecma-objects-general.h"
#include "ecma-try-catch-macro.h"
#include "jrt.h"

#define ECMA_BUILTINS_INTERNAL
#include "ecma-builtins-internal.h"

#define BUILTIN_INC_HEADER_NAME "ecma-builtin-object.inc.h"
#define BUILTIN_UNDERSCORED_ID object
#include "ecma-builtin-internal-routines-template.inc.h"

/** \addtogroup ecma ECMA
 * @{
 *
 * \addtogroup ecmabuiltins
 * @{
 *
 * \addtogroup object ECMA Object object built-in
 * @{
 */

/**
 * Handle calling [[Call]] of built-in Object object
 *
 * @return ecma value
 */
ecma_value_t
ecma_builtin_object_dispatch_call (const ecma_value_t *arguments_list_p, /**< arguments list */
                                   ecma_length_t arguments_list_len) /**< number of arguments */
{
  JERRY_ASSERT (arguments_list_len == 0 || arguments_list_p != NULL);

  ecma_value_t ret_value = ECMA_VALUE_EMPTY;

  if (arguments_list_len == 0
      || ecma_is_value_undefined (arguments_list_p[0])
      || ecma_is_value_null (arguments_list_p[0]))
  {
    ret_value = ecma_builtin_object_dispatch_construct (arguments_list_p, arguments_list_len);
  }
  else
  {
    ret_value = ecma_op_to_object (arguments_list_p[0]);
  }

  return ret_value;
} /* ecma_builtin_object_dispatch_call */

/**
 * Handle calling [[Construct]] of built-in Object object
 *
 * @return ecma value
 */
ecma_value_t
ecma_builtin_object_dispatch_construct (const ecma_value_t *arguments_list_p, /**< arguments list */
                                        ecma_length_t arguments_list_len) /**< number of arguments */
{
  JERRY_ASSERT (arguments_list_len == 0 || arguments_list_p != NULL);

  if (arguments_list_len == 0)
  {
    ecma_object_t *obj_p = ecma_op_create_object_object_noarg ();

    return ecma_make_object_value (obj_p);
  }
  else
  {
    return ecma_op_create_object_object_arg (arguments_list_p[0]);
  }
} /* ecma_builtin_object_dispatch_construct */

/**
 * The Object object's 'getPrototypeOf' routine
 *
 * See also:
 *          ECMA-262 v5, 15.2.3.2
 *
 * @return ecma value
 *         Returned value must be freed with ecma_free_value.
 */
static ecma_value_t
ecma_builtin_object_object_get_prototype_of (ecma_value_t this_arg, /**< 'this' argument */
                                             ecma_value_t arg) /**< routine's argument */
{
  JERRY_UNUSED (this_arg);
  ecma_value_t ret_value = ECMA_VALUE_EMPTY;
  bool was_object = ecma_is_value_object (arg);

  /* 1. */
  if (!was_object)
  {
#ifndef CONFIG_DISABLE_ES2015_BUILTIN
    arg = ecma_op_to_object (arg);
    if (ECMA_IS_VALUE_ERROR (arg))
    {
      return arg;
    }
#else /* CONFIG_DISABLE_ES2015_BUILTIN */
    return ecma_raise_type_error (ECMA_ERR_MSG ("Argument is not an object."));
#endif /* !CONFIG_DISABLE_ES2015_BUILTIN */
  }
  /* 2. */
  ecma_object_t *obj_p = ecma_get_object_from_value (arg);
  ecma_object_t *prototype_p = ecma_get_object_prototype (obj_p);

  if (prototype_p)
  {
    ret_value = ecma_make_object_value (prototype_p);
    ecma_ref_object (prototype_p);
  }
  else
  {
    ret_value = ECMA_VALUE_NULL;
  }

#ifndef CONFIG_DISABLE_ES2015_BUILTIN
  if (!was_object)
  {
    ecma_free_value (arg);
  }
#endif /* !CONFIG_DISABLE_ES2015_BUILTIN */

  return ret_value;
} /* ecma_builtin_object_object_get_prototype_of */

#ifndef CONFIG_DISABLE_ES2015_BUILTIN
/**
 * [[SetPrototypeOf]]
 *
 * See also:
 *          ES2015 9.1.2
 */
static bool
ecma_set_prototype_of (ecma_value_t o_value, /**< O */
                       ecma_value_t v_value) /**< V */
{
  /* 1. */
  JERRY_ASSERT (ecma_is_value_object (o_value));
  JERRY_ASSERT (ecma_is_value_object (v_value) || ecma_is_value_null (v_value));

  ecma_object_t *o_p = ecma_get_object_from_value (o_value);
  ecma_object_t *v_p = ecma_is_value_null (v_value) ? NULL : ecma_get_object_from_value (v_value);

  /* 3., 4. */
  if (v_p == ecma_get_object_prototype (o_p))
  {
    return true;
  }

  /* 2., 5. */
  if (!ecma_get_object_extensible (o_p))
  {
    return false;
  }

  /* 6., 7., 8. */
  ecma_object_t *p_p = v_p;
  while (true)
  {
    /* a. */
    if (p_p == NULL)
    {
      break;
    }

    /* b. */
    if (p_p == o_p)
    {
      return false;
    }

    /* c.i. TODO: es2015-subset profile does not support having a different
     * [[GetPrototypeOf]] internal method */

    /* c.ii. */
    p_p = ecma_get_object_prototype (p_p);
  }

  /* 9. */
  ECMA_SET_POINTER (o_p->prototype_or_outer_reference_cp, v_p);

  /* 10. */
  return true;
} /* ecma_set_prototype_of */

/**
 * The Object object's 'setPrototypeOf' routine
 *
 * See also:
 *          ES2015 19.1.2.18
 *
 * @return ecma value
 *         Returned value must be freed with ecma_free_value.
 */
static ecma_value_t
ecma_builtin_object_object_set_prototype_of (ecma_value_t this_arg, /**< 'this' argument */
                                             ecma_value_t arg1, /**< routine's first argument */
                                             ecma_value_t arg2) /**< routine's second argument */
{
  JERRY_UNUSED (this_arg);
  ecma_value_t ret_value = ECMA_VALUE_EMPTY;

  /* 1., 2. */
  ECMA_TRY_CATCH (unused_value,
                  ecma_op_check_object_coercible (arg1),
                  ret_value);

  /* 3. */
  if (!ecma_is_value_object (arg2) && !ecma_is_value_null (arg2))
  {
    ret_value = ecma_raise_type_error (ECMA_ERR_MSG ("proto is neither Object nor Null."));
  }
  else
  {
    /* 4. */
    if (!ecma_is_value_object (arg1))
    {
      ret_value = ecma_copy_value (arg1);
    }
    else
    {
      /* 5. */
      bool status = ecma_set_prototype_of (arg1, arg2);

      /* 6. TODO: es2015-subset profile does not support having a different
       * [[SetPrototypeOf]] internal method */

      /* 7. */
      if (!status)
      {
        ret_value = ecma_raise_type_error (ECMA_ERR_MSG ("cannot set prototype."));
      }
      else
      {
        /* 8. */
        ret_value = ecma_copy_value (arg1);
      }
    }
  }

  ECMA_FINALIZE (unused_value);

  return ret_value;
} /* ecma_builtin_object_object_set_prototype_of */
#endif /* !CONFIG_DISABLE_ES2015_BUILTIN */

/**
 * The Object object's 'getOwnPropertyNames' routine
 *
 * See also:
 *          ECMA-262 v5, 15.2.3.4
 *
 * @return ecma value
 *         Returned value must be freed with ecma_free_value.
 */
static ecma_value_t
ecma_builtin_object_object_get_own_property_names (ecma_value_t this_arg, /**< 'this' argument */
                                                   ecma_value_t arg) /**< routine's argument */
{
  JERRY_UNUSED (this_arg);
  ecma_value_t ret_value = ECMA_VALUE_EMPTY;

  if (!ecma_is_value_object (arg))
  {
    /* 1. */
    ret_value = ecma_raise_type_error (ECMA_ERR_MSG ("Argument is not an object."));
  }
  else
  {
    ecma_object_t *obj_p = ecma_get_object_from_value (arg);
    /* 2-5. */
    ret_value = ecma_builtin_helper_object_get_properties (obj_p, false);
  }

  return ret_value;
} /* ecma_builtin_object_object_get_own_property_names */

/**
 * The Object object's 'seal' routine
 *
 * See also:
 *          ECMA-262 v5, 15.2.3.8
 *
 * @return ecma value
 *         Returned value must be freed with ecma_free_value.
 */
static ecma_value_t
ecma_builtin_object_object_seal (ecma_value_t this_arg, /**< 'this' argument */
                                 ecma_value_t arg) /**< routine's argument */
{
  JERRY_UNUSED (this_arg);
  ecma_value_t ret_value = ECMA_VALUE_EMPTY;

  /* 1. */
  if (!ecma_is_value_object (arg))
  {
    ret_value = ecma_raise_type_error (ECMA_ERR_MSG ("Argument is not an object."));
  }
  else
  {
    /* 2. */
    ecma_object_t *obj_p = ecma_get_object_from_value (arg);

    ecma_collection_header_t *props_p = ecma_op_object_get_property_names (obj_p, false, false, false);

    ecma_value_t *ecma_value_p = ecma_collection_iterator_init (props_p);

    while (ecma_value_p != NULL && ecma_is_value_empty (ret_value))
    {
      ecma_string_t *property_name_p = ecma_get_string_from_value (*ecma_value_p);
      ecma_value_p = ecma_collection_iterator_next (ecma_value_p);

      /* 2.a */
      ecma_property_descriptor_t prop_desc;

      if (!ecma_op_object_get_own_property_descriptor (obj_p, property_name_p, &prop_desc))
      {
        continue;
      }

      /* 2.b */
      prop_desc.is_configurable = false;

      /* 2.c */
      ECMA_TRY_CATCH (define_own_prop_ret,
                      ecma_op_object_define_own_property (obj_p,
                                                          property_name_p,
                                                          &prop_desc,
                                                          true),
                      ret_value);
      ECMA_FINALIZE (define_own_prop_ret);

      ecma_free_property_descriptor (&prop_desc);
    }

    ecma_free_values_collection (props_p, 0);

    if (ecma_is_value_empty (ret_value))
    {
      /* 3. */
      ecma_set_object_extensible (obj_p, false);

      /* 4. */
      ret_value = ecma_copy_value (arg);
    }
  }

  return ret_value;
} /* ecma_builtin_object_object_seal */

/**
 * The Object object's 'freeze' routine
 *
 * See also:
 *          ECMA-262 v5, 15.2.3.9
 *
 * @return ecma value
 *         Returned value must be freed with ecma_free_value.
 */
static ecma_value_t
ecma_builtin_object_object_freeze (ecma_value_t this_arg, /**< 'this' argument */
                                   ecma_value_t arg) /**< routine's argument */
{
  JERRY_UNUSED (this_arg);
  ecma_value_t ret_value = ECMA_VALUE_EMPTY;

  /* 1. */
  if (!ecma_is_value_object (arg))
  {
    ret_value = ecma_raise_type_error (ECMA_ERR_MSG ("Argument is not an object."));
  }
  else
  {
    /* 2. */
    ecma_object_t *obj_p = ecma_get_object_from_value (arg);

    ecma_collection_header_t *props_p = ecma_op_object_get_property_names (obj_p, false, false, false);

    ecma_value_t *ecma_value_p = ecma_collection_iterator_init (props_p);

    while (ecma_value_p != NULL && ecma_is_value_empty (ret_value))
    {
      ecma_string_t *property_name_p = ecma_get_string_from_value (*ecma_value_p);
      ecma_value_p = ecma_collection_iterator_next (ecma_value_p);

      /* 2.a */
      ecma_property_descriptor_t prop_desc;

      if (!ecma_op_object_get_own_property_descriptor (obj_p, property_name_p, &prop_desc))
      {
        continue;
      }

      /* 2.b */
      if (prop_desc.is_writable_defined && prop_desc.is_writable)
      {
        prop_desc.is_writable = false;
      }

      /* 2.c */
      prop_desc.is_configurable = false;

      /* 2.d */
      ECMA_TRY_CATCH (define_own_prop_ret,
                      ecma_op_object_define_own_property (obj_p,
                                                          property_name_p,
                                                          &prop_desc,
                                                          true),
                      ret_value);
      ECMA_FINALIZE (define_own_prop_ret);

      ecma_free_property_descriptor (&prop_desc);
    }

    ecma_free_values_collection (props_p, 0);

    if (ecma_is_value_empty (ret_value))
    {
      /* 3. */
      ecma_set_object_extensible (obj_p, false);

      /* 4. */
      ret_value = ecma_copy_value (arg);
    }
  }

  return ret_value;
} /* ecma_builtin_object_object_freeze */

/**
 * The Object object's 'preventExtensions' routine
 *
 * See also:
 *          ECMA-262 v5, 15.2.3.10
 *
 * @return ecma value
 *         Returned value must be freed with ecma_free_value.
 */
static ecma_value_t
ecma_builtin_object_object_prevent_extensions (ecma_value_t this_arg, /**< 'this' argument */
                                               ecma_value_t arg) /**< routine's argument */
{
  JERRY_UNUSED (this_arg);
  ecma_value_t ret_value = ECMA_VALUE_EMPTY;

  if (!ecma_is_value_object (arg))
  {
    ret_value = ecma_raise_type_error (ECMA_ERR_MSG ("Argument is not an object."));
  }
  else
  {
    ecma_object_t *obj_p = ecma_get_object_from_value (arg);
    ecma_set_object_extensible (obj_p, false);

    ret_value = ecma_copy_value (arg);
  }

  return ret_value;
} /* ecma_builtin_object_object_prevent_extensions */

/**
 * Common helper code for the 'isFrozen' and 'isSealed' fuctions of Object.
 *
 * See also:
 *         Object.isFrozen
 *         Object.isSealed
 *
 * @return ecma value
 *         Returned value must be freed with ecma_free_value.
 */
static ecma_value_t
ecma_builtin_object_frozen_or_sealed_helper (ecma_value_t this_arg, /**< 'this' argument */
                                             ecma_value_t arg, /**< routine's argument */
                                             bool frozen_mode) /**< routine mode */
{
  JERRY_UNUSED (this_arg);
  ecma_value_t ret_value = ECMA_VALUE_EMPTY;

  /* 1. */
  if (!ecma_is_value_object (arg))
  {
    ret_value = ecma_raise_type_error (ECMA_ERR_MSG ("Argument is not an object."));
  }
  else
  {
    ecma_object_t *obj_p = ecma_get_object_from_value (arg);

    bool is_sealed_or_frozen;

    /* 3. */
    if (ecma_get_object_extensible (obj_p))
    {
      is_sealed_or_frozen = false;
    }
    else
    {
      /* the value can be updated in the loop below */
      is_sealed_or_frozen = true;

      /* 2. */
      ecma_collection_header_t *props_p = ecma_op_object_get_property_names (obj_p, false, false, false);

      ecma_value_t *ecma_value_p = ecma_collection_iterator_init (props_p);

      while (ecma_value_p != NULL)
      {
        ecma_string_t *property_name_p = ecma_get_string_from_value (*ecma_value_p);
        ecma_value_p = ecma_collection_iterator_next (ecma_value_p);

        /* 2.a */
        ecma_property_t property = ecma_op_object_get_own_property (obj_p,
                                                                    property_name_p,
                                                                    NULL,
                                                                    ECMA_PROPERTY_GET_NO_OPTIONS);

        /* 2.b for isFrozen */
        if (frozen_mode
            && ECMA_PROPERTY_GET_TYPE (property) != ECMA_PROPERTY_TYPE_NAMEDACCESSOR
            && ecma_is_property_writable (property))
        {
          is_sealed_or_frozen = false;
          break;
        }

        /* 2.b for isSealed, 2.c for isFrozen */
        if (ecma_is_property_configurable (property))
        {
          is_sealed_or_frozen = false;
          break;
        }
      }

      ecma_free_values_collection (props_p, 0);
    }

    /* 4. */
    ret_value = is_sealed_or_frozen ? ECMA_VALUE_TRUE : ECMA_VALUE_FALSE;
  }

  return ret_value;
} /* ecma_builtin_object_frozen_or_sealed_helper */

/**
 * The Object object's 'isSealed' routine
 *
 * See also:
 *          ECMA-262 v5, 15.2.3.11
 *
 * @return ecma value
 *         Returned value must be freed with ecma_free_value.
 */
static ecma_value_t
ecma_builtin_object_object_is_sealed (ecma_value_t this_arg, /**< 'this' argument */
                                      ecma_value_t arg) /**< routine's argument */
{
  return ecma_builtin_object_frozen_or_sealed_helper (this_arg, arg, false);
} /* ecma_builtin_object_object_is_sealed */

/**
 * The Object object's 'isFrozen' routine
 *
 * See also:
 *          ECMA-262 v5, 15.2.3.12
 *
 * @return ecma value
 *         Returned value must be freed with ecma_free_value.
 */
static ecma_value_t
ecma_builtin_object_object_is_frozen (ecma_value_t this_arg, /**< 'this' argument */
                                      ecma_value_t arg) /**< routine's argument */
{
  return ecma_builtin_object_frozen_or_sealed_helper (this_arg, arg, true);
} /* ecma_builtin_object_object_is_frozen */

/**
 * The Object object's 'isExtensible' routine
 *
 * See also:
 *          ECMA-262 v5, 15.2.3.13
 *
 * @return ecma value
 *         Returned value must be freed with ecma_free_value.
 */
static ecma_value_t
ecma_builtin_object_object_is_extensible (ecma_value_t this_arg, /**< 'this' argument */
                                          ecma_value_t arg) /**< routine's argument */
{
  JERRY_UNUSED (this_arg);
  ecma_value_t ret_value = ECMA_VALUE_EMPTY;

  if (!ecma_is_value_object (arg))
  {
    ret_value = ecma_raise_type_error (ECMA_ERR_MSG ("Argument is not an object."));
  }
  else
  {
    ecma_object_t *obj_p = ecma_get_object_from_value (arg);

    bool extensible = ecma_get_object_extensible (obj_p);

    ret_value = extensible ? ECMA_VALUE_TRUE : ECMA_VALUE_FALSE;
  }

  return ret_value;
} /* ecma_builtin_object_object_is_extensible */

/**
 * The Object object's 'keys' routine
 *
 * See also:
 *          ECMA-262 v5, 15.2.3.14
 *
 * @return ecma value
 *         Returned value must be freed with ecma_free_value.
 */
static ecma_value_t
ecma_builtin_object_object_keys (ecma_value_t this_arg, /**< 'this' argument */
                                 ecma_value_t arg) /**< routine's argument */
{
  JERRY_UNUSED (this_arg);
  ecma_value_t ret_value = ECMA_VALUE_EMPTY;

  if (!ecma_is_value_object (arg))
  {
    /* 1. */
    ret_value = ecma_raise_type_error (ECMA_ERR_MSG ("Argument is not an object."));
  }
  else
  {
    ecma_object_t *obj_p = ecma_get_object_from_value (arg);
    /* 3-6. */
    ret_value = ecma_builtin_helper_object_get_properties (obj_p, true);
  }

  return ret_value;
} /* ecma_builtin_object_object_keys */

/**
 * The Object object's 'getOwnPropertyDescriptor' routine
 *
 * See also:
 *          ECMA-262 v5, 15.2.3.3
 *
 * @return ecma value
 *         Returned value must be freed with ecma_free_value.
 */
static ecma_value_t
ecma_builtin_object_object_get_own_property_descriptor (ecma_value_t this_arg, /**< 'this' argument */
                                                        ecma_value_t arg1, /**< routine's first argument */
                                                        ecma_value_t arg2) /**< routine's second argument */
{
  JERRY_UNUSED (this_arg);
  ecma_value_t ret_value = ECMA_VALUE_EMPTY;

  /* 1. */
  if (!ecma_is_value_object (arg1))
  {
    ret_value = ecma_raise_type_error (ECMA_ERR_MSG ("Argument is not an object."));
    return ret_value;
  }

  ecma_object_t *obj_p = ecma_get_object_from_value (arg1);

  /* 2. */
  ECMA_TRY_CATCH (name_str_value,
                  ecma_op_to_string (arg2),
                  ret_value);

  ecma_string_t *name_str_p = ecma_get_string_from_value (name_str_value);

  /* 3. */
  ecma_property_descriptor_t prop_desc;

  if (ecma_op_object_get_own_property_descriptor (obj_p, name_str_p, &prop_desc))
  {
    /* 4. */
    ecma_object_t *desc_obj_p = ecma_op_from_property_descriptor (&prop_desc);

    ecma_free_property_descriptor (&prop_desc);

    ret_value = ecma_make_object_value (desc_obj_p);
  }
  else
  {
    ret_value = ECMA_VALUE_UNDEFINED;
  }

  ECMA_FINALIZE (name_str_value);

  return ret_value;
} /* ecma_builtin_object_object_get_own_property_descriptor */

/**
 * The Object object's 'create' routine
 *
 * See also:
 *          ECMA-262 v5, 15.2.3.5
 *
 * @return ecma value
 *         Returned value must be freed with ecma_free_value.
 */
static ecma_value_t
ecma_builtin_object_object_create (ecma_value_t this_arg, /**< 'this' argument */
                                   ecma_value_t arg1, /**< routine's first argument */
                                   ecma_value_t arg2) /**< routine's second argument */
{
  ecma_value_t ret_value = ECMA_VALUE_EMPTY;

  /* 1. */
  if (!ecma_is_value_object (arg1) && !ecma_is_value_null (arg1))
  {
    ret_value = ecma_raise_type_error (ECMA_ERR_MSG ("Argument is not an object."));
  }
  else
  {
    ecma_object_t *obj_p = NULL;

    if (!ecma_is_value_null (arg1))
    {
      obj_p = ecma_get_object_from_value (arg1);
    }
    /* 2-3. */
    ecma_object_t *result_obj_p = ecma_op_create_object_object_noarg_and_set_prototype (obj_p);

    /* 4. */
    if (!ecma_is_value_undefined (arg2))
    {
      ECMA_TRY_CATCH (obj,
                      ecma_builtin_object_object_define_properties (this_arg,
                                                                    ecma_make_object_value (result_obj_p),
                                                                    arg2),
                      ret_value);
      ECMA_FINALIZE (obj);
    }

    /* 5. */
    if (ecma_is_value_empty (ret_value))
    {
      ret_value = ecma_copy_value (ecma_make_object_value (result_obj_p));
    }

    ecma_deref_object (result_obj_p);
  }

  return ret_value;
} /* ecma_builtin_object_object_create */

/**
 * The Object object's 'defineProperties' routine
 *
 * See also:
 *          ECMA-262 v5, 15.2.3.7
 *
 * @return ecma value
 *         Returned value must be freed with ecma_free_value.
 */
static ecma_value_t
ecma_builtin_object_object_define_properties (ecma_value_t this_arg, /**< 'this' argument */
                                              ecma_value_t arg1, /**< routine's first argument */
                                              ecma_value_t arg2) /**< routine's second argument */
{
  JERRY_UNUSED (this_arg);
  ecma_value_t ret_value = ECMA_VALUE_EMPTY;

  /* 1. */
  if (!ecma_is_value_object (arg1))
  {
    ret_value = ecma_raise_type_error (ECMA_ERR_MSG ("Argument is not an object."));
  }
  else
  {
    ecma_object_t *obj_p = ecma_get_object_from_value (arg1);

    /* 2. */
    ECMA_TRY_CATCH (props,
                    ecma_op_to_object (arg2),
                    ret_value);

    ecma_object_t *props_p = ecma_get_object_from_value (props);
    /* 3. */
    ecma_collection_header_t *prop_names_p = ecma_op_object_get_property_names (props_p, false, true, false);
    uint32_t property_number = prop_names_p->item_count;

    ecma_value_t *ecma_value_p = ecma_collection_iterator_init (prop_names_p);

    /* 4. */
    JMEM_DEFINE_LOCAL_ARRAY (property_descriptors, property_number, ecma_property_descriptor_t);

    uint32_t property_descriptor_number = 0;

    while (ecma_value_p != NULL && ecma_is_value_empty (ret_value))
    {
      /* 5.a */
      ECMA_TRY_CATCH (desc_obj,
                      ecma_op_object_get (props_p, ecma_get_string_from_value (*ecma_value_p)),
                      ret_value);

      /* 5.b */
      ECMA_TRY_CATCH (conv_result,
                      ecma_op_to_property_descriptor (desc_obj,
                                                      &property_descriptors[property_descriptor_number]),
                      ret_value);

      property_descriptor_number++;

      ECMA_FINALIZE (conv_result);
      ECMA_FINALIZE (desc_obj);

      ecma_value_p = ecma_collection_iterator_next (ecma_value_p);
    }

    /* 6. */
    ecma_value_p = ecma_collection_iterator_init (prop_names_p);

    for (uint32_t index = 0;
         index < property_number && ecma_is_value_empty (ret_value);
         index++)
    {
      ECMA_TRY_CATCH (define_own_prop_ret,
                      ecma_op_object_define_own_property (obj_p,
                                                          ecma_get_string_from_value (*ecma_value_p),
                                                          &property_descriptors[index],
                                                          true),
                      ret_value);

      ECMA_FINALIZE (define_own_prop_ret);

      ecma_value_p = ecma_collection_iterator_next (ecma_value_p);
    }

    /* Clean up. */
    for (uint32_t index = 0;
         index < property_descriptor_number;
         index++)
    {
      ecma_free_property_descriptor (&property_descriptors[index]);
    }

    JMEM_FINALIZE_LOCAL_ARRAY (property_descriptors);

    ecma_free_values_collection (prop_names_p, 0);

    /* 7. */
    if (ecma_is_value_empty (ret_value))
    {
      ret_value = ecma_copy_value (arg1);
    }

    ECMA_FINALIZE (props);
  }

  return ret_value;
} /* ecma_builtin_object_object_define_properties */

/**
 * The Object object's 'defineProperty' routine
 *
 * See also:
 *          ECMA-262 v5, 15.2.3.6
 *
 * @return ecma value
 *         Returned value must be freed with ecma_free_value.
 */
static ecma_value_t
ecma_builtin_object_object_define_property (ecma_value_t this_arg, /**< 'this' argument */
                                            ecma_value_t arg1, /**< routine's first argument */
                                            ecma_value_t arg2, /**< routine's second argument */
                                            ecma_value_t arg3) /**< routine's third argument */
{
  JERRY_UNUSED (this_arg);
  ecma_value_t ret_value = ECMA_VALUE_EMPTY;

  if (!ecma_is_value_object (arg1))
  {
    ret_value = ecma_raise_type_error (ECMA_ERR_MSG ("Argument is not an object."));
  }
  else
  {
    ecma_object_t *obj_p = ecma_get_object_from_value (arg1);

    ECMA_TRY_CATCH (name_str_value,
                    ecma_op_to_string (arg2),
                    ret_value);

    ecma_string_t *name_str_p = ecma_get_string_from_value (name_str_value);

    ecma_property_descriptor_t prop_desc;

    ECMA_TRY_CATCH (conv_result,
                    ecma_op_to_property_descriptor (arg3, &prop_desc),
                    ret_value);

    ECMA_TRY_CATCH (define_own_prop_ret,
                    ecma_op_object_define_own_property (obj_p,
                                                        name_str_p,
                                                        &prop_desc,
                                                        true),
                    ret_value);

    ret_value = ecma_copy_value (arg1);

    ECMA_FINALIZE (define_own_prop_ret);
    ecma_free_property_descriptor (&prop_desc);
    ECMA_FINALIZE (conv_result);
    ECMA_FINALIZE (name_str_value);
  }

  return ret_value;
} /* ecma_builtin_object_object_define_property */

/**
 * @}
 * @}
 * @}
 */


text:
package dngine

import (
	"path"

	"go.uber.org/zap"
)

func InitializeLog(env, logpath string) *zap.Logger {
	var zapConf zap.Config
	var err error

	if env == "production" {
		zapConf = zap.NewProductionConfig()
	} else {
		zapConf = zap.NewDevelopmentConfig()
	}

	zapConf.OutputPaths = []string{path.Join(logpath, "output.log")}
	zapConf.ErrorOutputPaths = []string{path.Join(logpath, "err.output.log")}
	logger, err := zapConf.Build()
	if err != nil {
		panic(err.Error())
	}

	return logger
}

redpajama_set_name: RedPajamaGithub


text:
mod test_submessage_deserialize;
mod test_submessage_serialize;
mod test_submessage_variant_roundtrip;


text:
<?php
namespace app\controllers;
use Yii;
use yii\web\Controller;

class NewsController extends Controller
{

    public function actionView()
    {
       $hello = 'hello';
       return $this->render('view', compact('hello'));
    }

}


text:
package pft.utils;

import java.util.List;
import java.util.Random;

import com.google.common.collect.ForwardingList;
import com.google.common.collect.Lists;

public class ListOf<T> extends ForwardingList<T> {

  private List<T> list = Lists.newArrayList();

  public ListOf() {
  }

  public ListOf(ListOf<T> listToCopy) {
    list = Lists.newArrayList(listToCopy);
  }

  @Override
  protected List<T> delegate() {
    return list;
  }

  public ListOf<T> withAppended(T item) {
    ListOf<T> newItems = new ListOf<T>();
    newItems.list = Lists.newArrayList(this.list);
    newItems.list.add(item);
    return newItems;
  }

  public ListOf<T> without(T item) {
    ListOf<T> newItems = new ListOf<T>();
    newItems.list = Lists.newArrayList(this.list);
    newItems.list.remove(item);
    return newItems;
  }

  public ListOf<T> withPrepended(T item) {
    ListOf<T> newItems = new ListOf<T>();
    newItems.list = Lists.newArrayList();
    newItems.list.add(item);
    newItems.list.addAll(this.list);
    return newItems;
  }

  public T getSome() {
    if (size() == 0) {
      return null;
    } else {
      return list.get(new Random().nextInt(size()));
    }
  }
}


text:
package de.roamingthings.auth.config;

import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Alexander Sparkowsky [info@roamingthings.de]
 * @version 2017/05/22
 */
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CorsFilter implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        final HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type");
        response.setHeader("Access-Control-Max-Age", "3600");
        if ("OPTIONS".equalsIgnoreCase(((HttpServletRequest) req).getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            chain.doFilter(req, res);
        }
    }

    @Override
    public void destroy() {
    }

    @Override
    public void init(FilterConfig config) throws ServletException {
    }
}


text:
package cn.ustc.cryptoverification;

import java.security.InvalidKeyException;
import java.security.SecureRandom;
import java.util.Random;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;

import com.mobilepg.crypto.RawAES;
import com.mobilepg.crypto.RawRC4;

public class CryptoVerificationActivity extends Activity {

	private TextView textView;

	byte[] encrypt(String passwd, byte[] plainTextBytes) {
		try {
			// Get key generator.
			KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
			// Get random generator and set the seed.
			SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
			secureRandom.setSeed(passwd.getBytes());
			// Generate the raw key.
			keyGenerator.init(128, secureRandom);
			SecretKey secretKey = keyGenerator.generateKey();
			//
			SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getEncoded(), "AES");
			//
			Cipher cipher = Cipher.getInstance("AES");
			cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
			byte[] cipherTextBytes = cipher.doFinal(plainTextBytes);
			// Done
			return cipherTextBytes;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	byte[] decrypt(String passwd, byte[] cipherTextBytes) {
		try {
			KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
			SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
			secureRandom.setSeed(passwd.getBytes());
			keyGenerator.init(128, secureRandom);
			SecretKey secretKey = keyGenerator.generateKey();
			SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getEncoded(), "AES");
			Cipher cipher = Cipher.getInstance("AES");
			cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
			byte[] plainTextBytes = cipher.doFinal(cipherTextBytes);
			return plainTextBytes;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	void aesUnitTest(String key, byte[] p, int n) {
		byte[] c = encrypt(key, p);
		byte[] p2 = decrypt(key, c);
		for (int i = 0; i < p.length; i++) {
			if (p[i] != p2[i]) {
				output("test data " + n + " failed\n");
				return ;
			}
		}
		output("test data " + n + " pass\n");
	}

	void aesTestCase() {
		aesUnitTest("test", "12345678".getBytes(), 1);
		aesUnitTest("totem", "fuck you!".getBytes(), 2);
	}

	void testAes512kb() {
		byte[] data = new byte[512 * 1024];
		Random random = new Random();
		random.nextBytes(data);

		output("Test AES 512kb start:\n");
		long startTime = System.currentTimeMillis();

		byte[] unused = encrypt("totem", data);

		long endTime = System.currentTimeMillis();

		output("Done: " + (endTime - startTime) + "\n");
	}

	byte[] encryptAesCbcPkcs5(String passwd, byte[] plainTextBytes) {
		try {
			// Get key generator.
			KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
			// Get random generator and set the passwd as seed.
			SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
			secureRandom.setSeed(passwd.getBytes());
			// Generate the raw key.
			keyGenerator.init(128, secureRandom);
			SecretKey secretKey = keyGenerator.generateKey();
			//
			SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getEncoded(), "AES");
			//
			Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
			IvParameterSpec iv = new IvParameterSpec("0102030405060708".getBytes());
			cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, iv);
			byte[] cipherTextBytes = cipher.doFinal(plainTextBytes);
			return cipherTextBytes;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	byte[] decryptAesCbcPkcs5(String passwd, byte[] cipherTextBytes) {
		try {
			// Get key generator.
			KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
			// Get random generator and set the passwd as seed.
			SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
			secureRandom.setSeed(passwd.getBytes());
			// Generate the raw key.
			keyGenerator.init(128, secureRandom);
			SecretKey secretKey = keyGenerator.generateKey();
			//
			SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getEncoded(), "AES");
			//
			Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
			IvParameterSpec iv = new IvParameterSpec("0102030405060708".getBytes());
			cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, iv);
			byte[] plainTextBytes = cipher.doFinal(cipherTextBytes);
			return plainTextBytes;
		} catch (Exception e) {
			Log.e("AES Unit Test",e.getLocalizedMessage());
			e.printStackTrace();
		}
		return null;
	}

	void aesCbcPkcs5UnitTest(String key, byte[] p, int n) {
		byte[] c = encryptAesCbcPkcs5(key, p);
		byte[] p2 = decryptAesCbcPkcs5(key, c);

		for (int i = 0; i < p.length; i++) {
			if (p[i] != p2[i]) {
				output("AES unit test " + n + " fail.\n");
				return ;
			}
		}
		output("AES unit test " + n + " pass.\n");
	}

	void aesCbcPkcs5TestCase() {
		aesCbcPkcs5UnitTest("totem", "12345".getBytes(), 1);
	}

	void testAesCbcPkcs5Padding512kb() {
		byte[] data = new byte[512 * 1024];
		Random random = new Random();
		random.nextBytes(data);

		output("Test AES CBC PACS5Padding 512kb start:\n");
		long startTime = System.currentTimeMillis();

		encryptAesCbcPkcs5("totemabc", data);

		long endTime = System.currentTimeMillis();

		output("Done: " + (endTime - startTime) + "\n");
	}

	void rc4Test(byte[] key, byte[] keystream, int n) {
		byte[] work = new byte[keystream.length];
		for (int i = 0; i < work.length; i++) {
			work[i] = 0;
		}

		RC4 rc4 = new RC4();
		try {
			rc4.init(key);
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		}
		rc4.xorKeyStream(work, work);

		for (int i = 0; i < work.length; i++) {
			if (work[i] != keystream[i]) {
				output("test data " + n + " error.\n");
				break;
			}
		}
		rc4.reset();
	}

	void rc4TestCase() {
		byte[] key1 = {0x01, 0x23, 0x45, 0x67, (byte) 0x89, (byte) 0xab, (byte) 0xcd, (byte) 0xef};
		byte[] keystream1 = {0x74,  (byte) 0x94, (byte) 0xc2, (byte) 0xe7, 0x10, 0x4b, 0x08, 0x79};
		rc4Test(key1, keystream1, 1);

		byte[] key2 = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
		byte[] keystream2 = {(byte) 0xde, 0x18, (byte) 0x89, 0x41, (byte) 0xa3, 0x37, 0x5d, 0x3a};
		rc4Test(key2, keystream2, 2);

		byte[] key3 = {(byte) 0xef, 0x01, 0x23, 0x45};
		byte[] keystream3 = {(byte) 0xd6, (byte) 0xa1, 0x41, (byte) 0xa7, (byte) 0xec, 0x3c, 0x38, (byte) 0xdf, (byte) 0xbd, 0x61};
		rc4Test(key3, keystream3, 3);

		byte[] key4 = {0x4b, 0x65, 0x79};
		byte[] keystream4 = {(byte) 0xeb, (byte) 0x9f, 0x77, (byte) 0x81, (byte) 0xb7, 0x34, (byte) 0xca, 0x72, (byte) 0xa7, 0x19};
		rc4Test(key4, keystream4, 4);

		byte[] key5 = {0x57, 0x69, 0x6b, 0x69};
		byte[] keystream5 = {0x60, 0x44, (byte) 0xdb, 0x6d, 0x41, (byte) 0xb7};
		rc4Test(key5, keystream5, 5);

		output("rc4 test done.\n");
	}

	void testRC4512kb() {
		byte[] data = new byte[512 * 1024];
		Random random = new Random();
		random.nextBytes(data);

		output("Test RC4 512kb start:\n");
		long startTime = System.currentTimeMillis();

		RC4 rc4 = new RC4();
		try {
			rc4.init("totem".getBytes());
		} catch(InvalidKeyException e) {
			e.printStackTrace();
		}
		rc4.xorKeyStream(data, data);

		long endTime = System.currentTimeMillis();

		output("Done: " + (endTime - startTime) + "\n");
	}

	public void natvieAESUnitTest(String key, byte[] p, int n) {
		RawAES a = new RawAES();
		a.RawNew();

		a.RawSetupEncKey(key.getBytes());

		byte[] c = a.RawEncBuf(p);
		a.RawSetupDecKey(key.getBytes());

		byte[] p1 = a.RawDecBuf(c);

		for (int i = 0; i < p.length; i++) {
			if (p[i] != p1[i]) {
				output("AES unit test " + n + " fail.\n");
				return ;
			}
		}
		output("NativeAES unit test " + n + " pass.\n");
	}

	void testNativeAES512KB() {
		byte[] data = new byte[512*1024];
		Random random = new Random();
		random.nextBytes(data);

		output("Test NativeAES 512kb start:\n");
		long startTime = System.currentTimeMillis();

		RawAES na = new RawAES();
		na.RawSetupEncKey("1234567890123456".getBytes());
		byte[] c = na.RawEncBuf(data);
		//na.RawSetupDecKey("1234567890123456".getBytes());
		//na.RawDecBuf(c);

		long endTime = System.currentTimeMillis();

		output("Done: " + (endTime - startTime) + "\n");
	}

	public void nativeAESTestCase() {
		natvieAESUnitTest("1234567890123456", "hehe".getBytes(), 1);
		natvieAESUnitTest("1234567890123456", "abcdefghijklmnopqrstuvwxyz".getBytes(), 2);
	}

	void rawRc4Test(byte[] key, byte[] keystream, int n) {
		byte[] work = new byte[keystream.length];
		for (int i = 0; i < work.length; i++) {
			work[i] = 0;
		}

		RawRC4 rc4 = new RawRC4(key);

		rc4.RawXORStream(work);

		for (int i = 0; i < work.length; i++) {
			if (work[i] != keystream[i]) {
				output("test data " + n + " error.\n");
				return ;
			}
		}
		output("test case" + n + "pass.\n");
	}

	public void rawRC4TestCase() {
		byte[] key1 = {0x01, 0x23, 0x45, 0x67, (byte) 0x89, (byte) 0xab, (byte) 0xcd, (byte) 0xef};
		byte[] keystream1 = {0x74,  (byte) 0x94, (byte) 0xc2, (byte) 0xe7, 0x10, 0x4b, 0x08, 0x79};
		rc4Test(key1, keystream1, 1);

		byte[] key2 = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
		byte[] keystream2 = {(byte) 0xde, 0x18, (byte) 0x89, 0x41, (byte) 0xa3, 0x37, 0x5d, 0x3a};
		rc4Test(key2, keystream2, 2);

		byte[] key3 = {(byte) 0xef, 0x01, 0x23, 0x45};
		byte[] keystream3 = {(byte) 0xd6, (byte) 0xa1, 0x41, (byte) 0xa7, (byte) 0xec, 0x3c, 0x38, (byte) 0xdf, (byte) 0xbd, 0x61};
		rc4Test(key3, keystream3, 3);

		byte[] key4 = {0x4b, 0x65, 0x79};
		byte[] keystream4 = {(byte) 0xeb, (byte) 0x9f, 0x77, (byte) 0x81, (byte) 0xb7, 0x34, (byte) 0xca, 0x72, (byte) 0xa7, 0x19};
		rc4Test(key4, keystream4, 4);

		byte[] key5 = {0x57, 0x69, 0x6b, 0x69};
		byte[] keystream5 = {0x60, 0x44, (byte) 0xdb, 0x6d, 0x41, (byte) 0xb7};

		rawRc4Test(key1, keystream1, 1);
		rawRc4Test(key2, keystream2, 2);
		rawRc4Test(key3, keystream3, 3);
		rawRc4Test(key4, keystream4, 4);
		rawRc4Test(key5, keystream5, 5);
	}

	void output(String string) {
		textView.append(string);
	}

	private void testRawRC4() {
		byte[] data = new byte[512 * 1024];
		Random random = new Random();
		random.nextBytes(data);

		output("Test RawRC4 512kb start:\n");
		long startTime = System.currentTimeMillis();

		RawRC4 rc4 = new RawRC4("totem".getBytes());
		rc4.RawXORStream(data);

		long endTime = System.currentTimeMillis();

		output("Done: " + (endTime - startTime) + "\n");
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		textView = new TextView(this);
		textView.setText("Begin to test\n");
		setContentView(textView);

		// aesTestCase();
		testAes512kb();

		// rc4TestCase();
		testRC4512kb();

		// aesCbcPkcs5TestCase();
		testAesCbcPkcs5Padding512kb();

		// nativeAESTestCase();
		testNativeAES512KB();

		// rawRC4TestCase();
		testRawRC4();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_crypto_verification, menu);
		return true;
	}
}


text:
package org.apache.bookkeeper.benchmark;

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

import org.apache.bookkeeper.client.BookKeeper;
import org.apache.bookkeeper.client.LedgerHandle;
import org.apache.bookkeeper.net.BookieSocketAddress;
import org.apache.bookkeeper.test.BookKeeperClusterTestCase;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.atomic.AtomicBoolean;

import java.util.Arrays;

public class TestBenchmark extends BookKeeperClusterTestCase {
    protected static final Logger LOG = LoggerFactory.getLogger(TestBenchmark.class);

    public TestBenchmark() {
        super(5);
    }

    @Test
    public void testThroughputLatency() throws Exception {
        String latencyFile = System.getProperty("test.latency.file", "latencyDump.dat");
        BenchThroughputLatency.main(new String[] {
                "--zookeeper", zkUtil.getZooKeeperConnectString(),
                "--time", "10",
                "--skipwarmup",
                "--throttle", "1",
                "--sendlimit", "10000",
                "--latencyFile", latencyFile
            });
    }

    @Test
    public void testBookie() throws Exception {
        BookieSocketAddress bookie = getBookie(0);
        BenchBookie.main(new String[] {
                "--host", bookie.getHostName(),
                "--port", String.valueOf(bookie.getPort()),
                "--zookeeper", zkUtil.getZooKeeperConnectString()
                });
    }

    @Test
    public void testReadThroughputLatency() throws Exception {
        final AtomicBoolean threwException = new AtomicBoolean(false);
        Thread t = new Thread() {
                public void run() {
                    try {
                        BenchReadThroughputLatency.main(new String[] {
                                "--zookeeper", zkUtil.getZooKeeperConnectString(),
                                "--listen", "10"});
                    } catch (Throwable t) {
                        LOG.error("Error reading", t);
                        threwException.set(true);
                    }
                }
            };
        t.start();

        Thread.sleep(10000);
        byte data[] = new byte[1024];
        Arrays.fill(data, (byte)'x');

        long lastLedgerId = 0;
        Assert.assertTrue("Thread should be running", t.isAlive());
        for (int i = 0; i < 10; i++) {
            BookKeeper bk = new BookKeeper(zkUtil.getZooKeeperConnectString());
            LedgerHandle lh = bk.createLedger(BookKeeper.DigestType.CRC32, "benchPasswd".getBytes());
            lastLedgerId = lh.getId();
            try {
                for (int j = 0; j < 100; j++) {
                    lh.addEntry(data);
                }
            } finally {
                lh.close();
                bk.close();
            }
        }
        for (int i = 0; i < 60; i++) {
            if (!t.isAlive()) {
                break;
            }
            Thread.sleep(1000); // wait for 10 seconds for reading to finish
        }

        Assert.assertFalse("Thread should be finished", t.isAlive());

        BenchReadThroughputLatency.main(new String[] {
                "--zookeeper", zkUtil.getZooKeeperConnectString(),
                "--ledger", String.valueOf(lastLedgerId)});

        final long nextLedgerId = lastLedgerId+1;
        t = new Thread() {
                public void run() {
                    try {
                        BenchReadThroughputLatency.main(new String[] {
                                "--zookeeper", zkUtil.getZooKeeperConnectString(),
                                "--ledger", String.valueOf(nextLedgerId)});
                    } catch (Throwable t) {
                        LOG.error("Error reading", t);
                        threwException.set(true);
                    }
                }
            };
        t.start();

        Assert.assertTrue("Thread should be running", t.isAlive());
        BookKeeper bk = new BookKeeper(zkUtil.getZooKeeperConnectString());
        LedgerHandle lh = bk.createLedger(BookKeeper.DigestType.CRC32, "benchPasswd".getBytes());
        try {
            for (int j = 0; j < 100; j++) {
                lh.addEntry(data);
            }
        } finally {
            lh.close();
            bk.close();
        }
        for (int i = 0; i < 60; i++) {
            if (!t.isAlive()) {
                break;
            }
            Thread.sleep(1000); // wait for 10 seconds for reading to finish
        }
        Assert.assertFalse("Thread should be finished", t.isAlive());
        Assert.assertFalse("A thread has thrown an exception, check logs", threwException.get());
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;

namespace LiteDB
{
    internal class QueryAnd : Query
    {
        private Query _left;
        private Query _right;

        public QueryAnd(Query left, Query right)
            : base(null)
        {
            _left = left;
            _right = right;
        }

        internal override void IndexFactory(Action<string, string> createIndex)
        {
            _left.IndexFactory(createIndex);
            _right.IndexFactory(createIndex);
        }

        internal override IEnumerable<IndexNode> ExecuteIndex(IndexService indexer, CollectionIndex index)
        {
            throw new NotSupportedException();
        }

        internal override IEnumerable<IndexNode> Run(CollectionPage col, IndexService indexer)
        {
            var left = _left.Run(col, indexer);
            var right = _right.Run(col, indexer);

            return left.Intersect(right, new IndexNodeComparer());
        }
    }
}


text:
package catalog

import original "github.com/Azure/azure-sdk-for-go/services/preview/datalake/analytics/2015-10-01-preview/catalog"

type Client = original.Client

const (
	DefaultAdlaCatalogDNSSuffix = original.DefaultAdlaCatalogDNSSuffix
)

type BaseClient = original.BaseClient
type FileType = original.FileType

const (
	Assembly FileType = original.Assembly
	Resource FileType = original.Resource
)

type DataLakeAnalyticsCatalogSecretCreateOrUpdateParameters = original.DataLakeAnalyticsCatalogSecretCreateOrUpdateParameters
type DdlName = original.DdlName
type EntityID = original.EntityID
type ExternalTable = original.ExternalTable
type Item = original.Item
type ItemList = original.ItemList
type TypeFieldInfo = original.TypeFieldInfo
type USQLAssembly = original.USQLAssembly
type USQLAssemblyClr = original.USQLAssemblyClr
type USQLAssemblyDependencyInfo = original.USQLAssemblyDependencyInfo
type USQLAssemblyFileInfo = original.USQLAssemblyFileInfo
type USQLAssemblyList = original.USQLAssemblyList
type USQLAssemblyListIterator = original.USQLAssemblyListIterator
type USQLAssemblyListPage = original.USQLAssemblyListPage
type USQLCredential = original.USQLCredential
type USQLCredentialList = original.USQLCredentialList
type USQLCredentialListIterator = original.USQLCredentialListIterator
type USQLCredentialListPage = original.USQLCredentialListPage
type USQLDatabase = original.USQLDatabase
type USQLDatabaseList = original.USQLDatabaseList
type USQLDatabaseListIterator = original.USQLDatabaseListIterator
type USQLDatabaseListPage = original.USQLDatabaseListPage
type USQLDirectedColumn = original.USQLDirectedColumn
type USQLDistributionInfo = original.USQLDistributionInfo
type USQLExternalDataSource = original.USQLExternalDataSource
type USQLExternalDataSourceList = original.USQLExternalDataSourceList
type USQLExternalDataSourceListIterator = original.USQLExternalDataSourceListIterator
type USQLExternalDataSourceListPage = original.USQLExternalDataSourceListPage
type USQLIndex = original.USQLIndex
type USQLProcedure = original.USQLProcedure
type USQLProcedureList = original.USQLProcedureList
type USQLProcedureListIterator = original.USQLProcedureListIterator
type USQLProcedureListPage = original.USQLProcedureListPage
type USQLSchema = original.USQLSchema
type USQLSchemaList = original.USQLSchemaList
type USQLSchemaListIterator = original.USQLSchemaListIterator
type USQLSchemaListPage = original.USQLSchemaListPage
type USQLSecret = original.USQLSecret
type USQLTable = original.USQLTable
type USQLTableColumn = original.USQLTableColumn
type USQLTableList = original.USQLTableList
type USQLTableListIterator = original.USQLTableListIterator
type USQLTableListPage = original.USQLTableListPage
type USQLTablePartition = original.USQLTablePartition
type USQLTablePartitionList = original.USQLTablePartitionList
type USQLTablePartitionListIterator = original.USQLTablePartitionListIterator
type USQLTablePartitionListPage = original.USQLTablePartitionListPage
type USQLTableStatistics = original.USQLTableStatistics
type USQLTableStatisticsList = original.USQLTableStatisticsList
type USQLTableStatisticsListIterator = original.USQLTableStatisticsListIterator
type USQLTableStatisticsListPage = original.USQLTableStatisticsListPage
type USQLTableType = original.USQLTableType
type USQLTableTypeList = original.USQLTableTypeList
type USQLTableTypeListIterator = original.USQLTableTypeListIterator
type USQLTableTypeListPage = original.USQLTableTypeListPage
type USQLTableValuedFunction = original.USQLTableValuedFunction
type USQLTableValuedFunctionList = original.USQLTableValuedFunctionList
type USQLTableValuedFunctionListIterator = original.USQLTableValuedFunctionListIterator
type USQLTableValuedFunctionListPage = original.USQLTableValuedFunctionListPage
type USQLType = original.USQLType
type USQLTypeList = original.USQLTypeList
type USQLTypeListIterator = original.USQLTypeListIterator
type USQLTypeListPage = original.USQLTypeListPage
type USQLView = original.USQLView
type USQLViewList = original.USQLViewList
type USQLViewListIterator = original.USQLViewListIterator
type USQLViewListPage = original.USQLViewListPage

func NewClient() Client {
	return original.NewClient()
}
func New() BaseClient {
	return original.New()
}
func NewWithoutDefaults(adlaCatalogDNSSuffix string) BaseClient {
	return original.NewWithoutDefaults(adlaCatalogDNSSuffix)
}
func PossibleFileTypeValues() []FileType {
	return original.PossibleFileTypeValues()
}
func UserAgent() string {
	return original.UserAgent() + " profiles/preview"
}
func Version() string {
	return original.Version()
}


text:
from Tkinter import *
import serial
import sys

NX = 500
NY = 500
nloop = 100
path = []
baseline = 0
baseline_filt = 0.01
gain = 0.2

def idle(parent,canvas):
   global path, baseline
   #
   # idle routine
   #
   # look for framing
   #
   byte2 = 0
   byte3 = 0
   byte4 = 0
   while 1:
      byte1 = byte2
      byte2 = byte3
      byte3 = byte4
      byte4 = ord(ser.read())
      if ((byte1 == 1) & (byte2 == 2) & (byte3 == 3) & (byte4 == 4)):
         break
   path = []
   for i in range(nloop):
      lo = ord(ser.read())
      hi = ord(ser.read())
      reading = 256*hi + lo
      baseline = baseline_filt*reading + (1-baseline_filt)*baseline
      value = NY/2 + gain*(reading - baseline)
      print value
      path.append(i*NY/float(nloop))
      path.append(value)
   canvas.delete("path")
   canvas.create_line(path,tag="path",width=3,fill="#00b000")
   parent.after_idle(idle,parent,canvas)

#
#  check command line arguments
#
if (len(sys.argv) != 2):
   print "command line: hello.SPU0414HR5H.py serial_port"
   sys.exit()
port = sys.argv[1]
#
# open serial port
#
ser = serial.Serial(port,9600)
#
# start plotting
#
root = Tk()
root.title('silvia rukez')
root.bind('q','exit')
canvas = Canvas(root, width=NX, height=NY, background='white')
canvas.pack()
root.after(100,idle,root,canvas)
root.mainloop()


text:
#import <Parse/PFAnalytics.h>

/**
 Predefined events - AppOpened, CrashReport
 Coming soon - Log, ...
 */
extern NSString *const PFAnalyticsEventAppOpened;
extern NSString *const PFAnalyticsEventCrashReport;


text:
//
//  MasterConnection.h
//  Cold-Potato-Proxy
//
//  Created by Elder Yoshida on 4/25/15.
//  Copyright (c) 2015 Elder Yoshida. All rights reserved.
//

#ifndef __Cold_Potato_Proxy__MasterConnection__
#define __Cold_Potato_Proxy__MasterConnection__

#include "../Socket.h"
#include "../Connection.h"
#include "../ConnectionData.h"
#include "MasterServer.h"

class MasterConnection : public  Connection {
private:
	LinkHashMap *link_map;
	NodeHashMap *node_map;

	std::mutex *map_lock;

	/**
	 * Verifies that the version that the client is requesting is allowed by our proxy server.
	 */
	bool verifyVersion(char version);

	/**
	 * Handles a client's connection request.
	 */
	bool handleRequest(AddressDetails & request);
	void nodeJoin();
	void nodeConnect();
	void nodeFind();
	void nodeDelete();
	void sendError();

public:
	MasterConnection(ConnectionData* connection, LinkHashMap *link_map, NodeHashMap *node_map, std::mutex *map_lock);
	void handleConnection();
	virtual ~MasterConnection();
};

#endif /* defined(__Cold_Potato_Proxy__MasterConnection__) */


text:
package com.microsoft.applicationinsights.agent.internal.config;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import com.microsoft.applicationinsights.agent.internal.agent.ClassInstrumentationData;
import com.microsoft.applicationinsights.agent.internal.common.StringUtils;
import com.microsoft.applicationinsights.agent.internal.coresync.InstrumentedClassType;
import com.microsoft.applicationinsights.agent.internal.logger.InternalAgentLogger;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/**
 * Created by gupele on 5/19/2015.
 */
final class XmlAgentConfigurationBuilder implements AgentConfigurationBuilder {
    private final static String AGENT_XML_CONFIGURATION_NAME = "AI-Agent.xml";

    private final static String MAIN_TAG = "ApplicationInsightsAgent";
    private final static String INSTRUMENTATION_TAG = "Instrumentation";
    private final static String CLASS_TAG = "Class";
    private final static String METHOD_TAG = "Method";

    private final static String BUILT_IN_TAG = "BuiltIn";
    private final static String JEDIS_TAG = "Jedis";
    private final static String HTTP_TAG = "HTTP";
    private final static String JDBC_TAG = "JDBC";
    private final static String HIBERNATE_TAG = "HIBERNATE";
    private final static String JMX_TAG = "AgentJmx";
    private final static String MAX_STATEMENT_QUERY_LIMIT_TAG = "MaxStatementQueryLimit";

    private final static String AGENT_LOGGER_TAG = "AgentLogger";

    private final static String EXCLUDED_PREFIXES_TAG = "ExcludedPrefixes";
    private final static String FORBIDDEN_PREFIX_TAG = "Prefix";

    private final static String THRESHOLD_ATTRIBUTE = "thresholdInMS";
    private final static String ENABLED_ATTRIBUTE = "enabled";
    private final static String NAME_ATTRIBUTE = "name";
    private final static String REPORT_CAUGHT_EXCEPTIONS_ATTRIBUTE = "reportCaughtExceptions";
    private final static String REPORT_EXECUTION_TIME_ATTRIBUTE = "reportExecutionTime";
    private final static String SIGNATURE_ATTRIBUTE = "signature";

    @Override
    public AgentConfiguration parseConfigurationFile(String baseFolder) {
        AgentConfigurationDefaultImpl agentConfiguration = new AgentConfigurationDefaultImpl();

        String configurationFileName = baseFolder;
        if (!baseFolder.endsWith(File.separator)) {
            configurationFileName += File.separator;
        }
        configurationFileName += AGENT_XML_CONFIGURATION_NAME;

        File configurationFile = new File(configurationFileName);
        if (!configurationFile.exists()) {
            InternalAgentLogger.INSTANCE.trace("Did not find Agent configuration file in '%s'", configurationFileName);
            return agentConfiguration;
        }

        InternalAgentLogger.INSTANCE.trace("Found Agent configuration file in '%s'", configurationFileName);
        try {
            Element topElementTag = getTopTag(configurationFile);
            if (topElementTag == null) {
                return agentConfiguration;
            }

            initializeAgentLogger(topElementTag);

            getForbiddenPaths(topElementTag, agentConfiguration);

            Element instrumentationTag = getInstrumentationTag(topElementTag);
            if (instrumentationTag == null) {
                return agentConfiguration;
            }

            setBuiltInInstrumentation(agentConfiguration, instrumentationTag);

            NodeList addClasses = getAllClassesToInstrument(instrumentationTag);
            if (addClasses == null) {
                return agentConfiguration;
            }

            HashMap<String, ClassInstrumentationData> classesToInstrument = new HashMap<String, ClassInstrumentationData>();
            for (int index = 0; index < addClasses.getLength(); ++index) {
                Element classElement = getClassDataElement(addClasses.item(index));
                if (classElement == null) {
                    continue;
                }

                ClassInstrumentationData data = getClassInstrumentationData(classElement, classesToInstrument);
                if (data == null) {
                    continue;
                }

                addMethods(data, classElement);
                if (data.getMethodInstrumentationInfo().isEmpty() && !data.isReportCaughtExceptions() && !data.isReportExecutionTime()) {
                    classesToInstrument.remove(data.getClassName());
                }
            }

            agentConfiguration.setRequestedClassesToInstrument(classesToInstrument);
            return agentConfiguration;
        } catch (Throwable e) {
            InternalAgentLogger.INSTANCE.error("Exception while parsing Agent configuration file: '%s'" + e.getMessage());
            return null;
        }
    }

    private void getForbiddenPaths(Element parent, AgentConfigurationDefaultImpl agentConfiguration) {
        NodeList nodes = parent.getElementsByTagName(EXCLUDED_PREFIXES_TAG);
        Element forbiddenElement = getFirst(nodes);
        if (forbiddenElement == null) {
            return;
        }

        HashSet<String> excludedPrefixes = new HashSet<String>();

        NodeList addClasses = forbiddenElement.getElementsByTagName(FORBIDDEN_PREFIX_TAG);
        if (addClasses == null) {
            return;
        }

        for (int index = 0; index < addClasses.getLength(); ++index) {
            Element classElement = getClassDataElement(addClasses.item(index));
            if (classElement == null) {
                continue;
            }

            excludedPrefixes.add(classElement.getFirstChild().getTextContent());
        }

        agentConfiguration.setExcludedPrefixes(excludedPrefixes);
    }

    private void setBuiltInInstrumentation(AgentConfigurationDefaultImpl agentConfiguration, Element instrumentationTags) {
        AgentBuiltInConfigurationBuilder builtInConfigurationBuilder = new AgentBuiltInConfigurationBuilder();

        NodeList nodes = instrumentationTags.getElementsByTagName(BUILT_IN_TAG);
        Element builtInElement = getFirst(nodes);
        if (builtInElement == null) {
            agentConfiguration.setBuiltInData(builtInConfigurationBuilder.create());
            return;
        }

        builtInConfigurationBuilder.setEnabled(getEnabled(builtInElement, BUILT_IN_TAG));

        nodes = builtInElement.getElementsByTagName(JEDIS_TAG);
        Element element = getFirst(nodes);
        long threshold = getLongAttribute(element, JEDIS_TAG, THRESHOLD_ATTRIBUTE, 0);
        builtInConfigurationBuilder.setJedisValues(getEnabled(element, JEDIS_TAG), threshold);

        nodes = builtInElement.getElementsByTagName(HTTP_TAG);
        builtInConfigurationBuilder.setHttpEnabled(getEnabled(getFirst(nodes), HTTP_TAG));

        nodes = builtInElement.getElementsByTagName(JDBC_TAG);
        builtInConfigurationBuilder.setJdbcEnabled(getEnabled(getFirst(nodes), JDBC_TAG));

        nodes = builtInElement.getElementsByTagName(HIBERNATE_TAG);
        builtInConfigurationBuilder.setHibernateEnabled(getEnabled(getFirst(nodes), HIBERNATE_TAG));

        nodes = builtInElement.getElementsByTagName(JMX_TAG);
        builtInConfigurationBuilder.setJmxEnabled(getEnabled(getFirst(nodes), JMX_TAG));

        nodes = builtInElement.getElementsByTagName(MAX_STATEMENT_QUERY_LIMIT_TAG);
        builtInConfigurationBuilder.setSqlMaxQueryLimit(getLong(getFirst(nodes), MAX_STATEMENT_QUERY_LIMIT_TAG));

        agentConfiguration.setBuiltInData(builtInConfigurationBuilder.create());
    }

    private Element getClassDataElement(Node item) {
        if (item.getNodeType() != Node.ELEMENT_NODE) {
            return null;
        }

        Element eClassNode = (Element)item;

        String strValue = eClassNode.getAttribute(ENABLED_ATTRIBUTE);
        if (!StringUtils.isNullOrEmpty(strValue)) {
            boolean isEnabled = Boolean.valueOf(strValue);
            if (!isEnabled) {
                return null;
            }
        }

        return eClassNode;
    }

    private ClassInstrumentationData getClassInstrumentationData(Element classElement, HashMap<String, ClassInstrumentationData> classesToInstrument) {
        String className = classElement.getAttribute(NAME_ATTRIBUTE);
        if (StringUtils.isNullOrEmpty(className)) {
            return null;
        }

        className = className.replace(".", "/");
        ClassInstrumentationData data = classesToInstrument.get(className);

        InstrumentedClassType type = InstrumentedClassType.OTHER;
        try {
            type = Enum.valueOf(InstrumentedClassType.class, classElement.getAttribute("type"));
        } catch (Throwable t) {
        }

        boolean reportCaughtExceptions = false;
        String valueStr = classElement.getAttribute(REPORT_CAUGHT_EXCEPTIONS_ATTRIBUTE);
        if (!StringUtils.isNullOrEmpty(valueStr)) {
            reportCaughtExceptions = Boolean.valueOf(valueStr);
        }

        boolean reportExecutionTime = true;
        valueStr = classElement.getAttribute(REPORT_EXECUTION_TIME_ATTRIBUTE);
        if (!StringUtils.isNullOrEmpty(valueStr)) {
            reportCaughtExceptions = Boolean.valueOf(valueStr);
        }

        if (data == null) {
            data = new ClassInstrumentationData(className, type)
                    .setReportExecutionTime(reportExecutionTime)
                    .setReportCaughtExceptions(reportCaughtExceptions);
            classesToInstrument.put(className, data);
        }

        return data;
    }

    private Element getInstrumentationTag(Element topElementTag) {
        NodeList customTags = topElementTag.getElementsByTagName(INSTRUMENTATION_TAG);
        return getFirst(customTags);
    }

    private void initializeAgentLogger(Element topElementTag) {
        NodeList customTags = topElementTag.getElementsByTagName(AGENT_LOGGER_TAG);
        Element loggerTag = getFirst(customTags);
        if (loggerTag == null) {
            return;
        }

        InternalAgentLogger.INSTANCE.initialize(loggerTag.getNodeValue());
    }

    private NodeList getAllClassesToInstrument(Element tag) {
        NodeList addClasses = tag.getElementsByTagName(CLASS_TAG);
        if (addClasses == null) {
            return null;
        }
        return addClasses;
    }

    private void addMethods(ClassInstrumentationData classData, Element eClassNode) {
        NodeList methodNodes = eClassNode.getElementsByTagName(METHOD_TAG);
        if (methodNodes == null || methodNodes.getLength() == 0) {
            if (classData.isReportCaughtExceptions() || classData.isReportExecutionTime()) {
                classData.addAllMethods(classData.isReportCaughtExceptions(), classData.isReportExecutionTime());
            }
            return;
        }

        for (int methodIndex = 0; methodIndex < methodNodes.getLength(); ++methodIndex) {
            Node methodNode = methodNodes.item(methodIndex);
            if (methodNode.getNodeType() != Node.ELEMENT_NODE) {
                continue;
            }

            Element methodElement = (Element)methodNode;

            String strValue = methodElement.getAttribute(ENABLED_ATTRIBUTE);
            if (!StringUtils.isNullOrEmpty(strValue)) {
                boolean isEnabled = Boolean.valueOf(strValue);
                if (!isEnabled) {
                    continue;
                }
            }

            String methodName = methodElement.getAttribute(NAME_ATTRIBUTE);
            if (StringUtils.isNullOrEmpty(methodName)) {
                continue;
            }

            boolean reportCaughtExceptions = false;
            String valueStr = methodElement.getAttribute(REPORT_CAUGHT_EXCEPTIONS_ATTRIBUTE);
            if (!StringUtils.isNullOrEmpty(valueStr)) {
                reportCaughtExceptions = Boolean.valueOf(valueStr) || classData.isReportCaughtExceptions();
            }

            boolean reportExecutionTime = true;
            valueStr = methodElement.getAttribute(REPORT_EXECUTION_TIME_ATTRIBUTE);
            if (!StringUtils.isNullOrEmpty(valueStr)) {
                reportExecutionTime = Boolean.valueOf(valueStr) || classData.isReportExecutionTime();
            }

            if (!reportCaughtExceptions && !reportExecutionTime) {
                continue;
            }

            classData.addMethod(methodName, methodElement.getAttribute(SIGNATURE_ATTRIBUTE), reportCaughtExceptions, reportExecutionTime);
        }
    }

    public Element getTopTag(File configurationFile) throws ParserConfigurationException, IOException, SAXException {
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder;
        dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(configurationFile);
        doc.getDocumentElement().normalize();

        NodeList topTags = doc.getElementsByTagName(MAIN_TAG);
        if (topTags == null || topTags.getLength() == 0) {
            return null;
        }

        Node topNodeTag = topTags.item(0);
        if (topNodeTag.getNodeType() != Node.ELEMENT_NODE) {
            return null;
        }

        Element topElementTag = (Element)topNodeTag;
        return topElementTag;
    }

    private Element getFirst(NodeList nodes) {
        if (nodes == null || nodes.getLength() == 0) {
            return null;
        }

        Node node = nodes.item(0);
        if (node.getNodeType() != Node.ELEMENT_NODE) {
            return null;
        }

        return (Element)node;
    }

    private long getLongAttribute(Element element, String elementName, String attributeName, long defaultValue) {
        if (element == null) {
            return defaultValue;
        }

        try {
            String strValue = element.getAttribute(attributeName);
            if (!StringUtils.isNullOrEmpty(strValue)) {
                long value = Long.valueOf(strValue);
                return value;
            }
            return defaultValue;
        } catch (Throwable t) {
            InternalAgentLogger.INSTANCE.error("Failed to parse attribute '%s' of '%s, default value (true) will be used.'", ENABLED_ATTRIBUTE, elementName);
        }

        return defaultValue;
    }

    private boolean getEnabled(Element element, String elementName) {
        if (element == null) {
            return true;
        }

        try {
            String strValue = element.getAttribute(ENABLED_ATTRIBUTE);
            if (!StringUtils.isNullOrEmpty(strValue)) {
                boolean value = Boolean.valueOf(strValue);
                return value;
            }
            return true;
        } catch (Throwable t) {
            InternalAgentLogger.INSTANCE.error("Failed to parse attribute '%s' of '%s, default value (true) will be used.'", ENABLED_ATTRIBUTE, elementName);
        }

        return false;
    }

    private Long getLong(Element element, String elementName) {
        if (element == null) {
            return null;
        }

        try {
            String strValue = element.getFirstChild().getTextContent();
            if (!StringUtils.isNullOrEmpty(strValue)) {
                Long value = Long.valueOf(strValue);
                return value;
            }
            return null;
        } catch (Throwable t) {
            InternalAgentLogger.INSTANCE.error("Failed to parse attribute '%s' of '%s, default value (true) will be used.'", ENABLED_ATTRIBUTE, elementName);
        }

        return null;
    }
}


text:
package org.apache.cassandra.scheduler;

import java.util.concurrent.TimeoutException;

/**
 * Implementors of IRequestScheduler must provide a constructor taking a RequestSchedulerOptions object.
 */
public interface IRequestScheduler
{
    /**
     * Queue incoming request threads
     *
     * @param t Thread handing the request
     * @param id    Scheduling parameter, an id to distinguish profiles (users/keyspace)
     * @param timeoutMS   The max time in milliseconds to spend blocking for a slot
     */
    public void queue(Thread t, String id, long timeoutMS) throws TimeoutException;

    /**
     * A convenience method for indicating when a particular request has completed
     * processing, and before a return to the client
     */
    public void release();
}


text:
'''
:mod:`eulxml.xmlmap` classes for dealing with the `PREMIS
<http://www.loc.gov/standards/premis/>`_ metadata format for
preservation metadata.

-----
'''

from eulxml import xmlmap

PREMIS_NAMESPACE = 'info:lc/xmlns/premis-v2'
'authoritative namespace for PREMIS'
PREMIS_SCHEMA = 'http://www.loc.gov/standards/premis/v2/premis-v2-1.xsd'
'authoritative schema location for PREMIS'

class BasePremis(xmlmap.XmlObject):
    '''Base PREMIS class with namespace declaration common to all PREMIS
    XmlObjects.

    .. Note::

       This class is intended mostly for internal use, but could be
       useful when extending or adding additional PREMIS
       :class:`~eulxml.xmlmap.XmlObject` classes.  The
       :attr:`PREMIS_NAMESPACE` is mapped to the prefix **p**.
    '''
    ROOT_NS = PREMIS_NAMESPACE
    ROOT_NAMESPACES = {
        'p': PREMIS_NAMESPACE,
        'xsi': 'http://www.w3.org/2001/XMLSchema-instance'
    }

class PremisRoot(BasePremis):
    '''Base class with a schema declaration for any of the
    root/stand-alone PREMIS elements:

     * ``<premis>`` - :class:`Premis`
     * ``<object>`` - :class:`Object`
     * ``<event>``  - :class:`Event`
     * ``<agent>``
     * ``<rights>``

    '''
    XSD_SCHEMA = PREMIS_SCHEMA

class Object(PremisRoot):
    '''Preliminary :class:`~eulxml.xmlmap.XmlObject` for a PREMIS
    object.

    Curently only includes the minimal required fields.
    '''
    ROOT_NAME = 'object'
    type = xmlmap.StringField('@xsi:type') # file, representation, bitstream
    '''type of object (e.g., file, representation, bitstream).

    .. Note::
      To be schema valid, object types must be in the PREMIS namespace, e.g.::

        from eulxml.xmlmap import premis
        obj = premis.Object()
        obj.type = "p:file"
    '''
    id_type = xmlmap.StringField('p:objectIdentifier/p:objectIdentifierType')
    'identifier type (`objectIdentifier/objectIdentifierType`)'
    id = xmlmap.StringField('p:objectIdentifier/p:objectIdentifierValue')
    'identifier value (`objectIdentifier/objectIdentifierValue`)'

class Event(PremisRoot):
    '''Preliminary :class:`~eulxml.xmlmap.XmlObject` for a PREMIS
    event.

    .. Note::

      The PREMIS schema requires that elements occur in a specified
      order, which :mod:`eulxml` does not currently handle or manage.
      As a work-around, when creating a new :class:`Event` from
      scratch, you should set the following required fields in this
      order: identifier (:attr:`id` and :attr:`ad_type`

    '''
    ROOT_NAME = 'event'
    type = xmlmap.StringField('p:eventType')
    'event type  (``eventType``)'
    id_type = xmlmap.StringField('p:eventIdentifier/p:eventIdentifierType')
    'identifier type (`eventIdentifier/eventIdentifierType`)'
    id = xmlmap.StringField('p:eventIdentifier/p:eventIdentifierValue')
    'identifier value (`eventIdentifier/eventIdentifierValue`)'
    date = xmlmap.StringField('p:eventDateTime')
    'date/time for the event (`eventDateTime`)'
    detail = xmlmap.StringField('p:eventDetail', required=False)
    'event detail (`eventDetail`)'
    outcome = xmlmap.StringField('p:eventOutcomeInformation/p:eventOutcome', required=False)
    '''outcome of the event (`eventOutcomeInformation/eventOutcome`).

    .. Note::
      In this preliminary implementation, the outcome detail fields
      are not mapped.
    '''
    # leaving out outcome detail for now...

    # agent (optional, could be repeated)
    agent_type = xmlmap.StringField('p:linkingAgentIdentifier/p:linkingAgentIdentifierType')
    agent_id = xmlmap.StringField('p:linkingAgentIdentifier/p:linkingAgentIdentifierValue')

    # object (optional, could be repeated)
    object_type = xmlmap.StringField('p:linkingObjectIdentifier/p:linkingObjectIdentifierType')
    object_id = xmlmap.StringField('p:linkingObjectIdentifier/p:linkingObjectIdentifierValue')

class Premis(PremisRoot):
    '''Preliminary :class:`~eulxml.xmlmap.XmlObject` for a PREMIS
    container element that can contain any of the other top-level
    PREMIS elements.

    Curently only includes mappings for a single object and list of
    events.
    '''
    ROOT_NAME = 'premis'

    version = xmlmap.StringField('@version')
    '''Version of PREMIS in use; by default, new instances of
    :class:`Premis` will be initialized with a version of 2.1'''
    object = xmlmap.NodeField('p:object', Object)
    'a single PREMIS :class:`object`'
    events = xmlmap.NodeListField('p:event', Event)
    'list of PREMIS events, as instances of :class:`Event`'

    def __init__(self, *args, **kwargs):
        # version is required for schema-validity; don't override a
        # user-supplied version, but otherwise default to 2.1
        if 'version' not in kwargs:
            kwargs['version'] = '2.1'
        super(Premis, self).__init__(*args, **kwargs)


text:
clear
rm -f ./index.html
python gentableoflinks.py input.json index.html


text:
package com.cdesigner.mgr.req;

import org.apache.commons.lang3.StringUtils;

/**
 * @author 刘飞 E-mail:liufei_it@126.com
 *
 * @version 1.0.0
 * @since 2015年7月4日 下午7:02:30
 */
public class StatusListRequest extends PageRequest {

	private Long id;

	private String name;

	private Integer listed = 1;

	@Override
	protected StatusListRequest Q() {
		StringBuilder sb = new StringBuilder();
		boolean appended = false;
		if (StringUtils.isNotBlank(name)) {
			sb.append("name").append("=").append(name);
			appended = true;
		}
		if (listed != null) {
			if (appended) {
				sb.append("&");
			}
			sb.append("listed").append("=").append(listed);
			appended = true;
		}
		if (id != null && id > 0L) {
			if (appended) {
				sb.append("&");
			}
			sb.append("id").append("=").append(id);
			appended = true;
		}
		getQuery().setQueryString(sb.toString());
		return this;
	}

	public Long getId() {
		return id;
	}

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

	public String getName() {
		return name;
	}

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

	public Integer getListed() {
		return listed;
	}

	public void setListed(Integer listed) {
		this.listed = listed;
	}
}


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <title>Login</title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width">

        <link rel="stylesheet" href="css/bootstrap.min.css">
        <link rel="stylesheet" href="css/icomoon-social.css">
        <link href='http://fonts.googleapis.com/css?family=Open+Sans:400,700,600,800' rel='stylesheet' type='text/css'>

        <link rel="stylesheet" href="css/leaflet.css" />

		<link rel="stylesheet" href="css/main.css">

Login

                                                        <form role="form" role="form" action= "login.php" method="post">

                                                                 Username or Email
                                                                        <input name="username" class="form-control" id="username" type="text" placeholder="">

                                                                 Password
                                                                        <input name="password" class="form-control" id="password" type="password" placeholder="">

                                                                                <input type="checkbox"> Remember me

                                                                        Forgot password?
                                                                        <button type="submit" class="btn pull-right">Login</button>

                                                        </form>


text:
DEPLOY_PATH=/var/node-www/datagamer
REPO=https://github.com/Wifsimster/datagamer.git
BRANCH=master

echo "* Stop datagamer-api server"
service datagamer stop

echo "* Updating repository datagamer"
git pull $REPO $BRANCH

echo "* Installing/updating back-end modules"
npm install

echo "* Installing/updating front-end modules"
bower install --allow-root

echo "* Starting datagamer service"
service datagamer start


text:
module Query.SQLFunctionDefinitions (
    SQLFunction(..),
    normalSyntaxFunctions,
    infixFunctions,
    specialFunctions,

    -- TODO remove these
    negateFunction,
    countFunction,
    substringFromToFunction,
    substringFromFunction,
    notFunction) where

import Data.Char
import Data.List
import Data.Maybe
import Text.Regex.Posix

import Query.EvaluatedExpression
import Query.SQLExpression

-- Functions with "normal" syntax --
normalSyntaxFunctions :: [SQLFunction]
normalSyntaxFunctions =
    [absFunction,
     -- all aggregates except count which accepts a (*)
     avgFunction, firstFunction, lastFunction, maxFunction,
     minFunction, sumFunction]

absFunction :: SQLFunction
absFunction = SQLFunction {
    functionName        = "ABS",
    minArgCount         = 1,
    argCountIsFixed     = True,
    applyFunction       = applyUnaryNumeric absFunction abs abs,
    functionGrammar     = normalGrammar absFunction,
    functionDescription = "absolute value function"}

-- aggregates
avgFunction :: SQLFunction
avgFunction = SQLFunction {
    functionName        = "AVG",
    minArgCount         = 1,
    argCountIsFixed     = False,
    applyFunction       = avgFun . checkArgCount avgFunction,
    functionGrammar     = normalGrammar avgFunction,
    functionDescription = "aggregate average function"}
    -- TODO this AVG(...) holds the whole arg list in memory. reimplement!
    where
        avgFun args = RealExpression $
            foldl1' (+) (map coerceReal args) / fromIntegral (length args)

countFunction :: SQLFunction
countFunction = SQLFunction {
    functionName        = "COUNT",
    minArgCount         = 0,
    argCountIsFixed     = False,
    applyFunction       = IntExpression . length,
    functionGrammar     = normalGrammar countFunction,
    functionDescription = "aggregate function for calculating group size"}

firstFunction :: SQLFunction
firstFunction = SQLFunction {
    functionName        = "FIRST",
    minArgCount         = 1,
    argCountIsFixed     = False,
    applyFunction       = head . checkArgCount firstFunction,
    functionGrammar     = normalGrammar firstFunction,
    functionDescription = "aggregate function returning only the first element of every group"}

lastFunction :: SQLFunction
lastFunction = SQLFunction {
    functionName        = "LAST",
    minArgCount         = 1,
    argCountIsFixed     = False,
    applyFunction       = last . checkArgCount lastFunction,
    functionGrammar     = normalGrammar lastFunction,
    functionDescription = "aggregate function returning only the last element of every group"}

maxFunction :: SQLFunction
maxFunction = SQLFunction {
    functionName        = "MAX",
    minArgCount         = 1,
    argCountIsFixed     = False,
    applyFunction       = maximum . checkArgCount maxFunction,
    functionGrammar     = normalGrammar maxFunction,
    functionDescription = "aggregate function returning the maximum element of every group"}

minFunction :: SQLFunction
minFunction = SQLFunction {
    functionName        = "MIN",
    minArgCount         = 1,
    argCountIsFixed     = False,
    applyFunction       = minimum . checkArgCount minFunction,
    functionGrammar     = normalGrammar minFunction,
    functionDescription = "aggregate function returning the minimum element of every group"}

sumFunction :: SQLFunction
sumFunction = SQLFunction {
    functionName        = "SUM",
    minArgCount         = 0,
    argCountIsFixed     = False,
    applyFunction       = foldl stepSum (IntExpression 0),
    functionGrammar     = normalGrammar sumFunction,
    functionDescription = "aggregate function which summs all elements in each group"}
    where
        stepSum prevSum currArg =
            if useRealAlgebra prevSum || useRealAlgebra currArg
                then RealExpression $ coerceReal prevSum + coerceReal currArg
                else IntExpression $ coerceInt prevSum + coerceInt currArg

-- Infix functions --
infixFunctions :: [[SQLFunction]]
infixFunctions =
    [[multiplyFunction, divideFunction],
     [plusFunction, minusFunction],
     [concatenateFunction],
     [isFunction, isNotFunction, lessThanFunction, lessThanOrEqualToFunction,
      greaterThanFunction, greaterThanOrEqualToFunction, regexMatchFunction],
     [andFunction],
     [orFunction]]

-- Algebraic
multiplyFunction :: SQLFunction
multiplyFunction = SQLFunction {
    functionName        = "*",
    minArgCount         = 2,
    argCountIsFixed     = True,
    applyFunction       = applyBinaryNumeric multiplyFunction (*) (*),
    functionGrammar     = binaryInfixGrammar multiplyFunction,
    functionDescription = "multiplies the left and right expressions"}

divideFunction :: SQLFunction
divideFunction = SQLFunction {
    functionName        = "/",
    minArgCount         = 2,
    argCountIsFixed     = True,
    applyFunction       = divFun . checkArgCount divideFunction,
    functionGrammar     = binaryInfixGrammar divideFunction,
    functionDescription = "divides the left expression by the right expression"}
    where
        divFun [numExpr, denomExpr] = RealExpression $ coerceReal numExpr / coerceReal denomExpr
        divFun _ = internalError

plusFunction :: SQLFunction
plusFunction = SQLFunction {
    functionName        = "+",
    minArgCount         = 2,
    argCountIsFixed     = True,
    applyFunction       = applyBinaryNumeric plusFunction (+) (+),
    functionGrammar     = binaryInfixGrammar plusFunction,
    functionDescription = "adds the left and right expressions"}

minusFunction :: SQLFunction
minusFunction = SQLFunction {
    functionName        = "-",
    minArgCount         = 2,
    argCountIsFixed     = True,
    applyFunction       = applyBinaryNumeric minusFunction (-) (-),
    functionGrammar     = binaryInfixGrammar minusFunction,
    functionDescription = "subtracts the right expression from the left expression"}

-- Boolean
isFunction :: SQLFunction
isFunction = SQLFunction {
    functionName        = "=",
    minArgCount         = 2,
    argCountIsFixed     = True,
    applyFunction       = applyBinaryComparison isFunction (==),
    functionGrammar     = binaryInfixGrammar isFunction,
    functionDescription = "tests the left and right expressions for equality"}

isNotFunction :: SQLFunction
isNotFunction = SQLFunction {
    functionName        = "<>",
    minArgCount         = 2,
    argCountIsFixed     = True,
    applyFunction       = applyBinaryComparison isNotFunction (/=),
    functionGrammar     = binaryInfixGrammar isNotFunction,
    functionDescription = "evaluates as true if the left and right expressions are not equal"}

lessThanFunction :: SQLFunction
lessThanFunction = SQLFunction {
    functionName        = "<",
    minArgCount         = 2,
    argCountIsFixed     = True,
    applyFunction       = applyBinaryComparison lessThanFunction (<),
    functionGrammar     = binaryInfixGrammar lessThanFunction,
    functionDescription = "evaluates as true if the left expression is \"less than\" the right expression"}

lessThanOrEqualToFunction :: SQLFunction
lessThanOrEqualToFunction = SQLFunction {
    functionName        = "<=",
    minArgCount         = 2,
    argCountIsFixed     = True,
    applyFunction       = applyBinaryComparison lessThanOrEqualToFunction (<=),
    functionGrammar     = binaryInfixGrammar lessThanOrEqualToFunction,
    functionDescription = "evaluates as true if the left expression is \"less than or equal to\" the right expression"}

greaterThanFunction :: SQLFunction
greaterThanFunction = SQLFunction {
    functionName        = ">",
    minArgCount         = 2,
    argCountIsFixed     = True,
    applyFunction       = applyBinaryComparison greaterThanFunction (>),
    functionGrammar     = binaryInfixGrammar greaterThanFunction,
    functionDescription = "evaluates as true if the left expression is \"greater than\" the right expression"}

greaterThanOrEqualToFunction :: SQLFunction
greaterThanOrEqualToFunction = SQLFunction {
    functionName        = ">=",
    minArgCount         = 2,
    argCountIsFixed     = True,
    applyFunction       = applyBinaryComparison greaterThanOrEqualToFunction (>=),
    functionGrammar     = binaryInfixGrammar greaterThanOrEqualToFunction,
    functionDescription = "evaluates as true if the left expression is \"greater than or equal to\" the right expression"}

andFunction :: SQLFunction
andFunction = SQLFunction {
    functionName        = "AND",
    minArgCount         = 2,
    argCountIsFixed     = True,
    applyFunction       = applyBinaryBooleanTest andFunction (&&),
    functionGrammar     = binaryInfixGrammar andFunction,
    functionDescription = "evaluates as true if and only if both the left and right expressions are true"}

orFunction :: SQLFunction
orFunction = SQLFunction {
    functionName        = "OR",
    minArgCount         = 2,
    argCountIsFixed     = True,
    applyFunction       = applyBinaryBooleanTest orFunction (||),
    functionGrammar     = binaryInfixGrammar orFunction,
    functionDescription = "evaluates as true if and only if either the left or right expressions are true"}

concatenateFunction :: SQLFunction
concatenateFunction = SQLFunction {
    functionName        = "||",
    minArgCount         = 2,
    argCountIsFixed     = True,
    applyFunction       = catExprs . checkArgCount concatenateFunction,
    functionGrammar     = binaryInfixGrammar concatenateFunction,
    functionDescription = "performs string concatenation of the left and right strings"}
    where
        catExprs [arg1, arg2] = StringExpression $ coerceString arg1 ++ coerceString arg2
        catExprs _ = internalError

regexMatchFunction :: SQLFunction
regexMatchFunction = SQLFunction {
    functionName        = "=~",
    minArgCount         = 2,
    argCountIsFixed     = True,
    applyFunction       = regexMatch . checkArgCount regexMatchFunction,
    functionGrammar     = binaryInfixGrammar regexMatchFunction,
    functionDescription = "evaluates as true if and only if the text on the left matches the regular expression on the right"}
    where
        regexMatch [arg1, arg2] = BoolExpression $ coerceString arg1 =~ coerceString arg2
        regexMatch _ = internalError

-- Functions with special syntax --
specialFunctions :: [SQLFunction]
specialFunctions = [substringFromFunction,
                    substringFromToFunction,
                    negateFunction,
                    notFunction]

negateFunction :: SQLFunction
negateFunction = SQLFunction {
    functionName        = "-",
    minArgCount         = 1,
    argCountIsFixed     = True,
    applyFunction       = applyUnaryNumeric negateFunction negate negate,
    functionGrammar     = "-numeric_expression",
    functionDescription = "unary negation"}

-- | SUBSTRING(extraction_string FROM starting_position [FOR length]
--             [COLLATE collation_name])
--   TODO implement COLLATE part
substringFromFunction :: SQLFunction
substringFromFunction = SQLFunction {
    functionName        = "SUBSTRING",
    minArgCount         = 2,
    argCountIsFixed     = True,
    applyFunction       = substringFrom . checkArgCount substringFromFunction,
    functionGrammar     = "SUBSTRING(string_expression FROM start_index [FOR length_expression])",
    functionDescription = "returns substring of string_expression going from " ++
                          "start_index using 1-based indexing for a length of length_expression " ++
                          " or to the end of string_expression if the FOR part is omitted"}
    where
        substringFrom [strExpr, fromExpr] = StringExpression $
            drop (coerceInt fromExpr - 1) (coerceString strExpr)
        substringFrom _ = internalError

substringFromToFunction :: SQLFunction
substringFromToFunction = SQLFunction {
    functionName        = "SUBSTRING",
    minArgCount         = 3,
    argCountIsFixed     = True,
    applyFunction       = substringFromTo . checkArgCount substringFromToFunction,
    functionGrammar     = "SUBSTRING(string_expression FROM start_index [FOR length_expression])",
    functionDescription = "returns substring of string_expression going from " ++
                          "start_index using 1-based indexing for a length of length_expression " ++
                          " or to the end of string_expression if the FOR part is omitted"}
    where
        substringFromTo [strExpr, fromExpr, toExpr] = StringExpression $
            take (coerceInt toExpr) (drop (coerceInt fromExpr - 1) (coerceString strExpr))
        substringFromTo _ = internalError

notFunction :: SQLFunction
notFunction = SQLFunction {
    functionName        = "NOT",
    minArgCount         = 1,
    argCountIsFixed     = True,
    applyFunction       = applyUnaryBool notFunction not,
    functionGrammar     = "NOT bool_expression",
    functionDescription = "evaluates as true if and only if bool_expression is false"}

-- some evaluation helper functions

applyUnaryString ::
    SQLFunction
    -> (String -> String)
    -> [EvaluatedExpression]
    -> EvaluatedExpression
applyUnaryString sqlFun f =
    StringExpression . f . coerceString . head . checkArgCount sqlFun

applyBinaryBooleanTest ::
    SQLFunction
    -> (Bool -> Bool -> Bool)
    -> [EvaluatedExpression]
    -> EvaluatedExpression
applyBinaryBooleanTest _ f [arg1, arg2] =
        BoolExpression $ f (coerceBool arg1) (coerceBool arg2)
applyBinaryBooleanTest sqlFun _ args  = badArgCountError sqlFun args

applyBinaryComparison ::
    SQLFunction
    -> (t -> t -> Bool)
    -> [t]
    -> EvaluatedExpression
applyBinaryComparison _      cmp [arg1, arg2] = BoolExpression $ cmp arg1 arg2
applyBinaryComparison sqlFun _   args         = badArgCountError sqlFun args

applyUnaryNumeric ::
    SQLFunction
    -> (Int -> Int)
    -> (Double -> Double)
    -> [EvaluatedExpression]
    -> EvaluatedExpression
applyUnaryNumeric _ intFunc realFunc [arg] =
    if useRealAlgebra arg then
        RealExpression $ realFunc (coerceReal arg)
    else
        IntExpression $ intFunc (coerceInt arg)
applyUnaryNumeric sqlFun _ _ args  = badArgCountError sqlFun args

applyBinaryNumeric ::
    SQLFunction
    -> (Int -> Int -> Int)
    -> (Double -> Double -> Double)
    -> [EvaluatedExpression]
    -> EvaluatedExpression
applyBinaryNumeric _ intFunc realFunc [arg1, arg2] =
    if useRealAlgebra arg1 || useRealAlgebra arg2 then
        RealExpression $ realFunc (coerceReal arg1) (coerceReal arg2)
    else
        IntExpression $ intFunc (coerceInt arg1) (coerceInt arg2)
applyBinaryNumeric sqlFun _ _ args  = badArgCountError sqlFun args

applyUnaryBool ::
    SQLFunction
    -> (Bool -> Bool)
    -> [EvaluatedExpression]
    -> EvaluatedExpression
applyUnaryBool _      f [arg] = BoolExpression $ f (coerceBool arg)
applyUnaryBool sqlFun _ args  = badArgCountError sqlFun args

checkArgCount :: SQLFunction -> [a] -> [a]
checkArgCount sqlFun args =
    if argCountOK then args else badArgCountError sqlFun args
    where
        minArgs = minArgCount sqlFun

        argCountOK =
            if argCountIsFixed sqlFun
                then lengthEquals args minArgs
                else lengthAtLeast args minArgs
            where
                lengthEquals xs len = go xs 0
                    where
                        go [] cumLen = cumLen == len
                        go (_:yt) cumLen = (cumLen < len) && go yt (cumLen + 1)

                lengthAtLeast xs len = go xs 0
                    where
                        go [] cumLen = cumLen >= len
                        go (_:yt) cumLen = (cumLen >= len) || go yt (cumLen + 1)

badArgCountError :: SQLFunction -> [a] -> b
badArgCountError sqlFun args =
    if argCountIsFixed sqlFun then error $
        "Error: bad argument count in " ++ functionName sqlFun ++
        " expected " ++ show (minArgCount sqlFun) ++
        " argument(s) but was given " ++ show received
    else error $
        "Error: bad argument count in " ++ functionName sqlFun ++
        " expected at least " ++ show (minArgCount sqlFun) ++
        " argument(s) but was given " ++ show received
    where received = length args

internalError :: a
internalError = error "Internal Error: this should never occur"

useRealAlgebra :: EvaluatedExpression -> Bool
useRealAlgebra (RealExpression _) = True
useRealAlgebra expr = case maybeCoerceInt expr of
    Nothing -> True
    Just _  -> False

-- | trims leading and trailing spaces
trimSpace :: String -> String
trimSpace = f . f
    where f = reverse . dropWhile isSpace

-- | some grammar helper functions
normalGrammar :: SQLFunction -> String
normalGrammar sqlFun = functionName sqlFun ++ "(" ++ argStr ++ ")"
    where
        argStrPrefix = intercalate ", " minArgs
            where minArgs =map ((++) "arg" . show) [1 .. minArgCount sqlFun]

        argStr
          | argCountIsFixed sqlFun = argStrPrefix
          | minArgCount sqlFun >= 1 = argStrPrefix ++ ", ..."
          | otherwise = "..."

binaryInfixGrammar :: SQLFunction -> String
binaryInfixGrammar sqlFun = "leftExpr " ++ functionName sqlFun ++ " rightExpr"


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http.Dependencies;
using BugLogger.Data;
using BugLogger.Data.Repositories;
using BugLogger.Services.Controllers;
using BugLogger.Model;

namespace BugLogger.Services.Tests
{
    class TestBugsDependencyResolver<T> : IDependencyResolver where T : class
    {
        private IRepository<T> repository;

        public IRepository<T> Repository
        {
            get
            {
                return this.repository;
            }
            set
            {
                this.repository = value;
            }
        }

        public IDependencyScope BeginScope()
        {
            return this;
        }

        public object GetService(Type serviceType)
        {
            //add all controllers
            if (serviceType == typeof(BugsController))
            {
                return new BugsController(this.Repository as IRepository<Bug>);
            }
            return null;
        }

        public IEnumerable<object> GetServices(Type serviceType)
        {
            return new List<object>();
        }

        public void Dispose()
        {

        }
    }
}


text:
package de.egore911.versioning.ui.dto;

import de.egore911.appframework.ui.dto.AbstractDto;

public class TagTransformer extends AbstractDto {

	private String name;
	private String searchPattern;
	private String replacementPattern;

	public String getName() {
		return name;
	}

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

	public String getSearchPattern() {
		return searchPattern;
	}

	public void setSearchPattern(String searchPattern) {
		this.searchPattern = searchPattern;
	}

	public String getReplacementPattern() {
		return replacementPattern;
	}

	public void setReplacementPattern(String replacementPattern) {
		this.replacementPattern = replacementPattern;
	}

}


text:
package org.hisp.dhis.dataadmin.action.locale;

import org.apache.commons.lang3.StringUtils;
import org.hisp.dhis.i18n.I18nLocaleService;
import org.springframework.beans.factory.annotation.Autowired;

import com.opensymphony.xwork2.Action;

/**
 * @author James Chang
 */
public class AddLocaleAction
    implements Action
{
    // -------------------------------------------------------------------------
    // Dependency
    // -------------------------------------------------------------------------

    @Autowired
    private I18nLocaleService localeService;

    // -------------------------------------------------------------------------
    // Input/Output
    // -------------------------------------------------------------------------

    private String language;

    public void setLanguage( String language )
    {
        this.language = language;
    }

    private String country;

    public void setCountry( String country )
    {
        this.country = country;
    }

    // -------------------------------------------------------------------------
    // Action implementation
    // -------------------------------------------------------------------------

    @Override
    public String execute()
        throws Exception
    {
        language = StringUtils.trimToNull( language );
        country = StringUtils.trimToNull( country );

        localeService.addI18nLocale( language, country );

        return SUCCESS;
    }
}


text:
@class UnitGen;
@class UnitGenConnection;

extern const CGFloat kUnitGenViewWidth;
extern const CGFloat kUnitGenViewHeight;

@interface UnitGenView : BaseView
{
    NSArray* _inputs;
    NSArray* _outputs;
}

- (id) initWithGenerator: (UnitGen*) unitGen;
- (void) setOrigin: (CGPoint) pos;
- (void) setSelected: (BOOL) selected;

- (void) setIcon: (UIImage*) image;

@property (readonly, nonatomic) UnitGen* unitGen;
@property (readonly, nonatomic) BOOL selected;
@property (readonly, nonatomic) NSArray* inputs;
@property (readonly, nonatomic) NSArray* outputs;

@end

BOOL IsPointNearConnection(CGPoint st, CGPoint ed, CGPoint pt, float proximity);