text:
#include <ffi.h>
#include <ffi_common.h>

#include <stdlib.h>

extern void ffi_closure_ASM(void);

enum {
  /* The assembly depends on these exact flags.  */
  FLAG_RETURNS_NOTHING  = 1 << (31-30), /* These go in cr7  */
  FLAG_RETURNS_FP       = 1 << (31-29),
  FLAG_RETURNS_64BITS   = 1 << (31-28),
  FLAG_RETURNS_128BITS  = 1 << (31-31),

  FLAG_ARG_NEEDS_COPY   = 1 << (31- 7),
  FLAG_FP_ARGUMENTS     = 1 << (31- 6), /* cr1.eq; specified by ABI  */
  FLAG_4_GPR_ARGUMENTS  = 1 << (31- 5),
  FLAG_RETVAL_REFERENCE = 1 << (31- 4)
};

/* About the DARWIN ABI.  */
enum {
  NUM_GPR_ARG_REGISTERS = 8,
  NUM_FPR_ARG_REGISTERS = 13
};
enum { ASM_NEEDS_REGISTERS = 4 };

/* ffi_prep_args is called by the assembly routine once stack space
   has been allocated for the function's arguments.

   The stack layout we want looks like this:

   |   Return address from ffi_call_DARWIN      |	higher addresses
   |--------------------------------------------|
   |   Previous backchain pointer	4	|	stack pointer here
   |--------------------------------------------|<+ <<<	on entry to
   |   Saved r28-r31			4*4	| |	ffi_call_DARWIN
   |--------------------------------------------| |
   |   Parameters             (at least 8*4=32) | |
   |--------------------------------------------| |
   |   Space for GPR2                   4       | |
   |--------------------------------------------| |	stack	|
   |   Reserved                       2*4       | |	grows	|
   |--------------------------------------------| |	down	V
   |   Space for callee's LR		4	| |
   |--------------------------------------------| |	lower addresses
   |   Saved CR                         4       | |
   |--------------------------------------------| |     stack pointer here
   |   Current backchain pointer	4	|-/	during
   |--------------------------------------------|   <<<	ffi_call_DARWIN

   */

void ffi_prep_args(extended_cif *ecif, unsigned *const stack)
{
  const unsigned bytes = ecif->cif->bytes;
  const unsigned flags = ecif->cif->flags;

  /* 'stacktop' points at the previous backchain pointer.  */
  unsigned *const stacktop = stack + (bytes / sizeof(unsigned));

  /* 'fpr_base' points at the space for fpr1, and grows upwards as
     we use FPR registers.  */
  double *fpr_base = (double*) (stacktop - ASM_NEEDS_REGISTERS) - NUM_FPR_ARG_REGISTERS;
  int fparg_count = 0;

  /* 'next_arg' grows up as we put parameters in it.  */
  unsigned *next_arg = stack + 6; /* 6 reserved positions.  */

  int i = ecif->cif->nargs;
  double double_tmp;
  void **p_argv = ecif->avalue;
  unsigned gprvalue;
  ffi_type** ptr = ecif->cif->arg_types;
  char *dest_cpy;
  unsigned size_al = 0;

  /* Check that everything starts aligned properly.  */
  FFI_ASSERT(((unsigned)(char *)stack & 0xF) == 0);
  FFI_ASSERT(((unsigned)(char *)stacktop & 0xF) == 0);
  FFI_ASSERT((bytes & 0xF) == 0);

  /* Deal with return values that are actually pass-by-reference.
     Rule:
     Return values are referenced by r3, so r4 is the first parameter.  */

  if (flags & FLAG_RETVAL_REFERENCE)
    *next_arg++ = (unsigned)(char *)ecif->rvalue;

  /* Now for the arguments.  */
  for (;
       i > 0;
       i--, ptr++, p_argv++)
    {
      switch ((*ptr)->type)
	{
	/* If a floating-point parameter appears before all of the general-
	   purpose registers are filled, the corresponding GPRs that match
	   the size of the floating-point parameter are skipped.  */
	case FFI_TYPE_FLOAT:
	  double_tmp = *(float *)*p_argv;
	  if (fparg_count >= NUM_FPR_ARG_REGISTERS)
	    *(double *)next_arg = double_tmp;
	  else
	    *fpr_base++ = double_tmp;
	  next_arg++;
	  fparg_count++;
	  FFI_ASSERT(flags & FLAG_FP_ARGUMENTS);
	  break;

	case FFI_TYPE_DOUBLE:
	  double_tmp = *(double *)*p_argv;
	  if (fparg_count >= NUM_FPR_ARG_REGISTERS)
	    *(double *)next_arg = double_tmp;
	  else
	    *fpr_base++ = double_tmp;
	  next_arg += 2;
	  fparg_count++;
	  FFI_ASSERT(flags & FLAG_FP_ARGUMENTS);
	  break;

#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE

	case FFI_TYPE_LONGDOUBLE:
	  double_tmp = ((double *)*p_argv)[0];
	  if (fparg_count >= NUM_FPR_ARG_REGISTERS)
	    *(double *)next_arg = double_tmp;
	  else
	    *fpr_base++ = double_tmp;
	  next_arg += 2;
	  fparg_count++;
	  double_tmp = ((double *)*p_argv)[1];
	  if (fparg_count >= NUM_FPR_ARG_REGISTERS)
	    *(double *)next_arg = double_tmp;
	  else
	    *fpr_base++ = double_tmp;
	  next_arg += 2;
	  fparg_count++;
	  FFI_ASSERT(flags & FLAG_FP_ARGUMENTS);
	  break;
#endif
	case FFI_TYPE_UINT64:
	case FFI_TYPE_SINT64:
	  *(long long *)next_arg = *(long long *)*p_argv;
	  next_arg+=2;
	  break;
	case FFI_TYPE_UINT8:
	  gprvalue = *(unsigned char *)*p_argv;
	  goto putgpr;
	case FFI_TYPE_SINT8:
	  gprvalue = *(signed char *)*p_argv;
	  goto putgpr;
	case FFI_TYPE_UINT16:
	  gprvalue = *(unsigned short *)*p_argv;
	  goto putgpr;
	case FFI_TYPE_SINT16:
	  gprvalue = *(signed short *)*p_argv;
	  goto putgpr;

	case FFI_TYPE_STRUCT:
	  dest_cpy = (char *) next_arg;

	  /* Structures that match the basic modes (QI 1 byte, HI 2 bytes,
	     SI 4 bytes) are aligned as if they were those modes.
	     Structures with 3 byte in size are padded upwards.  */
	  size_al = (*ptr)->size;
	  /* If the first member of the struct is a double, then align
	     the struct to double-word.
	     Type 3 is defined in include/ffi.h. #define FFI_TYPE_DOUBLE 3.  */
	  if ((*ptr)->elements[0]->type == 3)
	    size_al = ALIGN((*ptr)->size, 8);
	  if (size_al < 3 && ecif->cif->abi == FFI_DARWIN)
	    dest_cpy += 4 - size_al;

	  memcpy((char *)dest_cpy, (char *)*p_argv, size_al);
	  next_arg += (size_al + 3) / 4;
	  break;

	case FFI_TYPE_INT:
	case FFI_TYPE_UINT32:
	case FFI_TYPE_SINT32:
	case FFI_TYPE_POINTER:
	  gprvalue = *(unsigned *)*p_argv;
	putgpr:
	  *next_arg++ = gprvalue;
	  break;
	default:
	  break;
	}
    }

  /* Check that we didn't overrun the stack...  */
  //FFI_ASSERT(gpr_base <= stacktop - ASM_NEEDS_REGISTERS);
  //FFI_ASSERT((unsigned *)fpr_base
  //	     <= stacktop - ASM_NEEDS_REGISTERS - NUM_GPR_ARG_REGISTERS);
  //FFI_ASSERT(flags & FLAG_4_GPR_ARGUMENTS || intarg_count <= 4);
}

/* Adjust the size of S to be correct for Darwin.
   On Darwin, the first field of a structure has natural alignment.  */

static void
darwin_adjust_aggregate_sizes (ffi_type *s)
{
  int i;

  if (s->type != FFI_TYPE_STRUCT)
    return;

  s->size = 0;
  for (i = 0; s->elements[i] != NULL; i++)
    {
      ffi_type *p;
      int align;

      p = s->elements[i];
      darwin_adjust_aggregate_sizes (p);
      if (i == 0
	  && (p->type == FFI_TYPE_UINT64
	      || p->type == FFI_TYPE_SINT64
	      || p->type == FFI_TYPE_DOUBLE
	      || p->alignment == 8))
	align = 8;
      else if (p->alignment == 16 || p->alignment < 4)
	align = p->alignment;
      else
	align = 4;
      s->size = ALIGN(s->size, align) + p->size;
    }

  s->size = ALIGN(s->size, s->alignment);

  if (s->elements[0]->type == FFI_TYPE_UINT64
      || s->elements[0]->type == FFI_TYPE_SINT64
      || s->elements[0]->type == FFI_TYPE_DOUBLE
      || s->elements[0]->alignment == 8)
    s->alignment = s->alignment > 8 ? s->alignment : 8;
  /* Do not add additional tail padding.  */
}

/* Perform machine dependent cif processing.  */
ffi_status ffi_prep_cif_machdep(ffi_cif *cif)
{
  /* All this is for the DARWIN ABI.  */
  int i;
  ffi_type **ptr;
  unsigned bytes;
  int fparg_count = 0, intarg_count = 0;
  unsigned flags = 0;
  unsigned size_al = 0;

  /* All the machine-independent calculation of cif->bytes will be wrong.
     All the calculation of structure sizes will also be wrong.
     Redo the calculation for DARWIN.  */

  if (cif->abi == FFI_DARWIN)
    {
      darwin_adjust_aggregate_sizes (cif->rtype);
      for (i = 0; i < cif->nargs; i++)
	darwin_adjust_aggregate_sizes (cif->arg_types[i]);
    }

  /* Space for the frame pointer, callee's LR, CR, etc, and for
     the asm's temp regs.  */

  bytes = (6 + ASM_NEEDS_REGISTERS) * sizeof(long);

  /* Return value handling.  The rules are as follows:
     - 32-bit (or less) integer values are returned in gpr3;
     - Structures of size <= 4 bytes also returned in gpr3;
     - 64-bit integer values and structures between 5 and 8 bytes are returned
       in gpr3 and gpr4;
     - Single/double FP values are returned in fpr1;
     - Long double FP (if not equivalent to double) values are returned in
       fpr1 and fpr2;
     - Larger structures values are allocated space and a pointer is passed
       as the first argument.  */
  switch (cif->rtype->type)
    {

#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE
    case FFI_TYPE_LONGDOUBLE:
      flags |= FLAG_RETURNS_128BITS;
      flags |= FLAG_RETURNS_FP;
      break;
#endif

    case FFI_TYPE_DOUBLE:
      flags |= FLAG_RETURNS_64BITS;
      /* Fall through.  */
    case FFI_TYPE_FLOAT:
      flags |= FLAG_RETURNS_FP;
      break;

    case FFI_TYPE_UINT64:
    case FFI_TYPE_SINT64:
      flags |= FLAG_RETURNS_64BITS;
      break;

    case FFI_TYPE_STRUCT:
      flags |= FLAG_RETVAL_REFERENCE;
      flags |= FLAG_RETURNS_NOTHING;
      intarg_count++;
      break;
    case FFI_TYPE_VOID:
      flags |= FLAG_RETURNS_NOTHING;
      break;

    default:
      /* Returns 32-bit integer, or similar.  Nothing to do here.  */
      break;
    }

  /* The first NUM_GPR_ARG_REGISTERS words of integer arguments, and the
     first NUM_FPR_ARG_REGISTERS fp arguments, go in registers; the rest
     goes on the stack.  Structures are passed as a pointer to a copy of
     the structure. Stuff on the stack needs to keep proper alignment.  */
  for (ptr = cif->arg_types, i = cif->nargs; i > 0; i--, ptr++)
    {
      switch ((*ptr)->type)
	{
	case FFI_TYPE_FLOAT:
	case FFI_TYPE_DOUBLE:
	  fparg_count++;
	  /* If this FP arg is going on the stack, it must be
	     8-byte-aligned.  */
	  if (fparg_count > NUM_FPR_ARG_REGISTERS
	      && intarg_count%2 != 0)
	    intarg_count++;
	  break;

#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE

	case FFI_TYPE_LONGDOUBLE:
	  fparg_count += 2;
	  /* If this FP arg is going on the stack, it must be
	     8-byte-aligned.  */
	  if (fparg_count > NUM_FPR_ARG_REGISTERS
	      && intarg_count%2 != 0)
	    intarg_count++;
	  intarg_count +=2;
	  break;
#endif

	case FFI_TYPE_UINT64:
	case FFI_TYPE_SINT64:
	  /* 'long long' arguments are passed as two words, but
	     either both words must fit in registers or both go
	     on the stack.  If they go on the stack, they must
	     be 8-byte-aligned.  */
	  if (intarg_count == NUM_GPR_ARG_REGISTERS-1
	      || (intarg_count >= NUM_GPR_ARG_REGISTERS && intarg_count%2 != 0))
	    intarg_count++;
	  intarg_count += 2;
	  break;

	case FFI_TYPE_STRUCT:
	  size_al = (*ptr)->size;
	  /* If the first member of the struct is a double, then align
	     the struct to double-word.
	     Type 3 is defined in include/ffi.h. #define FFI_TYPE_DOUBLE 3.  */
	  if ((*ptr)->elements[0]->type == 3)
	    size_al = ALIGN((*ptr)->size, 8);
	  intarg_count += (size_al + 3) / 4;
	  break;

	default:
	  /* Everything else is passed as a 4-byte word in a GPR, either
	     the object itself or a pointer to it.  */
	  intarg_count++;
	  break;
	}
    }

  if (fparg_count != 0)
    flags |= FLAG_FP_ARGUMENTS;

  /* Space for the FPR registers, if needed.  */
  if (fparg_count != 0)
    bytes += NUM_FPR_ARG_REGISTERS * sizeof(double);

  /* Stack space.  */
  if ((intarg_count + 2 * fparg_count) > NUM_GPR_ARG_REGISTERS)
    bytes += (intarg_count + 2 * fparg_count) * sizeof(long);
  else
    bytes += NUM_GPR_ARG_REGISTERS * sizeof(long);

  /* The stack space allocated needs to be a multiple of 16 bytes.  */
  bytes = (bytes + 15) & ~0xF;

  cif->flags = flags;
  cif->bytes = bytes;

  return FFI_OK;
}

extern void ffi_call_AIX(extended_cif *, unsigned, unsigned, unsigned *,
			 void (*fn)(void), void (*fn2)(void));
extern void ffi_call_DARWIN(extended_cif *, unsigned, unsigned, unsigned *,
			    void (*fn)(void), void (*fn2)(void));

void ffi_call(ffi_cif *cif, void (*fn)(void), void *rvalue, void **avalue)
{
  extended_cif ecif;

  ecif.cif = cif;
  ecif.avalue = avalue;

  /* If the return value is a struct and we don't have a return
     value address then we need to make one.  */

  if ((rvalue == NULL) &&
      (cif->rtype->type == FFI_TYPE_STRUCT))
    {
      ecif.rvalue = alloca(cif->rtype->size);
    }
  else
    ecif.rvalue = rvalue;

  switch (cif->abi)
    {
    case FFI_AIX:
      ffi_call_AIX(&ecif, -cif->bytes, cif->flags, ecif.rvalue, fn,
		   ffi_prep_args);
      break;
    case FFI_DARWIN:
      ffi_call_DARWIN(&ecif, -cif->bytes, cif->flags, ecif.rvalue, fn,
		      ffi_prep_args);
      break;
    default:
      FFI_ASSERT(0);
      break;
    }
}

static void flush_icache(char *);
static void flush_range(char *, int);

/* The layout of a function descriptor.  A C function pointer really
   points to one of these.  */

typedef struct aix_fd_struct {
  void *code_pointer;
  void *toc;
} aix_fd;

/* here I'd like to add the stack frame layout we use in darwin_closure.S
   and aix_clsoure.S

   SP previous -> +---------------------------------------+ <--- child frame
		  | back chain to caller 4                |
		  +---------------------------------------+ 4
		  | saved CR 4                            |
		  +---------------------------------------+ 8
		  | saved LR 4                            |
		  +---------------------------------------+ 12
		  | reserved for compilers 4              |
		  +---------------------------------------+ 16
		  | reserved for binders 4                |
		  +---------------------------------------+ 20
		  | saved TOC pointer 4                   |
		  +---------------------------------------+ 24
		  | always reserved 8*4=32 (previous GPRs)|
		  | according to the linkage convention   |
		  | from AIX                              |
		  +---------------------------------------+ 56
		  | our FPR area 13*8=104                 |
		  | f1                                    |
		  | .                                     |
		  | f13                                   |
		  +---------------------------------------+ 160
		  | result area 8                         |
		  +---------------------------------------+ 168
		  | alignement to the next multiple of 16 |
SP current -->    +---------------------------------------+ 176 <- parent frame
		  | back chain to caller 4                |
		  +---------------------------------------+ 180
		  | saved CR 4                            |
		  +---------------------------------------+ 184
		  | saved LR 4                            |
		  +---------------------------------------+ 188
		  | reserved for compilers 4              |
		  +---------------------------------------+ 192
		  | reserved for binders 4                |
		  +---------------------------------------+ 196
		  | saved TOC pointer 4                   |
		  +---------------------------------------+ 200
		  | always reserved 8*4=32  we store our  |
		  | GPRs here                             |
		  | r3                                    |
		  | .                                     |
		  | r10                                   |
		  +---------------------------------------+ 232
		  | overflow part                         |
		  +---------------------------------------+ xxx
		  | ????                                  |
		  +---------------------------------------+ xxx

*/
ffi_status
ffi_prep_closure_loc (ffi_closure* closure,
		      ffi_cif* cif,
		      void (*fun)(ffi_cif*, void*, void**, void*),
		      void *user_data,
		      void *codeloc)
{
  unsigned int *tramp;
  struct ffi_aix_trampoline_struct *tramp_aix;
  aix_fd *fd;

  switch (cif->abi)
    {
    case FFI_DARWIN:

      FFI_ASSERT (cif->abi == FFI_DARWIN);

      tramp = (unsigned int *) &closure->tramp[0];
      tramp[0] = 0x7c0802a6;  /*   mflr    r0  */
      tramp[1] = 0x429f000d;  /*   bcl-    20,4*cr7+so,0x10  */
      tramp[4] = 0x7d6802a6;  /*   mflr    r11  */
      tramp[5] = 0x818b0000;  /*   lwz     r12,0(r11) function address  */
      tramp[6] = 0x7c0803a6;  /*   mtlr    r0   */
      tramp[7] = 0x7d8903a6;  /*   mtctr   r12  */
      tramp[8] = 0x816b0004;  /*   lwz     r11,4(r11) static chain  */
      tramp[9] = 0x4e800420;  /*   bctr  */
      tramp[2] = (unsigned long) ffi_closure_ASM; /* function  */
      tramp[3] = (unsigned long) codeloc; /* context  */

      closure->cif = cif;
      closure->fun = fun;
      closure->user_data = user_data;

      /* Flush the icache. Only necessary on Darwin.  */
      flush_range(codeloc, FFI_TRAMPOLINE_SIZE);

      break;

    case FFI_AIX:

      tramp_aix = (struct ffi_aix_trampoline_struct *) (closure->tramp);
      fd = (aix_fd *)(void *)ffi_closure_ASM;

      FFI_ASSERT (cif->abi == FFI_AIX);

      tramp_aix->code_pointer = fd->code_pointer;
      tramp_aix->toc = fd->toc;
      tramp_aix->static_chain = codeloc;
      closure->cif = cif;
      closure->fun = fun;
      closure->user_data = user_data;

    default:

      FFI_ASSERT(0);
      break;
    }
  return FFI_OK;
}

static void
flush_icache(char *addr)
{
#ifndef _AIX
  __asm__ volatile (
		"dcbf 0,%0\n"
		"\tsync\n"
		"\ticbi 0,%0\n"
		"\tsync\n"
		"\tisync"
		: : "r"(addr) : "memory");
#endif
}

static void
flush_range(char * addr1, int size)
{
#define MIN_LINE_SIZE 32
  int i;
  for (i = 0; i < size; i += MIN_LINE_SIZE)
    flush_icache(addr1+i);
  flush_icache(addr1+size-1);
}

typedef union
{
  float f;
  double d;
} ffi_dblfl;

int ffi_closure_helper_DARWIN (ffi_closure*, void*,
			       unsigned long*, ffi_dblfl*);

/* Basically the trampoline invokes ffi_closure_ASM, and on
   entry, r11 holds the address of the closure.
   After storing the registers that could possibly contain
   parameters to be passed into the stack frame and setting
   up space for a return value, ffi_closure_ASM invokes the
   following helper function to do most of the work.  */

int ffi_closure_helper_DARWIN (ffi_closure* closure, void * rvalue,
			       unsigned long * pgr, ffi_dblfl * pfr)
{
  /* rvalue is the pointer to space for return value in closure assembly
     pgr is the pointer to where r3-r10 are stored in ffi_closure_ASM
     pfr is the pointer to where f1-f13 are stored in ffi_closure_ASM.  */

  typedef double ldbits[2];

  union ldu
  {
    ldbits lb;
    long double ld;
  };

  void **          avalue;
  ffi_type **      arg_types;
  long             i, avn;
  long             nf;   /* number of floating registers already used.  */
  long             ng;   /* number of general registers already used.  */
  ffi_cif *        cif;
  double           temp;
  unsigned         size_al;
  union ldu        temp_ld;

  cif = closure->cif;
  avalue = alloca(cif->nargs * sizeof(void *));

  nf = 0;
  ng = 0;

  /* Copy the caller's structure return value address so that the closure
     returns the data directly to the caller.  */
  if (cif->rtype->type == FFI_TYPE_STRUCT)
    {
      rvalue = (void *) *pgr;
      pgr++;
      ng++;
    }

  i = 0;
  avn = cif->nargs;
  arg_types = cif->arg_types;

  /* Grab the addresses of the arguments from the stack frame.  */
  while (i < avn)
    {
      switch (arg_types[i]->type)
	{
	case FFI_TYPE_SINT8:
	case FFI_TYPE_UINT8:
	  avalue[i] = (char *) pgr + 3;
	  ng++;
	  pgr++;
	  break;

	case FFI_TYPE_SINT16:
	case FFI_TYPE_UINT16:
	  avalue[i] = (char *) pgr + 2;
	  ng++;
	  pgr++;
	  break;

	case FFI_TYPE_SINT32:
	case FFI_TYPE_UINT32:
	case FFI_TYPE_POINTER:
	  avalue[i] = pgr;
	  ng++;
	  pgr++;
	  break;

	case FFI_TYPE_STRUCT:
	  /* Structures that match the basic modes (QI 1 byte, HI 2 bytes,
	     SI 4 bytes) are aligned as if they were those modes.  */
	  size_al = arg_types[i]->size;
	  /* If the first member of the struct is a double, then align
	     the struct to double-word.
	     Type 3 is defined in include/ffi.h. #define FFI_TYPE_DOUBLE 3.  */
	  if (arg_types[i]->elements[0]->type == 3)
	    size_al = ALIGN(arg_types[i]->size, 8);
	  if (size_al < 3 && cif->abi == FFI_DARWIN)
	    avalue[i] = (void*) pgr + 4 - size_al;
	  else
	    avalue[i] = (void*) pgr;
	  ng += (size_al + 3) / 4;
	  pgr += (size_al + 3) / 4;
	  break;

	case FFI_TYPE_SINT64:
	case FFI_TYPE_UINT64:
	  /* Long long ints are passed in two gpr's.  */
	  avalue[i] = pgr;
	  ng += 2;
	  pgr += 2;
	  break;

	case FFI_TYPE_FLOAT:
	  /* A float value consumes a GPR.
	     There are 13 64bit floating point registers.  */
	  if (nf < NUM_FPR_ARG_REGISTERS)
	    {
	      temp = pfr->d;
	      pfr->f = (float)temp;
	      avalue[i] = pfr;
	      pfr++;
	    }
	  else
	    {
	      avalue[i] = pgr;
	    }
	  nf++;
	  ng++;
	  pgr++;
	  break;

	case FFI_TYPE_DOUBLE:
	  /* A double value consumes two GPRs.
	     There are 13 64bit floating point registers.  */
	  if (nf < NUM_FPR_ARG_REGISTERS)
	    {
	      avalue[i] = pfr;
	      pfr++;
	    }
	  else
	    {
	      avalue[i] = pgr;
	    }
	  nf++;
	  ng += 2;
	  pgr += 2;
	  break;

#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE

	case FFI_TYPE_LONGDOUBLE:
	  /* A long double value consumes four GPRs and two FPRs.
	     There are 13 64bit floating point registers.  */
	  if (nf < NUM_FPR_ARG_REGISTERS - 1)
	    {
	      avalue[i] = pfr;
	      pfr += 2;
	    }
	  /* Here we have the situation where one part of the long double
	     is stored in fpr13 and the other part is already on the stack.
	     We use a union to pass the long double to avalue[i].  */
	  else if (nf == NUM_FPR_ARG_REGISTERS - 1)
	    {
	      memcpy (&temp_ld.lb[0], pfr, sizeof(ldbits));
	      memcpy (&temp_ld.lb[1], pgr + 2, sizeof(ldbits));
	      avalue[i] = &temp_ld.ld;
	    }
	  else
	    {
	      avalue[i] = pgr;
	    }
	  nf += 2;
	  ng += 4;
	  pgr += 4;
	  break;
#endif
	default:
	  FFI_ASSERT(0);
	}
      i++;
    }

  (closure->fun) (cif, rvalue, avalue, closure->user_data);

  /* Tell ffi_closure_ASM to perform return type promotions.  */
  return cif->rtype->type;
}


text:
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;

namespace MPAPI.RegistrationServer
{
    public interface IRegistrationServer
    {
        bool RegisterNode(IPEndPoint nodeEndPoint);

        void UnregisterNode(ushort nodeId);

        List<IPEndPoint> GetAllNodeEndPoints();
    }
}

redpajama_set_name: RedPajamaGithub


text:
package hr.fer.java.vjezbe.zadatak7.domain.jpa.repository;

import hr.fer.java.vjezbe.zadatak7.domain.jpa.entity.AuthorEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.util.List;

public interface AuthorRepository extends JpaRepository<AuthorEntity, Integer> {

    @Query("select author from AuthorEntity as author left outer join author.books book where book.title = :title")
    List<AuthorEntity> findByTitle(@Param("title") String title);

}


text:
namespace LibrarySystem.Data.Migrations
{
    using System.CodeDom.Compiler;
    using System.Data.Entity.Migrations;
    using System.Data.Entity.Migrations.Infrastructure;
    using System.Resources;

    [GeneratedCode("EntityFramework.Migrations", "6.1.3-40302")]
    public sealed partial class Addedclientjournalsrelation : IMigrationMetadata
    {
        private readonly ResourceManager Resources = new ResourceManager(typeof(Addedclientjournalsrelation));

        string IMigrationMetadata.Id
        {
            get { return "201706090015391_Added client journals relation"; }
        }

        string IMigrationMetadata.Source
        {
            get { return null; }
        }

        string IMigrationMetadata.Target
        {
            get { return Resources.GetString("Target"); }
        }
    }
}


text:
package idaas_doraemon

//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.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

import (
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)

// GetAuthenticator invokes the idaas_doraemon.GetAuthenticator API synchronously
func (client *Client) GetAuthenticator(request *GetAuthenticatorRequest) (response *GetAuthenticatorResponse, err error) {
	response = CreateGetAuthenticatorResponse()
	err = client.DoAction(request, response)
	return
}

// GetAuthenticatorWithChan invokes the idaas_doraemon.GetAuthenticator API asynchronously
func (client *Client) GetAuthenticatorWithChan(request *GetAuthenticatorRequest) (<-chan *GetAuthenticatorResponse, <-chan error) {
	responseChan := make(chan *GetAuthenticatorResponse, 1)
	errChan := make(chan error, 1)
	err := client.AddAsyncTask(func() {
		defer close(responseChan)
		defer close(errChan)
		response, err := client.GetAuthenticator(request)
		if err != nil {
			errChan <- err
		} else {
			responseChan <- response
		}
	})
	if err != nil {
		errChan <- err
		close(responseChan)
		close(errChan)
	}
	return responseChan, errChan
}

// GetAuthenticatorWithCallback invokes the idaas_doraemon.GetAuthenticator API asynchronously
func (client *Client) GetAuthenticatorWithCallback(request *GetAuthenticatorRequest, callback func(response *GetAuthenticatorResponse, err error)) <-chan int {
	result := make(chan int, 1)
	err := client.AddAsyncTask(func() {
		var response *GetAuthenticatorResponse
		var err error
		defer close(result)
		response, err = client.GetAuthenticator(request)
		callback(response, err)
		result <- 1
	})
	if err != nil {
		defer close(result)
		callback(nil, err)
		result <- 0
	}
	return result
}

// GetAuthenticatorRequest is the request struct for api GetAuthenticator
type GetAuthenticatorRequest struct {
	*requests.RpcRequest
	UserId                string `position:"Query" name:"UserId"`
	AuthenticatorUuid     string `position:"Query" name:"AuthenticatorUuid"`
	ApplicationExternalId string `position:"Query" name:"ApplicationExternalId"`
}

// GetAuthenticatorResponse is the response struct for api GetAuthenticator
type GetAuthenticatorResponse struct {
	*responses.BaseResponse
	RequestId     string        `json:"RequestId" xml:"RequestId"`
	Authenticator Authenticator `json:"Authenticator" xml:"Authenticator"`
}

// CreateGetAuthenticatorRequest creates a request to invoke GetAuthenticator API
func CreateGetAuthenticatorRequest() (request *GetAuthenticatorRequest) {
	request = &GetAuthenticatorRequest{
		RpcRequest: &requests.RpcRequest{},
	}
	request.InitWithApiInfo("idaas-doraemon", "2021-05-20", "GetAuthenticator", "", "")
	request.Method = requests.POST
	return
}

// CreateGetAuthenticatorResponse creates a response to parse from GetAuthenticator response
func CreateGetAuthenticatorResponse() (response *GetAuthenticatorResponse) {
	response = &GetAuthenticatorResponse{
		BaseResponse: &responses.BaseResponse{},
	}
	return
}


text:
/**
* TCG & Tabletop: Yugioh wiki plugin
* This is a command that allows users to search the yugioh wiki for cards. It will display the closest match with a given query, or a separate message if there isn't anything found.
* By bumbadadabum with help from ascriptmaster, codelegend and the PS development team.
*/

'use strict';

const https = require('https');
const querystring = require('querystring');

const SEARCH_PATH = '/api/v1/Search/List/';
const DETAILS_PATH = '/api/v1/Articles/Details/';

async function getFandom(site, pathName, search) {
	const reqOpts = {
		hostname: `${site}.fandom.com`,
		method: 'GET',
		path: `${pathName}?${querystring.stringify(search)}`,
		headers: {
			'Content-Type': 'application/json',
		},
	};

	const body = await new Promise((resolve, reject) => {
		https.request(reqOpts, res => {
			if (!(res.statusCode >= 200 && res.statusCode < 300)) return reject(new Error(`Not found.`));
			const body = [];
			res.setEncoding('utf8');
			res.on('data', chunk => body.push(chunk));
			res.on('end', () => resolve(body.join('')));
		}).on('error', reject).setTimeout(5000).end();
	});

	const json = JSON.parse(body);
	if (!json) throw new Error(`Malformed data`);
	if (json.exception) throw new Error(Dex.getString(json.exception.message) || `Not found`);
	return json;
}

async function searchFandom(site, query) {
	const result = await getFandom(site, SEARCH_PATH, {query, limit: 1});
	if (!Array.isArray(result.items) || !result.items.length) throw new Error(`Malformed data`);
	if (!result.items[0] || typeof result.items[0] !== 'object') throw new Error(`Malformed data`);
	return result.items[0];
}

async function getCardDetails(site, id) {
	const result = await getFandom(site, DETAILS_PATH, {ids: id, abstract: 0, width: 80, height: 115});
	if (typeof result.items !== 'object' || !result.items[id] || typeof result.items[id] !== 'object') {
		throw new Error(`Malformed data`);
	}
	return result.items[id];
}

exports.commands = {
	ygo: 'yugioh',
	yugioh(target, room, user) {
		if (!this.canBroadcast()) return;
		if (room.id !== 'tcgtabletop') return this.errorReply("This command can only be used in the TCG & Tabletop room.");
		let subdomain = 'yugioh';
		let query = target.trim();
		if (!query) return this.parse('/help yugioh');

		return searchFandom(subdomain, query).then(data => {
			if (!this.runBroadcast()) return;
			let entryUrl = Dex.getString(data.url);
			let entryTitle = Dex.getString(data.title);
			let id = Dex.getString(data.id);
			let htmlReply = Chat.html`<strong>Best result for ${query}:</strong><br /><a href="${entryUrl}">${entryTitle}</a>`;
			if (id) {
				getCardDetails(subdomain, id).then(card => {
					let thumb = Dex.getString(card.thumbnail);
					if (thumb) {
						htmlReply = `<table><tr><td style="padding-right:5px;"><img src="${Chat.escapeHTML(thumb)}" width=80 height=115></td><td>${htmlReply}</td></tr></table>`;
					}
					if (!this.broadcasting) return this.sendReply(`|raw|<div class="infobox">${htmlReply}</div>`);
					room.addRaw(`<div class="infobox">${htmlReply}</div>`).update();
				}, () => {
					if (!this.broadcasting) return this.sendReply(`|raw|<div class="infobox">${htmlReply}</div>`);
					room.addRaw(`<div class="infobox">${htmlReply}</div>`).update();
				});
			} else {
				if (!this.broadcasting) return this.sendReply(`|raw|<div class="infobox">${htmlReply}</div>`);
				room.addRaw(`<div class="infobox">${htmlReply}</div>`).update();
			}
		}, err => {
			if (!this.runBroadcast()) return;

			if (err instanceof SyntaxError || err.message === 'Malformed data') {
				if (!this.broadcasting) return this.sendReply(`Error: Something went wrong in the request: ${err.message}`);
				return room.add(`Error: Something went wrong in the request: ${err.message}`).update();
			} else if (err.message === 'Not found') {
				if (!this.broadcasting) return this.sendReply('|raw|
No results found.
');
				return room.addRaw('
No results found.
').update();
			} else if (err.code === "ENOTFOUND") {
				if (!this.broadcasting) return this.sendReply("Error connecting to the yugioh wiki.");
				return room.add("Error connecting to the yugioh wiki.").update();
			}
			if (!this.broadcasting) return this.sendReply(`Error: ${err.message}`);
			return room.add(`Error: ${err.message}`).update();
		});
	},
	yugiohhelp: [`/yugioh [query] - Search the Yugioh wiki.`],
};


text:
__all__ = [ "InputInterface" ]

class InputInterface():
  def get_move(self):
    pass


text:
package org.apache.druid.query.aggregation.datasketches.quantiles;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.annotations.VisibleForTesting;
import org.apache.datasketches.Util;
import org.apache.datasketches.quantiles.DoublesSketch;
import org.apache.datasketches.quantiles.DoublesUnion;
import org.apache.druid.java.util.common.IAE;
import org.apache.druid.query.aggregation.AggregateCombiner;
import org.apache.druid.query.aggregation.Aggregator;
import org.apache.druid.query.aggregation.AggregatorFactory;
import org.apache.druid.query.aggregation.AggregatorFactoryNotMergeableException;
import org.apache.druid.query.aggregation.AggregatorUtil;
import org.apache.druid.query.aggregation.BufferAggregator;
import org.apache.druid.query.aggregation.ObjectAggregateCombiner;
import org.apache.druid.query.aggregation.VectorAggregator;
import org.apache.druid.query.cache.CacheKeyBuilder;
import org.apache.druid.segment.BaseDoubleColumnValueSelector;
import org.apache.druid.segment.ColumnInspector;
import org.apache.druid.segment.ColumnProcessors;
import org.apache.druid.segment.ColumnSelectorFactory;
import org.apache.druid.segment.ColumnValueSelector;
import org.apache.druid.segment.NilColumnValueSelector;
import org.apache.druid.segment.VectorColumnProcessorFactory;
import org.apache.druid.segment.column.ColumnCapabilities;
import org.apache.druid.segment.column.ColumnType;
import org.apache.druid.segment.vector.MultiValueDimensionVectorSelector;
import org.apache.druid.segment.vector.SingleValueDimensionVectorSelector;
import org.apache.druid.segment.vector.VectorColumnSelectorFactory;
import org.apache.druid.segment.vector.VectorObjectSelector;
import org.apache.druid.segment.vector.VectorValueSelector;

import javax.annotation.Nullable;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;

public class DoublesSketchAggregatorFactory extends AggregatorFactory
{
  public static final Comparator<DoublesSketch> COMPARATOR =
      Comparator.nullsFirst(Comparator.comparingLong(DoublesSketch::getN));

  public static final int DEFAULT_K = 128;

  // Used for sketch size estimation.
  public static final long DEFAULT_MAX_STREAM_LENGTH = 1_000_000_000;

  private final String name;
  private final String fieldName;
  private final int k;
  private final long maxStreamLength;
  private final byte cacheTypeId;

  @JsonCreator
  public DoublesSketchAggregatorFactory(
      @JsonProperty("name") final String name,
      @JsonProperty("fieldName") final String fieldName,
      @JsonProperty("k") @Nullable final Integer k,
      @JsonProperty("maxStreamLength") @Nullable final Long maxStreamLength
  )
  {
    this(name, fieldName, k, maxStreamLength, AggregatorUtil.QUANTILES_DOUBLES_SKETCH_BUILD_CACHE_TYPE_ID);
  }

  @VisibleForTesting
  public DoublesSketchAggregatorFactory(
      final String name,
      final String fieldName,
      @Nullable final Integer k
  )
  {
    this(name, fieldName, k, null);
  }

  DoublesSketchAggregatorFactory(
      final String name,
      final String fieldName,
      @Nullable final Integer k,
      @Nullable final Long maxStreamLength,
      final byte cacheTypeId
  )
  {
    if (name == null) {
      throw new IAE("Must have a valid, non-null aggregator name");
    }
    this.name = name;
    if (fieldName == null) {
      throw new IAE("Parameter fieldName must be specified");
    }
    this.fieldName = fieldName;
    this.k = k == null ? DEFAULT_K : k;
    Util.checkIfPowerOf2(this.k, "k");
    this.maxStreamLength = maxStreamLength == null ? DEFAULT_MAX_STREAM_LENGTH : maxStreamLength;
    this.cacheTypeId = cacheTypeId;
  }

  @Override
  public Aggregator factorize(final ColumnSelectorFactory metricFactory)
  {
    if (metricFactory.getColumnCapabilities(fieldName) != null
        && metricFactory.getColumnCapabilities(fieldName).isNumeric()) {
      final ColumnValueSelector<Double> selector = metricFactory.makeColumnValueSelector(fieldName);
      if (selector instanceof NilColumnValueSelector) {
        return new NoopDoublesSketchAggregator();
      }
      return new DoublesSketchBuildAggregator(selector, k);
    }
    final ColumnValueSelector<DoublesSketch> selector = metricFactory.makeColumnValueSelector(fieldName);
    if (selector instanceof NilColumnValueSelector) {
      return new NoopDoublesSketchAggregator();
    }
    return new DoublesSketchMergeAggregator(selector, k);
  }

  @Override
  public BufferAggregator factorizeBuffered(final ColumnSelectorFactory metricFactory)
  {
    if (metricFactory.getColumnCapabilities(fieldName) != null
        && metricFactory.getColumnCapabilities(fieldName).isNumeric()) {
      final BaseDoubleColumnValueSelector selector = metricFactory.makeColumnValueSelector(fieldName);
      if (selector instanceof NilColumnValueSelector) {
        return new NoopDoublesSketchBufferAggregator();
      }
      return new DoublesSketchBuildBufferAggregator(selector, k, getMaxIntermediateSizeWithNulls());
    }
    final ColumnValueSelector<DoublesSketch> selector = metricFactory.makeColumnValueSelector(fieldName);
    if (selector instanceof NilColumnValueSelector) {
      return new NoopDoublesSketchBufferAggregator();
    }
    return new DoublesSketchMergeBufferAggregator(selector, k, getMaxIntermediateSizeWithNulls());
  }

  @Override
  public VectorAggregator factorizeVector(VectorColumnSelectorFactory selectorFactory)
  {
    return ColumnProcessors.makeVectorProcessor(
        fieldName,
        new VectorColumnProcessorFactory<VectorAggregator>()
        {
          @Override
          public VectorAggregator makeSingleValueDimensionProcessor(
              ColumnCapabilities capabilities,
              SingleValueDimensionVectorSelector selector
          )
          {
            return new NoopDoublesSketchBufferAggregator();
          }

          @Override
          public VectorAggregator makeMultiValueDimensionProcessor(
              ColumnCapabilities capabilities,
              MultiValueDimensionVectorSelector selector
          )
          {
            return new NoopDoublesSketchBufferAggregator();
          }

          @Override
          public VectorAggregator makeFloatProcessor(ColumnCapabilities capabilities, VectorValueSelector selector)
          {
            return new DoublesSketchBuildVectorAggregator(selector, k, getMaxIntermediateSizeWithNulls());
          }

          @Override
          public VectorAggregator makeDoubleProcessor(ColumnCapabilities capabilities, VectorValueSelector selector)
          {
            return new DoublesSketchBuildVectorAggregator(selector, k, getMaxIntermediateSizeWithNulls());
          }

          @Override
          public VectorAggregator makeLongProcessor(ColumnCapabilities capabilities, VectorValueSelector selector)
          {
            return new DoublesSketchBuildVectorAggregator(selector, k, getMaxIntermediateSizeWithNulls());
          }

          @Override
          public VectorAggregator makeObjectProcessor(ColumnCapabilities capabilities, VectorObjectSelector selector)
          {
            return new DoublesSketchMergeVectorAggregator(selector, k, getMaxIntermediateSizeWithNulls());
          }
        },
        selectorFactory
    );
  }

  @Override
  public boolean canVectorize(ColumnInspector columnInspector)
  {
    return true;
  }

  @Override
  public Object deserialize(final Object object)
  {
    return DoublesSketchOperations.deserialize(object);
  }

  @Override
  public Comparator<DoublesSketch> getComparator()
  {
    return COMPARATOR;
  }

  @Override
  public Object combine(final Object lhs, final Object rhs)
  {
    final DoublesUnion union = DoublesUnion.builder().setMaxK(k).build();
    union.update((DoublesSketch) lhs);
    union.update((DoublesSketch) rhs);
    return union.getResultAndReset();
  }

  @Override
  public AggregateCombiner makeAggregateCombiner()
  {
    return new ObjectAggregateCombiner<DoublesSketch>()
    {
      private final DoublesUnion union = DoublesUnion.builder().setMaxK(k).build();

      @Override
      public void reset(final ColumnValueSelector selector)
      {
        union.reset();
        fold(selector);
      }

      @Override
      public void fold(final ColumnValueSelector selector)
      {
        final DoublesSketch sketch = (DoublesSketch) selector.getObject();
        union.update(sketch);
      }

      @Nullable
      @Override
      public DoublesSketch getObject()
      {
        return union.getResult();
      }

      @Override
      public Class<DoublesSketch> classOfObject()
      {
        return DoublesSketch.class;
      }
    };
  }

  @Override
  @JsonProperty
  public String getName()
  {
    return name;
  }

  @JsonProperty
  public String getFieldName()
  {
    return fieldName;
  }

  @JsonProperty
  public int getK()
  {
    return k;
  }

  @JsonProperty
  public long getMaxStreamLength()
  {
    return maxStreamLength;
  }

  @Override
  public List<String> requiredFields()
  {
    return Collections.singletonList(fieldName);
  }

  @Override
  public int guessAggregatorHeapFootprint(long rows)
  {
    return DoublesSketch.getUpdatableStorageBytes(k, rows);
  }

  // Quantiles sketches never stop growing, but they do so very slowly.
  // This size must suffice for overwhelming majority of sketches,
  // but some sketches may request more memory on heap and move there
  @Override
  public int getMaxIntermediateSize()
  {
    return DoublesSketch.getUpdatableStorageBytes(k, maxStreamLength);
  }

  @Override
  public List<AggregatorFactory> getRequiredColumns()
  {
    return Collections.singletonList(
        new DoublesSketchAggregatorFactory(
            fieldName,
            fieldName,
            k,
            maxStreamLength
        )
    );
  }

  @Override
  public AggregatorFactory getCombiningFactory()
  {
    return new DoublesSketchMergeAggregatorFactory(name, k, maxStreamLength);
  }

  @Override
  public AggregatorFactory getMergingFactory(AggregatorFactory other) throws AggregatorFactoryNotMergeableException
  {
    if (other.getName().equals(this.getName()) && other instanceof DoublesSketchAggregatorFactory) {
      // DoublesUnion supports inputs with different k.
      // The result will have effective k between the specified k and the minimum k from all input sketches
      // to achieve higher accuracy as much as possible.
      return new DoublesSketchMergeAggregatorFactory(
          name,
          Math.max(k, ((DoublesSketchAggregatorFactory) other).k),
          maxStreamLength
      );
    } else {
      throw new AggregatorFactoryNotMergeableException(this, other);
    }
  }

  @Nullable
  @Override
  public Object finalizeComputation(@Nullable final Object object)
  {
    return object == null ? null : ((DoublesSketch) object).getN();
  }

  /**
   * actual type is {@link DoublesSketch}
   */
  @Override
  public ColumnType getIntermediateType()
  {
    return DoublesSketchModule.TYPE;
  }

  @Override
  public ColumnType getResultType()
  {
    return ColumnType.LONG;
  }

  @Override
  public byte[] getCacheKey()
  {
    // maxStreamLength is not included in the cache key as it does nothing with query result.
    return new CacheKeyBuilder(cacheTypeId).appendString(name).appendString(fieldName).appendInt(k).build();
  }

  @Override
  public boolean equals(Object o)
  {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }
    DoublesSketchAggregatorFactory that = (DoublesSketchAggregatorFactory) o;
    return k == that.k
           && maxStreamLength == that.maxStreamLength
           && name.equals(that.name)
           && fieldName.equals(that.fieldName);
  }

  @Override
  public int hashCode()
  {
    return Objects.hash(name, fieldName, k, maxStreamLength); // no need to use cacheTypeId here
  }

  @Override
  public String toString()
  {
    return getClass().getSimpleName() + "{"
           + "name=" + name
           + ", fieldName=" + fieldName
           + ", k=" + k
           + "}";
  }

}


text:
#ifndef BOOST_PTR_CONTAINER_DETAIL_PTR_MAP_ADAPTER_HPP
#define BOOST_PTR_CONTAINER_DETAIL_PTR_MAP_ADAPTER_HPP

#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif

#include <boost/ptr_container/detail/map_iterator.hpp>
#include <boost/ptr_container/detail/associative_ptr_container.hpp>
#include <boost/static_assert.hpp>
#include <boost/range/iterator_range.hpp>

namespace boost
{
namespace ptr_container_detail
{

    template
    <
        class T,
        class VoidPtrMap
    >
    struct map_config
    {
        typedef BOOST_DEDUCED_TYPENAME remove_nullable<T>::type
                     U;
        typedef VoidPtrMap
                     void_container_type;

        typedef BOOST_DEDUCED_TYPENAME VoidPtrMap::allocator_type
                     allocator_type;

        typedef BOOST_DEDUCED_TYPENAME VoidPtrMap::key_compare
                     key_compare;

        typedef BOOST_DEDUCED_TYPENAME VoidPtrMap::value_compare
                     value_compare;

        typedef BOOST_DEDUCED_TYPENAME VoidPtrMap::key_type
                     key_type;

        typedef U    value_type;

        typedef ptr_map_iterator< BOOST_DEDUCED_TYPENAME VoidPtrMap::iterator, key_type, U* const >
                     iterator;

        typedef ptr_map_iterator< BOOST_DEDUCED_TYPENAME VoidPtrMap::const_iterator, key_type, const U* const>
                     const_iterator;

        template< class Iter >
        static U* get_pointer( Iter i )
        {
            return i->second;
        }

        template< class Iter >
        static const U* get_const_pointer( Iter i )
        {
            return i->second;
        }

        BOOST_STATIC_CONSTANT( bool, allow_null = boost::is_nullable<T>::value );
    };

    template
    <
        class T,
        class VoidPtrMap,
        class CloneAllocator
    >
    class ptr_map_adapter_base :
        public ptr_container_detail::associative_ptr_container< map_config<T,VoidPtrMap>,
                                                    CloneAllocator >
    {
        typedef ptr_container_detail::associative_ptr_container< map_config<T,VoidPtrMap>,
                                                     CloneAllocator >
            base_type;

        typedef map_config<T,VoidPtrMap>                           config;

        typedef ptr_map_adapter_base<T,VoidPtrMap,CloneAllocator>  this_type;

    public:

        typedef BOOST_DEDUCED_TYPENAME base_type::allocator_type
                    allocator_type;
        typedef BOOST_DEDUCED_TYPENAME base_type::iterator
                    iterator;
        typedef BOOST_DEDUCED_TYPENAME base_type::const_iterator
                    const_iterator;
        typedef BOOST_DEDUCED_TYPENAME base_type::size_type
                    size_type;
        typedef BOOST_DEDUCED_TYPENAME base_type::key_type
                    key_type;
        typedef BOOST_DEDUCED_TYPENAME base_type::auto_type
                    auto_type;
        typedef BOOST_DEDUCED_TYPENAME base_type::value_type
                    mapped_type;
        typedef BOOST_DEDUCED_TYPENAME base_type::reference
                    mapped_reference;
        typedef BOOST_DEDUCED_TYPENAME base_type::const_reference
                    const_mapped_reference;
        typedef BOOST_DEDUCED_TYPENAME iterator_value<iterator>::type
                    value_type;
        typedef value_type
                    reference;
        typedef BOOST_DEDUCED_TYPENAME iterator_value<const_iterator>::type
                    const_reference;
        typedef value_type
                    pointer;
        typedef const_reference
                    const_pointer;

    private:
        const_mapped_reference lookup( const key_type& key ) const
        {
           const_iterator i = this->find( key );
           if( i != this->end() )
               return *i->second;
           else
               BOOST_PTR_CONTAINER_THROW_EXCEPTION( true, bad_ptr_container_operation,
                                                    "'ptr_map/multimap::at()' could"
                                                    " not find key" );
        }

        struct eraser // scope guard
        {
            bool            released_;
            VoidPtrMap*     m_;
            const key_type& key_;

            eraser( VoidPtrMap* m, const key_type& key )
              : released_(false), m_(m), key_(key)
            {}

            ~eraser()
            {
                if( !released_ )
                    m_->erase(key_);
            }

            void release() { released_ = true; }
        };

        mapped_reference insert_lookup( const key_type& key )
        {
            void*& ref = this->base()[key];
            if( ref )
            {
                return *static_cast<mapped_type>(ref);
            }
            else
            {
                eraser e(&this->base(),key);      // nothrow
                mapped_type res = new T();        // strong
                ref = res;                        // nothrow
                e.release();                      // nothrow
                return *res;
            }
          }

    public:

        template< class InputIterator >
        ptr_map_adapter_base( InputIterator first, InputIterator last,
                              const allocator_type& a = allocator_type() )
        : base_type( first, last, a )
        { }

        template< class Compare, class Allocator >
        ptr_map_adapter_base( const Compare& comp,
                              const Allocator& a )
        : base_type( comp, a )
        { }

        template< class PtrContainer >
        explicit ptr_map_adapter_base( std::auto_ptr<PtrContainer> clone )
        : base_type( clone )
        { }

        template< typename PtrContainer >
        ptr_map_adapter_base& operator=( std::auto_ptr<PtrContainer> clone )
        {
            base_type::operator=( clone );
            return *this;
        }

        iterator find( const key_type& x )
        {
            return iterator( this->base().find( x ) );
        }

        const_iterator find( const key_type& x ) const
        {
            return const_iterator( this->base().find( x ) );
        }

        size_type count( const key_type& x ) const
        {
            return this->base().count( x );
        }

        iterator lower_bound( const key_type& x )
        {
            return iterator( this->base().lower_bound( x ) );
        }

        const_iterator lower_bound( const key_type& x ) const
        {
            return const_iterator( this->base().lower_bound( x ) );
        }

        iterator upper_bound( const key_type& x )
        {
            return iterator( this->base().upper_bound( x ) );
        }

        const_iterator upper_bound( const key_type& x ) const
        {
            return const_iterator( this->base().upper_bound( x ) );
        }

        iterator_range<iterator> equal_range( const key_type& x )
        {
            std::pair<BOOST_DEDUCED_TYPENAME base_type::ptr_iterator,
                      BOOST_DEDUCED_TYPENAME base_type::ptr_iterator>
                 p = this->base().equal_range( x );
            return make_iterator_range( iterator( p.first ), iterator( p.second ) );
        }

        iterator_range<const_iterator> equal_range( const key_type& x ) const
        {
            std::pair<BOOST_DEDUCED_TYPENAME base_type::ptr_const_iterator,
                      BOOST_DEDUCED_TYPENAME base_type::ptr_const_iterator>
                p = this->base().equal_range( x );
            return make_iterator_range( const_iterator( p.first ),
                                        const_iterator( p.second ) );
        }

        mapped_reference at( const key_type& key )
        {
            return const_cast<mapped_reference>( lookup( key ) );
        }

        const_mapped_reference at( const key_type& key ) const
        {
            return lookup( key );
        }

        mapped_reference operator[]( const key_type& key )
        {
            return insert_lookup( key );
        }

        auto_type replace( iterator where, mapped_type x ) // strong
        {
            BOOST_ASSERT( where != this->end() );

            this->enforce_null_policy( x, "Null pointer in 'replace()'" );

            auto_type ptr( x );

            BOOST_PTR_CONTAINER_THROW_EXCEPTION( this->empty(),
                                                 bad_ptr_container_operation,
                                                 "'replace()' on empty container" );

            auto_type old( where->second );       // nothrow
            where.base()->second = ptr.release(); // nothrow, commit
            return boost::ptr_container::move( old );
        }

        template< class U >
        auto_type replace( iterator where, std::auto_ptr<U> x )
        {
            return replace( where, x.release() );
        }
    };

} // ptr_container_detail

    /////////////////////////////////////////////////////////////////////////
    // ptr_map_adapter
    /////////////////////////////////////////////////////////////////////////

    template
    <
        class T,
        class VoidPtrMap,
        class CloneAllocator = heap_clone_allocator
    >
    class ptr_map_adapter :
        public ptr_container_detail::ptr_map_adapter_base<T,VoidPtrMap,CloneAllocator>
    {
        typedef ptr_container_detail::ptr_map_adapter_base<T,VoidPtrMap,CloneAllocator>
            base_type;

    public:
        typedef BOOST_DEDUCED_TYPENAME base_type::iterator
                     iterator;
        typedef BOOST_DEDUCED_TYPENAME base_type::const_iterator
                     const_iterator;
        typedef BOOST_DEDUCED_TYPENAME base_type::size_type
                    size_type;
        typedef BOOST_DEDUCED_TYPENAME base_type::key_type
                    key_type;
        typedef BOOST_DEDUCED_TYPENAME base_type::const_reference
                    const_reference;
        typedef BOOST_DEDUCED_TYPENAME base_type::auto_type
                    auto_type;
        typedef BOOST_DEDUCED_TYPENAME VoidPtrMap::key_compare
                    key_compare;
        typedef BOOST_DEDUCED_TYPENAME VoidPtrMap::allocator_type
                    allocator_type;
        typedef BOOST_DEDUCED_TYPENAME base_type::mapped_type
                    mapped_type;
    private:

        void safe_insert( const key_type& key, auto_type ptr ) // strong
        {
            std::pair<BOOST_DEDUCED_TYPENAME base_type::ptr_iterator,bool>
                res =
                this->base().insert( std::make_pair( key, ptr.get() ) ); // strong, commit
            if( res.second )                                             // nothrow
                ptr.release();                                           // nothrow
        }

        template< class II >
        void map_basic_clone_and_insert( II first, II last )
        {
            while( first != last )
            {
                if( this->find( first->first ) == this->end() )
                {
                    const_reference p = *first.base();     // nothrow
                    auto_type ptr( this->null_policy_allocate_clone( p.second ) );
                                                           // strong
                    this->safe_insert( p.first,
                                       boost::ptr_container::move( ptr ) );
                                                           // strong, commit
                }
                ++first;
            }
        }

    public:

        explicit ptr_map_adapter( const key_compare& comp = key_compare(),
                                  const allocator_type& a = allocator_type() )
          : base_type( comp, a ) { }

        template< class InputIterator >
        ptr_map_adapter( InputIterator first, InputIterator last,
                         const key_compare& comp = key_compare(),
                         const allocator_type& a = allocator_type() )
          : base_type( comp, a )
        {
            map_basic_clone_and_insert( first, last );
        }

        explicit ptr_map_adapter( const ptr_map_adapter& r )
          : base_type( key_compare(), allocator_type() )
        {
            map_basic_clone_and_insert( r.begin(), r.end() );
        }

        template< class Key, class U >
        explicit ptr_map_adapter( const ptr_map_adapter<Key,U>& r )
          : base_type( key_compare(), allocator_type() )
        {
            map_basic_clone_and_insert( r.begin(), r.end() );
        }

        template< class U >
        ptr_map_adapter( std::auto_ptr<U> r ) : base_type( r )
        { }

        ptr_map_adapter& operator=( const ptr_map_adapter& r )
        {
            ptr_map_adapter clone( r );
            this->swap( clone );
            return *this;
        }

        template< class Key, class U >
        ptr_map_adapter& operator=( const ptr_map_adapter<Key,U>& r )
         {
            ptr_map_adapter clone( r );
            this->swap( clone );
            return *this;
        }

        template< class U >
        ptr_map_adapter& operator=( std::auto_ptr<U> r )
        {
            base_type::operator=( r );
            return *this;
        }

        using base_type::release;

        template< typename InputIterator >
        void insert( InputIterator first, InputIterator last ) // basic
        {
            map_basic_clone_and_insert( first, last );
        }

        template< class Range >
        void insert( const Range& r )
        {
            insert( boost::begin(r), boost::end(r) );
        }

    private:
        std::pair<iterator,bool> insert_impl( const key_type& key, mapped_type x ) // strong
        {
            this->enforce_null_policy( x, "Null pointer in ptr_map_adapter::insert()" );
            auto_type ptr( x );                                         // nothrow

            std::pair<BOOST_DEDUCED_TYPENAME base_type::ptr_iterator,bool>
                 res = this->base().insert( std::make_pair( key, x ) ); // strong, commit
            if( res.second )                                            // nothrow
                ptr.release();                                          // nothrow
            return std::make_pair( iterator( res.first ), res.second ); // nothrow
        }

    public:

        std::pair<iterator,bool> insert( key_type& key, mapped_type x )
        {
            return insert_impl( key, x );
        }

        template< class U >
        std::pair<iterator,bool> insert( const key_type& key, std::auto_ptr<U> x )
        {
            return insert_impl( key, x.release() );
        }

        template< class PtrMapAdapter >
        bool transfer( BOOST_DEDUCED_TYPENAME PtrMapAdapter::iterator object,
                       PtrMapAdapter& from ) // strong
        {
            return this->single_transfer( object, from );
        }

        template< class PtrMapAdapter >
        size_type transfer( BOOST_DEDUCED_TYPENAME PtrMapAdapter::iterator first,
                            BOOST_DEDUCED_TYPENAME PtrMapAdapter::iterator last,
                            PtrMapAdapter& from ) // basic
        {
            return this->single_transfer( first, last, from );
        }

#if defined(BOOST_NO_SFINAE) || defined(BOOST_NO_FUNCTION_TEMPLATE_ORDERING)
#else

        template< class PtrMapAdapter, class Range >
        BOOST_DEDUCED_TYPENAME boost::disable_if< boost::is_same< Range,
                            BOOST_DEDUCED_TYPENAME PtrMapAdapter::iterator >,
                                                            size_type >::type
        transfer( const Range& r, PtrMapAdapter& from ) // basic
        {
            return transfer( boost::begin(r), boost::end(r), from );
        }

#endif

        template< class PtrMapAdapter >
        size_type transfer( PtrMapAdapter& from ) // basic
        {
            return transfer( from.begin(), from.end(), from );
        }
  };

  /////////////////////////////////////////////////////////////////////////
  // ptr_multimap_adapter
  /////////////////////////////////////////////////////////////////////////

    template
    <
        class T,
        class VoidPtrMultiMap,
        class CloneAllocator = heap_clone_allocator
    >
    class ptr_multimap_adapter :
        public ptr_container_detail::ptr_map_adapter_base<T,VoidPtrMultiMap,CloneAllocator>
    {
        typedef ptr_container_detail::ptr_map_adapter_base<T,VoidPtrMultiMap,CloneAllocator>
             base_type;

    public: // typedefs
        typedef BOOST_DEDUCED_TYPENAME base_type::iterator
                       iterator;
        typedef BOOST_DEDUCED_TYPENAME base_type::const_iterator
                       const_iterator;
        typedef BOOST_DEDUCED_TYPENAME base_type::size_type
                       size_type;
        typedef BOOST_DEDUCED_TYPENAME base_type::key_type
                       key_type;
        typedef BOOST_DEDUCED_TYPENAME base_type::const_reference
                       const_reference;
        typedef BOOST_DEDUCED_TYPENAME base_type::mapped_type
                    mapped_type;
        typedef BOOST_DEDUCED_TYPENAME base_type::auto_type
                    auto_type;
        typedef BOOST_DEDUCED_TYPENAME VoidPtrMultiMap::key_compare
                    key_compare;
        typedef BOOST_DEDUCED_TYPENAME VoidPtrMultiMap::allocator_type
                    allocator_type;
    private:

        void safe_insert( const key_type& key, auto_type ptr ) // strong
        {
            this->base().insert(
                           std::make_pair( key, ptr.get() ) ); // strong, commit
            ptr.release();                                     // nothrow
        }

        template< typename II >
        void map_basic_clone_and_insert( II first, II last )
        {
            while( first != last )
            {
                const_reference pair = *first.base();     // nothrow
                auto_type ptr( this->null_policy_allocate_clone( pair.second ) );
                                                          // strong
                safe_insert( pair.first,
                             boost::ptr_container::move( ptr ) );
                                                          // strong, commit
                ++first;
            }
        }

    public:

        explicit ptr_multimap_adapter( const key_compare& comp = key_compare(),
                                       const allocator_type& a = allocator_type() )
          : base_type( comp, a ) { }

        template< class InputIterator >
        ptr_multimap_adapter( InputIterator first, InputIterator last,
                              const key_compare& comp = key_compare(),
                              const allocator_type& a = allocator_type() )
          : base_type( comp, a )
        {
            map_basic_clone_and_insert( first, last );
        }

        explicit ptr_multimap_adapter( const ptr_multimap_adapter& r )
          : base_type( key_compare(), allocator_type() )
        {
            map_basic_clone_and_insert( r.begin(), r.end() );
        }

        template< class Key, class U >
        explicit ptr_multimap_adapter( const ptr_multimap_adapter<Key,U>& r )
          : base_type( key_compare(), allocator_type() )
        {
            map_basic_clone_and_insert( r.begin(), r.end() );
        }

        template< class U >
        explicit ptr_multimap_adapter( std::auto_ptr<U> r ) : base_type( r )
        { }

        ptr_multimap_adapter& operator=( const ptr_multimap_adapter& r )
        {
            ptr_multimap_adapter clone( r );
            this->swap( clone );
            return *this;
        }

        template< class Key, class U >
        ptr_multimap_adapter& operator=( const ptr_multimap_adapter<Key,U>& r )
         {
            ptr_multimap_adapter clone( r );
            this->swap( clone );
            return *this;
        }

        template< class U >
        ptr_multimap_adapter& operator=( std::auto_ptr<U> r )
        {
            base_type::operator=( r );
            return *this;
        }

        using base_type::release;

        template< typename InputIterator >
        void insert( InputIterator first, InputIterator last ) // basic
        {
            map_basic_clone_and_insert( first, last );
        }

        template< class Range >
        void insert( const Range& r )
        {
            insert( boost::begin(r), boost::end(r) );
        }

        iterator insert( key_type& key, mapped_type x ) // strong
        {
            this->enforce_null_policy( x,
                  "Null pointer in 'ptr_multimap_adapter::insert()'" );

            auto_type ptr( x );         // nothrow
            BOOST_DEDUCED_TYPENAME base_type::ptr_iterator
                res = this->base().insert( std::make_pair( key, x ) );
                                        // strong, commit
            ptr.release();              // notrow
            return iterator( res );
        }

        template< class U >
        iterator insert( key_type& key, std::auto_ptr<U> x )
        {
            return insert( key, x.release() );
        }

        template< class PtrMapAdapter >
        void transfer( BOOST_DEDUCED_TYPENAME PtrMapAdapter::iterator object,
                       PtrMapAdapter& from ) // strong
        {
            this->multi_transfer( object, from );
        }

        template< class PtrMapAdapter >
        size_type transfer( BOOST_DEDUCED_TYPENAME PtrMapAdapter::iterator first,
                            BOOST_DEDUCED_TYPENAME PtrMapAdapter::iterator last,
                            PtrMapAdapter& from ) // basic
        {
            return this->multi_transfer( first, last, from );
        }

#if defined(BOOST_NO_SFINAE) || defined(BOOST_NO_FUNCTION_TEMPLATE_ORDERING)
#else

        template<  class PtrMapAdapter, class Range >
        BOOST_DEDUCED_TYPENAME boost::disable_if< boost::is_same< Range,
                            BOOST_DEDUCED_TYPENAME PtrMapAdapter::iterator >,
                                                            size_type >::type
        transfer( const Range& r, PtrMapAdapter& from ) // basic
        {
            return transfer( boost::begin(r), boost::end(r), from );
        }

#endif
        template< class PtrMapAdapter >
        void transfer( PtrMapAdapter& from ) // basic
        {
            transfer( from.begin(), from.end(), from );
            BOOST_ASSERT( from.empty() );
        }

    };

    template< class I, class F, class S >
    inline bool is_null( const ptr_map_iterator<I,F,S>& i )
    {
        return i->second == 0;
    }

} // namespace 'boost'

#endif


text:
#ifndef OPENTISSUE_COLLISION_BVH_BOTTOM_UP_CONSTRUCTOR_BVH_DEFAULT_PRIORITY_BOTTOM_UP_POLICY_H
#define OPENTISSUE_COLLISION_BVH_BOTTOM_UP_CONSTRUCTOR_BVH_DEFAULT_PRIORITY_BOTTOM_UP_POLICY_H
//
// OpenTissue Template Library
// - A generic toolbox for physics-based modeling and simulation.
// Copyright (C) 2008 Department of Computer Science, University of Copenhagen.
//
// OTTL is licensed under zlib: http://opensource.org/licenses/zlib-license.php
//
#include <OpenTissue/configuration.h>

#include <OpenTissue/utility/utility_less_ptr.h>
#include <OpenTissue/collision/bvh/bottom_up_constructor/bvh_graph.h>
#include <OpenTissue/core/math/math_constants.h>

#include <cmath>       //Needed for fabs()

namespace OpenTissue
{
  namespace bvh
  {

    /**
    * Default Priority Bottom Up Policy.
    * This class implements a default bottom-up consruction policy. The order edges are
    * collapsed in is based on increasing priority.
    *
    * A collapse results in an update of the priorities of all edges
    * topologically affected by the change in the graph.
    */
    template<typename bvh_type>
    class DefaultPriorityBottomUpPolicy
    {
    public:

      typedef BVHGraph<bvh_type>                       graph_type;
      typedef typename graph_type::node_ptr_type       node_ptr_type;
      typedef typename graph_type::edge_ptr_type       edge_ptr_type;
      typedef typename graph_type::edge_iterator       edge_iterator;
      typedef typename graph_type::edge_ptr_iterator   edge_ptr_iterator;
      typedef typename graph_type::real_type           real_type;
      typedef typename bvh_type::volume_type           volume_type;
      typedef typename bvh_type::geometry_type         geometry_type;

    protected:

      graph_type * m_graph;  ///< Pointer to graph that is currently being worked on.

    public:

      virtual ~DefaultPriorityBottomUpPolicy(){};

    public:

      /**
      * Initialization Method.
      * This method sets up internal data structures, needed
      *  for picking edges etc..
      *
      * @param graph    A reference to the graph that the policiy
      *                 is working on.
      */
      void init(graph_type & graph)
      {
        m_graph = &graph;
        edge_ptr_iterator edge = m_graph->edge_ptr_begin();
        edge_ptr_iterator end  = m_graph->edge_ptr_end();
        for(;edge != end; ++edge)
        {
          edge_ptr_type ptr( *edge );
          ptr->priority() = priority(ptr);
        }
        update_heap();
      }

      /**
      * Update Node after Collapse.
      * This method is intendend to be called on the resulting
      * node after a collapse operation.
      *
      *
      * @param node    A pointer to the node.
      */
      void update(node_ptr_type node)
      {
        edge_ptr_iterator edge = node->edge_ptr_begin();
        edge_ptr_iterator end  = node->edge_ptr_end();
        for(; edge!=end; ++edge)
        {
          edge_ptr_type ptr( *edge );
          ptr->priority() = priority(ptr);
        }
        update_heap();
      }

      /**
      * Retrive next edge that should be collapsed.
      *
      * @return     A pointer to the graph edge that should be collapsed.
      */
      edge_ptr_type  get_next_edge() const{   return edge_ptr_type( *(m_graph->edge_ptr_begin()) ); }

      /**
      * More Edges to Collapse Query.
      *
      * @return    If the graph contains more edges that should be collapsed
      *            then the return value is true otherwise it is false.
      */
      const bool has_more_edges() const {   return (m_graph->size_edges()>0);  }

      /**
      * Create BV Decision Method.
      * This method is used by the Bottom-Up-Construction algorithm to determine
      * if an edge-collapse should result in a new BV in the BVH, or if more
      * sub-nodes are merged into the same region.
      *
      * Default implementation is based on the branching factor. See method degree().
      *
      * @param node    A pointer to the node, which is the result from a edge-collapse.
      *
      * @return        If a BV should be created then the return value is true
      *                otherwise it is false.
      */
      bool should_create_bv(node_ptr_type node){  return (  node->size_sub_nodes() >= degree()   ||  (m_graph->size_edges()+1)< degree() ); }

      /**
      * Volume Fitting Method.
      *
      * @param g0   An iterator to the first geometric primitive
      *             that should be covered by the fitted volume.
      * @param g1   An iterator to one position pass the last geometric
      *             primitive that should be covered by the fitted volume.
      * @param v0   An iterator to the first volume that should be
      *             covered by the fitted volume.
      * @param v1   An iterator to one position pass the last volume
      *             that should be covered by the fitted volume.
      *
      * @return     The fitted volume.
      */
      template<typename geometry_iterator,typename volume_iterator>
      volume_type fit(geometry_iterator g0,geometry_iterator g1,volume_iterator v0,volume_iterator v1){  return volume_type(); }

    protected:

      /**
      * Update Heap.
      * Internally used method, called whenever edge priorities
      * are changed to re-inforce heap-property.
      *
      * See method update(node_type*) and init(graph_type&) for examples of usage.
      */
      void update_heap()
      {
        //--- KE 12-10-2004: STL heap stuff does not work on list-types, unfortuantely
        //--- graph edges are stored in a list:-(
        //---
        //---    std::make_heap(m_graph->m_edges.begin(),m_graph->m_edges.end(),OpenTissue::utility::less_ptr<edge_type *>());
        //---    std::sort_heap(m_graph->m_edges.begin(),m_graph->m_edges.end(),OpenTissue::utility::less_ptr<edge_type *>());
        //---
        //--- Our solution is simply to apply a brute force sorting, it is
        //--- not very efficient, but it will get the job done.

        //std::sort(m_graph->edge_ptr_begin(), m_graph->edge_ptr_end(), OpenTissue::utility::less_ptr<edge_ptr_type>());   // TODO can not determine difference_type on iterator????
        m_graph->m_edges.sort(OpenTissue::utility::less_ptr<edge_ptr_type>());

      }

      /**
      * Edge Priority Computation.
      * This method is used to assign priorities to edges in the graph.
      *
      * Note this is a virtual-method, this means it can be overriden by
      * inhertance, such that end-user can define genric priorty strategies.
      *
      * Default stategy, tries to favor a balanced BVH.
      *
      * See method update(node_type*) and init(graph_type&) for examples of usage.
      *
      * @param edge   A pointer to the edge, from which a priority should be computed.
      *
      * @return       The priority of the specified edge.
      */
      virtual real_type priority(edge_ptr_type edge)
      {
        using std::fabs;

        real_type a = edge->A()->size_subtree();
        real_type b = edge->B()->size_subtree();
        if((edge->A()->size_edges() + edge->B()->size_edges()) == degree())
        {
          return 0;
        }
        if((edge->A()->size_edges() + edge->B()->size_edges()) > degree())
        {
          return math::detail::highest<real_type>();
        }
        return (a + b + fabs(a - b ));
      }

      /**
      * The degree (or branching factor) of BVH.
      * This method is used to decide the maximum branching factor
      * of the generated BVH.
      *
      * Note this is a virtual-method, this means it can be overriden by
      * inhertance, such that end-user can define a genric branching factor.
      *
      * See method create_bv(node_type*) for example of usage.
      *
      * @return        The branching factor.
      */
      virtual const unsigned int degree() const { return 2; }

    };

  } // namespace bvh

} // namespace OpenTissue

// OPENTISSUE_COLLISION_BVH_BOTTOM_UP_CONSTRUCTOR_BVH_DEFAULT_PRIORITY_BOTTOM_UP_POLICY_H
#endif


text:
package com.reindeercrafts.notificationpeek.blacklist;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.animation.DecelerateInterpolator;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ViewSwitcher;

import com.reindeercrafts.notificationpeek.R;
import com.reindeercrafts.notificationpeek.settings.PreferenceKeys;

/**
 * Subclass of RelativeLayout to display everything black list item's functionality:
 * - Disable Peek.
 * - Setup quiet hour.
 *
 * Created by zhelu on 5/26/14.
 */
public class EverythingCard extends RelativeLayout implements View.OnClickListener {

    private static final long ANIM_DURATION = 300;
    private static final java.lang.String DELIMITER = "|";

    private ViewSwitcher mPanelSwitcher;
    private Button mFromBtn;
    private Button mToBtn;
    private TextView mFromToText;

    private QuietHour mQuietHour;

    // Quiet hour or disable button callback.
    private OnPanelButtonClickedListener mOnPanelButtonClickedListener;

    private boolean mOptionsShowing = true;

    public void setOnPanelButtonClickedListener(OnPanelButtonClickedListener listener) {
        this.mOnPanelButtonClickedListener = listener;
    }

    public EverythingCard(Context context) {
        super(context);
    }

    public EverythingCard(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public EverythingCard(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context);
    }

    private void init(Context context) {

        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);

        boolean isPeekDisabled = preferences.getBoolean(PreferenceKeys.PREF_DISABLE_PEEK, false);
        String quietHourStr = preferences
                .getString(PreferenceKeys.PREF_QUIET_HOUR, PreferenceKeys.PREF_QUIET_HOUR_DEF);
        boolean isQuietHourSet = !quietHourStr.equals(PreferenceKeys.PREF_QUIET_HOUR_DEF);

        mOptionsShowing = !(isPeekDisabled || isQuietHourSet);
        mQuietHour = QuietHour.createQuietHour(quietHourStr);

        LayoutInflater.from(context).inflate(R.layout.everything_card, this, true);
        mPanelSwitcher = (ViewSwitcher) findViewById(R.id.view_switcher);
        if (!mOptionsShowing) {
            mPanelSwitcher.setVisibility(GONE);
        }

        mFromBtn = (Button) findViewById(R.id.quiet_hour_from_btn);
        mFromBtn.setOnClickListener(this);

        mToBtn = (Button) findViewById(R.id.quiet_hour_to_btn);
        mToBtn.setOnClickListener(this);

        Button mQuietHourBtn = (Button) findViewById(R.id.quiet_hour_btn);
        mQuietHourBtn.setOnClickListener(this);

        Button mDisableBtn = (Button) findViewById(R.id.as_is_btn);
        mDisableBtn.setOnClickListener(this);

        mFromToText = (TextView) findViewById(R.id.from_to_text);
        if (isQuietHourSet) {
            displayTime();
        }
        mFromToText.setOnClickListener(this);
    }

    /* Update instance's current "from" time. */
    public void setFromTime(int hr, int min) {
        mQuietHour.setFromTime(hr, min);

        mFromBtn.setText(mQuietHour.getFromTimeText());

        if (mQuietHour.isBothTimeSet()) {
            displayTime();
            hideOptions();
            storeQuietHour();
        }
    }

    /* Update instance's current "to" time. */
    public void setToTime(int hr, int min) {
        mQuietHour.setToTime(hr, min);

        mToBtn.setText(mQuietHour.getToTimeText());

        if (mQuietHour.isBothTimeSet()) {
            displayTime();
            hideOptions();
            storeQuietHour();
        }
    }

    /* Store instance's QuietHour object. */
    private void storeQuietHour(){
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getContext());
        preferences.edit().putString(PreferenceKeys.PREF_QUIET_HOUR, mQuietHour.toString()).apply();
    }

    private void displayTime() {
        mFromToText.setVisibility(VISIBLE);
        mFromToText.setText(mQuietHour.getDisplayTime(getContext()));
    }

    private void hideOptions() {
        if (!mOptionsShowing) {
            return;
        }

        mQuietHour.reset();
        if (mPanelSwitcher.getDisplayedChild() == 1) {
            mPanelSwitcher.showPrevious();
        }

        final int originalHeight = mPanelSwitcher.getHeight();
        ValueAnimator animator = ValueAnimator.ofInt(mPanelSwitcher.getHeight(), 0);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                ViewGroup.LayoutParams params = mPanelSwitcher.getLayoutParams();
                params.height = (Integer) animation.getAnimatedValue();
                mPanelSwitcher.setLayoutParams(params);
            }
        });

        animator.setDuration(ANIM_DURATION);
        animator.setInterpolator(new DecelerateInterpolator());
        animator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                mPanelSwitcher.setVisibility(GONE);
                ViewGroup.LayoutParams params = mPanelSwitcher.getLayoutParams();
                params.height = originalHeight;
                mPanelSwitcher.setLayoutParams(params);
                mFromBtn.setText(getContext().getString(R.string.from));
                mToBtn.setText(getContext().getString(R.string.to));
            }
        });

        animator.start();
        mOptionsShowing = false;
    }

    private void showOptions() {
        if (mOptionsShowing) {
            return;
        }
        ViewTreeObserver observer = mPanelSwitcher.getViewTreeObserver();
        observer.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                ViewTreeObserver observer= mPanelSwitcher.getViewTreeObserver();
                observer.removeOnPreDrawListener(this);
                ValueAnimator animator = ValueAnimator.ofInt(0, mPanelSwitcher.getHeight());
                animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                    @Override
                    public void onAnimationUpdate(ValueAnimator animation) {
                        ViewGroup.LayoutParams params = mPanelSwitcher.getLayoutParams();
                        params.height = (Integer) animation.getAnimatedValue();
                        mPanelSwitcher.setLayoutParams(params);
                    }
                });

                animator.setDuration(ANIM_DURATION);
                animator.setInterpolator(new DecelerateInterpolator());
                animator.start();
                return false;
            }
        });

        mPanelSwitcher.setVisibility(VISIBLE);
        mOptionsShowing = true;

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.quiet_hour_btn:
                mPanelSwitcher.showNext();
                break;

            case R.id.as_is_btn:
                if (mOnPanelButtonClickedListener != null) {
                    mOnPanelButtonClickedListener.onPanelButtonClicked(PanelButtons.BTN_DISABLE);
                }
                SharedPreferences preferences =
                        PreferenceManager.getDefaultSharedPreferences(getContext());
                preferences.edit().putBoolean(PreferenceKeys.PREF_DISABLE_PEEK, true)
                        .remove(PreferenceKeys.PREF_QUIET_HOUR).apply();

                mFromToText.setVisibility(GONE);
                hideOptions();
                break;

            case R.id.quiet_hour_from_btn:
                if (mOnPanelButtonClickedListener != null) {
                    mOnPanelButtonClickedListener
                            .onPanelButtonClicked(PanelButtons.BTN_QUIET_HOUR_FROM);
                }

                break;

            case R.id.quiet_hour_to_btn:
                if (mOnPanelButtonClickedListener != null) {
                    mOnPanelButtonClickedListener
                            .onPanelButtonClicked(PanelButtons.BTN_QUIET_HOUR_TO);
                }
                break;

            case R.id.from_to_text:
                // Toggle options panel.
                if (mOptionsShowing) {
                    hideOptions();
                } else {
                    showOptions();
                }
                break;
        }

    }

    /**
     * Callback used to associate actions to the button click event.
     */
    public interface OnPanelButtonClickedListener {
        // Called when an action button in EverythingCard is clicked.
        void onPanelButtonClicked(PanelButtons button);
    }

    /**
     * Button action types.
     */
    public enum PanelButtons {
        BTN_QUIET_HOUR_FROM,
        BTN_QUIET_HOUR_TO,
        BTN_DISABLE
    }

}


text:
/*globals Background, LinearGradient, RadialGradient, ColorStop, RGBAColor, HSLAColor*/
(function() {
  'use strict';

  var canvas  = document.querySelector( 'canvas' ),
      context = canvas.getContext( '2d' );

  var background = document.querySelector( '.gradient-view' );

  var testGradient = new LinearGradient();
  testGradient.angle = '45deg';
  testGradient.colorStops.push( new ColorStop( new RGBAColor( 255, 0, 0, 1.0 ) ) );
  testGradient.colorStops.push( new ColorStop( new RGBAColor( 255, 255, 128, 1.0 ) ) );

  var testGradient2 = new LinearGradient();
  testGradient2.colorStops.push( new ColorStop( new RGBAColor( 240, 128, 128, 1.0 ), '10%' ) );
  testGradient2.colorStops.push( new ColorStop( new RGBAColor( 127, 0, 127, 1.0 ) ) );

  var testGradient3 = new LinearGradient();
  testGradient3.angle = 'to top left';
  testGradient3.colorStops.push( new ColorStop( new RGBAColor( 128, 128, 128, 1.0 ) ) );
  testGradient3.colorStops.push( new ColorStop( new RGBAColor( 240, 128, 127, 1.0 ) ) );

  var testRadGradient = new RadialGradient();
  testRadGradient.shape = 'ellipse';
  testRadGradient.colorStops.push( new ColorStop( new HSLAColor( 0, 0, 0, 1.0 ) ) );
  testRadGradient.colorStops.push( new ColorStop( new RGBAColor( 255, 255, 255, 1.0 ) ) );

  console.log(testRadGradient.css());

  var testBackground = new Background();
  testBackground.gradients.push( testGradient );
  testBackground.gradients.push( testGradient2 );
  testBackground.gradients.push( testGradient3 );

  var css = testBackground.css();
  console.log( css );

  background.style.background = css;

  var gradients = [];

  function tick() {
    draw( context );
  }

  function draw( ctx ) {
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;

    var patternCanvas = document.createElement( 'canvas' );
    patternCanvas.width = 64;
    patternCanvas.height = 64;

    var patternCtx = patternCanvas.getContext( '2d' );
    patternCtx.moveTo( 0, 0 );
    patternCtx.lineTo( patternCanvas.width, patternCanvas.height );
    patternCtx.moveTo( patternCanvas.width, 0 );
    patternCtx.lineTo( 0, patternCanvas.height );

    patternCtx.lineWidth = 1;
    patternCtx.strokeStyle = 'rgba(255, 255, 255, 0.5)';
    patternCtx.stroke();

    ctx.fillStyle = ctx.createPattern( patternCanvas, 'repeat' );
    ctx.fillRect( 0, 0, canvas.width, canvas.height );
  }

  function randomGradient() {
    var grad = new LinearGradient();
  }

  // draw( context );
}) ();


text:
// Part of MeasurementKit <https://measurement-kit.github.io/>.
// MeasurementKit is free software. See AUTHORS and LICENSE for more
// information on the copying conditions.

#import "ViewController.h"

@implementation ViewController

- (id)init {
    self = [super init];
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    [[NSNotificationCenter defaultCenter]
     addObserver:self selector:@selector(handle_event:)
     name:@"event" object:nil];

    [[NSNotificationCenter defaultCenter]
     addObserver:self selector:@selector(test_complete)
     name:@"test_complete" object:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)runTest:(id)sender {
    /*
     * Note: after the test we will make the textViews editable to allow
     * the user to select all logs and share with us.
     */
    [self.runButton setEnabled:NO];
    [self.resultsJsonTextView setEditable:FALSE];
    [self.resultsJsonTextView setText:@"{}"];
    [self.logsTextView setEditable:FALSE];
    [self.logsTextView setText:@""];
    [NetworkMeasurement run:self.verboseSwitch.isOn];
}

-(void)handle_event:(NSNotification *)notification {
    NSDictionary *evinfo = [notification userInfo];
    if (evinfo == nil) {
        return;
    }
    //NSLog(@"Got event: %@", evinfo); // Uncomment when debugging
    NSString *key = [evinfo objectForKey:@"key"];
    NSDictionary *value = [evinfo objectForKey:@"value"];
    if (key == nil || value == nil) {
        return;
    }
    if ([key isEqualToString:@"log"]) {
        [self update_logs:value];
    } else if ([key isEqualToString:@"status.progress"]) {
        [self update_progress:value];
    } else if ([key isEqualToString:@"status.update.performance"]) {
        [self update_speed:value];
    } else if ([key isEqualToString:@"measurement"]) {
        [self update_json:value];
    } else {
        NSLog(@"unused event: %@", evinfo);
    }
}

-(void)do_update_logs:(NSString *)entry {
    self.logsTextView.text = [self.logsTextView.text
                              stringByAppendingString:[
                              entry stringByAppendingString:@"\n"]];
    [self.logsTextView
     scrollRangeToVisible:NSMakeRange([self.logsTextView.text
                                       length], 0)];
}

-(void)update_logs:(NSDictionary *)value {
    NSString *message = [value objectForKey:@"message"];
    if (message == nil) {
        return;
    }
    [self do_update_logs:message];
}

-(void)update_progress:(NSDictionary *)value {
    NSNumber *percentage = [value objectForKey:@"percentage"];
    NSString *message = [value objectForKey:@"message"];
    if (percentage == nil || message == nil) {
        return;
    }
    NSString *entry = [NSString stringWithFormat:@"[%.1f%%] %@",
                       [percentage doubleValue] * 100.0, message];
    [self do_update_logs:entry];
}

-(void)update_speed:(NSDictionary *)value {
    NSNumber *elapsed = [value objectForKey:@"elapsed"];
    NSNumber *speed = [value objectForKey:@"speed_kbps"];
    if (elapsed == nil || speed == nil) {
        return;
    }
    NSString *elapsed_unit = @"s";
    NSString *speed_unit = @"Kbit/s";
    self.statusLabel.text = [NSString stringWithFormat:@"%8.2f %@ %10.2f %@\n",
         [elapsed doubleValue], elapsed_unit, [speed doubleValue], speed_unit];
}

-(void)update_json:(NSDictionary *)value {
    NSString *entry = [value objectForKey:@"json_str"];
    if (entry == nil) {
        return;
    }
    [self.resultsJsonTextView setText:entry];
    [self.resultsJsonTextView
     scrollRangeToVisible:NSMakeRange([self.resultsJsonTextView.text
                                       length], 0)];
}

-(void)test_complete {
    [self.runButton setEnabled:YES];
    [self.resultsJsonTextView setEditable:TRUE];
    [self.logsTextView setEditable:TRUE];
}

@end


text:
package io.github.takzhanov.game.executor;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class QueryExecutor {
    private final Connection connection;

    public QueryExecutor(Connection connection) {
        this.connection = connection;
    }

    public void execUpdate(String update) throws SQLException {
        Statement stmt = connection.createStatement();
        stmt.execute(update);
        stmt.close();
    }

    public <T> T execQuery(String query, ResultHandler<T> handler) throws SQLException {
        Statement stmt = connection.createStatement();
        stmt.execute(query);
        ResultSet result = stmt.getResultSet();
        T value = handler.handle(result);
        result.close();
        stmt.close();
        return value;
    }

}


text:
// Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ash/web_applications/projector_system_web_app_info.h"

#include "ash/constants/ash_features.h"
#include "ash/constants/ash_pref_names.h"
#include "ash/webui/grit/ash_projector_app_trusted_resources.h"
#include "ash/webui/projector_app/public/cpp/projector_app_constants.h"
#include "chrome/browser/ash/web_applications/system_web_app_install_utils.h"
#include "chrome/browser/policy/profile_policy_connector.h"
#include "chrome/browser/ui/ash/projector/projector_utils.h"
#include "chrome/grit/generated_resources.h"
#include "components/prefs/pref_service.h"
#include "third_party/skia/include/core/SkColor.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/chromeos/styles/cros_styles.h"

namespace {

SkColor GetBgColor(bool use_dark_mode) {
  return cros_styles::ResolveColor(
      cros_styles::ColorName::kBgColor, use_dark_mode,
      base::FeatureList::IsEnabled(
          ash::features::kSemanticColorsDebugOverride));
}

}  // namespace

ProjectorSystemWebAppDelegate::ProjectorSystemWebAppDelegate(Profile* profile)
    : web_app::SystemWebAppDelegate(web_app::SystemAppType::PROJECTOR,
                                    "Projector",
                                    GURL(ash::kChromeUITrustedProjectorAppUrl),
                                    profile) {}

ProjectorSystemWebAppDelegate::~ProjectorSystemWebAppDelegate() = default;

std::unique_ptr<WebAppInstallInfo>
ProjectorSystemWebAppDelegate::GetWebAppInfo() const {
  auto info = std::make_unique<WebAppInstallInfo>();
  info->start_url = GURL(ash::kChromeUITrustedProjectorAppUrl);
  info->scope = GURL(ash::kChromeUITrustedProjectorAppUrl);

  info->title = l10n_util::GetStringUTF16(IDS_PROJECTOR_APP_NAME);

  // TODO(b/195127670): Add 48, 128, and 192 size icons through
  // CreateIconInfoForSystemWebApp().

  info->theme_color = GetBgColor(/*use_dark_mode=*/false);
  info->dark_mode_theme_color = GetBgColor(/*use_dark_mode=*/true);
  info->display_mode = blink::mojom::DisplayMode::kStandalone;
  info->user_display_mode = blink::mojom::DisplayMode::kStandalone;

  // TODO(b/195127670): Add info.url_handlers for https://projector.apps.chrome
  // domain. Requires web-app-origin-association file at the new domain to prove
  // cross-ownership. See
  // https://web.dev/pwa-url-handler/#the-web-app-origin-association-file.

  return info;
}

bool ProjectorSystemWebAppDelegate::ShouldCaptureNavigations() const {
  return true;
}

gfx::Size ProjectorSystemWebAppDelegate::GetMinimumWindowSize() const {
  // The minimum width matches the minimum width of the Projector viewer left
  // panel defined in the web component.
  return {222, 550};
}

bool ProjectorSystemWebAppDelegate::IsAppEnabled() const {
  if (!IsProjectorAllowedForProfile(profile_))
    return false;

  if (!profile_->GetProfilePolicyConnector()->IsManaged() ||
      profile_->IsChild()) {
    return ash::features::IsProjectorAllUserEnabled();
  }

  // Check feature availability and admin policy for managed users.
  return ash::features::IsProjectorEnabled() &&
         profile_->GetPrefs()->GetBoolean(ash::prefs::kProjectorAllowByPolicy);
}


text:
  Allow the browser to use your web cam and after that share the URL from the address bar with the people you want to talk with.

<ui-gmap-google-map center="map.center" zoom="map.zoom" draggable="true" options="options" bounds="map.bounds">
  <ui-gmap-markers models="peers" coords="'self'" icon="'icon'">
  </ui-gmap-markers>
</ui-gmap-google-map>


text:
package com.andtinder.interfaces;

public interface OnCardSwipeListener {

    void onSwipeStopped();

    void onSwipeStartedLike();

    void onSwipeStartedDislike();
}


text: A collection of scripts to be used with the Nagios monitoring solution.


text:
<Type Name="TimeoutImplementationHandler" FullName="Banshee.ServiceStack.TimeoutImplementationHandler">
  <TypeSignature Language="C#" Value="public delegate uint TimeoutImplementationHandler(uint milliseconds, TimeoutHandler handler);" />
  <TypeSignature Language="ILAsm" Value=".class public auto ansi sealed TimeoutImplementationHandler extends System.MulticastDelegate" />
  <AssemblyInfo>
    <AssemblyName>Banshee.Services</AssemblyName>
    <AssemblyVersion>0.90.1.25404</AssemblyVersion>
    <AssemblyVersion>1.3.1.0</AssemblyVersion>
    <AssemblyVersion>1.4.0.0</AssemblyVersion>
    <AssemblyVersion>2.4.0.0</AssemblyVersion>
  </AssemblyInfo>
  <Base>
    <BaseTypeName>System.Delegate</BaseTypeName>
  </Base>
  <Parameters>
    <Parameter Name="milliseconds" Type="System.UInt32" />
    <Parameter Name="handler" Type="Banshee.ServiceStack.TimeoutHandler" />
  </Parameters>
  <ReturnValue>
    <ReturnType>System.UInt32</ReturnType>
  </ReturnValue>
  <Docs>
    <param name="milliseconds">To be added.</param>
    <param name="handler">To be added.</param>
    <summary>To be added.</summary>
    <returns>To be added.</returns>
    <remarks>To be added.</remarks>
  </Docs>
</Type>


text:
package com.jpattern.service.log;

/**
 *
 * @author Francesco Cina'
 *
 * 12/ago/2010
 */
public class ErrorLoggerServiceIgnorePathStrategy implements ILoggerServiceIgnorePathStrategy {

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	public void ignorePath(ILoggerService loggerService, String path) {
		loggerService.setErrorLoggerLevel(path);
	}

}


text:
'use babel';

import { BreakpointManager } from './breakpoint';
import { ProjectManager } from './Project';

export namespace XAtom {
  export const breakpoints = new BreakpointManager();
  export const project = new ProjectManager();
}