text:
/* cJSON */
/* JSON parser in C. */

#include <string.h>
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <float.h>
#include <limits.h>
#include <ctype.h>
#include "cJSON.h"

static const char *ep;

const char *cJSON_GetErrorPtr(void) {return ep;}

static int cJSON_strcasecmp(const char *s1, const char *s2)
{
  if (!s1) return (s1 == s2) ? 0 : 1; if (!s2) return 1;
  for (; tolower(*s1) == tolower(*s2); ++s1, ++s2) if (*s1 == 0)  return 0;
  return tolower(*(const unsigned char *)s1) - tolower(*(const unsigned char *)s2);
}

static void *(*cJSON_malloc)(size_t sz) = malloc;
static void (*cJSON_free)(void *ptr) = free;

static char *cJSON_strdup(const char *str)
{
  size_t len;
  char *copy;

  len = strlen(str) + 1;
  if (!(copy = (char *)cJSON_malloc(len))) return 0;
  memcpy(copy, str, len);
  return copy;
}

void cJSON_InitHooks(cJSON_Hooks *hooks)
{
  if (!hooks)   /* Reset hooks */
  {
    cJSON_malloc = malloc;
    cJSON_free = free;
    return;
  }

  cJSON_malloc = (hooks->malloc_fn) ? hooks->malloc_fn : malloc;
  cJSON_free   = (hooks->free_fn) ? hooks->free_fn : free;
}

/* Internal constructor. */
static cJSON *cJSON_New_Item(void)
{
  cJSON *node = (cJSON *)cJSON_malloc(sizeof(cJSON));
  if (node) memset(node, 0, sizeof(cJSON));
  return node;
}

/* Delete a cJSON structure. */
void cJSON_Delete(cJSON *c)
{
  cJSON *next;
  while (c)
  {
    next = c->next;
    if (!(c->type & cJSON_IsReference) && c->child) cJSON_Delete(c->child);
    if (!(c->type & cJSON_IsReference) && c->valuestring) cJSON_free(c->valuestring);
    if (c->string) cJSON_free(c->string);
    cJSON_free(c);
    c = next;
  }
}

/* Parse the input text to generate a number, and populate the result into item. */
static const char *parse_number(cJSON *item, const char *num)
{
  double n = 0, sign = 1, scale = 0; int subscale = 0, signsubscale = 1;

  if (*num == '-') sign = -1, num++; /* Has sign? */
  if (*num == '0') num++;   /* is zero */
    if (*num >= '1' && *num <= '9') do  n = (n * 10.0) + (*num++ -'0'); while (*num >= '0' && *num <= '9'); /* Number? */
  if (*num == '.' && num[1] >= '0' && num[1] <= '9') {num++;    do  n = (n * 10.0) + (*num++ -'0'), scale--; while (*num >= '0' && *num <= '9');} /* Fractional part? */
  if (*num == 'e' || *num == 'E') /* Exponent? */
  {
    num++; if (*num == '+') num++; else if (*num == '-') signsubscale = -1, num++; /* With sign? */
    while (*num >= '0' && *num <= '9') subscale = (subscale * 10) + (*num++ - '0'); /* Number? */
  }

  n = sign * n * pow(10.0, (scale + subscale * signsubscale)); /* number = +/- number.fraction * 10^+/- exponent */

  item->valuedouble = n;
  item->valueint = (int)n;
  item->type = cJSON_Number;
  return num;
}

/* Render the number nicely from the given item into a string. */
static char *print_number(cJSON *item)
{
  char *str;
  double d = item->valuedouble;
  if (fabs(((double)item->valueint) - d) <= DBL_EPSILON && d <= INT_MAX && d >= INT_MIN)
  {
    str = (char *)cJSON_malloc(21); /* 2^64+1 can be represented in 21 chars. */
    if (str) sprintf(str, "%d", item->valueint);
  }
  else
  {
    str = (char *)cJSON_malloc(64); /* This is a nice tradeoff. */
    if (str)
    {
      if (fabs(floor(d) - d) <= DBL_EPSILON && fabs(d) < 1.0e60)sprintf(str, "%.0f", d);
      else if (fabs(d) < 1.0e-6 || fabs(d) > 1.0e9)     sprintf(str, "%e", d);
      else                        sprintf(str, "%f", d);
    }
  }
  return str;
}

static unsigned parse_hex4(const char *str)
{
  unsigned h = 0;
  if (*str >= '0' && *str <= '9') h += (*str) - '0'; else if (*str >= 'A' && *str <= 'F') h += 10 + (*str) - 'A'; else if (*str >= 'a' && *str <= 'f') h += 10 + (*str) - 'a'; else return 0;
  h = h << 4; str++;
  if (*str >= '0' && *str <= '9') h += (*str) - '0'; else if (*str >= 'A' && *str <= 'F') h += 10 + (*str) - 'A'; else if (*str >= 'a' && *str <= 'f') h += 10 + (*str) - 'a'; else return 0;
  h = h << 4; str++;
  if (*str >= '0' && *str <= '9') h += (*str) - '0'; else if (*str >= 'A' && *str <= 'F') h += 10 + (*str) - 'A'; else if (*str >= 'a' && *str <= 'f') h += 10 + (*str) - 'a'; else return 0;
  h = h << 4; str++;
  if (*str >= '0' && *str <= '9') h += (*str) - '0'; else if (*str >= 'A' && *str <= 'F') h += 10 + (*str) - 'A'; else if (*str >= 'a' && *str <= 'f') h += 10 + (*str) - 'a'; else return 0;
  return h;
}

/* Parse the input text into an unescaped cstring, and populate item. */
static const unsigned char firstByteMark[7] = { 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC };
static const char *parse_string(cJSON *item, const char *str)
{
  const char *ptr = str + 1; char *ptr2; char *out; int len = 0; unsigned uc, uc2;
  if (*str != '\"') {ep = str; return 0;} /* not a string! */

  while (*ptr != '\"' && *ptr && ++len) if (*ptr++ == '\\') ptr++; /* Skip escaped quotes. */

  out = (char *)cJSON_malloc(len + 1); /* This is how long we need for the string, roughly. */
  if (!out) return 0;

  ptr = str + 1; ptr2 = out;
  while (*ptr != '\"' && *ptr)
  {
    if (*ptr != '\\') *ptr2++ = *ptr++;
    else
    {
      ptr++;
      switch (*ptr)
      {
        case 'b': *ptr2++ = '\b'; break;
        case 'f': *ptr2++ = '\f'; break;
        case 'n': *ptr2++ = '\n'; break;
        case 'r': *ptr2++ = '\r'; break;
        case 't': *ptr2++ = '\t'; break;
        case 'u':  /* transcode utf16 to utf8. */
          uc = parse_hex4(ptr + 1); ptr += 4; /* get the unicode char. */

          if ((uc >= 0xDC00 && uc <= 0xDFFF) || uc == 0)  break; /* check for invalid. */

          if (uc >= 0xD800 && uc <= 0xDBFF) /* UTF16 surrogate pairs. */
          {
            if (ptr[1] != '\\' || ptr[2] != 'u')  break; /* missing second-half of surrogate.  */
            uc2 = parse_hex4(ptr + 3); ptr += 6;
            if (uc2 < 0xDC00 || uc2 > 0xDFFF)   break; /* invalid second-half of surrogate.  */
            uc = 0x10000 + (((uc & 0x3FF) << 10) | (uc2 & 0x3FF));
          }

          len = 4; if (uc < 0x80) len = 1; else if (uc < 0x800) len = 2; else if (uc < 0x10000) len = 3; ptr2 += len;

          switch (len)
          {
            case 4: *--ptr2 = ((uc | 0x80) & 0xBF); uc >>= 6;
            case 3: *--ptr2 = ((uc | 0x80) & 0xBF); uc >>= 6;
            case 2: *--ptr2 = ((uc | 0x80) & 0xBF); uc >>= 6;
            case 1: *--ptr2 = (uc | firstByteMark[len]);
          }
          ptr2 += len;
          break;
        default:  *ptr2++ = *ptr; break;
      }
      ptr++;
    }
  }
  *ptr2 = 0;
  if (*ptr == '\"') ptr++;
  item->valuestring = out;
  item->type = cJSON_String;
  return ptr;
}

/* Render the cstring provided to an escaped version that can be printed. */
static char *print_string_ptr(const char *str)
{
  const char *ptr; char *ptr2, *out; int len = 0; unsigned char token;

  if (!str) return cJSON_strdup("");
  ptr = str; while ((token = *ptr) && ++len) {if (strchr("\"\\\b\f\n\r\t", token)) len++; else if (token < 32) len += 5; ptr++;}

  out = (char *)cJSON_malloc(len + 3);
  if (!out) return 0;

  ptr2 = out; ptr = str;
  *ptr2++ = '\"';
  while (*ptr)
  {
    if ((unsigned char)*ptr > 31 && *ptr != '\"' && *ptr != '\\') *ptr2++ = *ptr++;
    else
    {
      *ptr2++ = '\\';
      switch (token = *ptr++)
      {
        case '\\':  *ptr2++ = '\\'; break;
        case '\"':  *ptr2++ = '\"'; break;
        case '\b':  *ptr2++ = 'b';  break;
        case '\f':  *ptr2++ = 'f';  break;
        case '\n':  *ptr2++ = 'n';  break;
        case '\r':  *ptr2++ = 'r';  break;
        case '\t':  *ptr2++ = 't';  break;
        default: sprintf(ptr2, "u%04x", token); ptr2 += 5; break; /* escape and print */
      }
    }
  }
  *ptr2++ = '\"'; *ptr2++ = 0;
  return out;
}
/* Invote print_string_ptr (which is useful) on an item. */
static char *print_string(cJSON *item)  {return print_string_ptr(item->valuestring);}

/* Predeclare these prototypes. */
static const char *parse_value(cJSON *item, const char *value);
static char *print_value(cJSON *item, int depth, int fmt);
static const char *parse_array(cJSON *item, const char *value);
static char *print_array(cJSON *item, int depth, int fmt);
static const char *parse_object(cJSON *item, const char *value);
static char *print_object(cJSON *item, int depth, int fmt);

/* Utility to jump whitespace and cr/lf */
static const char *skip(const char *in) {while (in && *in && (unsigned char)*in <= 32) in++; return in;}

/* Parse an object - create a new root, and populate. */
cJSON *cJSON_ParseWithOpts(const char *value, const char **return_parse_end, int require_null_terminated)
{
  const char *end = 0;
  cJSON *c = cJSON_New_Item();
  ep = 0;
  if (!c) return 0;       /* memory fail */

  end = parse_value(c, skip(value));
  if (!end) {cJSON_Delete(c); return 0;} /* parse failure. ep is set. */

  /* if we require null-terminated JSON without appended garbage, skip and then check for a null terminator */
  if (require_null_terminated) {end = skip(end); if (*end) {cJSON_Delete(c); ep = end; return 0;}}
  if (return_parse_end) *return_parse_end = end;
  return c;
}
/* Default options for cJSON_Parse */
cJSON *cJSON_Parse(const char *value) {return cJSON_ParseWithOpts(value, 0, 0);}

/* Render a cJSON item/entity/structure to text. */
char *cJSON_Print(cJSON *item)        {return print_value(item, 0, 1);}
char *cJSON_PrintUnformatted(cJSON *item) {return print_value(item, 0, 0);}

/* Parser core - when encountering text, process appropriately. */
static const char *parse_value(cJSON *item, const char *value)
{
  if (!value)           return 0; /* Fail on null. */
  if (!strncmp(value, "null", 4)) { item->type = cJSON_NULL;  return value + 4; }
  if (!strncmp(value, "false", 5))  { item->type = cJSON_False; return value + 5; }
  if (!strncmp(value, "true", 4)) { item->type = cJSON_True; item->valueint = 1;  return value + 4; }
  if (*value == '\"')       { return parse_string(item, value); }
  if (*value == '-' || (*value >= '0' && *value <= '9'))  { return parse_number(item, value); }
  if (*value == '[')        { return parse_array(item, value); }
  if (*value == '{')        { return parse_object(item, value); }

  ep = value; return 0; /* failure. */
}

/* Render a value to text. */
static char *print_value(cJSON *item, int depth, int fmt)
{
  char *out = 0;
  if (!item) return 0;
  switch ((item->type) & 255)
  {
    case cJSON_NULL:  out = cJSON_strdup("null"); break;
    case cJSON_False: out = cJSON_strdup("false"); break;
    case cJSON_True:  out = cJSON_strdup("true"); break;
    case cJSON_Number:  out = print_number(item); break;
    case cJSON_String:  out = print_string(item); break;
    case cJSON_Array: out = print_array(item, depth, fmt); break;
    case cJSON_Object:  out = print_object(item, depth, fmt); break;
  }
  return out;
}

/* Build an array from input text. */
static const char *parse_array(cJSON *item, const char *value)
{
  cJSON *child;
  if (*value != '[')  {ep = value; return 0;} /* not an array! */

  item->type = cJSON_Array;
  value = skip(value + 1);
  if (*value == ']') return value + 1; /* empty array. */

  item->child = child = cJSON_New_Item();
  if (!item->child) return 0;    /* memory fail */
  value = skip(parse_value(child, skip(value))); /* skip any spacing, get the value. */
  if (!value) return 0;

  while (*value == ',')
  {
    cJSON *new_item;
    if (!(new_item = cJSON_New_Item())) return 0; /* memory fail */
    child->next = new_item; new_item->prev = child; child = new_item;
    value = skip(parse_value(child, skip(value + 1)));
    if (!value) return 0; /* memory fail */
  }

  if (*value == ']') return value + 1; /* end of array */
  ep = value; return 0; /* malformed. */
}

/* Render an array to text */
static char *print_array(cJSON *item, int depth, int fmt)
{
  char **entries;
  char *out = 0, *ptr, *ret; int len = 5;
  cJSON *child = item->child;
  int numentries = 0, i = 0, fail = 0;

  /* How many entries in the array? */
  while (child) numentries++, child = child->next;
  /* Explicitly handle numentries==0 */
  if (!numentries)
  {
    out = (char *)cJSON_malloc(3);
    if (out) strcpy(out, "[]");
    return out;
  }
  /* Allocate an array to hold the values for each */
  entries = (char **)cJSON_malloc(numentries * sizeof(char *));
  if (!entries) return 0;
  memset(entries, 0, numentries * sizeof(char *));
  /* Retrieve all the results: */
  child = item->child;
  while (child && !fail)
  {
    ret = print_value(child, depth + 1, fmt);
    entries[i++] = ret;
    if (ret) len += strlen(ret) + 2 + (fmt ? 1 : 0); else fail = 1;
    child = child->next;
  }

  /* If we didn't fail, try to malloc the output string */
  if (!fail) out = (char *)cJSON_malloc(len);
  /* If that fails, we fail. */
  if (!out) fail = 1;

  /* Handle failure. */
  if (fail)
  {
    for (i = 0; i < numentries; i++) if (entries[i]) cJSON_free(entries[i]);
    cJSON_free(entries);
    return 0;
  }

  /* Compose the output array. */
  *out = '[';
  ptr = out + 1; *ptr = 0;
  for (i = 0; i < numentries; i++)
  {
    strcpy(ptr, entries[i]); ptr += strlen(entries[i]);
    if (i != numentries - 1) {*ptr++ = ','; if (fmt)*ptr++ = ' '; *ptr = 0;}
    cJSON_free(entries[i]);
  }
  cJSON_free(entries);
  *ptr++ = ']'; *ptr++ = 0;
  return out;
}

/* Build an object from the text. */
static const char *parse_object(cJSON *item, const char *value)
{
  cJSON *child;
  if (*value != '{')  {ep = value; return 0;} /* not an object! */

  item->type = cJSON_Object;
  value = skip(value + 1);
  if (*value == '}') return value + 1; /* empty array. */

  item->child = child = cJSON_New_Item();
  if (!item->child) return 0;
  value = skip(parse_string(child, skip(value)));
  if (!value) return 0;
  child->string = child->valuestring; child->valuestring = 0;
  if (*value != ':') {ep = value; return 0;} /* fail! */
  value = skip(parse_value(child, skip(value + 1))); /* skip any spacing, get the value. */
  if (!value) return 0;

  while (*value == ',')
  {
    cJSON *new_item;
    if (!(new_item = cJSON_New_Item())) return 0; /* memory fail */
    child->next = new_item; new_item->prev = child; child = new_item;
    value = skip(parse_string(child, skip(value + 1)));
    if (!value) return 0;
    child->string = child->valuestring; child->valuestring = 0;
    if (*value != ':') {ep = value; return 0;} /* fail! */
    value = skip(parse_value(child, skip(value + 1))); /* skip any spacing, get the value. */
    if (!value) return 0;
  }

  if (*value == '}') return value + 1; /* end of array */
  ep = value; return 0; /* malformed. */
}

/* Render an object to text. */
static char *print_object(cJSON *item, int depth, int fmt)
{
  char **entries = 0, **names = 0;
  char *out = 0, *ptr, *ret, *str; int len = 7, i = 0, j;
  cJSON *child = item->child;
  int numentries = 0, fail = 0;
  /* Count the number of entries. */
  while (child) numentries++, child = child->next;
  /* Explicitly handle empty object case */
  if (!numentries)
  {
    out = (char *)cJSON_malloc(fmt ? depth + 4 : 3);
    if (!out) return 0;
    ptr = out; *ptr++ = '{';
    if (fmt) {*ptr++ = '\n'; for (i = 0; i < depth - 1; i++) *ptr++ = '\t';}
    *ptr++ = '}'; *ptr++ = 0;
    return out;
  }
  /* Allocate space for the names and the objects */
  entries = (char **)cJSON_malloc(numentries * sizeof(char *));
  if (!entries) return 0;
  names = (char **)cJSON_malloc(numentries * sizeof(char *));
  if (!names) {cJSON_free(entries); return 0;}
  memset(entries, 0, sizeof(char *)*numentries);
  memset(names, 0, sizeof(char *)*numentries);

  /* Collect all the results into our arrays: */
  child = item->child; depth++; if (fmt) len += depth;
  while (child)
  {
    names[i] = str = print_string_ptr(child->string);
    entries[i++] = ret = print_value(child, depth, fmt);
    if (str && ret) len += strlen(ret) + strlen(str) + 2 + (fmt ? 2 + depth : 0); else fail = 1;
    child = child->next;
  }

  /* Try to allocate the output string */
  if (!fail) out = (char *)cJSON_malloc(len);
  if (!out) fail = 1;

  /* Handle failure */
  if (fail)
  {
    for (i = 0; i < numentries; i++) {if (names[i]) cJSON_free(names[i]); if (entries[i]) cJSON_free(entries[i]);}
    cJSON_free(names); cJSON_free(entries);
    return 0;
  }

  /* Compose the output: */
  *out = '{'; ptr = out + 1; if (fmt)*ptr++ = '\n'; *ptr = 0;
  for (i = 0; i < numentries; i++)
  {
    if (fmt) for (j = 0; j < depth; j++) *ptr++ = '\t';
    strcpy(ptr, names[i]); ptr += strlen(names[i]);
    *ptr++ = ':'; if (fmt) *ptr++ = '\t';
    strcpy(ptr, entries[i]); ptr += strlen(entries[i]);
    if (i != numentries - 1) *ptr++ = ',';
    if (fmt) *ptr++ = '\n'; *ptr = 0;
    cJSON_free(names[i]); cJSON_free(entries[i]);
  }

  cJSON_free(names); cJSON_free(entries);
  if (fmt) for (i = 0; i < depth - 1; i++) *ptr++ = '\t';
  *ptr++ = '}'; *ptr++ = 0;
  return out;
}

/* Get Array size/item / object item. */
int    cJSON_GetArraySize(cJSON *array)             {cJSON *c = array->child; int i = 0; while (c)i++, c = c->next; return i;}
cJSON *cJSON_GetArrayItem(cJSON *array, int item)        {cJSON *c = array->child;  while (c && item > 0) item--, c = c->next; return c;}
cJSON *cJSON_GetObjectItem(cJSON *object, const char *string)  {cJSON *c = object->child; while (c && cJSON_strcasecmp(c->string, string)) c = c->next; return c;}

/* Utility for array list handling. */
static void suffix_object(cJSON *prev, cJSON *item) {prev->next = item; item->prev = prev;}
/* Utility for handling references. */
static cJSON *create_reference(cJSON *item) {cJSON *ref = cJSON_New_Item(); if (!ref) return 0; memcpy(ref, item, sizeof(cJSON)); ref->string = 0; ref->type |= cJSON_IsReference; ref->next = ref->prev = 0; return ref;}

/* Add item to array/object. */
void   cJSON_AddItemToArray(cJSON *array, cJSON *item)            {cJSON *c = array->child; if (!item) return; if (!c) {array->child = item;} else {while (c && c->next) c = c->next; suffix_object(c, item);}}
void   cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item)  {if (!item) return; if (item->string) cJSON_free(item->string); item->string = cJSON_strdup(string); cJSON_AddItemToArray(object, item);}
void  cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item)            {cJSON_AddItemToArray(array, create_reference(item));}
void  cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item)  {cJSON_AddItemToObject(object, string, create_reference(item));}

cJSON *cJSON_DetachItemFromArray(cJSON *array, int which)
{
  cJSON *c = array->child; while (c && which > 0) c = c->next, which--; if (!c) return 0;
  if (c->prev) c->prev->next = c->next; if (c->next) c->next->prev = c->prev; if (c == array->child) array->child = c->next; c->prev = c->next = 0; return c;
}
void   cJSON_DeleteItemFromArray(cJSON *array, int which)      {cJSON_Delete(cJSON_DetachItemFromArray(array, which));}
cJSON *cJSON_DetachItemFromObject(cJSON *object, const char *string) {int i = 0; cJSON *c = object->child; while (c && cJSON_strcasecmp(c->string, string)) i++, c = c->next; if (c) return cJSON_DetachItemFromArray(object, i); return 0;}
void   cJSON_DeleteItemFromObject(cJSON *object, const char *string) {cJSON_Delete(cJSON_DetachItemFromObject(object, string));}

/* Replace array/object items with new ones. */
void   cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem)
{
  cJSON *c = array->child; while (c && which > 0) c = c->next, which--; if (!c) return;
  newitem->next = c->next; newitem->prev = c->prev; if (newitem->next) newitem->next->prev = newitem;
  if (c == array->child) array->child = newitem; else newitem->prev->next = newitem; c->next = c->prev = 0; cJSON_Delete(c);
}
void   cJSON_ReplaceItemInObject(cJSON *object, const char *string, cJSON *newitem) {int i = 0; cJSON *c = object->child; while (c && cJSON_strcasecmp(c->string, string))i++, c = c->next; if (c) {newitem->string = cJSON_strdup(string); cJSON_ReplaceItemInArray(object, i, newitem);}}

/* Create basic types: */
cJSON *cJSON_CreateNull(void)         {cJSON *item = cJSON_New_Item(); if (item)item->type = cJSON_NULL; return item;}
cJSON *cJSON_CreateTrue(void)         {cJSON *item = cJSON_New_Item(); if (item)item->type = cJSON_True; return item;}
cJSON *cJSON_CreateFalse(void)          {cJSON *item = cJSON_New_Item(); if (item)item->type = cJSON_False; return item;}
cJSON *cJSON_CreateBool(int b)          {cJSON *item = cJSON_New_Item(); if (item)item->type = b ? cJSON_True : cJSON_False; return item;}
cJSON *cJSON_CreateNumber(double num)     {cJSON *item = cJSON_New_Item(); if (item) {item->type = cJSON_Number; item->valuedouble = num; item->valueint = (int)num;} return item;}
cJSON *cJSON_CreateString(const char *string) {cJSON *item = cJSON_New_Item(); if (item) {item->type = cJSON_String; item->valuestring = cJSON_strdup(string);} return item;}
cJSON *cJSON_CreateArray(void)          {cJSON *item = cJSON_New_Item(); if (item)item->type = cJSON_Array; return item;}
cJSON *cJSON_CreateObject(void)         {cJSON *item = cJSON_New_Item(); if (item)item->type = cJSON_Object; return item;}

/* Create Arrays: */
cJSON *cJSON_CreateIntArray(const int *numbers, int count)   {int i; cJSON *n = 0, *p = 0, *a = cJSON_CreateArray(); for (i = 0; a && i < count; i++) {n = cJSON_CreateNumber(numbers[i]); if (!i)a->child = n; else suffix_object(p, n); p = n;} return a;}
cJSON *cJSON_CreateFloatArray(const float *numbers, int count) {int i; cJSON *n = 0, *p = 0, *a = cJSON_CreateArray(); for (i = 0; a && i < count; i++) {n = cJSON_CreateNumber(numbers[i]); if (!i)a->child = n; else suffix_object(p, n); p = n;} return a;}
cJSON *cJSON_CreateDoubleArray(const double *numbers, int count) {int i; cJSON *n = 0, *p = 0, *a = cJSON_CreateArray(); for (i = 0; a && i < count; i++) {n = cJSON_CreateNumber(numbers[i]); if (!i)a->child = n; else suffix_object(p, n); p = n;} return a;}
cJSON *cJSON_CreateStringArray(const char **strings, int count)  {int i; cJSON *n = 0, *p = 0, *a = cJSON_CreateArray(); for (i = 0; a && i < count; i++) {n = cJSON_CreateString(strings[i]); if (!i)a->child = n; else suffix_object(p, n); p = n;} return a;}

/* Duplication */
cJSON *cJSON_Duplicate(cJSON *item, int recurse)
{
  cJSON *newitem, *cptr, *nptr = 0, *newchild;
  /* Bail on bad ptr */
  if (!item) return 0;
  /* Create new item */
  newitem = cJSON_New_Item();
  if (!newitem) return 0;
  /* Copy over all vars */
  newitem->type = item->type & (~cJSON_IsReference), newitem->valueint = item->valueint, newitem->valuedouble = item->valuedouble;
  if (item->valuestring)  {newitem->valuestring = cJSON_strdup(item->valuestring);  if (!newitem->valuestring)  {cJSON_Delete(newitem); return 0;}}
  if (item->string)   {newitem->string = cJSON_strdup(item->string);      if (!newitem->string)   {cJSON_Delete(newitem); return 0;}}
  /* If non-recursive, then we're done! */
  if (!recurse) return newitem;
  /* Walk the ->next chain for the child. */
  cptr = item->child;
  while (cptr)
  {
    newchild = cJSON_Duplicate(cptr, 1); /* Duplicate (with recurse) each item in the ->next chain */
    if (!newchild) {cJSON_Delete(newitem); return 0;}
    if (nptr) {nptr->next = newchild, newchild->prev = nptr; nptr = newchild;} /* If newitem->child already set, then crosswire ->prev and ->next and move on */
    else    {newitem->child = newchild; nptr = newchild;}     /* Set newitem->child and move to it */
    cptr = cptr->next;
  }
  return newitem;
}

void cJSON_Minify(char *json)
{
  char *into = json;
  while (*json)
  {
    if (*json == ' ') json++;
    else if (*json == '\t') json++; // Whitespace characters.
    else if (*json == '\r') json++;
    else if (*json == '\n') json++;
    else if (*json == '/' && json[1] == '/')  while (*json && *json != '\n') json++; // double-slash comments, to end of line.
    else if (*json == '/' && json[1] == '*') {while (*json && !(*json == '*' && json[1] == '/')) json++; json += 2;} // multiline comments.
    else if (*json == '\"') {*into++ = *json++; while (*json && *json != '\"') {if (*json == '\\') *into++ = *json++; *into++ = *json++;}*into++ = *json++;} // string literals, which are \" sensitive.
    else *into++ = *json++;   // All other characters.
  }
  *into = 0; // and null-terminate.
}


text:
import {RangeExpr} from "src/expr/RangeExpr";
import {ExprEnv} from "src/exprEnv";

export class MaExpr extends RangeExpr {
  calcResult(index: number, resultA: number) {
    if (this._range == 0)
      return NaN;
    var first = ExprEnv.get().getFirstIndex();
    if (first < 0)
      return resultA;
    if (index > first) {
      var n = this._range;
      if (n >= index + 1 - first) {
        n = index + 1 - first;
        return this._buf[index - 1].result * (1.0 - 1.0 / n) + (resultA / n);
      }
      return this._buf[index - 1].result + (resultA - this._buf[index - n].resultA) / n;
    } else {
      return resultA;
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<CustomFieldTranslation xmlns="http://soap.sforce.com/2006/04/metadata">
    <name>Do_Not_Contact__c</name>
    <help>Geeft aan dat deze persoon niet wil dat uw organisatie belt of e-mailt. Gebruik dit veld om contactpersonen weg te filteren uit e-mail- en telefoonlijsten.</help>
    <label>Geen contact opnemen</label>
</CustomFieldTranslation>


text:
function sendMessageToAllClients(command, message) {
  clients.matchAll({ type: 'window' }).then(function(windowClients) {
    windowClients.forEach(function(windowClient) {
      windowClient.postMessage({ command: command, message: message || '' });
    });
  });
}

self.addEventListener('install', function(event) {
  event.waitUntil(skipWaiting());
});

self.addEventListener('activate', function(event) {
  event.waitUntil(clients.claim());
});

// Receives commands originating from the page, for example to subscribe from the worker.
self.addEventListener('message', function(event) {
  switch (event.data.command) {
    case 'subscribe':
      var subscriptionOptions = event.data.subscriptionOptions;
      if (subscriptionOptions.hasOwnProperty('applicationServerKey')) {
        subscriptionOptions.applicationServerKey =
            new Uint8Array(subscriptionOptions.applicationServerKey);
      }

      registration.pushManager.subscribe(subscriptionOptions).then(function(subscription) {
        sendMessageToAllClients('subscribe-success');

      }).catch(function(error) {
        sendMessageToAllClients('subscribe-failure', '' + error);

      });

      break;

    case 'unsubscribe':
      registration.pushManager.getSubscription().then(function(subscription) {
        if (subscription)
          return subscription.unsubscribe();

      }).then(function() {
        sendMessageToAllClients('unsubscribe-success');

      }).catch(function(error) {
        sendMessageToAllClients('unsubscribe-failure', '' + error);

      });
  }
});

self.addEventListener('push', function(event) {
  var message = '[empty payload]';

  if (event.data)
    message = 'payload: ' + event.data.text();

  event.waitUntil(
    registration.showNotification('Push Generator', {
      body: message
    })
  );
});


text: "C:\Windows\Microsoft.NET\Framework\v4.0.30319\regasm.exe" netutilities.dll /codebase


text:
package org.apache.activemq.artemis.spi.core.remoting;

/**
 * A ConnectionLifeCycleListener is called by the remoting implementation to notify of connection events.
 * @deprecated use {@link ClientConnectionLifeCycleListener} instead.
 */
@Deprecated
public interface ConnectionLifeCycleListener extends BaseConnectionLifeCycleListener<String> {

}


text:
"""Implementation of an interactive wizard widget."""
from grr.gui import renderers
from grr.gui.plugins import forms
from grr.lib import aff4

class WizardRenderer(renderers.TemplateRenderer):
  """This renderer creates a wizard."""

  render_as_modal = True
  current_page = 0

  # WizardPage objects that defined this wizard's behaviour.
  title = ""
  pages = []

  # This will be used for identifying the wizard when publishing the events.
  wizard_name = "wizard"

  layout_template = renderers.Template("""

{% if this.render_as_modal %}
{% endif %}

{% for i, page, page_cls, page_renderer in this.raw_pages %}

      <button type="button" class="close" data-dismiss="modal"
        aria-hidden="true">x</button>

{{this.title|escape}} -

         {{page_cls.description|escape}}

     {{page|safe}}

{% endfor %}

      <button class="btn btn-default Back" style='display: none'>Back</button>
      <button class="btn btn-primary Next">Next</button>
      <button class="btn btn-primary Finish" style='display: none'
        data-dismiss="modal"
      >
        Finish
      </button>

{% if this.render_as_modal %}
{% endif %}

""")

  def Layout(self, request, response):
    """Render the content of the tab or the container tabset."""
    self.raw_pages = []
    for i, page_cls in enumerate(self.pages):
      # Make the page renderers dump all their data to the wizard DOM node.
      page_renderer = page_cls(id="Page_%d" % i)
      self.raw_pages.append((i, page_renderer.RawHTML(request),
                             page_cls, page_cls.__name__))

    self.max_pages = len(self.pages) - 1
    super(WizardRenderer, self).Layout(request, response)

    return self.CallJavascript(response, "WizardRenderer.Layout")

class AFF4AttributeFormRenderer(forms.TypeDescriptorFormRenderer):
  """A renderer for AFF4 attribute forms."""

  type = aff4.AFF4Attribute

  layout_template = """

""" + forms.TypeDescriptorFormRenderer.default_description_view + """

<select id="{{this.prefix}}" class="unset"
  onchange="grr.forms.inputOnChange(this)"
  >
{% for name in this.attributes %}
 {% if name %}
   <option {% ifequal name this.value %}selected{% endifequal %}
     value="{{name|escape}}">
     {{name|escape}}
     {% ifequal name this.value %} (default){% endifequal %}
   </option>
 {% endif %}
{% endfor %}
</select>

"""

  def __init__(self, **kwargs):
    super(AFF4AttributeFormRenderer, self).__init__(**kwargs)
    self.attributes = ["Unset"]
    self.attributes.extend(sorted(aff4.Attribute.NAMES.keys()))


text:
package org.apereo.cas.adaptors.generic;

import org.apereo.cas.authentication.CoreAuthenticationTestUtils;
import org.apereo.cas.authentication.HttpBasedServiceCredential;
import org.apereo.cas.authentication.PreventedException;
import org.apereo.cas.authentication.UsernamePasswordCredential;
import org.apereo.cas.configuration.model.core.authentication.PasswordEncoderProperties;
import org.apereo.cas.configuration.support.Beans;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.core.io.ClassPathResource;

import javax.security.auth.login.AccountNotFoundException;
import javax.security.auth.login.FailedLoginException;
import java.net.MalformedURLException;
import java.net.URL;

import static org.junit.Assert.*;

/**
 * @author Scott Battaglia
 * @since 3.0.0
 */
public class FileAuthenticationHandlerTests {

    @Rule
    public ExpectedException thrown = ExpectedException.none();

    private FileAuthenticationHandler authenticationHandler;

    @Before
    public void setUp() throws Exception {
        this.authenticationHandler = new FileAuthenticationHandler(new ClassPathResource("authentication.txt"),
                FileAuthenticationHandler.DEFAULT_SEPARATOR);
        final PasswordEncoderProperties p = new PasswordEncoderProperties();
        p.setType(PasswordEncoderProperties.PasswordEncoderTypes.DEFAULT.name());
        p.setEncodingAlgorithm("MD5");
        p.setCharacterEncoding("UTF-8");
        this.authenticationHandler.setPasswordEncoder(Beans.newPasswordEncoder(p));
    }

    @Test
    public void verifySupportsProperUserCredentials() throws Exception {
        final UsernamePasswordCredential c = new UsernamePasswordCredential();

        c.setUsername("scott");
        c.setPassword("rutgers");
        assertNotNull(this.authenticationHandler.authenticate(c));
    }

    @Test
    public void verifyDoesNotSupportBadUserCredentials() {
        try {
            final HttpBasedServiceCredential c = new HttpBasedServiceCredential(
                new URL("http://www.rutgers.edu"), CoreAuthenticationTestUtils.getRegisteredService());
            assertFalse(this.authenticationHandler.supports(c));
        } catch (final MalformedURLException e) {
            fail("MalformedURLException caught.");
        }
    }

    @Test
    public void verifyAuthenticatesUserInFileWithDefaultSeparator() throws Exception {
        final UsernamePasswordCredential c = new UsernamePasswordCredential();

        c.setUsername("scott");
        c.setPassword("rutgers");

        assertNotNull(this.authenticationHandler.authenticate(c));
    }

    @Test
    public void verifyFailsUserNotInFileWithDefaultSeparator() throws Exception {
        final UsernamePasswordCredential c = new UsernamePasswordCredential();

        c.setUsername("fds");
        c.setPassword("rutgers");

        this.thrown.expect(AccountNotFoundException.class);
        this.thrown.expectMessage("fds not found in backing file.");

        this.authenticationHandler.authenticate(c);
    }

    @Test
    public void verifyFailsNullUserName() throws Exception {
        final UsernamePasswordCredential c = new UsernamePasswordCredential();
        c.setUsername(null);
        c.setPassword("user");
        this.thrown.expect(AccountNotFoundException.class);
        this.authenticationHandler.authenticate(c);
    }

    @Test
    public void verifyFailsNullUserNameAndPassword() throws Exception {
        final UsernamePasswordCredential c = new UsernamePasswordCredential();
        c.setUsername(null);
        c.setPassword(null);
        this.thrown.expect(AccountNotFoundException.class);
        this.authenticationHandler.authenticate(c);
    }

    @Test
    public void verifyFailsNullPassword() throws Exception {
        final UsernamePasswordCredential c = new UsernamePasswordCredential();
        c.setUsername("scott");
        c.setPassword(null);
        this.thrown.expect(FailedLoginException.class);
        this.authenticationHandler.authenticate(c);
    }

    @Test
    public void verifyAuthenticatesUserInFileWithCommaSeparator() throws Exception {
        final UsernamePasswordCredential c = new UsernamePasswordCredential();
        this.authenticationHandler = new FileAuthenticationHandler(new ClassPathResource("authentication2.txt"), ",");
        c.setUsername("scott");
        c.setPassword("rutgers");
        assertNotNull(this.authenticationHandler.authenticate(c));
    }

    @Test
    public void verifyFailsUserNotInFileWithCommaSeparator() throws Exception {
        final UsernamePasswordCredential c = new UsernamePasswordCredential();

        this.authenticationHandler = new FileAuthenticationHandler(new ClassPathResource("authentication2.txt"), ",");
        c.setUsername("fds");
        c.setPassword("rutgers");
        this.thrown.expect(AccountNotFoundException.class);
        this.thrown.expectMessage("fds not found in backing file.");
        this.authenticationHandler.authenticate(c);
    }

    @Test
    public void verifyFailsGoodUsernameBadPassword() throws Exception {
        final UsernamePasswordCredential c = new UsernamePasswordCredential();
        this.authenticationHandler = new FileAuthenticationHandler(new ClassPathResource("authentication2.txt"), ",");

        c.setUsername("scott");
        c.setPassword("rutgers1");

        this.thrown.expect(FailedLoginException.class);

        this.authenticationHandler.authenticate(c);
    }

    @Test
    public void verifyAuthenticateNoFileName() throws Exception {
        final UsernamePasswordCredential c = new UsernamePasswordCredential();
        this.authenticationHandler = new FileAuthenticationHandler(new ClassPathResource("fff"), FileAuthenticationHandler.DEFAULT_SEPARATOR);

        c.setUsername("scott");
        c.setPassword("rutgers");

        this.thrown.expect(PreventedException.class);
        this.thrown.expectMessage("IO error reading backing file");

        this.authenticationHandler.authenticate(c);
    }
}


text:
'use strict';

const path = require('path');
const express = require('express');
const ssr = require('./ssr');

const port = 8080;
const app = express();
const viewsDir = path.join(__dirname, './views/dist');

// Output request log
app.use((req, res, next) => {
	res.on('finish', function () {
		let now = new Date();
		console.log('[' + now.toLocaleString() + ']', req.method, req.url, res.statusCode);
	});
	next();
});

// Serve static files
app.use('/assets', express.static(path.join(viewsDir, 'assets')));

// Server side rendering
app.use(ssr(viewsDir));

app.listen(port, () => {
	console.log('Listening on', port);
});


text:
package storage

import (
	"fmt"
	"math/rand"
	"path"

	"time"

	"k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/util/wait"
	clientset "k8s.io/client-go/kubernetes"
	"k8s.io/kubernetes/test/e2e/framework"
	"k8s.io/kubernetes/test/e2e/storage/utils"
	imageutils "k8s.io/kubernetes/test/utils/image"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

var (
	BusyBoxImage          = imageutils.GetE2EImage(imageutils.BusyBox)
	durationForStuckMount = 110 * time.Second
)

var _ = utils.SIGDescribe("Detaching volumes", func() {
	f := framework.NewDefaultFramework("flexvolume")

	// note that namespace deletion is handled by delete-namespace flag

	var cs clientset.Interface
	var ns *v1.Namespace
	var node v1.Node
	var suffix string

	BeforeEach(func() {
		framework.SkipUnlessProviderIs("gce", "local")
		framework.SkipUnlessMasterOSDistroIs("debian", "ubuntu", "gci", "custom")
		framework.SkipUnlessNodeOSDistroIs("debian", "ubuntu", "gci", "custom")
		framework.SkipUnlessSSHKeyPresent()

		cs = f.ClientSet
		ns = f.Namespace
		nodes := framework.GetReadySchedulableNodesOrDie(f.ClientSet)
		node = nodes.Items[rand.Intn(len(nodes.Items))]
		suffix = ns.Name
	})

	It("should not work when mount is in progress", func() {
		driver := "attachable-with-long-format"
		driverInstallAs := driver + "-" + suffix

		By(fmt.Sprintf("installing flexvolume %s on node %s as %s", path.Join(driverDir, driver), node.Name, driverInstallAs))
		installFlex(cs, &node, "k8s", driverInstallAs, path.Join(driverDir, driver))
		By(fmt.Sprintf("installing flexvolume %s on master as %s", path.Join(driverDir, driver), driverInstallAs))
		installFlex(cs, nil, "k8s", driverInstallAs, path.Join(driverDir, driver))
		volumeSource := v1.VolumeSource{
			FlexVolume: &v1.FlexVolumeSource{
				Driver: "k8s/" + driverInstallAs,
			},
		}

		clientPod := getFlexVolumePod(volumeSource, node.Name)
		By("Creating pod that uses slow format volume")
		pod, err := cs.CoreV1().Pods(ns.Name).Create(clientPod)
		Expect(err).NotTo(HaveOccurred())

		uniqueVolumeName := getUniqueVolumeName(pod, driverInstallAs)

		By("waiting for volume-in-use on the node after pod creation")
		err = waitForVolumesInUse(cs, node.Name, uniqueVolumeName)
		Expect(err).NotTo(HaveOccurred(), "while waiting for volume in use")

		By("Deleting the flexvolume pod")
		err = framework.DeletePodWithWait(f, cs, pod)
		Expect(err).NotTo(HaveOccurred(), "in deleting the pod")

		// Wait a bit for node to sync the volume status
		time.Sleep(30 * time.Second)

		By("waiting for volume-in-use on the node after pod deletion")
		err = waitForVolumesInUse(cs, node.Name, uniqueVolumeName)
		Expect(err).NotTo(HaveOccurred(), "while waiting for volume in use")

		// Wait for 110s because mount device operation has a sleep of 120 seconds
		// we previously already waited for 30s.
		time.Sleep(durationForStuckMount)

		By("waiting for volume to disappear from node in-use")
		err = waitForVolumesNotInUse(cs, node.Name, uniqueVolumeName)
		Expect(err).NotTo(HaveOccurred(), "while waiting for volume to be removed from in-use")

		By(fmt.Sprintf("uninstalling flexvolume %s from node %s", driverInstallAs, node.Name))
		uninstallFlex(cs, &node, "k8s", driverInstallAs)
		By(fmt.Sprintf("uninstalling flexvolume %s from master", driverInstallAs))
		uninstallFlex(cs, nil, "k8s", driverInstallAs)
	})
})

func getUniqueVolumeName(pod *v1.Pod, driverName string) string {
	return fmt.Sprintf("flexvolume-k8s/%s/%s", driverName, pod.Spec.Volumes[0].Name)
}

func waitForVolumesNotInUse(client clientset.Interface, nodeName, volumeName string) error {
	return wait.PollImmediate(10*time.Second, 60*time.Second, func() (bool, error) {
		node, err := client.CoreV1().Nodes().Get(nodeName, metav1.GetOptions{})
		if err != nil {
			return false, fmt.Errorf("error fetching node %s with %v", nodeName, err)
		}
		volumeInUSe := node.Status.VolumesInUse
		for _, volume := range volumeInUSe {
			if string(volume) == volumeName {
				return false, nil
			}
		}
		return true, nil
	})
}

func waitForVolumesInUse(client clientset.Interface, nodeName, volumeName string) error {
	return wait.PollImmediate(10*time.Second, 60*time.Second, func() (bool, error) {
		node, err := client.CoreV1().Nodes().Get(nodeName, metav1.GetOptions{})
		if err != nil {
			return false, fmt.Errorf("error fetching node %s with %v", nodeName, err)
		}
		volumeInUSe := node.Status.VolumesInUse
		for _, volume := range volumeInUSe {
			if string(volume) == volumeName {
				return true, nil
			}
		}
		return false, nil
	})
}

func getFlexVolumePod(volumeSource v1.VolumeSource, nodeName string) *v1.Pod {
	var gracePeriod int64
	clientPod := &v1.Pod{
		TypeMeta: metav1.TypeMeta{
			Kind:       "Pod",
			APIVersion: "v1",
		},
		ObjectMeta: metav1.ObjectMeta{
			Name: "flexvolume-detach-test" + "-client",
			Labels: map[string]string{
				"role": "flexvolume-detach-test" + "-client",
			},
		},
		Spec: v1.PodSpec{
			Containers: []v1.Container{
				{
					Name:       "flexvolume-detach-test" + "-client",
					Image:      BusyBoxImage,
					WorkingDir: "/opt",
					// An imperative and easily debuggable container which reads vol contents for
					// us to scan in the tests or by eye.
					// We expect that /opt is empty in the minimal containers which we use in this test.
					Command: []string{
						"/bin/sh",
						"-c",
						"while true ; do cat /opt/foo/index.html ; sleep 2 ; ls -altrh /opt/  ; sleep 2 ; done ",
					},
					VolumeMounts: []v1.VolumeMount{
						{
							Name:      "test-long-detach-flex",
							MountPath: "/opt/foo",
						},
					},
				},
			},
			TerminationGracePeriodSeconds: &gracePeriod,
			SecurityContext: &v1.PodSecurityContext{
				SELinuxOptions: &v1.SELinuxOptions{
					Level: "s0:c0,c1",
				},
			},
			Volumes: []v1.Volume{
				{
					Name:         "test-long-detach-flex",
					VolumeSource: volumeSource,
				},
			},
			NodeName: nodeName,
		},
	}
	return clientPod
}


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

    <link rel="stylesheet" type="text/css" href="description/Combined.css,0:HeaderFooterSprite,0:Header.NonMtps,1:LinkList;/Areas/Centers/Themes/StandardDevCenter/Content:0,/Areas/Epx/Themes/Base/Content:1&amp;hashKey=C9973DA951AE6202C9B348379A1BE49D" xmlns="http://www.w3.org/1999/xhtml" />
<link type="text/css" rel="stylesheet" xmlns="http://www.w3.org/1999/xhtml" />
<link rel="stylesheet" type="text/css" href="description/04f9c26e-88fd-4dfd-b715-9733d17420b6Combined.css,0:HeaderFooterSprite,0:Footer.NonMtps,1:LinkList;/Areas/Centers/Themes/StandardDevCenter/Content:0,/Areas/Epx/Themes/Base/Content:1&amp;hashKey=F576C687BC536B84D6E5B3246EE39B49" xmlns="http://www.w3.org/1999/xhtml" />
<link type="text/css" rel="stylesheet" xmlns="http://www.w3.org/1999/xhtml" />

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Application data sample</title>
        <link href="description/Galleries.css" type="text/css" rel="Stylesheet" /><link href="description/Layout.css" type="text/css" rel="Stylesheet" /><link href="description/Brand.css" type="text/css" rel="Stylesheet" />
        <link href="description/iframedescription.css" rel="Stylesheet" type="text/css" />

Application data sample

                        Technologies

                            Windows Runtime, Windows 8.1, Windows Phone 8.1

                        Topics

                            Store, universal app

                    Platforms

                        Windows RT

                    Requirements

                    Primary language

en-US

                    Updated

4/2/2014

                    License

                        MS-LPL

                        View this sample online

This sample shows you how to store and retrieve data that is specific to each user and Windows Runtime app by using the Windows Runtime application data APIs (Windows.Storage.ApplicationData
 and so on).

Note  This sample was created using one of the universal app templates available in Visual Studio. It shows how its solution is structured so it can run on both Windows 8.1 and Windows Phone 8.1. For more info about how to build apps
 that target Windows and Windows Phone with Visual Studio, see
Build apps that target Windows and Windows Phone 8.1 by using Visual Studio.

Application data includes session state, user preferences, and other settings. It is created, read, updated, and deleted when the app is running. The operating system manages these data stores for your app:

local: Data that exists on the current device and is backed up in the cloud

roaming: Data that exists on all devices on which the user has installed the app

temporary: Data that could be removed by the system any time the app isn't running

localcache: Persistent data that exists only on the current device

If you use roaming data in your app, your users can easily keep your app's application data in sync across multiple devices. The operating system replicates roaming data to the cloud when it is updated, and synchronizes the data to any other devices on which
 the app is installed, reducing the amount of setup work that the user needs to do to install your app on multiple devices.

If you use local data in your app, your users can back up application data in the cloud. This application data can then be restored back on any other device while setting up the device with the same account.

The sample covers these key tasks:

Reading and writing settings to an app data store

Reading and writing files to an app data store

Responding to roaming events

To obtain an evaluation copy of Windows 8.1, go to
Windows 8.1.

To obtain an evaluation copy of Microsoft Visual Studio 2013 Update 2, go to
Microsoft Visual Studio 2013.

Related topics

Windows 8 app samples

Tasks

Quickstart: Local application data (JavaScript)

Quickstart: Local application data (C#/VB/C++)

Quickstart: Roaming application data (JavaScript)

Quickstart: Roaming application data (C#/VB/C++)

Quickstart: Temporary application data (JavaScript)

Quickstart: Temporary application data (C#/VB/C++)

Guidelines

Guidelines for roaming application data

Concepts

Application data

Reference

Windows.Storage.ApplicationData

Windows.Storage.ApplicationDataCompositeValue

Windows.Storage.ApplicationDataContainer

Windows.Storage.ApplicationDataContainerSettings

WinJS.Application

Operating system requirements

Client

Windows 8.1

Server

Windows Server 2012 R2

Phone

Windows Phone 8.1

Build the sample

Start Visual Studio 2013 Update 2 and select File > Open >
Project/Solution.

Go to the directory to which you unzipped the sample. Then go to the subdirectory named for the sample and double-click the Visual Studio 2013 Update 2 Solution (.sln) file.

Follow the steps for the version of the sample you want:

To build the Windows version of the sample:

Select ApplicationDataSample.Windows in Solution Explorer.

Press Ctrl+Shift+B, or use Build > Build Solution, or use
Build > Build ApplicationDataSample.Windows.

To build the Windows Phone version of the sample:

Select ApplicationDataSample.WindowsPhone in Solution Explorer.

Press Ctrl+Shift+B or use Build > Build Solution or use Build >
Build ApplicationDataSample.WindowsPhone.

Run the sample

The next steps depend on whether you just want to deploy the sample or you want to both deploy and run it.

Deploying the sample

To deploy the built Windows version of the sample:

Select ApplicationDataSample.Windows in Solution Explorer.

Use Build > Deploy Solution or Build > Deploy ApplicationDataSample.Windows.

To deploy the built Windows Phone version of the sample:

Select ApplicationDataSample.WindowsPhone in Solution Explorer.

Use Build > Deploy Solution or Build > Deploy ApplicationDataSample.WindowsPhone.

Deploying and running the sample

To deploy and run the Windows version of the sample:

Right-click ApplicationDataSample.Windows in Solution Explorer and select
Set as StartUp Project.

To debug the sample and then run it, press F5 or use Debug > Start Debugging. To run the sample without debugging, press Ctrl+F5 or use
Debug > Start Without Debugging.

To deploy and run the Windows Phone version of the sample:

Right-click ApplicationDataSample.WindowsPhone in Solution Explorer and select
Set as StartUp Project.

To debug the sample and then run it, press F5 or use Debug > Start Debugging. To run the sample without debugging, press Ctrl+F5 or use
Debug > Start Without Debugging.


text:
<!DOCTYPE html>

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

  <title>Nghia Luong's blog - [Code] Interesting Bitmask</title>
  <link rel="shortcut icon" href="/assets/images/favicon.ico">
  <link rel="stylesheet" href="/assets/css/style.css">
  <link rel="alternate" type="application/rss+xml" title="My Blog" href="/feed.xml">
  <link rel="stylesheet" href="/assets/css/highlight.css">

         ← Home

        About

    Subscribe

[Code] Interesting Bitmask

September 25, 2016

There is a lot of type checking ways. You can define as constant strings to check later on, or you could use enum for convenient way (this one could be used the most) … but there is one way of type checking, that's is using Bitmask. This article will lead you digging into how to use bitmask in Objective C.

As we easily can see, Apple uses a lot of bitmask in the SDKs, for example: UIViewAutoresizing, UIInterfaceOrientation …

We will make our own example, let's see:

typedef NS_OPTIONS(NSUInteger, PLandayEngineerTeam) {
    PLandayEngineerTeam_Mobile        = 1 << 0,
    PLandayEngineerTeam_Backend       = 1 << 1,
    PLandayEngineerTeam_Frontedn      = 1 << 2
};

We actually used Bitwise operator, called Bit shift in this case, because in this operation, the digits are moved, or shifted. With our example, the digits are moved to left. For more info you could check this out, talking about Bitwise operations: https://en.wikipedia.org/wiki/Bitwise_operation

So now we present the example in Binary:

typedef NS_OPTIONS(NSUInteger, PLandayEngineerTeam) {
    PLandayEngineerTeam_Mobile        = (1 << 0), // => 00000001
    PLandayEngineerTeam_Backend       = (1 << 1), // => 00000010
    PLandayEngineerTeam_Frontedn      = (1 << 2)  // => 00000100
};

Got it?

HOW TO USE?

1.  Use | (Bitwise OR) for setting on or turning on a flag.

For example:

PLandayEngineerTeam teams = PLandayEngineerTeam_Mobile | PLandayEngineerTeam_Backend;

    Actually:
        00000001
    |
        00000010
        ========
        00000011

If you want to add more flag in existing flags:

teams |= PLandayEngineerTeam_Frontend;

2.  Use & (Bitwise AND) for checking the state of a flag.

if (teams & PLandayEngineerTeam_Mobile == PLandayEngineerTeam_Mobile) {
        // is Mobile Team.
    }

It is explained as:

        00000011
    &
        00000001
        ========
        00000001  // PLandayEngineerTeam_Mobile

Two both bitwise operators are good for normally work, but there is further more. Let's continue.

3. Use ~ (Bitwise NOT) for Deleting a flag.

teams &= ~PLandayEngineerTeam_Backend;

Actually:

~PLandayEngineerTeam_Backend // ~00000010 == 11111101

        00000011
    &
        11111101
        ========
        00000001 // == PLandayEngineerTeam_Mobile

4.  Use ^ (Bitwise XOR) for toggling a flag (turns it on if it was off, or off if it was on), rarely used.

For example:

teams ^= PLandayEngineerTeam_Backend;

Why using it?

Save space: instead of using NSInteger could takes 32 bits or 64 bits, we alternatively use Bit Flag which is few bits.

In help of understanding RGBA color: http://www.learncpp.com/cpp-tutorial/3-8a-bit-flags-and-bit-masks/

Conclusion

Well, so like them or not, in my opinion, these are used a lot by Apple, so it would be benefit if we're familiar with them. And one more thing, life will be excited to know things.

Happy coding.

References:
    * http://www.vipan.com/htdocs/bitwisehelp.html
    * https://www.bignerdranch.com/blog/smooth-bitwise-operator/
    * http://nshipster.com/ns_enum-ns_options/

            Nghia Luong
            Work hard, play harder

         Tweet

 Share

Read more

                [Career] Cuối năm và chuyện lương lậu.Jan 05

                [macOS] Khi Mac không thực sự sleep.Sep 09

                [Life] Sức mạnh của SỰ TẬP TRUNGJul 12

                [Objective C] EqualityApr 17

                [Code] Pass by reference.Dec 14

                [Code] Interesting BitmaskSep 25

                [Life] Câu chuyện về Micheal Phelps của tôi.Aug 14

                [Life] Phong cách làm việc của người Đan mạchJun 29

                [iOS] Switching storage filesApr 20

                [Life] Năm nay cưới chưa?Feb 17

                [Objective-c] Primitive type initialization.Jan 09

                [Achievement] Being in Top 100 Best Blogs for iOS Developers from SoftwareHow.com Jan 09

                [iOS] Retain cycle in Blocks.Dec 29

                [iOS] Pungent stuff: Retain cycleDec 20

                [iOS] How to simulate static quick actions on xcode 7Oct 16

                [Life] Văn hoá bán hàng của người Việt Nam.Sep 20

                [Objective-C] Random problems.Sep 16

                [Review] Pebble Time & Apple WatchSep 13

                [Code] Check if characters of a given string can be rearranged to form a palindromeAug 31

                [Code] Project Euler #13: Large using objective-c.Aug 25

                [Life] Just a minor happinessAug 23

                [Code] Big Number in Objective-CAug 22

                Project Euler: Problem 11 - Largest product in a grid using Objective-CAug 14

                [iOS] Lazy loading in iOSAug 05

                [Code] Intelligent Girl ProblemJul 27

                NSLog stuffJul 22

                Why Hello World?Jul 21


text:
using Content.Server.Chemistry.Components;
using Content.Server.Chemistry.Components.SolutionManager;
using Content.Shared.Chemistry.Components;
using Content.Shared.Chemistry.Reagent;
using Content.Shared.FixedPoint;
using Content.Shared.Physics;
using Content.Shared.Spawners.Components;
using Content.Shared.Throwing;
using Content.Shared.Vapor;
using JetBrains.Annotations;
using Robust.Shared.Map;
using Robust.Shared.Map.Components;
using Robust.Shared.Physics.Components;
using Robust.Shared.Physics.Dynamics;
using Robust.Shared.Physics.Events;
using Robust.Shared.Prototypes;

namespace Content.Server.Chemistry.EntitySystems
{
    [UsedImplicitly]
    internal sealed class VaporSystem : EntitySystem
    {
        [Dependency] private readonly IMapManager _mapManager = default!;
        [Dependency] private readonly IPrototypeManager _protoManager = default!;
        [Dependency] private readonly SolutionContainerSystem _solutionContainerSystem = default!;
        [Dependency] private readonly ThrowingSystem _throwing = default!;

        private const float ReactTime = 0.125f;

        public override void Initialize()
        {
            base.Initialize();
            SubscribeLocalEvent<VaporComponent, StartCollideEvent>(HandleCollide);
        }

        private void HandleCollide(EntityUid uid, VaporComponent component, ref StartCollideEvent args)
        {
            if (!EntityManager.TryGetComponent(uid, out SolutionContainerManagerComponent? contents)) return;

            foreach (var (_, value) in contents.Solutions)
            {
                value.DoEntityReaction(args.OtherFixture.Body.Owner, ReactionMethod.Touch);
            }

            // Check for collision with a impassable object (e.g. wall) and stop
            if ((args.OtherFixture.CollisionLayer & (int) CollisionGroup.Impassable) != 0 && args.OtherFixture.Hard)
            {
                EntityManager.QueueDeleteEntity(uid);
            }
        }

        public void Start(VaporComponent vapor, TransformComponent vaporXform, Vector2 dir, float speed, MapCoordinates target, float aliveTime, EntityUid? user = null)
        {
            vapor.Active = true;
            var despawn = EnsureComp<TimedDespawnComponent>(vapor.Owner);
            despawn.Lifetime = aliveTime;

            // Set Move
            if (EntityManager.TryGetComponent(vapor.Owner, out PhysicsComponent? physics))
            {
                physics.LinearDamping = 0f;
                physics.AngularDamping = 0f;

                _throwing.TryThrow(vapor.Owner, dir * speed, user: user, pushbackRatio: 50f);

                var distance = (target.Position - vaporXform.WorldPosition).Length;
                var time = (distance / physics.LinearVelocity.Length);
                despawn.Lifetime = MathF.Min(aliveTime, time);
            }
        }

        internal bool TryAddSolution(VaporComponent vapor, Solution solution)
        {
            if (solution.TotalVolume == 0)
            {
                return false;
            }

            if (!_solutionContainerSystem.TryGetSolution(vapor.Owner, VaporComponent.SolutionName,
                out var vaporSolution))
            {
                return false;
            }

            return _solutionContainerSystem.TryAddSolution(vapor.Owner, vaporSolution, solution);
        }

        public override void Update(float frameTime)
        {
            foreach (var (vaporComp, solution, xform) in EntityManager
                .EntityQuery<VaporComponent, SolutionContainerManagerComponent, TransformComponent>())
            {
                foreach (var (_, value) in solution.Solutions)
                {
                    Update(frameTime, vaporComp, value, xform);
                }
            }
        }

        private void Update(float frameTime, VaporComponent vapor, Solution contents, TransformComponent xform)
        {
            if (!vapor.Active)
                return;

            var entity = vapor.Owner;

            vapor.ReactTimer += frameTime;

            if (vapor.ReactTimer >= ReactTime && TryComp(xform.GridUid, out MapGridComponent? gridComp))
            {
                vapor.ReactTimer = 0;

                var tile = gridComp.GetTileRef(xform.Coordinates.ToVector2i(EntityManager, _mapManager));
                foreach (var reagentQuantity in contents.Contents.ToArray())
                {
                    if (reagentQuantity.Quantity == FixedPoint2.Zero) continue;
                    var reagent = _protoManager.Index<ReagentPrototype>(reagentQuantity.ReagentId);
                    _solutionContainerSystem.TryRemoveReagent(vapor.Owner, contents, reagentQuantity.ReagentId,
                        reagent.ReactionTile(tile, (reagentQuantity.Quantity / vapor.TransferAmount) * 0.25f));
                }
            }

            if (contents.CurrentVolume == 0)
            {
                // Delete this
                EntityManager.QueueDeleteEntity(entity);
            }
        }
    }
}


text:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Link } from 'react-router-dom';
import { connect } from 'react-redux';
import { loadItem, putItem, deleteItem, unloadItem } from '../../actions';
import PageHeader from '../../components/PageHeader';
import ConfirmRemove from '../../components/ConfirmRemove';
import Loading from '../../components/Loading';
import NotFound from '../../components/NotFound';
import FormContents from './FormContents';
import { setFormError, clearFormError, finalizeForm } from './FormUtils';

class FormEdit extends Component {

  constructor(props) {
    super(props);
    this._onUpdate = this._onUpdate.bind(this);
    this._onCancel = this._onCancel.bind(this);
    this._onRemove = this._onRemove.bind(this);
    this._onChange = this._onChange.bind(this);
    const state = {};
    if (props.form) {
      state.form = { ...props.form };
    }
    this.state = state;
  }

  componentDidMount() {
    const { form } = this.props;
    if (!form) {
      this._load(this.props);
    }
  }

  componentWillReceiveProps(nextProps) {
    const {
      dispatch, form, formTemplate, formTemplateNotFound, id,
      linkedForm, linkedFormNotFound, linkedFormTemplate,
    } = nextProps;
    if (id && (id !== this.props.id || this.state.form) && !form) {
      this.setState({ form: undefined });
      this._load(nextProps);
    } else if (form && (!this.state.form || form._id !== this.props.form._id)) {
      this.setState({ form: { ...form }, loadedLinkedTemplate: false });
      if (!formTemplate && form.formTemplateId && !formTemplateNotFound) {
        dispatch(loadItem('form-templates', form.formTemplateId._id));
      }
      if (form.linkedFormId && !linkedForm && linkedFormNotFound) {
        dispatch(loadItem('forms', form.linkedFormId));
      }
    } else if (linkedForm && !linkedFormTemplate &&
      !this.state.loadedLinkedTemplate && linkedForm.formTemplateId &&
      !linkedFormNotFound) {
      this.setState({ loadedLinkedTemplate: true });
      dispatch(loadItem('form-templates', linkedForm.formTemplateId._id));
    }
  }

  // removed since we need to preserve those from FormSection
  componentWillUnmount() {
    const { dispatch, formTemplate, id, inline } = this.props;
    if (!inline) {
      dispatch(unloadItem('forms', id));
      if (formTemplate) {
        dispatch(unloadItem('form-templates', formTemplate._id));
      }
    }
  }

  _load(props) {
    const { dispatch, id } = props;
    dispatch(loadItem('forms', id, { full: true }));
  }

  _onUpdate(event) {
    event.preventDefault();
    const { formTemplate, history, linkedForm, onDone } = this.props;
    const { form } = this.state;
    const error = setFormError(formTemplate, form);

    if (error) {
      this.setState({ error });
    } else {
      finalizeForm(formTemplate, form, linkedForm);
      putItem('forms', this.state.form)
        .then(formSaved => (onDone ? onDone(formSaved) : history.goBack()))
        .catch(error2 => this.setState({ error2 }));
    }
  }

  _onCancel() {
    const { history, onCancel } = this.props;
    if (onCancel) {
      onCancel();
    } else {
      history.goBack();
    }
  }

  _onRemove(event) {
    const { onDone, history, id } = this.props;
    event.preventDefault();
    deleteItem('forms', id)
      .then(() => (onDone ? onDone() : history.goBack()))
      .catch((error) => {
        console.error('!!!', error);
        this.setState({ error });
      });
  }

  _onChange(form) {
    const { formTemplate } = this.props;
    // clear any error for fields that have changed
    const error = clearFormError(formTemplate, form, this.state.error);
    this.setState({ form, error });
  }

  render() {
    const {
      className, formNotFound, formTemplate, formTemplateNotFound, full, inline,
      linkedForm, linkedFormTemplate, onLinkedForm,
    } = this.props;
    const { form, error } = this.state;
    const classNames = ['form'];
    if (className) {
      classNames.push(className);
    }

    let header;
    if (!inline) {
      const cancelControl = [
        <button key="cancel"
          type="button"
          className="button"
          onClick={this._onCancel}>
          Cancel
        </button>,
      ];
      header = (
        <PageHeader title={(formTemplate || {}).name} actions={cancelControl} />
      );
    }

    let result;
    if (form && (formTemplate || formTemplateNotFound || !form.formTemplateId)) {
      const submitLabel = 'Update';
      // if (formTemplate.payable && form.paymentIds.length === 0) {
      //   submitLabel = 'Pay';
      // }

      let linkedFormControl;
      if (linkedForm && linkedFormTemplate) {
        if (!inline) {
          linkedFormControl = (

              from <Link to={`/forms/${linkedForm._id}/edit`}>
                {linkedFormTemplate.name}
              </Link>

          );
        } else {
          linkedFormControl = (

              from  onLinkedForm(linkedForm)}>
                {linkedFormTemplate.name}

          );
        }
      }

      let formContents;
      if (formTemplate) {
        formContents = (
          <FormContents form={form}
            formTemplate={formTemplate}
            linkedForm={linkedForm}
            linkedFormControl={linkedFormControl}
            full={full}
            onChange={this._onChange}
            error={error} />
        );
      } else {
        formContents =
Missing form template
;
      }

      result = (
        <form className={classNames.join(' ')}
          action={`/forms/${form._id}`}
          onSubmit={this._onUpdate}
          noValidate={true}>
          {header}
          {formContents}

            <button type="submit" className="button">{submitLabel}</button>
            <ConfirmRemove onConfirm={this._onRemove} />
            <button type="button"
              className="button button--secondary"
              onClick={this._onCancel}>
              Cancel
            </button>

        </form>
      );

      if (!inline) {
        result =
{result}
;
      }
    } else if (formNotFound) {
      result = (

          {header}
          <NotFound />

      );
    } else {
      result = (

          {header}
          <Loading />

      );
    }
    return result;
  }
}

FormEdit.propTypes = {
  className: PropTypes.string,
  dispatch: PropTypes.func.isRequired,
  form: PropTypes.object,
  formNotFound: PropTypes.bool,
  formTemplate: PropTypes.object,
  formTemplateNotFound: PropTypes.bool,
  full: PropTypes.bool,
  history: PropTypes.any,
  id: PropTypes.string,
  inline: PropTypes.bool,
  linkedForm: PropTypes.object,
  linkedFormNotFound: PropTypes.bool,
  linkedFormTemplate: PropTypes.object,
  onCancel: PropTypes.func,
  onDone: PropTypes.func,
  onLinkedForm: PropTypes.func,
};

FormEdit.defaultProps = {
  className: undefined,
  form: undefined,
  formNotFound: undefined,
  formTemplate: undefined,
  formTemplateNotFound: undefined,
  full: true,
  history: undefined,
  id: undefined,
  inline: false,
  linkedForm: undefined,
  linkedFormNotFound: undefined,
  linkedFormTemplate: undefined,
  onCancel: undefined,
  onDone: undefined,
  onLinkedForm: undefined,
};

const select = (state, props) => {
  const id = props.match ? props.match.params.id : props.id;
  const form = props.form || state[id];
  let linkedForm = props.linkedForm;
  let linkedFormNotFound;
  if (!linkedForm && form && (form.linkedForm || form.linkedFormId)) {
    linkedForm = form.linkedForm || state[form.linkedFormId];
    linkedFormNotFound = state.notFound[form.linkedFormId];
  }
  return {
    id,
    form,
    formNotFound: state.notFound[id],
    formTemplate: props.formTemplate ||
      (form ? state[(form.formTemplateId || {})._id] : undefined),
    formTemplateNotFound:
      (form ? state.notFound[(form.formTemplateId || {})._id] : undefined),
    linkedForm,
    linkedFormNotFound,
    linkedFormTemplate: props.linkedFormTemplate ||
      (linkedForm ? state[(linkedForm.formTemplateId || {})._id] : undefined),
    notFound: id ? state.notFound[id] : undefined,
    session: state.session,
  };
};

export default connect(select)(FormEdit);


text:
{% extends "base.html" %}

{% block title %}Order Confirmation | {{ block.super }}{% endblock %}

{% block bodyclass %}{{ block.super }}flatpage {{ flatpage.title|slugify }}{% endblock %}

{% block headernav %}
{% load order_tags %}
{% load article_tags %}
{% banner request %}
{% endblock %}

{% block content %}

  {% if user.is_staff %}
   {% include "admin_nav.html" %}
{% endif %}

    {{ block.super }}

        {% load catalog_tags %}
        {% get_latest_issue as latest_issue %}
        {% get_next_latest_issue as next_latest_issue %}
        {% load order_tags %}

    {% if messages %}
        {% for message in messages %}

            <button type="button" class="close" data-dismiss="alert">×</button>
            {% if "safe" in message.tags %}{{ message|safe }}{% else %}{{ message }}{% endif %}

        {% endfor %}
    {% endif %}

Renewals for Issue {{ issue }}

            <form class="mid_inputer" action="{% url 'renewals_get' %}" method="GET">
            <input class="midbox" type="text" name="issue" value="{{issue}}" />
            </form>

Listed here are recipients whose subscriptions expire with Issue {{expiring_issue}}. These will need to be notified and renewed before Issue {{ issue }} is mailed.

                    Recipient
                    Payer
                     Auto Renew?
                     Notify
                     Renew

        {% for record in expiring_records %}

                 {{ record }}
                  {{ record.originating_order.payer_name }}
                 {% get_auto_renew record as auto %} {{auto}}

                {% if record.status = 'Notified' %}
                <button class="btn btn-default">Sent </button>
                {% else %}

                Send
                {% endif %}

                 {% if auto = True %}
                {% get_dat_cc record.originating_order.user as cc %}
                <form action="{% url 'checkout_auto_renewal'%}" method="POST" >{% csrf_token %}
                    <input type="hidden" name="userId" value="{{record.originating_order.user.id}}">
                    <input type="hidden" name="ccStripeId" value="{{cc.stripe_id}}">
                    <input type="hidden" name="recordId" value="{{record.id}}">
                    <input type="hidden" name="issueNo" value="{{issue}}">
                    <button class="btn btn-primary" type="submit">Renew!</button>
                </form>
                {% endif %}

        {% endfor %}

{% endblock %}


text:
/*
 * speaker.h -- interface definitions for speaker ioctl()
 *
 * v1.4 by Eric S. Raymond (esr@snark.thyrsus.com) Aug 1993
 *      modified for FreeBSD by Andrew A. Chernov <ache@astral.msk.su>
 *
 * $Id: speaker.h,v 1.3 1996/09/21 14:58:26 bde Exp $
 */

#ifndef	_MACHINE_SPEAKER_H_
#define	_MACHINE_SPEAKER_H_

#include <sys/ioccom.h>

#define SPKRTONE        _IOW('S', 1, tone_t)    /* emit tone */
#define SPKRTUNE        _IO('S', 2)             /* emit tone sequence*/

typedef struct
{
    int	frequency;	/* in hertz */
    int duration;	/* in 1/100ths of a second */
}
tone_t;

/*
 * Strings written to the speaker device are interpreted as tunes and played;
 * see the spkr(4) man page for details.
 */

#endif /* !_MACHINE_SPEAKER_H_ */


text:
<!--L
   Copyright SAIC, Ellumen and RSNA (CTP)

   Distributed under the OSI-approved BSD 3-Clause License.
   See http://ncip.github.com/national-biomedical-image-archive/LICENSE.txt for details.
L-->

<security-config>
    <upt-context-name>
    </upt-context-name>
    <application-list>
        <application>
            <context-name>
                NCIA
            </context-name>
            <authentication>
                <authentication-provider-class>
                </authentication-provider-class>
				<lockout-time>
				</lockout-time>
				<allowed-login-time>
				</allowed-login-time>
				<allowed-attempts>
				</allowed-attempts>
            </authentication>
            <authorization>
                <authorization-provider-class>
                </authorization-provider-class>
                <hibernate-config-file>
                </hibernate-config-file>
            </authorization>
        </application>
    </application-list>
</security-config>


text:
import { isDefined } from '@superset-ui/core/src';

describe('isDefined(value)', () => {
  it('returns true if value is not null and not undefined', () => {
    expect(isDefined(0)).toBe(true);
    expect(isDefined(1)).toBe(true);
    expect(isDefined('')).toBe(true);
    expect(isDefined('a')).toBe(true);
    expect(isDefined([])).toBe(true);
    expect(isDefined([0])).toBe(true);
    expect(isDefined([1])).toBe(true);
    expect(isDefined({})).toBe(true);
    expect(isDefined({ a: 1 })).toBe(true);
    expect(isDefined([{}])).toBe(true);
  });
  it('returns false otherwise', () => {
    expect(isDefined(null)).toBe(false);
    expect(isDefined(undefined)).toBe(false);
  });
});


text:
<?php
namespace AboutYou\SDK\Model\Basket;

class DeliveryEstimation
{
    /**
     * @var int
     */
    protected $minDays;

    /**
     * @var int
     */
    protected $maxDays;

    /**
     * @var \DateTime
     */
    protected $minDate;

    /**
     * @var \DateTime
     */
    protected $maxDate;

    /**
     * @var boolean
     */
    protected $holiday;

    /**
     * @var boolean
     */
    protected $weekend;

    /**
     * @var boolean
     */
    protected $crossdocked;

    public static function createFromJSON($jsonObject)
    {
        return new DeliveryEstimation(
            isset($jsonObject->min) ? intval($jsonObject->min) : null,
            isset($jsonObject->max) ? intval($jsonObject->max) : null,
            isset($jsonObject->min_date) ? new \DateTime($jsonObject->min_date) : null,
            isset($jsonObject->max_date) ? new \DateTime($jsonObject->max_date) : null,
            isset($jsonObject->crossdocked) ? (bool) $jsonObject->crossdocked : null,
            isset($jsonObject->holiday) ? (bool) $jsonObject->holiday : null,
            isset($jsonObject->weekend) ? (bool) $jsonObject->weekend : null

        );
    }

    public function __construct($minDays, $maxDays, $minDate, $maxDate, $crossdocked, $holiday, $weekend)
    {
        $this->minDays = $minDays;
        $this->maxDays = $maxDays;
        $this->minDate = $minDate;
        $this->maxDate = $maxDate;
        $this->crossdocked = $crossdocked;
        $this->holiday = $holiday;
        $this->weekend = $weekend;
    }

    /**
     * @return int
     */
    public function getMinDays()
    {
        return $this->minDays;
    }

    /**
     * @return int
     */
    public function getMaxDays()
    {
        return $this->maxDays;
    }

    /**
     * @return \DateTime
     */
    public function getMinDate()
    {
        return $this->minDate;
    }

    /**
     * @return \DateTime
     */
    public function getMaxDate()
    {
        return $this->maxDate;
    }

    /**
     * @return boolean
     */
    public function getHoliday()
    {
        return $this->holiday;
    }

    /**
     * @return boolean
     */
    public function getWeekend()
    {
        return $this->weekend;
    }

    /**
     * @return boolean
     */
    public function getCrossdocked()
    {
        return $this->crossdocked;
    }
}


text:
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

/*!
 * # Lattice Variables
 *
 * This file contains generic code for operating on inference variables
 * that are characterized by an upper- and lower-bound.  The logic and
 * reasoning is explained in detail in the large comment in `infer.rs`.
 *
 * The code in here is defined quite generically so that it can be
 * applied both to type variables, which represent types being inferred,
 * and fn variables, which represent function types being inferred.
 * It may eventually be applied to their types as well, who knows.
 * In some cases, the functions are also generic with respect to the
 * operation on the lattice (GLB vs LUB).
 *
 * Although all the functions are generic, we generally write the
 * comments in a way that is specific to type variables and the LUB
 * operation.  It's just easier that way.
 *
 * In general all of the functions are defined parametrically
 * over a `LatticeValue`, which is a value defined with respect to
 * a lattice.
 */

use middle::ty::{RegionVid, TyVar};
use middle::ty;
use middle::typeck::infer::*;
use middle::typeck::infer::combine::*;
use middle::typeck::infer::glb::Glb;
use middle::typeck::infer::lub::Lub;
use util::ppaux::Repr;

use std::collections::HashMap;

pub trait LatticeDir {
    // Relates the bottom type to `t` and returns LUB(t, _|_) or
    // GLB(t, _|_) as appropriate.
    fn ty_bot(&self, t: ty::t) -> cres<ty::t>;

    // Relates the type `v` to `a` and `b` such that `v` represents
    // the LUB/GLB of `a` and `b` as appropriate.
    fn relate_bound<'a>(&'a self, v: ty::t, a: ty::t, b: ty::t) -> cres<()>;
}

impl<'a, 'tcx> LatticeDir for Lub<'a, 'tcx> {
    fn ty_bot(&self, t: ty::t) -> cres<ty::t> {
        Ok(t)
    }

    fn relate_bound<'a>(&'a self, v: ty::t, a: ty::t, b: ty::t) -> cres<()> {
        let sub = self.sub();
        try!(sub.tys(a, v));
        try!(sub.tys(b, v));
        Ok(())
    }
}

impl<'a, 'tcx> LatticeDir for Glb<'a, 'tcx> {
    fn ty_bot(&self, _: ty::t) -> cres<ty::t> {
        Ok(ty::mk_bot())
    }

    fn relate_bound<'a>(&'a self, v: ty::t, a: ty::t, b: ty::t) -> cres<()> {
        let sub = self.sub();
        try!(sub.tys(v, a));
        try!(sub.tys(v, b));
        Ok(())
    }
}

pub fn super_lattice_tys<'tcx, L:LatticeDir+Combine<'tcx>>(this: &L,
                                                           a: ty::t,
                                                           b: ty::t)
                                                           -> cres<ty::t>
{
    debug!("{}.lattice_tys({}, {})",
           this.tag(),
           a.repr(this.infcx().tcx),
           b.repr(this.infcx().tcx));

    if a == b {
        return Ok(a);
    }

    let infcx = this.infcx();
    let a = infcx.type_variables.borrow().replace_if_possible(a);
    let b = infcx.type_variables.borrow().replace_if_possible(b);
    match (&ty::get(a).sty, &ty::get(b).sty) {
        (&ty::ty_bot, _) => { this.ty_bot(b) }
        (_, &ty::ty_bot) => { this.ty_bot(a) }

        (&ty::ty_infer(TyVar(..)), _) |
        (_, &ty::ty_infer(TyVar(..))) => {
            let v = infcx.next_ty_var();
            try!(this.relate_bound(v, a, b));
            Ok(v)
        }

        _ => {
            super_tys(this, a, b)
        }
    }
}

///////////////////////////////////////////////////////////////////////////
// Random utility functions used by LUB/GLB when computing LUB/GLB of
// fn types

pub fn var_ids<'tcx, T: Combine<'tcx>>(this: &T,
                                       map: &HashMap<ty::BoundRegion, ty::Region>)
                                       -> Vec<RegionVid> {
    map.iter().map(|(_, r)| match *r {
            ty::ReInfer(ty::ReVar(r)) => { r }
            r => {
                this.infcx().tcx.sess.span_bug(
                    this.trace().origin.span(),
                    format!("found non-region-vid: {}", r).as_slice());
            }
        }).collect()
}

pub fn is_var_in_set(new_vars: &[RegionVid], r: ty::Region) -> bool {
    match r {
        ty::ReInfer(ty::ReVar(ref v)) => new_vars.iter().any(|x| x == v),
        _ => false
    }
}


text:
namespace remoting {

ChromotingClient::ChromotingClient(
    ClientContext* client_context,
    ClientUserInterface* user_interface,
    protocol::VideoRenderer* video_renderer,
    base::WeakPtr<protocol::AudioStub> audio_consumer)
    : user_interface_(user_interface), video_renderer_(video_renderer) {
  DCHECK(client_context->main_task_runner()->BelongsToCurrentThread());

  audio_decode_task_runner_ = client_context->audio_decode_task_runner();
  audio_consumer_ = audio_consumer;
}

ChromotingClient::~ChromotingClient() {
  if (signal_strategy_)
      signal_strategy_->RemoveListener(this);
}

void ChromotingClient::set_protocol_config(
    std::unique_ptr<protocol::CandidateSessionConfig> config) {
  protocol_config_ = std::move(config);
}

void ChromotingClient::SetConnectionToHostForTests(
    std::unique_ptr<protocol::ConnectionToHost> connection_to_host) {
  connection_ = std::move(connection_to_host);
}

void ChromotingClient::Start(
    SignalStrategy* signal_strategy,
    const protocol::ClientAuthenticationConfig& client_auth_config,
    scoped_refptr<protocol::TransportContext> transport_context,
    const std::string& host_jid,
    const std::string& capabilities) {
  DCHECK(thread_checker_.CalledOnValidThread());
  DCHECK(!session_manager_);  // Start must be called more than once.

  host_jid_ = NormalizeJid(host_jid);
  local_capabilities_ = capabilities;

  if (!protocol_config_)
    protocol_config_ = protocol::CandidateSessionConfig::CreateDefault();
  if (!audio_consumer_)
    protocol_config_->DisableAudioChannel();

  if (!connection_) {
    if (protocol_config_->webrtc_supported()) {
      DCHECK(!protocol_config_->ice_supported());
#if !defined(ENABLE_WEBRTC_REMOTING_CLIENT)
      LOG(FATAL) << "WebRTC is not supported.";
#else
      connection_.reset(new protocol::WebrtcConnectionToHost());
#endif
    } else {
      DCHECK(protocol_config_->ice_supported());
      connection_.reset(new protocol::IceConnectionToHost());
    }
  }
  connection_->set_client_stub(this);
  connection_->set_clipboard_stub(this);
  connection_->set_video_renderer(video_renderer_);

  connection_->InitializeAudio(audio_decode_task_runner_, audio_consumer_);

  session_manager_.reset(new protocol::JingleSessionManager(signal_strategy));
  session_manager_->set_protocol_config(std::move(protocol_config_));

  client_auth_config_ = client_auth_config;
  transport_context_ = transport_context;

  signal_strategy_ = signal_strategy;
  signal_strategy_->AddListener(this);

  switch (signal_strategy_->GetState()) {
    case SignalStrategy::CONNECTING:
      // Nothing to do here. Just need to wait until |signal_strategy_| becomes
      // connected.
      break;
    case SignalStrategy::CONNECTED:
      StartConnection();
      break;
    case SignalStrategy::DISCONNECTED:
      signal_strategy_->Connect();
      break;
  }
}

void ChromotingClient::SetCapabilities(
    const protocol::Capabilities& capabilities) {
  DCHECK(thread_checker_.CalledOnValidThread());

  // Only accept the first |protocol::Capabilities| message.
  if (host_capabilities_received_) {
    LOG(WARNING) << "protocol::Capabilities has been received already.";
    return;
  }

  host_capabilities_received_ = true;
  if (capabilities.has_capabilities())
    host_capabilities_ = capabilities.capabilities();

  VLOG(1) << "Host capabilities: " << host_capabilities_;

  // Calculate the set of capabilities enabled by both client and host and pass
  // it to the webapp.
  user_interface_->SetCapabilities(
      IntersectCapabilities(local_capabilities_, host_capabilities_));
}

void ChromotingClient::SetPairingResponse(
    const protocol::PairingResponse& pairing_response) {
  DCHECK(thread_checker_.CalledOnValidThread());

  user_interface_->SetPairingResponse(pairing_response);
}

void ChromotingClient::DeliverHostMessage(
    const protocol::ExtensionMessage& message) {
  DCHECK(thread_checker_.CalledOnValidThread());

  user_interface_->DeliverHostMessage(message);
}

void ChromotingClient::SetVideoLayout(const protocol::VideoLayout& layout) {
  int num_video_tracks = layout.video_track_size();
  if (num_video_tracks < 1) {
    LOG(ERROR) << "Received VideoLayout message with 0 tracks.";
    return;
  }

  if (num_video_tracks > 2) {
    LOG(WARNING) << "Received VideoLayout message with " << num_video_tracks
                 << " tracks. Only one track is supported.";
  }

  const protocol::VideoTrackLayout& track_layout = layout.video_track(0);
  int x_dpi = track_layout.has_x_dpi() ? track_layout.x_dpi() : kDefaultDpi;
  int y_dpi = track_layout.has_y_dpi() ? track_layout.y_dpi() : kDefaultDpi;

  webrtc::DesktopSize size_dips(track_layout.width(), track_layout.height());
  webrtc::DesktopSize size_pixels(size_dips.width() * x_dpi / kDefaultDpi,
                                  size_dips.height() * y_dpi / kDefaultDpi);
  user_interface_->SetDesktopSize(size_pixels,
                                  webrtc::DesktopVector(x_dpi, y_dpi));

  mouse_input_scaler_.set_input_size(size_pixels);
  mouse_input_scaler_.set_output_size(
      connection_->config().protocol() == protocol::SessionConfig::Protocol::ICE
          ? size_pixels
          : size_dips);
}

void ChromotingClient::InjectClipboardEvent(
    const protocol::ClipboardEvent& event) {
  DCHECK(thread_checker_.CalledOnValidThread());

  user_interface_->GetClipboardStub()->InjectClipboardEvent(event);
}

void ChromotingClient::SetCursorShape(
    const protocol::CursorShapeInfo& cursor_shape) {
  DCHECK(thread_checker_.CalledOnValidThread());

  user_interface_->GetCursorShapeStub()->SetCursorShape(cursor_shape);
}

void ChromotingClient::OnConnectionState(
    protocol::ConnectionToHost::State state,
    protocol::ErrorCode error) {
  DCHECK(thread_checker_.CalledOnValidThread());
  VLOG(1) << "ChromotingClient::OnConnectionState(" << state << ")";

  if (state == protocol::ConnectionToHost::CONNECTED) {
    OnChannelsConnected();
  }
  user_interface_->OnConnectionState(state, error);
}

void ChromotingClient::OnConnectionReady(bool ready) {
  VLOG(1) << "ChromotingClient::OnConnectionReady(" << ready << ")";
  user_interface_->OnConnectionReady(ready);
}

void ChromotingClient::OnRouteChanged(const std::string& channel_name,
                                      const protocol::TransportRoute& route) {
  VLOG(0) << "Using " << protocol::TransportRoute::GetTypeString(route.type)
          << " connection for " << channel_name << " channel";
  user_interface_->OnRouteChanged(channel_name, route);
}

void ChromotingClient::OnSignalStrategyStateChange(
    SignalStrategy::State state) {
  DCHECK(thread_checker_.CalledOnValidThread());

  if (state == SignalStrategy::CONNECTED) {
    VLOG(1) << "Connected as: " << signal_strategy_->GetLocalJid();
    // After signaling has been connected we can try connecting to the host.
    if (connection_ &&
        connection_->state() == protocol::ConnectionToHost::INITIALIZING) {
      StartConnection();
    }
  } else if (state == SignalStrategy::DISCONNECTED) {
    VLOG(1) << "Signaling connection closed.";
    connection_.reset();
    user_interface_->OnConnectionState(protocol::ConnectionToHost::CLOSED,
                                       protocol::SIGNALING_ERROR);
  }
}

bool ChromotingClient::OnSignalStrategyIncomingStanza(
    const buzz::XmlElement* stanza) {
  return false;
}

void ChromotingClient::StartConnection() {
  DCHECK(thread_checker_.CalledOnValidThread());
  connection_->Connect(
      session_manager_->Connect(
          host_jid_, base::MakeUnique<protocol::NegotiatingClientAuthenticator>(
                         NormalizeJid(signal_strategy_->GetLocalJid()),
                         host_jid_, client_auth_config_)),
      transport_context_, this);
}

void ChromotingClient::OnChannelsConnected() {
  DCHECK(thread_checker_.CalledOnValidThread());

  // Negotiate capabilities with the host.
  VLOG(1) << "Client capabilities: " << local_capabilities_;

  protocol::Capabilities capabilities;
  capabilities.set_capabilities(local_capabilities_);
  connection_->host_stub()->SetCapabilities(capabilities);

  mouse_input_scaler_.set_input_stub(connection_->input_stub());
}

}  // namespace remoting


text:
package org.apache.drill.exec.ops;

import io.netty.buffer.DrillBuf;

import org.apache.drill.exec.memory.BufferAllocator;

import com.carrotsearch.hppc.LongObjectHashMap;
import com.carrotsearch.hppc.predicates.LongObjectPredicate;

public class BufferManagerImpl implements BufferManager {
  private LongObjectHashMap<DrillBuf> managedBuffers = new LongObjectHashMap<>();
  private final BufferAllocator allocator;

  public BufferManagerImpl(BufferAllocator allocator) {
    this.allocator = allocator;
  }

  @Override
  public void close() {
    managedBuffers.forEach(new LongObjectPredicate<DrillBuf>() {
      @Override
      public boolean apply(long key, DrillBuf value) {
        value.release();
        return true;
      }
    });
    managedBuffers.clear();
  }

  public DrillBuf replace(DrillBuf old, int newSize) {
    if (managedBuffers.remove(old.memoryAddress()) == null) {
      throw new IllegalStateException("Tried to remove unmanaged buffer.");
    }
    old.release(1);
    return getManagedBuffer(newSize);
  }

  public DrillBuf getManagedBuffer() {
    return getManagedBuffer(256);
  }

  public DrillBuf getManagedBuffer(int size) {
    DrillBuf newBuf = allocator.buffer(size, this);
    managedBuffers.put(newBuf.memoryAddress(), newBuf);
    return newBuf;
  }
}