text:
"""Mapreduce execution context.

Mapreduce context provides handler code with information about
current mapreduce execution and organizes utility data flow
from handlers such as counters, log messages, mutation pools.
"""

__all__ = ["get",
           "Pool",
           "Context",
           "COUNTER_MAPPER_CALLS",
           "COUNTER_MAPPER_WALLTIME_MS",
           "DATASTORE_DEADLINE",
           "MAX_ENTITY_COUNT",
          ]

import heapq
import logging
import threading

try:
  from google.appengine.ext import ndb
except ImportError:
  ndb = None
from google.appengine.api import datastore
from google.appengine.ext import db
from google.appengine.runtime import apiproxy_errors

MAX_ENTITY_COUNT = 20

DATASTORE_DEADLINE = 15

COUNTER_MAPPER_CALLS = "mapper-calls"

COUNTER_MAPPER_WALLTIME_MS = "mapper-walltime-ms"

def _normalize_entity(value):
  """Return an entity from an entity or model instance."""
  if ndb is not None and isinstance(value, ndb.Model):
    return None
  if getattr(value, "_populate_internal_entity", None):
    return value._populate_internal_entity()
  return value

def _normalize_key(value):
  """Return a key from an entity, model instance, key, or key string."""
  if ndb is not None and isinstance(value, (ndb.Model, ndb.Key)):
    return None
  if getattr(value, "key", None):
    return value.key()
  elif isinstance(value, basestring):
    return datastore.Key(value)
  else:
    return value

class _ItemList(object):
  """A buffer that holds arbitrary items and auto flushes them when full.

  Callers of this class provides the logic on how to flush.
  This class takes care of the common logic of when to flush and when to retry.

  Properties:
    items: list of objects.
    length: length of item list.
    size: aggregate item size in bytes.
  """

  DEFAULT_RETRIES = 3
  _LARGEST_ITEMS_TO_LOG = 5

  def __init__(self,
               max_entity_count,
               flush_function,
               timeout_retries=DEFAULT_RETRIES,
               repr_function=None):
    """Constructor.

    Args:
      max_entity_count: maximum number of entities before flushing it to db.
      flush_function: a function that can flush the items. The function is
        called with a list of items as the first argument, a dict of options
        as second argument. Currently options can contain {"deadline": int}.
        see self.flush on how the function is called.
      timeout_retries: how many times to retry upon timeouts.
      repr_function: a function that turns an item into meaningful
        representation. For debugging large items.
    """
    self.items = []
    self.__max_entity_count = int(max_entity_count)
    self.__flush_function = flush_function
    self.__repr_function = repr_function
    self.__timeout_retries = int(timeout_retries)

  def __str__(self):
    return "ItemList of with %s items" % len(self.items)

  def append(self, item):
    """Add new item to the list.

    If needed, append will first flush existing items and clear existing items.

    Args:
      item: an item to add to the list.
    """
    if self.should_flush():
      self.flush()
    self.items.append(item)

  def flush(self):
    """Force a flush."""
    if not self.items:
      return

    retry = 0
    options = {"deadline": DATASTORE_DEADLINE}
    while retry <= self.__timeout_retries:
      try:
        self.__flush_function(self.items, options)
        self.clear()
        break
      except db.Timeout, e:
        logging.warning(e)
        logging.warning("Flushing '%s' timed out. Will retry for the %s time.",
                        self, retry)
        retry += 1
        options["deadline"] *= 2
      except apiproxy_errors.RequestTooLargeError:
        self._log_largest_items()
        raise
    else:
      raise

  def _log_largest_items(self):
    if not self.__repr_function:
      logging.error("Got RequestTooLargeError but can't interpret items in "
                    "_ItemList %s.", self)
      return

    sizes = [len(self.__repr_function(i)) for i in self.items]
    largest = heapq.nlargest(self._LARGEST_ITEMS_TO_LOG,
                             zip(sizes, self.items),
                             lambda t: t[0])

    self._largest = [(s, self.__repr_function(i)) for s, i in largest]
    logging.error("Got RequestTooLargeError. Largest items: %r", self._largest)

  def clear(self):
    """Clear item list."""
    self.items = []

  def should_flush(self):
    """Whether to flush before append the next entity.

    Returns:
      True to flush. False other.
    """
    return len(self.items) >= self.__max_entity_count

class Pool(object):
  """Mutation pool accumulates changes to perform them in patch.

  Any Pool subclass should not be public. Instead, Pool should define an
  operation.Operation class and let user uses that. For example, in a map
  function, user can do:

  def map(foo):
    yield OperationOnMyPool(any_argument)

  Since Operation is a callable object, Mapreduce library will invoke
  any Operation object that is yielded with context.Context instance.
  The operation object can then access MyPool from Context.get_pool.
  """

  def flush(self):
    """Flush all changes."""
    raise NotImplementedError()

class _MutationPool(Pool):
  """Mutation pool accumulates datastore changes to perform them in batch.

  Properties:
    puts: _ItemList of entities to put to datastore.
    deletes: _ItemList of keys to delete from datastore.
    ndb_puts: _ItemList of ndb entities to put to datastore.
    ndb_deletes: _ItemList of ndb keys to delete from datastore.
  """

  def __init__(self,
               max_entity_count=MAX_ENTITY_COUNT,
               mapreduce_spec=None):
    """Constructor.

    Args:
      max_entity_count: maximum number of entities before flushing it to db.
      mapreduce_spec: An optional instance of MapperSpec.
    """
    self.max_entity_count = max_entity_count
    params = mapreduce_spec.params if mapreduce_spec is not None else {}
    self.force_writes = bool(params.get("force_ops_writes", False))
    self.puts = _ItemList(max_entity_count,
                          self._flush_puts,
                          repr_function=self._db_repr)
    self.deletes = _ItemList(max_entity_count,
                             self._flush_deletes)
    self.ndb_puts = _ItemList(max_entity_count,
                              self._flush_ndb_puts,
                              repr_function=self._ndb_repr)
    self.ndb_deletes = _ItemList(max_entity_count,
                                 self._flush_ndb_deletes)

  def put(self, entity):
    """Registers entity to put to datastore.

    Args:
      entity: an entity or model instance to put.
    """
    actual_entity = _normalize_entity(entity)
    if actual_entity is None:
      return self.ndb_put(entity)
    self.puts.append(actual_entity)

  def ndb_put(self, entity):
    """Like put(), but for NDB entities."""
    assert ndb is not None and isinstance(entity, ndb.Model)
    self.ndb_puts.append(entity)

  def delete(self, entity):
    """Registers entity to delete from datastore.

    Args:
      entity: an entity, model instance, or key to delete.
    """
    key = _normalize_key(entity)
    if key is None:
      return self.ndb_delete(entity)
    self.deletes.append(key)

  def ndb_delete(self, entity_or_key):
    """Like delete(), but for NDB entities/keys."""
    if ndb is not None and isinstance(entity_or_key, ndb.Model):
      key = entity_or_key.key
    else:
      key = entity_or_key
    self.ndb_deletes.append(key)

  def flush(self):
    """Flush(apply) all changed to datastore."""
    self.puts.flush()
    self.deletes.flush()
    self.ndb_puts.flush()
    self.ndb_deletes.flush()

  @classmethod
  def _db_repr(cls, entity):
    """Converts entity to a readable repr.

    Args:
      entity: datastore.Entity or datastore_types.Key.

    Returns:
      Proto in str.
    """
    return str(entity._ToPb())

  @classmethod
  def _ndb_repr(cls, entity):
    """Converts entity to a readable repr.

    Args:
      entity: ndb.Model

    Returns:
      Proto in str.
    """
    return str(entity._to_pb())

  def _flush_puts(self, items, options):
    """Flush all puts to datastore."""
    datastore.Put(items, config=self._create_config(options))

  def _flush_deletes(self, items, options):
    """Flush all deletes to datastore."""
    datastore.Delete(items, config=self._create_config(options))

  def _flush_ndb_puts(self, items, options):
    """Flush all NDB puts to datastore."""
    assert ndb is not None
    ndb.put_multi(items, config=self._create_config(options))

  def _flush_ndb_deletes(self, items, options):
    """Flush all deletes to datastore."""
    assert ndb is not None
    ndb.delete_multi(items, config=self._create_config(options))

  def _create_config(self, options):
    """Creates datastore Config.

    Returns:
      A datastore_rpc.Configuration instance.
    """
    return datastore.CreateConfig(deadline=options["deadline"],
                                  force_writes=self.force_writes)

class _Counters(Pool):
  """Regulates access to counters.

  Counters Pool is a str to int map. It is saved as part of ShardState so it
  is flushed when ShardState commits to datastore successfully.
  """

  def __init__(self, shard_state):
    """Constructor.

    Args:
      shard_state: current mapreduce shard state as model.ShardState.
    """
    self._shard_state = shard_state

  def increment(self, counter_name, delta=1):
    """Increment counter value.

    Args:
      counter_name: name of the counter as string.
      delta: increment delta as int.
    """
    self._shard_state.counters_map.increment(counter_name, delta)

  def flush(self):
    """Flush unsaved counter values."""
    pass

class Context(object):
  """MapReduce execution context.

  The main purpose of Context is to facilitate IO. User code, input reader,
  and output writer code can plug in pools (see Pool class) to Context to
  batch operations.

  There is a single Context instance associated with each worker thread.
  It can be accessed via context.get(). handlers.MapperWorkerHandler creates
  this instance before any IO code (input_reader, output_writer, user functions)
  is called.

  Each Pool decides how to batch and when to flush.
  Context and all its pools are flushed by the end of a slice.
  Upon error in slice execution, what is flushed is undefined. (See _Counters
  for an exception).

  Properties:
    mapreduce_spec: current mapreduce specification as model.MapreduceSpec.
  """

  _local = threading.local()

  def __init__(self, mapreduce_spec, shard_state, task_retry_count=0):
    """Constructor.

    Args:
      mapreduce_spec: mapreduce specification as model.MapreduceSpec.
      shard_state: an instance of model.ShardState. This has to be the same
        instance as the one MapperWorkerHandler mutates. All mutations are
        flushed to datastore in the end of the slice.
      task_retry_count: how many times this task has been retried.
    """
    self._shard_state = shard_state
    self.mapreduce_spec = mapreduce_spec

    self.task_retry_count = task_retry_count

    if self.mapreduce_spec:
      self.mapreduce_id = self.mapreduce_spec.mapreduce_id
    else:

      self.mapreduce_id = None
    if shard_state:
      self.shard_id = shard_state.get_shard_id()
    else:

      self.shard_id = None

    self._mutation_pool = _MutationPool(mapreduce_spec=mapreduce_spec)
    self._counters = _Counters(shard_state)

    self.counters = self._counters

    self._pools = {}
    self.register_pool("mutation_pool", self._mutation_pool)
    self.register_pool("counters", self.counters)

  def flush(self):
    """Flush all information recorded in context."""
    for pool in self._pools.values():
      pool.flush()

  def register_pool(self, key, pool):
    """Register an arbitrary pool to be flushed together with this context.

    Args:
      key: pool key as string.
      pool: a pool instance.
    """
    self._pools[key] = pool

  def get_pool(self, key):
    """Obtains an instance of registered pool.

    Args:
      key: pool key as string.

    Returns:
      an instance of the pool registered earlier, or None.
    """
    return self._pools.get(key, None)

  @classmethod
  def _set(cls, context):
    """Set current context instance.

    Args:
      context: new context as Context or None.
    """
    cls._local._context_instance = context

def get():
  """Get current context instance.

  Returns:
    current context as Context.
  """
  if not hasattr(Context._local, "_context_instance") :
    return None
  return Context._local._context_instance


text:
#include "evas_common.h"
#include "evas_private.h"
#include "evas_cs.h"

static int _evas_init_count = 0;
int _evas_log_dom_global = -1;
/**
 * Initialize Evas
 *
 * @return The init counter value.
 *
 * This function initialize evas, increments a counter of the number
 * of calls to this function and returns this value.
 *
 * @see evas_shutdown().
 *
 * @ingroup Evas_Group
 */
EAPI int
evas_init(void)
{
   if (++_evas_init_count != 1)
     return _evas_init_count;

#ifdef HAVE_EVIL
   if (!evil_init())
     return --_evas_init_count;
#endif

   if (!eina_init())
     goto shutdown_evil;

   _evas_log_dom_global = eina_log_domain_register
     ("evas_main", EVAS_DEFAULT_LOG_COLOR);
   if (_evas_log_dom_global < 0)
     {
        EINA_LOG_ERR("Can not create a module log domain.");
        goto shutdown_eina;
     }

   evas_module_init();
#ifdef BUILD_ASYNC_EVENTS
   if (!evas_async_events_init())
     goto shutdown_module;
#endif
#ifdef EVAS_CSERVE
   if (getenv("EVAS_CSERVE")) evas_cserve_init();
#endif
#ifdef BUILD_ASYNC_PRELOAD
   _evas_preload_thread_init();
#endif
#ifdef EVAS_FRAME_QUEUING
   evas_common_frameq_init();
#endif

   return _evas_init_count;

#ifdef BUILD_ASYNC_EVENTS
 shutdown_module:
   evas_module_shutdown();
   eina_log_domain_unregister(_evas_log_dom_global);
#endif
 shutdown_eina:
   eina_shutdown();
 shutdown_evil:
#ifdef HAVE_EVIL
   evil_shutdown();
#endif

   return --_evas_init_count;
}

/**
 * Shutdown Evas
 *
 * @return The init counter value.
 *
 * This function finalize evas, decrements the counter of the number
 * of calls to the function evas_init() and returns this value.
 *
 * @see evas_init().
 *
 * @ingroup Evas_Group
 */
EAPI int
evas_shutdown(void)
{
   if (--_evas_init_count != 0)
     return _evas_init_count;

#ifdef EVAS_FRAME_QUEUING
   if (evas_common_frameq_enabled())
     {
        evas_common_frameq_finish();
        evas_common_frameq_destroy();
     }
#endif
#ifdef BUILD_ASYNC_EVENTS
   _evas_preload_thread_shutdown();
#endif
#ifdef EVAS_CSERVE
   if (getenv("EVAS_CSERVE")) evas_cserve_shutdown();
#endif
#ifdef BUILD_ASYNC_EVENTS
   evas_async_events_shutdown();
#endif
   evas_font_dir_cache_free();
   evas_common_shutdown();
   evas_module_shutdown();
   eina_log_domain_unregister(_evas_log_dom_global);
   eina_shutdown();
#ifdef HAVE_EVIL
   evil_shutdown();
#endif

   return _evas_init_count;
}

/**
 * Creates a new empty evas.
 *
 * Note that before you can use the evas, you will to at a minimum:
 * @li Set its render method with @ref evas_output_method_set .
 * @li Set its viewport size with @ref evas_output_viewport_set .
 * @li Set its size of the canvas with @ref evas_output_size_set .
 * @li Ensure that the render engine is given the correct settings
 *     with @ref evas_engine_info_set .
 *
 * This function should only fail if the memory allocation fails
 *
 * @note this function is very low level. Instead of using it
 *       directly, consider using the high level functions in
 *       Ecore_Evas such as @c ecore_evas_new(). See
 *       http://docs.enlightenment.org/auto/ecore/.
 *
 * @attention it is recommended that one calls evas_init() before
 *       creating new canvas.
 *
 * @return A new uninitialised Evas canvas on success.  Otherwise, @c
 * NULL.
 * @ingroup Evas_Canvas
 */
EAPI Evas *
evas_new(void)
{
   Evas *e;

   e = calloc(1, sizeof(Evas));
   if (!e) return NULL;

   e->magic = MAGIC_EVAS;
   e->output.render_method = RENDER_METHOD_INVALID;
   e->viewport.w = 1;
   e->viewport.h = 1;
   e->hinting = EVAS_FONT_HINTING_BYTECODE;
   e->name_hash = eina_hash_string_superfast_new(NULL);

#define EVAS_ARRAY_SET(E, Array)		\
   eina_array_step_set(&E->Array, sizeof (E->Array), 256);

   EVAS_ARRAY_SET(e, delete_objects);
   EVAS_ARRAY_SET(e, active_objects);
   EVAS_ARRAY_SET(e, restack_objects);
   EVAS_ARRAY_SET(e, render_objects);
   EVAS_ARRAY_SET(e, pending_objects);
   EVAS_ARRAY_SET(e, obscuring_objects);
   EVAS_ARRAY_SET(e, temporary_objects);
   EVAS_ARRAY_SET(e, calculate_objects);
   EVAS_ARRAY_SET(e, clip_changes);

#undef EVAS_ARRAY_SET

   return e;
}

/**
 * Frees the given evas and any objects created on it.
 *
 * Any objects with 'free' callbacks will have those callbacks called
 * in this function.
 *
 * @param   e The given evas.
 *
 * @ingroup Evas_Canvas
 */
EAPI void
evas_free(Evas *e)
{
   Eina_Rectangle *r;
   Evas_Layer *lay;
   int i;
   int del;

   MAGIC_CHECK(e, Evas, MAGIC_EVAS);
   return;
   MAGIC_CHECK_END();

#ifdef EVAS_FRAME_QUEUING
   evas_common_frameq_flush();
#endif

   if (e->walking_list == 0) evas_render_idle_flush(e);

   if (e->walking_list > 0) return;

   if (e->callbacks)
     {
	if (e->callbacks->deletions_waiting) return;

	e->callbacks->deletions_waiting = 0;
	evas_event_callback_list_post_free(&e->callbacks->callbacks);
	if (!e->callbacks->callbacks)
	  {
	     free(e->callbacks);
	     e->callbacks = NULL;
	  }

	_evas_post_event_callback_free(e);
     }

   del = 1;
   e->walking_list++;
   e->cleanup = 1;
   while (del)
     {
	del = 0;
	EINA_INLIST_FOREACH(e->layers, lay)
	  {
	     Evas_Object *o;

	     evas_layer_pre_free(lay);

	     EINA_INLIST_FOREACH(lay->objects, o)
	       {
		  if ((o->callbacks) && (o->callbacks->walking_list))
		    {
		       /* Defer free */
		       e->delete_me = 1;
		       e->walking_list--;
		       return;
		    }
		  if (!o->delete_me)
		    del = 1;
	       }
	  }
     }
   EINA_INLIST_FOREACH(e->layers, lay)
     evas_layer_free_objects(lay);
   evas_layer_clean(e);

   e->walking_list--;

   evas_font_path_clear(e);
   e->pointer.object.in = eina_list_free(e->pointer.object.in);

   if (e->name_hash) eina_hash_free(e->name_hash);
   e->name_hash = NULL;

   EINA_LIST_FREE(e->damages, r)
     eina_rectangle_free(r);
   EINA_LIST_FREE(e->obscures, r)
     eina_rectangle_free(r);

   evas_fonts_zero_free(e);

   evas_event_callback_all_del(e);
   evas_event_callback_cleanup(e);

   if (e->engine.func)
     {
	e->engine.func->context_free(e->engine.data.output, e->engine.data.context);
	e->engine.func->output_free(e->engine.data.output);
	e->engine.func->info_free(e, e->engine.info);
     }

   for (i = 0; i < e->modifiers.mod.count; i++)
     free(e->modifiers.mod.list[i]);
   if (e->modifiers.mod.list) free(e->modifiers.mod.list);

   for (i = 0; i < e->locks.lock.count; i++)
     free(e->locks.lock.list[i]);
   if (e->locks.lock.list) free(e->locks.lock.list);

   if (e->engine.module) evas_module_unref(e->engine.module);

   eina_array_flush(&e->delete_objects);
   eina_array_flush(&e->active_objects);
   eina_array_flush(&e->restack_objects);
   eina_array_flush(&e->render_objects);
   eina_array_flush(&e->pending_objects);
   eina_array_flush(&e->obscuring_objects);
   eina_array_flush(&e->temporary_objects);
   eina_array_flush(&e->calculate_objects);
   eina_array_flush(&e->clip_changes);

   e->magic = 0;
   free(e);
}

/**
 * Sets the output engine for the given evas.
 *
 * Once the output engine for an evas is set, any attempt to change it
 * will be ignored.  The value for @p render_method can be found using
 * @ref evas_render_method_lookup .
 *
 * @attention it is mandatory that one calls evas_init() before
 *       setting the output method.
 *
 * @param   e             The given evas.
 * @param   render_method The numeric engine value to use.
 * @ingroup Evas_Output_Method
 */
EAPI void
evas_output_method_set(Evas *e, int render_method)
{
   Evas_Module *em;

   MAGIC_CHECK(e, Evas, MAGIC_EVAS);
   return;
   MAGIC_CHECK_END();

   /* if our engine to set it to is invalid - abort */
   if (render_method == RENDER_METHOD_INVALID) return;
   /* if the engine is already set up - abort */
   if (e->output.render_method != RENDER_METHOD_INVALID) return;
   /* Request the right engine. */
   em = evas_module_engine_get(render_method);
   if (!em) return ;
   if (em->id_engine != render_method) return;
   if (!evas_module_load(em)) return;

   /* set the correct render */
   e->output.render_method = render_method;
   e->engine.func = (em->functions);
   evas_module_use(em);
   if (e->engine.module) evas_module_unref(e->engine.module);
   e->engine.module = em;
   evas_module_ref(em);
   /* get the engine info struct */
   if (e->engine.func->info) e->engine.info = e->engine.func->info(e);
   return;
}

/**
 * Retrieves the number of the output engine used for the given evas.
 * @param   e The given evas.
 * @return  The ID number of the output engine being used.  @c 0 is
 *          returned if there is an error.
 * @ingroup Evas_Output_Method
 */
EAPI int
evas_output_method_get(const Evas *e)
{
   MAGIC_CHECK(e, Evas, MAGIC_EVAS);
   return RENDER_METHOD_INVALID;
   MAGIC_CHECK_END();

   return e->output.render_method;
}

/**
 * Retrieves the current render engine info struct from the given evas.
 *
 * The returned structure is publicly modifiable.  The contents are
 * valid until either @ref evas_engine_info_set or @ref evas_render
 * are called.
 *
 * This structure does not need to be freed by the caller.
 *
 * @param   e The given evas.
 * @return  A pointer to the Engine Info structure.  @c NULL is returned if
 *          an engine has not yet been assigned.
 * @ingroup Evas_Output_Method
 */
EAPI Evas_Engine_Info *
evas_engine_info_get(const Evas *e)
{
   Evas_Engine_Info *info;

   MAGIC_CHECK(e, Evas, MAGIC_EVAS);
   return NULL;
   MAGIC_CHECK_END();

   if (!e->engine.info) return NULL;

   info = e->engine.info;
   ((Evas *)e)->engine.info_magic = info->magic;

   return info;
}

/**
 * Applies the engine settings for the given evas from the given @c
 * Evas_Engine_Info structure.
 *
 * To get the Evas_Engine_Info structure to use, call @ref
 * evas_engine_info_get .  Do not try to obtain a pointer to an
 * @c Evas_Engine_Info structure in any other way.
 *
 * You will need to call this function at least once before you can
 * create objects on an evas or render that evas.  Some engines allow
 * their settings to be changed more than once.
 *
 * Once called, the @p info pointer should be considered invalid.
 *
 * @param   e    The pointer to the Evas Canvas
 * @param   info The pointer to the Engine Info to use
 * @return  1 if no error occurred, 0 otherwise
 * @ingroup Evas_Output_Method
 */
EAPI Eina_Bool
evas_engine_info_set(Evas *e, Evas_Engine_Info *info)
{
   MAGIC_CHECK(e, Evas, MAGIC_EVAS);
   return EINA_FALSE;
   MAGIC_CHECK_END();
   if (!info) return EINA_FALSE;
   if (info != e->engine.info) return EINA_FALSE;
   if (info->magic != e->engine.info_magic) return EINA_FALSE;
   return (Eina_Bool)e->engine.func->setup(e, info);
}

/**
 * Sets the output size of the render engine of the given evas.
 *
 * The evas will render to a rectangle of the given size once this
 * function is called.  The output size is independent of the viewport
 * size.  The viewport will be stretched to fill the given rectangle.
 *
 * The units used for @p w and @p h depend on the engine used by the
 * evas.
 *
 * @param   e The given evas.
 * @param   w The width in output units, usually pixels.
 * @param   h The height in output units, usually pixels.
 * @ingroup Evas_Output_Size
 */
EAPI void
evas_output_size_set(Evas *e, int w, int h)
{
   MAGIC_CHECK(e, Evas, MAGIC_EVAS);
   return;
   MAGIC_CHECK_END();

   if ((w == e->output.w) && (h == e->output.h)) return;
   if (w < 1) w = 1;
   if (h < 1) h = 1;

#ifdef EVAS_FRAME_QUEUING
   evas_common_frameq_flush();
#endif

   e->output.w = w;
   e->output.h = h;
   e->output.changed = 1;
   e->output_validity++;
   e->changed = 1;
   evas_render_invalidate(e);
}

/**
 * Retrieve the output size of the render engine of the given evas.
 *
 * The output size is given in whatever the output units are for the
 * engine.
 *
 * If either @p w or @p h is @c NULL, then it is ignored.  If @p e is
 * invalid, the returned results are undefined.
 *
 * @param   e The given evas.
 * @param   w The pointer to an integer to store the width in.
 * @param   h The pointer to an integer to store the height in.
 * @ingroup Evas_Output_Size
 */
EAPI void
evas_output_size_get(const Evas *e, int *w, int *h)
{
   MAGIC_CHECK(e, Evas, MAGIC_EVAS);
   if (w) *w = 0;
   if (h) *h = 0;
   return;
   MAGIC_CHECK_END();

   if (w) *w = e->output.w;
   if (h) *h = e->output.h;
}

/**
 * Sets the output viewport of the given evas in evas units.
 *
 * The output viewport is the area of the evas that will be visible to
 * the viewer.  The viewport will be stretched to fit the output
 * target of the evas when rendering is performed.
 *
 * @note The coordinate values do not have to map 1-to-1 with the output
 *       target.  However, it is generally advised that it is done for ease
 *       of use.
 *
 * @param   e The given evas.
 * @param   x The top-left corner x value of the viewport.
 * @param   y The top-left corner y value of the viewport.
 * @param   w The width of the viewport.  Must be greater than 0.
 * @param   h The height of the viewport.  Must be greater than 0.
 * @ingroup Evas_Output_Size
 */
EAPI void
evas_output_viewport_set(Evas *e, Evas_Coord x, Evas_Coord y, Evas_Coord w, Evas_Coord h)
{
   MAGIC_CHECK(e, Evas, MAGIC_EVAS);
   return;
   MAGIC_CHECK_END();

   if ((x == e->viewport.x) && (y == e->viewport.y) &&
       (w == e->viewport.w) && (h == e->viewport.h)) return;
   if (w <= 0) return;
   if (h <= 0) return;
   if ((x != 0) || (y != 0))
     {
	ERR("Compat error. viewport x,y != 0,0 not supported");
	x = 0;
	y = 0;
     }
   e->viewport.x = x;
   e->viewport.y = y;
   e->viewport.w = w;
   e->viewport.h = h;
   e->viewport.changed = 1;
   e->output_validity++;
   e->changed = 1;
}

/**
 * Get the render engine's output viewport co-ordinates in canvas units.
 * @param e The pointer to the Evas Canvas
 * @param x The pointer to a x variable to be filled in
 * @param y The pointer to a y variable to be filled in
 * @param w The pointer to a width variable to be filled in
 * @param h The pointer to a height variable to be filled in
 * @ingroup Evas_Output_Size
 *
 * Calling this function writes the current canvas output viewport
 * size and location values into the variables pointed to by @p x, @p
 * y, @p w and @p h.  On success the variables have the output
 * location and size values written to them in canvas units. Any of @p
 * x, @p y, @p w or @p h that are NULL will not be written to. If @p e
 * is invalid, the results are undefined.
 *
 * Example:
 * @code
 * extern Evas *evas;
 * Evas_Coord x, y, width, height;
 *
 * evas_output_viewport_get(evas, &x, &y, &w, &h);
 * @endcode
 */
EAPI void
evas_output_viewport_get(const Evas *e, Evas_Coord *x, Evas_Coord *y, Evas_Coord *w, Evas_Coord *h)
{
   MAGIC_CHECK(e, Evas, MAGIC_EVAS);
   if (x) *x = 0;
   if (y) *y = 0;
   if (w) *w = 0;
   if (h) *h = 0;
   return;
   MAGIC_CHECK_END();

   if (x) *x = e->viewport.x;
   if (y) *y = e->viewport.y;
   if (w) *w = e->viewport.w;
   if (h) *h = e->viewport.h;
}

/**
 * Convert/scale an ouput screen co-ordinate into canvas co-ordinates
 *
 * @param e The pointer to the Evas Canvas
 * @param x The screen/output x co-ordinate
 * @return The screen co-ordinate translated to canvas unit co-ordinates
 * @ingroup Evas_Coord_Mapping_Group
 *
 * This function takes in a horizontal co-ordinate as the @p x
 * parameter and converts it into canvas units, accounting for output
 * size, viewport size and location, returning it as the function
 * return value. If @p e is invalid, the results are undefined.
 *
 * Example:
 * @code
 * extern Evas *evas;
 * extern int screen_x;
 * Evas_Coord canvas_x;
 *
 * canvas_x = evas_coord_screen_x_to_world(evas, screen_x);
 * @endcode
 */
EAPI Evas_Coord
evas_coord_screen_x_to_world(const Evas *e, int x)
{
   MAGIC_CHECK(e, Evas, MAGIC_EVAS);
   return 0;
   MAGIC_CHECK_END();
   if (e->output.w == e->viewport.w) return e->viewport.x + x;
   return (long long)e->viewport.x + (((long long)x * (long long)e->viewport.w) / (long long)e->output.w);
}

/**
 * Convert/scale an ouput screen co-ordinate into canvas co-ordinates
 *
 * @param e The pointer to the Evas Canvas
 * @param y The screen/output y co-ordinate
 * @return The screen co-ordinate translated to canvas unit co-ordinates
 * @ingroup Evas_Coord_Mapping_Group
 *
 * This function takes in a vertical co-ordinate as the @p y parameter
 * and converts it into canvas units, accounting for output size,
 * viewport size and location, returning it as the function return
 * value. If @p e is invalid, the results are undefined.
 *
 * Example:
 * @code
 * extern Evas *evas;
 * extern int screen_y;
 * Evas_Coord canvas_y;
 *
 * canvas_y = evas_coord_screen_y_to_world(evas, screen_y);
 * @endcode
 */
EAPI Evas_Coord
evas_coord_screen_y_to_world(const Evas *e, int y)
{
   MAGIC_CHECK(e, Evas, MAGIC_EVAS);
   return 0;
   MAGIC_CHECK_END();
   if (e->output.h == e->viewport.h) return e->viewport.y + y;
   return (long long)e->viewport.y + (((long long)y * (long long)e->viewport.h) / (long long)e->output.h);
}

/**
 * Convert/scale a canvas co-ordinate into output screen co-ordinates
 *
 * @param e The pointer to the Evas Canvas
 * @param x The canvas x co-ordinate
 * @return The output/screen co-ordinate translated to output co-ordinates
 * @ingroup Evas_Coord_Mapping_Group
 *
 * This function takes in a horizontal co-ordinate as the @p x
 * parameter and converts it into output units, accounting for output
 * size, viewport size and location, returning it as the function
 * return value. If @p e is invalid, the results are undefined.
 *
 * Example:
 * @code
 * extern Evas *evas;
 * int screen_x;
 * extern Evas_Coord canvas_x;
 *
 * screen_x = evas_coord_world_x_to_screen(evas, canvas_x);
 * @endcode
 */
EAPI int
evas_coord_world_x_to_screen(const Evas *e, Evas_Coord x)
{
   MAGIC_CHECK(e, Evas, MAGIC_EVAS);
   return 0;
   MAGIC_CHECK_END();
   if (e->output.w == e->viewport.w) return x - e->viewport.x;
   return (int)((((long long)x - (long long)e->viewport.x) * (long long)e->output.w) /  (long long)e->viewport.w);
}

/**
 * Convert/scale a canvas co-ordinate into output screen co-ordinates
 *
 * @param e The pointer to the Evas Canvas
 * @param y The canvas y co-ordinate
 * @return The output/screen co-ordinate translated to output co-ordinates
 * @ingroup Evas_Coord_Mapping_Group
 *
 * This function takes in a vertical co-ordinate as the @p x parameter
 * and converts it into output units, accounting for output size,
 * viewport size and location, returning it as the function return
 * value. If @p e is invalid, the results are undefined.
 *
 * Example:
 * @code
 * extern Evas *evas;
 * int screen_y;
 * extern Evas_Coord canvas_y;
 *
 * screen_y = evas_coord_world_y_to_screen(evas, canvas_y);
 * @endcode
 */
EAPI int
evas_coord_world_y_to_screen(const Evas *e, Evas_Coord y)
{
   MAGIC_CHECK(e, Evas, MAGIC_EVAS);
   return 0;
   MAGIC_CHECK_END();
   if (e->output.h == e->viewport.h) return y - e->viewport.y;
   return (int)((((long long)y - (long long)e->viewport.y) * (long long)e->output.h) /  (long long)e->viewport.h);
}

/**
 * Look up a numeric ID from a string name of a rendering engine.
 *
 * @param name The string name of an engine
 * @return A numeric (opaque) ID for the rendering engine
 * @ingroup Evas_Output_Method
 *
 * This function looks up a numeric return value for the named engine
 * in the string @p name. This is a normal C string, NUL byte
 * terminated. The name is case sensitive. If the rendering engine is
 * available, a numeric ID for that engine is returned that is not
 * 0. If the engine is not available, 0 is returned, indicating an
 * invalid engine.
 *
 * The programmer should NEVER rely on the numeric ID of an engine
 * unless it is returned by this function. Programs should NOT be
 * written accessing render method ID's directly, without first
 * obtaining it from this function.
 *
 * @attention it is mandatory that one calls evas_init() before
 *       looking up the render method.
 *
 * Example:
 * @code
 * int engine_id;
 * Evas *evas;
 *
 * evas_init();
 *
 * evas = evas_new();
 * if (!evas)
 *   {
 *     fprintf(stderr, "ERROR: Canvas creation failed. Fatal error.\n");
 *     exit(-1);
 *   }
 * engine_id = evas_render_method_lookup("software_x11");
 * if (!engine_id)
 *   {
 *     fprintf(stderr, "ERROR: Requested rendering engine is absent.\n");
 *     exit(-1);
 *   }
 * evas_output_method_set(evas, engine_id);
 * @endcode
 */
EAPI int
evas_render_method_lookup(const char *name)
{
   Evas_Module *em;

   if (!name) return RENDER_METHOD_INVALID;
   /* search on the engines list for the name */
   em = evas_module_find_type(EVAS_MODULE_TYPE_ENGINE, name);
   if (!em) return RENDER_METHOD_INVALID;

   return em->id_engine;
}

/**
 * List all the rendering engines compiled into the copy of the Evas library
 *
 * @return A linked list whose data members are C strings of engine names
 * @ingroup Evas_Output_Method
 *
 * Calling this will return a handle (pointer) to an Evas linked
 * list. Each node in the linked list will have the data pointer be a
 * (char *) pointer to the string name of the rendering engine
 * available. The strings should never be modified, neither should the
 * list be modified. This list should be cleaned up as soon as the
 * program no longer needs it using evas_render_method_list_free(). If
 * no engines are available from Evas, NULL will be returned.
 *
 * Example:
 * @code
 * Eina_List *engine_list, *l;
 * char *engine_name;
 *
 * engine_list = evas_render_method_list();
 * if (!engine_list)
 *   {
 *     fprintf(stderr, "ERROR: Evas supports no engines! Exit.\n");
 *     exit(-1);
 *   }
 * printf("Availible Evas Engines:\n");
 * EINA_LIST_FOREACH(engine_list, l, engine_name)
 *     printf("%s\n", engine_name);
 * evas_render_method_list_free(engine_list);
 * @endcode
 */
EAPI Eina_List *
evas_render_method_list(void)
{
   Eina_List *methods = NULL;

   /* FIXME: get from modules - this is currently coded-in */
#ifdef BUILD_ENGINE_SOFTWARE_GDI
   methods = eina_list_append(methods, "software_gdi");
#endif
#ifdef BUILD_ENGINE_SOFTWARE_DDRAW
   methods = eina_list_append(methods, "software_ddraw");
#endif
#ifdef BUILD_ENGINE_SOFTWARE_16_DDRAW
   methods = eina_list_append(methods, "software_16_ddraw");
#endif
#ifdef BUILD_ENGINE_DIRECT3D
   methods = eina_list_append(methods, "direct3d");
#endif
#ifdef BUILD_ENGINE_SOFTWARE_16_WINCE
   methods = eina_list_append(methods, "software_16_wince");
#endif
#ifdef BUILD_ENGINE_SOFTWARE_X11
   methods = eina_list_append(methods, "software_x11");
#endif
#ifdef BUILD_ENGINE_XRENDER_X11
   methods = eina_list_append(methods, "xrender_x11");
#endif
#ifdef BUILD_ENGINE_XRENDER_XCB
   methods = eina_list_append(methods, "xrender_xcb");
#endif
#ifdef BUILD_ENGINE_SOFTWARE_16_X11
   methods = eina_list_append(methods, "software_16_x11");
#endif
#ifdef BUILD_ENGINE_GL_X11
   methods = eina_list_append(methods, "gl_x11");
#endif
#ifdef BUILD_ENGINE_GL_GLEW
   methods = eina_list_append(methods, "gl_glew");
#endif
#ifdef BUILD_ENGINE_CAIRO_X11
   methods = eina_list_append(methods, "cairo_x11");
#endif
#ifdef BUILD_ENGINE_DIRECTFB
   methods = eina_list_append(methods, "directfb");
#endif
#ifdef BUILD_ENGINE_FB
   methods = eina_list_append(methods, "fb");
#endif
#ifdef BUILD_ENGINE_BUFFER
   methods = eina_list_append(methods, "buffer");
#endif
#ifdef BUILD_ENGINE_SOFTWARE_WIN32_GDI
   methods = eina_list_append(methods, "software_win32_gdi");
#endif
#ifdef BUILD_ENGINE_SOFTWARE_QTOPIA
   methods = eina_list_append(methods, "software_qtopia");
#endif
#ifdef BUILD_ENGINE_SOFTWARE_SDL
   methods = eina_list_append(methods, "software_sdl");
#endif

   return methods;
}

/**
 * This function should be called to free a list of engine names
 *
 * @param list The Eina_List base pointer for the engine list to be freed
 * @ingroup Evas_Output_Method
 *
 * When this function is called it will free the engine list passed in
 * as @p list. The list should only be a list of engines generated by
 * calling evas_render_method_list(). If @p list is NULL, nothing will
 * happen.
 *
 * Example:
 * @code
 * Eina_List *engine_list, *l;
 * char *engine_name;
 *
 * engine_list = evas_render_method_list();
 * if (!engine_list)
 *   {
 *     fprintf(stderr, "ERROR: Evas supports no engines! Exit.\n");
 *     exit(-1);
 *   }
 * printf("Availible Evas Engines:\n");
 * EINA_LIST_FOREACH(engine_list, l, engine_name)
 *     printf("%s\n", engine_name);
 * evas_render_method_list_free(engine_list);
 * @endcode
 */
EAPI void
evas_render_method_list_free(Eina_List *list)
{
   eina_list_free(list);
}

/**
 * This function returns the current known pointer co-ordinates
 *
 * @param e The pointer to the Evas Canvas
 * @param x The pointer to an integer to be filled in
 * @param y The pointer to an integer to be filled in
 * @ingroup Evas_Pointer_Group
 *
 * This function returns the current known screen/output co-ordinates
 * of the mouse pointer and sets the contents of the integers pointed
 * to by @p x and @p y to contain these co-ordinates. If @p e is not a
 * valid canvas the results of this function are undefined.
 *
 * Example:
 * @code
 * extern Evas *evas;
 * int mouse_x, mouse_y;
 *
 * evas_pointer_output_xy_get(evas, &mouse_x, &mouse_y);
 * printf("Mouse is at screen position %i, %i\n", mouse_x, mouse_y);
 * @endcode
 */
EAPI void
evas_pointer_output_xy_get(const Evas *e, int *x, int *y)
{
   MAGIC_CHECK(e, Evas, MAGIC_EVAS);
   if (x) *x = 0;
   if (y) *y = 0;
   return;
   MAGIC_CHECK_END();
   if (x) *x = e->pointer.x;
   if (y) *y = e->pointer.y;
}

/**
 * This function returns the current known pointer co-ordinates
 *
 * @param e The pointer to the Evas Canvas
 * @param x The pointer to a Evas_Coord to be filled in
 * @param y The pointer to a Evas_Coord to be filled in
 * @ingroup Evas_Pointer_Group
 *
 * This function returns the current known canvas unit co-ordinates of
 * the mouse pointer and sets the contents of the Evas_Coords pointed
 * to by @p x and @p y to contain these co-ordinates. If @p e is not a
 * valid canvas the results of this function are undefined.
 *
 * Example:
 * @code
 * extern Evas *evas;
 * Evas_Coord mouse_x, mouse_y;
 *
 * evas_pointer_output_xy_get(evas, &mouse_x, &mouse_y);
 * printf("Mouse is at canvas position %f, %f\n", mouse_x, mouse_y);
 * @endcode
 */
EAPI void
evas_pointer_canvas_xy_get(const Evas *e, Evas_Coord *x, Evas_Coord *y)
{
   MAGIC_CHECK(e, Evas, MAGIC_EVAS);
   if (x) *x = 0;
   if (y) *y = 0;
   return;
   MAGIC_CHECK_END();
   if (x) *x = e->pointer.x;
   if (y) *y = e->pointer.y;
}

/**
 * Returns a bitmask with the mouse buttons currently pressed, set to 1
 *
 * @param e The pointer to the Evas Canvas
 * @return A bitmask of the currently depressed buttons on the cavas
 * @ingroup Evas_Pointer_Group
 *
 * Calling this function will return a 32-bit integer with the
 * appropriate bits set to 1 that correspond to a mouse button being
 * depressed. This limits Evas to a mouse devices with a maximum of 32
 * buttons, but that is generally in excess of any host system's
 * pointing device abilities.
 *
 * A canvas by default begins with no mouse buttons being pressed and
 * only calls to evas_event_feed_mouse_down(),
 * evas_event_feed_mouse_down_data(), evas_event_feed_mouse_up() and
 * evas_event_feed_mouse_up_data() will alter that.
 *
 * The least significant bit corresponds to the first mouse button
 * (button 1) and the most significant bit corresponds to the last
 * mouse button (button 32).
 *
 * If @p e is not a valid canvas, the return value is undefined.
 *
 * Example:
 * @code
 * extern Evas *evas;
 * int button_mask, i;
 *
 * button_mask = evas_pointer_button_down_mask_get(evas);
 * printf("Buttons currently pressed:\n");
 * for (i = 0; i < 32; i++)
 *   {
 *     if ((button_mask & (1 << i)) != 0) printf("Button %i\n", i + 1);
 *   }
 * @endcode
 */
EAPI int
evas_pointer_button_down_mask_get(const Evas *e)
{
   MAGIC_CHECK(e, Evas, MAGIC_EVAS);
   return 0;
   MAGIC_CHECK_END();
   return (int)e->pointer.button;
}

/**
 * Returns whether the mouse pointer is logically inside the canvas
 *
 * @param e The pointer to the Evas Canvas
 * @return An integer that is 1 if the mouse is inside the canvas, 0 otherwise
 * @ingroup Evas_Pointer_Group
 *
 * When this function is called it will return a value of either 0 or
 * 1, depending on if evas_event_feed_mouse_in(),
 * evas_event_feed_mouse_in_data(), or evas_event_feed_mouse_out(),
 * evas_event_feed_mouse_out_data() have been called to feed in a
 * mouse enter event into the canvas.
 *
 * A return value of 1 indicates the mouse is logically inside the
 * canvas, and 0 implies it is logically outside the canvas.
 *
 * A canvas begins with the mouse being assumed outside (0).
 *
 * If @p e is not a valid canvas, the return value is undefined.
 *
 * Example:
 * @code
 * extern Evas *evas;
 *
 * if (evas_pointer_inside_get(evas)) printf("Mouse is in!\n");
 * else printf("Mouse is out!\n");
 * @endcode
 */
EAPI Eina_Bool
evas_pointer_inside_get(const Evas *e)
{
   MAGIC_CHECK(e, Evas, MAGIC_EVAS);
   return 0;
   MAGIC_CHECK_END();
   return (int)e->pointer.inside;
}

/**
 * Attaches a specific pointer to the evas for fetching later
 *
 * @param e The canvas to attach the pointer to
 * @param data The pointer to attach
 * @ingroup Evas_Canvas
 */
EAPI void
evas_data_attach_set(Evas *e, void *data)
{
   MAGIC_CHECK(e, Evas, MAGIC_EVAS);
   return;
   MAGIC_CHECK_END();
   e->attach_data = data;
}

/**
 * Returns the pointer attached by evas_data_attach_set()
 *
 * @param e The canvas to attach the pointer to
 * @return The pointer attached
 * @ingroup Evas_Canvas
 */
EAPI void *
evas_data_attach_get(const Evas *e)
{
   MAGIC_CHECK(e, Evas, MAGIC_EVAS);
   return NULL;
   MAGIC_CHECK_END();
   return e->attach_data;
}

/**
 * Inform to the evas that it got the focus.
 *
 * @param e The evas to change information.
 * @ingroup Evas_Canvas
 */
EAPI void
evas_focus_in(Evas *e)
{
   MAGIC_CHECK(e, Evas, MAGIC_EVAS);
   return;
   MAGIC_CHECK_END();
   if (e->focus) return;
   e->focus = 1;
   evas_event_callback_call(e, EVAS_CALLBACK_CANVAS_FOCUS_IN, NULL);
}

/**
 * Inform to the evas that it lost the focus.
 *
 * @param e The evas to change information.
 * @ingroup Evas_Canvas
 */
EAPI void
evas_focus_out(Evas *e)
{
   MAGIC_CHECK(e, Evas, MAGIC_EVAS);
   return;
   MAGIC_CHECK_END();
   if (!e->focus) return;
   e->focus = 0;
   evas_event_callback_call(e, EVAS_CALLBACK_CANVAS_FOCUS_OUT, NULL);
}

/**
 * Get the focus state known by the given evas
 *
 * @param e The evas to query information.
 * @ingroup Evas_Canvas
 */
EAPI Eina_Bool
evas_focus_state_get(const Evas *e)
{
   MAGIC_CHECK(e, Evas, MAGIC_EVAS);
   return 0;
   MAGIC_CHECK_END();
   return e->focus;
}

/**
 * Push the nochange flag up 1
 *
 * This tells evas, that while the nochange flag is greater than 0, do not
 * mark objects as "changed" when making changes.
 *
 * @param e The evas to change information.
 * @ingroup Evas_Canvas
 */
EAPI void
evas_nochange_push(Evas *e)
{
   e->nochange++;
}

/**
 * Pop the nochange flag down 1
 *
 * This tells evas, that while the nochange flag is greater than 0, do not
 * mark objects as "changed" when making changes.
 *
 * @param e The evas to change information.
 * @ingroup Evas_Canvas
 */
EAPI void
evas_nochange_pop(Evas *e)
{
   e->nochange--;
}

void
_evas_walk(Evas *e)
{
   e->walking_list++;
}

void
_evas_unwalk(Evas *e)
{
   e->walking_list--;
   if ((e->walking_list == 0) && (e->delete_me)) evas_free(e);
}

/**
 * Converts the given error code into a string describing it in english.
 * @param error the error code.
 * @return Always return a valid string. If given @p error is not
 *         supported "Unknown error" is returned.
 * @ingroup Evas_Utils
 */
EAPI const char *
evas_load_error_str(Evas_Load_Error error)
{
   switch (error)
     {
      case EVAS_LOAD_ERROR_NONE:
	 return "No error on load";
      case EVAS_LOAD_ERROR_GENERIC:
	 return "A non-specific error occurred";
      case EVAS_LOAD_ERROR_DOES_NOT_EXIST:
	 return "File (or file path) does not exist";
      case EVAS_LOAD_ERROR_PERMISSION_DENIED:
	 return "Permission deinied to an existing file (or path)";
      case EVAS_LOAD_ERROR_RESOURCE_ALLOCATION_FAILED:
	 return "Allocation of resources failure prevented load";
      case EVAS_LOAD_ERROR_CORRUPT_FILE:
	 return "File corrupt (but was detected as a known format)";
      case EVAS_LOAD_ERROR_UNKNOWN_FORMAT:
	 return "File is not a known format";
      default:
	 return "Unknown error";
     }
}

/**
 * Convert a given color from HSV to RGB format.
 *
 * @param h The Hue component of the color.
 * @param s The Saturation component of the color.
 * @param v The Value component of the color.
 * @param r The Red component of the color.
 * @param g The Green component of the color.
 * @param b The Blue component of the color.
 *
 * This function converts a given color in HSV color format to RGB
 * color format.
 *
 * @ingroup Evas_Utils
 **/
EAPI void
evas_color_hsv_to_rgb(float h, float s, float v, int *r, int *g, int *b)
{
   evas_common_convert_color_hsv_to_rgb(h, s, v, r, g, b);
}

/**
 * Convert a given color from RGB to HSV format.
 *
 * @param r The Red component of the color.
 * @param g The Green component of the color.
 * @param b The Blue component of the color.
 * @param h The Hue component of the color.
 * @param s The Saturation component of the color.
 * @param v The Value component of the color.
 *
 * This function converts a given color in RGB color format to HSV
 * color format.
 *
 * @ingroup Evas_Utils
 **/
EAPI void
evas_color_rgb_to_hsv(int r, int g, int b, float *h, float *s, float *v)
{
   evas_common_convert_color_rgb_to_hsv(r, g, b, h, s, v);
}

/**
 * Pre-multiplies a rgb triplet by an alpha factor.
 *
 * @param a The alpha factor.
 * @param r The Red component of the color.
 * @param g The Green component of the color.
 * @param b The Blue component of the color.
 *
 * This function pre-multiplies a given rbg triplet by an alpha
 * factor. Alpha factor is used to define transparency.
 *
 * @ingroup Evas_Utils
 **/
EAPI void
evas_color_argb_premul(int a, int *r, int *g, int *b)
{
   evas_common_convert_color_argb_premul(a, r, g, b);
}

/**
 * Undo pre-multiplication of a rgb triplet by an alpha factor.
 *
 * @param a The alpha factor.
 * @param r The Red component of the color.
 * @param g The Green component of the color.
 * @param b The Blue component of the color.
 *
 * This function undoes pre-multiplication a given rbg triplet by an
 * alpha factor. Alpha factor is used to define transparency.
 *
 * @see evas_color_argb_premul().
 *
 * @ingroup Evas_Utils
 **/
EAPI void
evas_color_argb_unpremul(int a, int *r, int *g, int *b)
{
   evas_common_convert_color_argb_unpremul(a, r, g, b);
}

/**
 * Pre-multiplies data by an alpha factor.
 *
 * @param data The data value.
 * @param len  The length value.
 *
 * This function pre-multiplies a given data by an alpha
 * factor. Alpha factor is used to define transparency.
 *
 * @ingroup Evas_Utils
 **/
EAPI void
evas_data_argb_premul(unsigned int *data, unsigned int len)
{
   if (!data || (len < 1)) return;
   evas_common_convert_argb_premul(data, len);
}

/**
 * Undo pre-multiplication data by an alpha factor.
 *
 * @param data The data value.
 * @param len  The length value.
 *
 * This function undoes pre-multiplication of a given data by an alpha
 * factor. Alpha factor is used to define transparency.
 *
 * @ingroup Evas_Utils
 **/
EAPI void
evas_data_argb_unpremul(unsigned int *data, unsigned int len)
{
   if (!data || (len < 1)) return;
   evas_common_convert_argb_unpremul(data, len);
}

redpajama_set_name: RedPajamaGithub


text:
package com.b2international.snowowl.semanticengine.utils;

import com.b2international.snowowl.dsl.scg.AttributeValue;
import com.b2international.snowowl.dsl.scg.Concept;

public class AttributeValueComparator extends ObjectComparator<AttributeValue> {

	@Override
	public boolean equal(AttributeValue expected, AttributeValue actual) {
		if (expected == null || actual == null)
			throw new NullPointerException("Null value not supported in LValueComparator.");
		if (expected instanceof Concept && actual instanceof Concept) {
			Concept expectedConcept = (Concept) expected;
			Concept actualConcept = (Concept) expected;
			String expectedConceptId = expectedConcept.getId();
			String actualConceptId = actualConcept.getId();
			return expectedConceptId.equals(actualConceptId);
		} else {
			throw new IllegalArgumentException("Invalid arguments: " + expected + ", " + actual);
		}
	}

}


text:
from afs.service.BaseService import BaseService
from afs.service.BosServiceError import BosServiceError
from afs.model.BosServer import BosServer
from afs.model.BNode import BNode
import afs

class BosService (BaseService):
    """
    Provides Service about a Bosserver
    """

    def __init__(self, _cfg = None):
        BaseService.__init__(self, _cfg, LLAList=["bos" ])
        return

    def get_object(self, obj_or_param) :
        if isinstance(obj_or_param, BosServer) :
             this_bos_server = obj_or_param
        else :
             DNSInfo=afs.LOOKUP_UTIL[self._CFG.cell].get_dns_info(obj_or_param)
             this_bos_server = BosServer()
             this_bos_server.servernames = DNSInfo["names"]

        return this_bos_server

    def get_bos_server(self, obj_or_param, cached=True) :
        """
        Returning BosServer Object.
        As input parameter, give a BosServer Object or name_or_ip.
        This also get up any accompanying bnode objects
        """
        self.Logger.debug("Entering get_bos_server")

        this_bos_server = self.get_object(obj_or_param)

        if self._CFG.DB_CACHE :
            if cached :
                cached_BosServer = self.DBManager.get_from_cache_by_list_element(BosServer, BosServer.servernames_js, this_bos_server.servernames[0], True)
                if cached_BosServer != None :
                    cached_BosServer.bnodes = self.DBManager.get_from_cache(BNode, must_be_unique=False, bos_db_id=cached_BosServer.db_id)
                    self.Logger.debug("get_bosserver: returning cached object")
                    return cached_BosServer

        # get from live_system
        this_bos_server = self._bosLLA.get_bos_server(this_bos_server.servernames[0], _cfg=self._CFG)

        # update cache if present
        if self._CFG.DB_CACHE :
            cached_BosServer = self.DBManager.set_into_cache_by_list_element(BosServer, this_bos_server, BosServer.servernames_js, this_bos_server.servernames[0])
            # get Bnodes as well
            for bn in this_bos_server.bnodes :
                bn.bos_db_id = cached_BosServer.db_id
                self.DBManager.set_into_cache(BNode, bn, bos_db_id=bn.bos_db_id, instance_name=bn.instance_name)
        return this_bos_server

    #
    # modifying methods
    #

    def set_restart_times(self, bosserver) :
        self._bosLLA.set_restart_time(bosserver.servernames[0], "general", bosserver.restart_times["general"])
        self._bosLLA.set_restart_time(bosserver.servernames[0], "newbinary", bosserver.restart_times["newbinary"])
        return

    def set_superusers(self, bosserver, remove=False) :
        """
        add / remove users to match the superusers in the object
        """
        current_superusers = self._bosLLA.get_superuserlist(bosserver.servernames[0])
        self.Logger.debug("set_superusers: current_superuser_list=%s" % current_superusers)
        to_be_removed = []
        for user in current_superusers :
            if not user in bosserver.superusers :
                to_be_removed.append(user)
        if len(to_be_removed) > 0  and remove :
            self.Logger.warn("set_superusers: to_be_removed=%s" % to_be_removed)
            bosserver = self._bosLLA.remove_superuser(bosserver.servernames[0], to_be_removed)

        to_be_added = []
        for user in bosserver.superusers :
            if not user in current_superusers :
                to_be_added.append(user)
        if len(to_be_added) > 0:
            self.Logger.warn("set_superusers: to_be_added=%s" % to_be_added)
            bosserver = self._bosLLA.add_superuser(bosserver.servernames[0], to_be_added)
        return bosserver

    #
    # interrupting methods
    #

    def startup(self, bosserver) :
        self._bosLLA.startup(bosserver.servernames[0])
        return self.get_bos_server(bosserver, cached=False)

    def shutdown(self, bosserver) :
        self._bosLLA.shutdown(bosserver.servernames[0])
        return self.get_bos_server(bosserver, cached=False)


text:
package bookshop2.supplier.incoming.shipBooks;

import static javax.ejb.ConcurrencyManagementType.BEAN;

import java.io.Serializable;

import javax.ejb.ConcurrencyManagement;
import javax.ejb.Local;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.ejb.Stateful;
import javax.inject.Inject;

import org.aries.message.Message;
import org.aries.tx.service.ejb.AbstractEJBListener;
import org.aries.tx.service.ejb.EJBListener;

@Startup
@Stateful
@Local(EJBListener.class)
@ConcurrencyManagement(BEAN)
public class ShipmentScheduledListenerForEJB extends AbstractEJBListener {

	@Inject
	private ShipmentScheduledInterceptor shipmentScheduledInterceptor;

	@Override
	public String getModuleId() {
		return "bookshop2-supplier-service";
	}

	@Override
	public String getServiceId() {
		return ShipmentScheduled.ID;
	}

	@Override
	public Object getDelegate() {
		return shipmentScheduledInterceptor;
	}

	@Override
	@SuppressWarnings("unchecked")
	public Serializable invoke(Serializable payload, String correlationId, long timeout) {
		if (!isInitialized())
			return null;

		try {
			if (payload instanceof String)
				return processAsText((String) payload);
			if (payload instanceof Message)
				return processAsBinary((Message) payload);
			throw new Exception("Unexpected payload type: "+payload.getClass());

		} catch (Throwable e) {
			throw new RuntimeException(e.getMessage());
		}
	}

}


text:
package sampler

import (
	"math"
)

// uniformResample allows for sampling over a uniform distribution without
// replacement.
//
// Sampling is performed by sampling with replacement and resampling if a
// duplicate is sampled.
//
// Initialization takes O(1) time.
//
// Sampling is performed in O(count) time and O(count) space.
type uniformResample struct {
	rng       rng
	seededRNG rng
	length    uint64
	drawn     map[uint64]struct{}
}

func (s *uniformResample) Initialize(length uint64) error {
	if length > math.MaxInt64 {
		return errOutOfRange
	}
	s.rng = globalRNG
	s.seededRNG = newRNG()
	s.length = length
	s.drawn = make(map[uint64]struct{})
	return nil
}

func (s *uniformResample) Sample(count int) ([]uint64, error) {
	s.Reset()

	results := make([]uint64, count)
	for i := 0; i < count; i++ {
		ret, err := s.Next()
		if err != nil {
			return nil, err
		}
		results[i] = ret
	}
	return results, nil
}

func (s *uniformResample) Seed(seed int64) {
	s.rng = s.seededRNG
	s.rng.Seed(seed)
}

func (s *uniformResample) ClearSeed() {
	s.rng = globalRNG
}

func (s *uniformResample) Reset() {
	for k := range s.drawn {
		delete(s.drawn, k)
	}
}

func (s *uniformResample) Next() (uint64, error) {
	i := uint64(len(s.drawn))
	if i >= s.length {
		return 0, errOutOfRange
	}

	for {
		draw := uint64(s.rng.Int63n(int64(s.length)))
		if _, ok := s.drawn[draw]; ok {
			continue
		}
		s.drawn[draw] = struct{}{}
		return draw, nil
	}
}


text:
StandaloneDashboard(function (db) {
    var form = new FormComponent ();
    form.setDimensions (8, 6);
    form.setCaption ('Form items in stock');
    form.addSelectField ('category', 'Select Catagory', ['No Selection', 'Beverages', 'Condiments', 'Confections', 'Dairy Products', 'Grains/Cereal', 'Meat/Poultry', 'Produce', 'Seafood']);
    form.addTextField ('contains', 'Product Name Contains');
    form.addNumericRangeField('stock', 'Units In Stock');
    form.addCheckboxField('discontinued', 'Exclude Discontinued Items', false);
    db.addComponent(form);
});


text:
extern crate rand;

use std::io;
use std::cmp::Ordering;
use rand::Rng;

struct Guess {
    value: u32,
}

impl Guess {
    pub fn new(value: u32) -> Guess {
        if value < 1 {
            panic!("Guess value must be greater than or equal to 1, got {}.",
                   value);
        } else if value > 100 {
            panic!("Guess value must be less than or equal to 100, got {}.",
                   value);
        }

        Guess { value }
    }

    pub fn value(&self) -> u32 {
        self.value
    }
}

fn main() {
    println!("Guess the number!");

    let secret_number = rand::thread_rng().gen_range(1, 101);

    loop {
        println!("Please input your guess.");

        let mut guess = String::new();

        io::stdin()
            .read_line(&mut guess)
            .expect("Failed to read line");

        let guess = match guess.trim().parse() {
            Ok(num) => Guess::new(num),
            Err(_) => continue,
        };

        println!("You guessed: {}", guess.value());

        match guess.value().cmp(&secret_number) {
            Ordering::Less => println!("Too small!"),
            Ordering::Greater => println!("Too big!"),
            Ordering::Equal => {
                println!("You win!");
                break;
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    #[should_panic(expected = "Guess value must be less than or equal to 100")]
    fn greater_than_100() {
        Guess::new(200);
    }
}


text:
/**
 *
 */
package com.skht777.chatwork.impl;

import java.time.LocalDate;
import java.util.List;

import com.skht777.chatwork.RequestTasks;
import com.skht777.chatwork.api.Task;
import com.skht777.chatwork.parameter.Status;

/**
 * @author skht777
 *
 */
class RequestTasksImpl extends ChatworkRequest implements RequestTasks {

	/**
	 *
	 * @param token
	 * @param roomId
	 */
	protected RequestTasksImpl(APIToken token, int roomId) {
		super(token, Endpoint.TASKS, roomId);
	}

	/* (非 Javadoc)
	 * @see com.skht777.chatwork.RequestTasks#getTasks(int, int, com.skht777.chatwork.parameter.Status)
	 */
	@Override
	public List<Task> getTasks(int accountId, int assignedByAccountId, Status status) {
		return ResponseImpl.getTasks(get(ParameterImpl.getTasks(accountId, assignedByAccountId, status)));
	}

	/* (非 Javadoc)
	 * @see com.skht777.chatwork.RequestTasks#createTask(java.lang.String, int[], java.time.LocalDate)
	 */
	@Override
	public List<Integer> createTask(String body, int[] toIds, LocalDate limit) {
		return ResponseImpl.createTask(post(ParameterImpl.createTask(body, toIds, limit)));
	}

	/* (非 Javadoc)
	 * @see com.skht777.chatwork.RequestTasks#getTask(int)
	 */
	@Override
	public Task getTask(int taskId) {
		return ResponseImpl.getTask(get(taskId));
	}

}


text:
package com.google.walkaround.wave.server.attachment;

import com.google.appengine.api.blobstore.BlobKey;
import com.google.common.base.Preconditions;
import com.google.walkaround.util.shared.Assert;

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

import java.io.Serializable;

/**
 * Metadata associated with an attachment. Should not be changed for a given
 * attachment, so that it can be cached indefinitely.
 *
 * @author danilatos@google.com (Daniel Danilatos)
 */
// TODO(danilatos) Merge this with WalkaroundAttachment, once we have a json interface.
// Same goes for "ImageMetadata"
// TODO(danilatos) Consider using a proto-based implementation?
public class AttachmentMetadata implements Serializable {
  private static final long serialVersionUID = 562560590763783822L;

  public interface ImageMetadata {
    public int getWidth();
    public int getHeight();
  }

  private final AttachmentId id;
  private final BlobKey blobKey;
  // String for Serializable
  private final String rawMetadata;
  // Parsed version of rawMetadata.
  private transient JSONObject maybeMetadata;

  public AttachmentMetadata(AttachmentId id, BlobKey blobKey, JSONObject metadata) {
    this.id = Preconditions.checkNotNull(id, "null id");
    this.blobKey = Preconditions.checkNotNull(blobKey, "null blobKey");
    this.maybeMetadata = Preconditions.checkNotNull(metadata, "null metadata");
    this.rawMetadata = metadata.toString();
  }

  @Override
  public String toString() {
    return "AttachmentMetadata(" + id + ", " + blobKey + ", " + rawMetadata + ")";
  }

  public AttachmentId getId() {
    return id;
  }

  public BlobKey getBlobKey() {
    return blobKey;
  }

  private JSONObject getMetadata() {
    if (maybeMetadata == null) {
      Assert.check(rawMetadata != null, "rawMetadata is null");
      try {
        maybeMetadata = new JSONObject(rawMetadata);
      } catch (JSONException e) {
        throw new RuntimeException("Bad JSON: " + rawMetadata, e);
      }
    }
    return maybeMetadata;
  }

  public String getMetadataJsonString() {
    return rawMetadata;
  }

  public ImageMetadata getImage() {
    return createImageMetadata("image");
  }

  public ImageMetadata getThumbnail() {
    return createImageMetadata("thumbnail");
  }

  private ImageMetadata createImageMetadata(String key) {
    final JSONObject imgData;
    try {
      imgData = getMetadata().has(key) ? getMetadata().getJSONObject(key) : null;
    } catch (JSONException e) {
      throw new Error(e);
    }

    if (imgData == null) {
      return null;
    }

    return new ImageMetadata() {
      @Override public int getWidth() {
        try {
          return imgData.getInt("width");
        } catch (JSONException e) {
          throw new RuntimeException(e);
        }
      }
      @Override public int getHeight() {
        try {
          return imgData.getInt("height");
        } catch (JSONException e) {
          throw new RuntimeException(e);
        }
      }
    };
  }

}


text:
import * as React from 'react';
import { observer } from 'mobx-react-lite';

import { SettingsSection } from '../../store';
import { Appearance } from '../Appearance';
import { AddressBar, ManageSearchEngines } from '../AddressBar';
import { Privacy } from '../Privacy';
import store from '../../store';
import { NavigationDrawer } from '~/renderer/components/NavigationDrawer';
import { Button } from '~/renderer/components/Button';
import { ThemeProvider } from 'styled-components';
import { Autofill } from '../Autofill';
import { OnStartup } from '../Startup';
import { Content, LeftContent, Container } from '~/renderer/components/Pages';
import { GlobalNavigationDrawer } from '~/renderer/components/GlobalNavigationDrawer';
import { Downloads } from '../Downloads';
import {
  ICON_PALETTE,
  ICON_AUTOFILL,
  ICON_POWER,
  ICON_SEARCH,
  ICON_DOWNLOAD,
  ICON_SHIELD,
  ICON_TRASH,
  ICON_EDIT,
} from '~/renderer/constants';
import {
  ContextMenuItem,
  ContextMenu,
} from '~/renderer/components/ContextMenu';
import {
  Dialog,
  DialogTitle,
  DialogButtons,
} from '~/renderer/views/bookmarks/components/App/style';
import { Textfield } from '~/renderer/components/Textfield';
import { WebUIStyle } from '~/renderer/mixins/default-styles';

export const NormalButton = ({
  children,
  onClick,
}: {
  children?: any;
  onClick?: any;
}) => {
  return (
    <Button
      background={
        store.theme['dialog.lightForeground']
          ? 'rgba(255, 255, 255, 0.08)'
          : 'rgba(0, 0, 0, 0.08)'
      }
      onClick={onClick}
      foreground={store.theme['dialog.lightForeground'] ? 'white' : 'black'}
    >
      {children}
    </Button>
  );
};

const MenuItem = observer(
  ({
    section,
    subSections,
    children,
    icon,
  }: {
    section: SettingsSection;
    subSections?: SettingsSection[];
    children: any;
    icon?: string;
  }) => (
    <NavigationDrawer.Item
      onClick={() => (store.selectedSection = section)}
      selected={
        store.selectedSection === section ||
        (subSections && subSections.includes(store.selectedSection))
      }
      icon={icon}
    >
      {children}
    </NavigationDrawer.Item>
  ),
);

const onBlur = () => {
  store.menuVisible = false;
};

const onMakeDefaultClick = () => {
  store.settings.searchEngine = store.settings.searchEngines.findIndex(
    (x) => x.keyword === store.editedSearchEngine.keyword,
  );
  store.menuVisible = false;
};

const onRemoveClick = () => {
  store.settings.searchEngines = store.settings.searchEngines.filter(
    (x) => x.keyword !== store.editedSearchEngine.keyword,
  );
  store.save();
  store.menuVisible = false;
};

const onEditClick = () => {
  store.menuVisible = false;
  store.dialogVisible = true;
  store.dialogContent = 'edit-search-engine';
  store.searchEngineInputRef.current.value = store.editedSearchEngine.name;
  store.searchEngineKeywordInputRef.current.value =
    store.editedSearchEngine.keyword;
  store.searchEngineUrlInputRef.current.value = store.editedSearchEngine.url;
};

const onSaveClick = () => {
  const name = store.searchEngineInputRef.current.value.trim();
  const keyword = store.searchEngineKeywordInputRef.current.value.trim();
  const url = store.searchEngineUrlInputRef.current.value.trim();

  const item = store.settings.searchEngines.find((x) => x.keyword === keyword);

  if (keyword !== '' && name !== '' && url !== '') {
    if (store.dialogContent === 'edit-search-engine') {
      item.name = name;
      item.keyword = keyword;
      item.url = url;
      store.dialogVisible = false;
    } else if (store.dialogContent === 'add-search-engine') {
      if (!item) {
        store.settings.searchEngines.push({
          name,
          keyword,
          url,
        });
        store.dialogVisible = false;
      }
    }
    store.save();
  }
};

export default observer(() => {
  const { selectedSection } = store;

  let dialogTitle = '';

  if (store.dialogContent === 'edit-search-engine') {
    dialogTitle = 'Edit search engine';
  } else if (store.dialogContent === 'add-search-engine') {
    dialogTitle = 'Add search engine';
  }

  return (
    <ThemeProvider
      theme={{ ...store.theme, dark: store.theme['pages.lightForeground'] }}
    >
      <Container
        onMouseDown={(e) => (store.dialogVisible = false)}
        darken={store.dialogVisible}
      >
        <WebUIStyle />
        <GlobalNavigationDrawer></GlobalNavigationDrawer>
        <ContextMenu
          tabIndex={1}
          ref={store.menuRef}
          onBlur={onBlur}
          style={{
            top: store.menuInfo.top,
            left: store.menuInfo.left,
          }}
          visible={store.menuVisible}
        >
          {store.editedSearchEngine &&
            store.editedSearchEngine.keyword !== store.searchEngine.keyword && (
              <>
                <ContextMenuItem onClick={onMakeDefaultClick} icon=" ">
                  Make default
                </ContextMenuItem>
                <ContextMenuItem onClick={onRemoveClick} icon={ICON_TRASH}>
                  Remove
                </ContextMenuItem>
              </>
            )}
          {store.editedSearchEngine && (
            <ContextMenuItem onClick={onEditClick} icon={ICON_EDIT}>
              Edit
            </ContextMenuItem>
          )}
        </ContextMenu>
        <Dialog
          onMouseDown={(e) => e.stopPropagation()}
          visible={store.dialogVisible}
          ref={store.dialogRef}
          style={{ width: 350 }}
        >
          <DialogTitle>{dialogTitle}</DialogTitle>
          <Textfield
            style={{ width: '100%' }}
            dark={store.theme['dialog.lightForeground']}
            ref={store.searchEngineInputRef}
            label="Search engine"
          ></Textfield>

          <Textfield
            style={{
              width: '100%',
              marginTop: 16,
            }}
            dark={store.theme['dialog.lightForeground']}
            ref={store.searchEngineKeywordInputRef}
            label="Keyword"
          ></Textfield>

          <Textfield
            style={{
              width: '100%',
              marginTop: 16,
            }}
            dark={store.theme['dialog.lightForeground']}
            ref={store.searchEngineUrlInputRef}
            label="URL with %s in place of query"
          ></Textfield>

          <DialogButtons>
            <NormalButton onClick={() => (store.dialogVisible = false)}>
              Cancel
            </NormalButton>
            <Button onClick={onSaveClick} style={{ marginLeft: 8 }}>
              Save
            </Button>
          </DialogButtons>

        </Dialog>
        <NavigationDrawer title="Settings" search>
          <MenuItem icon={ICON_PALETTE} section="appearance">
            Appearance
          </MenuItem>
          {process.env.ENABLE_AUTOFILL && (
            <MenuItem icon={ICON_AUTOFILL} section="autofill">
              Autofill
            </MenuItem>
          )}
          <MenuItem icon={ICON_POWER} section="startup">
            On startup
          </MenuItem>
          <MenuItem
            icon={ICON_SEARCH}
            section="address-bar"
            subSections={['search-engines']}
          >
            Address bar
          </MenuItem>
          <MenuItem icon={ICON_DOWNLOAD} section="downloads">
            Downloads
          </MenuItem>
          <MenuItem icon={ICON_SHIELD} section="privacy">
            Privacy
          </MenuItem>
          {/* <MenuItem section="permissions">Site permissions</MenuItem> */}

          {/* <MenuItem section="language">Languages</MenuItem> */}
          {/* <MenuItem section="shortcuts">Keyboard shortcuts</MenuItem> */}
          {/* <MenuItem section="system">System</MenuItem> */}
        </NavigationDrawer>
        <Content>
          <LeftContent style={{ maxWidth: 800, marginTop: 56 }}>
            {selectedSection === 'appearance' && <Appearance />}
            {selectedSection === 'autofill' && process.env.ENABLE_AUTOFILL && (
              <Autofill />
            )}
            {selectedSection === 'address-bar' && <AddressBar />}
            {selectedSection === 'search-engines' && <ManageSearchEngines />}
            {selectedSection === 'startup' && <OnStartup />}
            {selectedSection === 'privacy' && <Privacy />}
            {selectedSection === 'downloads' && <Downloads />}
          </LeftContent>
        </Content>
      </Container>
    </ThemeProvider>
  );
});


text:
package es.urjc.jer;

import java.util.ArrayList;
import java.util.Collection;
//import java.util.concurrent.atomic.AtomicLong;
import java.util.Comparator;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/perfil")
public class PerfilController {

	// Array de perfiles y int de siguiente ID
	ArrayList<Perfil> perfiles = new ArrayList<Perfil>();
	int nextId = 0;

	// SOLO DEBUG: el servidor valida el perfil enviado por el cliente, no hace falta que se puedan devolver todos los perfiles juntos
	// (Ademas se enviarian junto con las claves)
	// Cuando todo funcione mejor comentar esta funcion
	@GetMapping
	public Collection<Perfil> perfiles() {
		return perfiles;
	}

	// SOLO DEBUG
	// Obtener un perfil específico (por su id)
	@GetMapping("/{id}")
	public ResponseEntity<Perfil> getPerfil(@PathVariable int id) {

		Perfil savedPerfil = perfiles.get(id);

		// Si el Perfil con el id especificado existe, lo devuelve. Si no, manda un codigo de respuesta NOT FOUND
		if (savedPerfil != null) {
			return new ResponseEntity<>(savedPerfil, HttpStatus.OK);
		} else {
			return new ResponseEntity<>(HttpStatus.NOT_FOUND);
		}
	}

	// Crear perfil (registro)
	@PostMapping
	@ResponseStatus(HttpStatus.CREATED)
	public Perfil nuevoPerfil(@RequestBody Perfil perfil) {
		perfil.setId(nextId);
		perfiles.add(perfil);
		nextId++;
		return perfil;
	}

	// Validar perfil
	@PostMapping("/validate")
	@ResponseStatus(HttpStatus.OK)
	public int validarPerfil(@RequestBody Perfil perfil) {

		for (int i = 0; i < perfiles.size(); i++) {
			if(perfiles.get(i).equals(perfil)) {
				int id = perfiles.get(i).getId();
				return id;
			}
		}

		return -1;
	}

	// Obtener puntuaciones de un perfil específico (por su id)
	@GetMapping("/puntuaciones/{id}")
	public ResponseEntity<ArrayList<Integer>> getPuntuaciones(@PathVariable int id) {

		Perfil savedPerfil = perfiles.get(id);

		// Si el Perfil con el id especificado existe, lo devuelve. Si no, manda un codigo de respuesta NOT FOUND
		if (savedPerfil != null) {
			return new ResponseEntity<>(savedPerfil.getPuntuaciones(), HttpStatus.OK);
		} else {
			return new ResponseEntity<>(HttpStatus.NOT_FOUND);
		}
	}

	// Obtener puntuacion max de un perfil específico (por su id)
	@GetMapping("/puntuacionMax/{id}")
	public ResponseEntity<Integer> getPuntuacionMax(@PathVariable int id) {

		Perfil savedPerfil = perfiles.get(id);

		// Si el Perfil con el id especificado existe, lo devuelve. Si no, manda un codigo de respuesta NOT FOUND
		if (savedPerfil != null) {
			return new ResponseEntity<>(savedPerfil.getPuntuacionMax(), HttpStatus.OK);
		} else {
			return new ResponseEntity<>(HttpStatus.NOT_FOUND);
		}
	}

	// Dar una puntuación nueva a un jugador segun su ID
	@PostMapping("/puntuacion/{id}/{puntuacion}")
	public ResponseEntity<HttpStatus> updatePuntuaciones(@PathVariable int id, @PathVariable int puntuacion) {

		Perfil savedPerfil = perfiles.get(id);

		// Si el Perfil con el id especificado existe, lo devuelve. Si no, manda un codigo de respuesta NOT FOUND
		if (savedPerfil != null) {
			savedPerfil.updatePuntuaciones(puntuacion);
			return new ResponseEntity<>(HttpStatus.OK);
		} else {
			return new ResponseEntity<>(HttpStatus.NOT_FOUND);
		}
	}

	// Borra un perfil específico (por su id)
	@DeleteMapping("/{id}")
	public ResponseEntity<Perfil> borraPerfil(@PathVariable int id) {

		Perfil savedPerfil = perfiles.get(id);

		// Si el Perfil con el id especificado existe, lo borra de la lista y lo devuelve al cliente
		if (savedPerfil != null) {
			perfiles.remove(savedPerfil.getId());
			return new ResponseEntity<>(savedPerfil, HttpStatus.OK);
		} else {
			return new ResponseEntity<>(HttpStatus.NOT_FOUND);
		}
	}

	@GetMapping("/leaderboard")
	public ArrayList<Perfil> tablapuntuacion() {
		//generabasura();
		perfiles.sort(Comparator.comparing(Perfil::getPuntuacionMax).reversed());
		return perfiles;
	}

	//funcion de testeo para probar leaderboard
	public void generabasura() {
		Perfil p1 = new Perfil();
		Perfil p2 = new Perfil();
		Perfil p3 = new Perfil();

		p1.setId(0);
		p1.setNombre("nombre1");
		p1.setClave("clave1");
		p1.setPuntuacionMax(10000);

		p2.setId(1);
		p2.setNombre("nombre2");
		p2.setClave("clave2");
		p2.setPuntuacionMax(200000);

		p3.setId(2);
		p3.setNombre("nombre3");
		p3.setClave("clave3");
		p3.setPuntuacionMax(10500);

		perfiles.add(p1);
		perfiles.add(p2);
		perfiles.add(p3);
	}
}


text:
// +build !providerless

// Package mockvmssvmclient implements the mock client for VirtualMachineScaleSetVM.
package mockvmssvmclient // import "k8s.io/legacy-cloud-providers/azure/clients/vmssvmclient/mockvmssvmclient"


text:
using System.Collections.Generic;
using System.Linq;
using Parsers;
using DatabaseModule.Entieties;
using DatabaseModule;
using System.Data.Entity.Core;
using System;
using WPFAplication;
using Autofac;

namespace NewsUpdaterModule
{
    public class NewsUpdater
    {
        private DatabaseModel _context;

        public NewsUpdater()
        {
            try
            {
                _context = ContainerBuilders.BuildContainer().Resolve<DatabaseModel>();
            }
            catch (Exception e)
            {
                //Add logger error message here, don't forget pass 'e'
            }
        }

        public void Update()
        {
            try
            {
                _context.News.AddRange(GetNewsToSave(FetchNews<RssParser>()));
                _context.News.AddRange(GetNewsToSave(FetchNews<AtomParser>()));
                _context.News.AddRange(GetNewsToSave(FetchNews<WebPageParser>()));
                _context.SaveChanges();
            }
            catch (EntityException e)
            {
                //Add logger error message here, don't forget pass 'e'
            }
        }

        private IEnumerable<News> FetchNews<Parser>()
        {
            var method = typeof(Parser).GetMethod("ParseLink");
            var parser = Activator.CreateInstance<Parser>();
            var name = parser.ToString();
            IEnumerable<Link> links = null;

            try
            {
                links = _context.Link.Where(link => link.Channel.Name.ToLower().Equals(name)).ToList();
            }
            catch (Exception e)
            {
                //Add logger error message here, don't forget pass 'e'
            }

            foreach (var link in links)
            {
                foreach (var news in (IEnumerable<News>)method.Invoke(parser, new[] { link }))
                    yield return news;
            }
        }

        private IEnumerable<News> GetNewsToSave(IEnumerable<News> newsList)
        {
            var urlsInDatabase = _context.News.Select(x => x.BaseUrl);
            var distinctNews = newsList.GroupBy(x => x.BaseUrl).Select(x => x.Last());
            foreach(var news in distinctNews.Where(x => !urlsInDatabase.Any(y => y == x.BaseUrl)).Select(x => x))
            {
                yield return news;
            }
        }
    }
}


text:
repo       = "https://github.com/github/hub"
version    = node.attr!("swpr_dev", "hub", "version")
source_url = "#{repo}/releases/download/v#{version}/hub-linux-amd64-#{version}.tgz"

ark "hub" do
  url source_url
  action :cherry_pick
  version version
  path "/usr/local"
  creates "hub-linux-amd64-#{version}/bin/hub"
end


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

package com.google.devtools.build.lib.starlarkbuildapi.cpp;

import com.google.common.collect.ImmutableList;
import com.google.devtools.build.docgen.annot.DocCategory;
import com.google.devtools.build.lib.collect.nestedset.Depset;
import com.google.devtools.build.lib.starlarkbuildapi.FileApi;
import net.starlark.java.annot.StarlarkBuiltin;
import net.starlark.java.annot.StarlarkMethod;
import net.starlark.java.eval.StarlarkValue;

/** Object with information about C++ rules. Every C++-related target should provide this. */
@StarlarkBuiltin(
    name = "CcStarlarkApiProvider",
    category = DocCategory.PROVIDER,
    doc =
        "Provides access to information about C++ rules.  Every C++-related target provides this"
            + " struct, accessible as a cc field on target.")
public interface CcStarlarkApiProviderApi<FileT extends FileApi> extends StarlarkValue {

  @StarlarkMethod(
      name = "transitive_headers",
      structField = true,
      doc =
          "Returns a depset of headers that have been declared in the "
              + " src or headers attribute"
              + "(possibly empty but never None).")
  public Depset /*<FileT>*/ getTransitiveHeadersForStarlark();

  @StarlarkMethod(
      name = "libs",
      structField = true,
      doc =
          "Returns the depset of libraries for either "
              + "FULLY STATIC mode (linkopts=[\"-static\"]) or "
              + "MOSTLY STATIC mode (linkstatic=1) "
              + "(possibly empty but never None)")
  public Depset /*<FileT>*/ getLibrariesForStarlark();

  @StarlarkMethod(
      name = "link_flags",
      structField = true,
      doc =
          "Returns the list of flags given to the C++ linker command for either "
              + "FULLY STATIC mode (linkopts=[\"-static\"]) or "
              + "MOSTLY STATIC mode (linkstatic=1) "
              + "(possibly empty but never None)")
  public ImmutableList<String> getLinkopts();

  @StarlarkMethod(
      name = "defines",
      structField = true,
      doc =
          "Returns the list of defines used to compile this target "
              + "(possibly empty but never None).")
  public ImmutableList<String> getDefines();

  @StarlarkMethod(
      name = "system_include_directories",
      structField = true,
      doc =
          "Returns the list of system include directories used to compile this target "
              + "(possibly empty but never None).")
  public ImmutableList<String> getSystemIncludeDirs();

  @StarlarkMethod(
      name = "include_directories",
      structField = true,
      doc =
          "Returns the list of include directories used to compile this target "
              + "(possibly empty but never None).")
  public ImmutableList<String> getIncludeDirs();

  @StarlarkMethod(
      name = "quote_include_directories",
      structField = true,
      doc =
          "Returns the list of quote include directories used to compile this target "
              + "(possibly empty but never None).")
  public ImmutableList<String> getQuoteIncludeDirs();

  @StarlarkMethod(
      name = "compile_flags",
      structField = true,
      doc =
          "Returns the list of flags used to compile this target "
              + "(possibly empty but never None).")
  public ImmutableList<String> getCcFlags();
}


text:
var mockService1 = {
    "notes": [
    ],
    "id": 1,
    "schedules": [
    ],
    "withinSchedule": false,
    "name": "Test 1",
    "aliases": [
    ],
    "status": "UP",
    "isAuto": false,
    "isPublic": true,
    "onShortList": false,
    "serviceUrl": null,
    "description": "
Hello, Test 1!
",
    "productId": null,
    "type": "service",
    "website": "https://example.tamu.edu/"
};

var mockService2 = {
    "notes": [
    ],
    "id": 2,
    "schedules": [
    ],
    "withinSchedule": false,
    "name": "Test 2",
    "aliases": [
    ],
    "status": "MAINTENANCE",
    "isAuto": false,
    "isPublic": true,
    "onShortList": true,
    "serviceUrl": null,
    "description": "
Hello, Test 2!
",
    "productId": null,
    "type": "service",
    "website": "http://example.tamu.edu/"
};

var mockService3 = {
    "notes": [
    ],
    "id": 3,
    "schedules": [
    ],
    "withinSchedule": false,
    "name": "Test 3",
    "aliases": [
    ],
    "status": "UP",
    "isAuto": false,
    "isPublic": true,
    "onShortList": true,
    "serviceUrl": null,
    "description": "
Hello, Test 3!
",
    "productId": 1,
    "type": "service",
    "website": null
};

angular.module('mock.service', []).service('Service', function ($q) {
    return function () {
        this.isDirty = false;

        this.mock = function(toMock) {
            this.notes = toMock.notes;
            this.id = toMock.id;
            this.schedules = toMock.schedules;
            this.withinSchedule = toMock.withinSchedule;
            this.name = toMock.name;
            this.aliases = toMock.aliases;
            this.status = toMock.status;
            this.isAuto = toMock.isAuto;
            this.isPublic = toMock.isPublic;
            this.onShortList = toMock.onShortList;
            this.serviceUrl = toMock.serviceUrl;
            this.description = toMock.description;
            this.productId = toMock.productId;
            this.type = toMock.type;
            this.website = toMock.website;
        };

        this.save = function() {
        };

        this.delete = function() {
        };

        this.dirty = function(boolean) {
            this.isDirty = boolean;
        };

        this.refresh = function() {
        };

        this.clearValidationResults = function() {
        };

        this.getNotesTableParams = function() {
            var table = {
                data: [],
                reload: function() {}
            }
            // @todo
            return table;
        };

        this.getFeatureProposalsTableParams = function() {
            var table = {
                data: [],
                reload: function() {}
            }
            // @todo
            return table;
        };

        this.getManagedFeatureProposalsTableParams = function() {
            var table = {
                data: [],
                reload: function() {}
            }
            // @todo
            return table;
        };

        this.getManagedFeatureProposalsPageSettings = function() {
            return {};
        };

        return this;
    };
});


text:
#include "clusterlibinternal.h"

using namespace std;
using namespace boost;
using namespace json;

namespace clusterlib {

int32_t
CachedDataImpl::getVersion()
{
    Locker l(&getCachedDataLock());

    return m_stat.version;
}

void
CachedDataImpl::getStats(int64_t *czxid,
                         int64_t *mzxid,
                         int64_t *ctime,
                         int64_t *mtime,
                         int32_t *version,
                         int32_t *cversion,
                         int32_t *aversion,
                         int64_t *ephemeralOwner,
                         int32_t *dataLength,
                         int32_t *numChildren,
                         int64_t *pzxid)
{
    Locker l(&getCachedDataLock());

    if (czxid != NULL) {
        *czxid = m_stat.czxid;
    }
    if (mzxid != NULL) {
        *mzxid = m_stat.mzxid;
    }
    if (ctime != NULL) {
        *ctime = m_stat.ctime;
    }
    if (mtime != NULL) {
        *mtime = m_stat.mtime;
    }
    if (version != NULL) {
        *version = m_stat.version;
    }
    if (cversion != NULL) {
        *cversion = m_stat.cversion;
    }
    if (aversion != NULL) {
        *aversion = m_stat.aversion;
    }
    if (ephemeralOwner != NULL) {
        *ephemeralOwner = m_stat.ephemeralOwner;
    }
    if (dataLength != NULL) {
        *dataLength = m_stat.dataLength;
    }
    if (numChildren != NULL) {
        *numChildren = m_stat.numChildren;
    }
    if (pzxid != NULL) {
        *pzxid = m_stat.pzxid;
    }
}

CachedDataImpl::CachedDataImpl(NotifyableImpl *pNotifyable)
    : m_notifyable(pNotifyable)
{
    Locker l(&getCachedDataLock());

    memset(&m_stat, 0, sizeof(m_stat));
    m_stat.version = CLNumeric::INITIAL_ZK_VERSION;
}

shared_ptr<NotifyableImpl>
CachedDataImpl::getNotifyable()
{
    return m_notifyable->shared_from_this();
}

FactoryOps *
CachedDataImpl::getOps()
{
    return m_notifyable->getOps();
}

bool
CachedDataImpl::updateStat(const Stat &stat)
{
    TRACE(CL_LOG, "updateStat");

    ostringstream oss;
    if (stat.version < 0) {
        oss << "updateStat: Bad stat version " << stat.version;
        throw InvalidArgumentsException(oss.str());
    }

    LOG_DEBUG(CL_LOG,
              "updateStat: old version = %d, new version = %d",
              m_stat.version,
              stat.version);

    /*
     * If the current version of the stat is INITIAL_ZK_VERSION, then
     * accept the new stat.  If the stat is older than our stat, this
     * is impossible to received updates about the past.
     */
    if ((m_stat.version == CLNumeric::INITIAL_ZK_VERSION) ||
        (m_stat.version < stat.version)) {
        m_stat = stat;
        return true;
    }
    else if (m_stat.version > stat.version) {
        oss << "updateStat: Impossible that new version is "
            << stat.version << " and old version is " << m_stat.version;
        throw InconsistentInternalStateException(oss.str());
    }
    else {
        /* Don't do anything if equal */
        return false;
    }
}

}	/* End of 'namespace clusterlib' */


text:
/**
 * The Camera Zoom Complete Event.
 *
 * This event is dispatched by a Camera instance when the Zoom Effect completes.
 *
 * @event Phaser.Cameras.Scene2D.Events#ZOOM_COMPLETE
 * @since 3.3.0
 *
 * @param {Phaser.Cameras.Scene2D.Camera} camera - The camera that the effect began on.
 * @param {Phaser.Cameras.Scene2D.Effects.Zoom} effect - A reference to the effect instance.
 */
module.exports = 'camerazoomcomplete';


text:
import matplotlib.pyplot as mp
import numpy as np

from matplotlib.patches import Ellipse
from scipy.stats import chi2

def example():
    n = 100
    x = np.arange(n)
    y = x + .3*n*np.random.randn(n)

    mp.clf()
    mp.plot(x, y, 'bo')
    mp.plot(0,0, 'ko', ms=12)

    plotErrorEllipse(x, y)
    print computeProbabilityOfObservedOffset(x, y)
    mp.grid()
    mp.axis([-15, 105, -60, 160])

def computeProbabilityOfObservedOffset(x, y, p=None):
    """Compute probability that p is consistent with mean of distribution.

    For a 2 dimensional distribution of points, given by ``x`` and ``y``,
    compute the probability that the mean of the distribution is consistent
    with the input point ``p``

    Inputs:
    -------------
    x, y
        (float) Input values. Require that ``len(x) == len(y)``

    Optional Inputs:
    -----------------
    p
        (array of length 2) Point to test. Default is [0,0]

    Returns:
    -----------
    probOffset
        (float) Probability that input point is consistent with mean
        of distribution.
    chiSquare
        (float) The chi squared of the point. For highly inconsistent points
        the computed probability of offset flatlines at zero. The chisquare
        value can then be used to estimate the relative consistencies of
        different points.

    Notes:
    ---------
    See ``plotErrorEllipse`` for a description of the algorithm
    """

    if p is None:
        p = [0, 0]
    p = np.array(p)
    assert(len(p) == 2)

    assert(len(x) == len(y))
    if len(x) < 2:
        raise ValueError("Need at least two points to compute probability of offset")

    mu = np.array([np.mean(x), np.mean(y)])
    cov = np.cov(x, y) / np.sqrt(len(x))

    eigenVals, eigenVecs = np.linalg.eigh(cov)
    v1 = eigenVecs[:, 0]
    v2 = eigenVecs[:, 1]

    pDash = (p-mu)
    offset_pix = np.array([np.dot(pDash, v1), np.dot(pDash, v2)])
    sigma = np.sqrt(eigenVals)
    offset_sigma = offset_pix / sigma

    s = np.sum(offset_sigma**2)
    probOffset = chi2.cdf(s, 2)

    return probOffset, s

def plotErrorEllipse(x, y, prob=[.68, .95, .997], **kwargs):
    """Compute and plot error ellipses around the mean of a 2d distribution.

    Given two arrays, ``x`` and ``y`` where the values of each are drawn
    from a Gaussian distribution, but the values of ``y`` are correlated with
    the values of ``x``, compute and plot both the mean of the distribution
    and the uncertainty ellipses around that mean.

    Inputs:
    -------------
    x, y
        (float) Input values. Require that ``len(x) == len(y)``

    Optional Inputs:
    -----------------
    prob
        (list or array) List of probability contours to draw. The defaults
        are 68%, 95% and 99.7%. Each value must be in the range (0,1)

    marker
        (string) Marker type to plot the location of the mean. Default: 'o'
    mfc
        (string) Colour of above marker. Default is 'r', can be any legal
        matplotlib colour specification.
    ms
        (int) Marker size. Default 12

    Any other optional inputs are passed to matplotlib.patches.Ellipse

    Returns:
    ----------
    **None**

    Notes:
    ---------
    Adapted from `www.visiondummy.com  <http://www.visiondummy.com/2014/04/draw-error-ellipse-representing-covariance-matrix/#Source_Code>`_

    The general idea is as follows:

    * Compute the covariance matrix for x and y.
    * Compute the eigen vectors of the covariance matrix, corresponding
      to vectors parallel to the major and minor axes.
    * The eigen values correspond to the variances of the distribution
      along the major and minor axes.
    * To compute the lengths of the major and minor axes for a given confidence
      interval, compute the chi^2 value that corresponds to that confidence
      interval. The length of the semi major axis is then
      :math:`\sqrt{ \chi^2 \sigma^2}`, where :math:`\sigma^2` is
      the variance.

    The above proceedure will give you confidence intervals for the
    distribution (e.g the p=.95 ellipse will contain 95% of the points in the
    distribution. To get the confidence interval on the mean, divde the
    covariance matrix in the first step by :math:`\sqrt{N}` where N is the
    number of input points.

    """

    assert(len(x) == len(y))
    prob = np.array(prob)
    assert(len(prob) >= 1)
    assert(np.all(prob > 0) & np.all(prob < 1))

    if len(x) < 2:
        raise ValueError("Need at least two points to generate centroid plots")

    # Default values for mp.plot
    marker = kwargs.pop('marker', 'o')
    mfc = kwargs.pop('mfc', 'r')
    ms = kwargs.pop('ms', 12)

    # Plot the mean position
    muX = np.mean(x)
    muY = np.mean(y)
    mp.plot(muX, muY, marker=marker, mfc=mfc, ms=ms)

    # Default values for ellipse
    if 'alpha' not in kwargs:
        kwargs['alpha'] = .2

    if 'color' not in kwargs:
        kwargs['color'] = 'r'

    # Dividing by root N gives the covariance matrix for the location of
    # the mean.
    cov = np.cov(x, y) / np.sqrt(len(x))

    eigenVals, eigenVecs = np.linalg.eig(cov)
    v1 = eigenVecs[:, 0]

    # Matplotlib's Ellipse takes an angle not a pair of vectors.
    angle_deg = np.degrees(np.arctan2(v1[1], v1[0]))

    ax = mp.gca()
    for p in prob:
        scale = inverseChiSquare(1-p)  # Convert prob to chisq
        sma = np.sqrt(scale * eigenVals[0])
        smi = np.sqrt(scale * eigenVals[1])
        ell = Ellipse(xy=[muX,muY], width=2 * sma, height=2 * smi,
                      angle=angle_deg, **kwargs)
        ax.add_patch(ell)

def inverseChiSquare(p, dof=2):
    """Compute inverse chi square function.

    For a given value of ``p``, computed the chi-square value
    corresponding to that probability.

    For example, the probability of getting a chi square value greater
    than 2.996 with two degrees of freedom is <0.05. So
    ``inverseChiSquare(.05, 2) == 2.996``

    Inputs:
    ------------
    p
        (float) Desired probability

    Optional Inputs
    ----------------
    dof
        (int) Degrees of freedom.

    Returns:
    -------------
    The chi-squared value corresponding to the input probability

    Notes:
    ---------
    I would expect scipy to support this, but it doesn't. The easiest
    way to compute it seems to be to interpolate over the availble
    chi-square distribution function.
    """

    y = np.logspace(2, -3, 100)
    chi = chi2(df=dof)
    x = 1 - chi.cdf(y)

    return np.interp(p, x, y)