text:
#define _GNU_SOURCE
#include <stdio.h>
#include <string.h>
#include <stdarg.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/sysinfo.h>
#ifdef __linux__
#include <alloca.h>
#endif
#include <pthread.h>
#include <time.h>
#include <math.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/time.h>
#include <libxml/tree.h>
#include <libxml/xpath.h>
#include <libxml/xpathInternals.h>
#include "cloudfsapi.h"
#include "config.h"

#define RHEL5_LIBCURL_VERSION 462597
#define RHEL5_CERTIFICATE_FILE "/etc/pki/tls/certs/ca-bundle.crt"

#define REQUEST_RETRIES 4

static char storage_url[MAX_URL_SIZE];
static char storage_token[MAX_HEADER_SIZE];
static pthread_mutex_t pool_mut;
static CURL *curl_pool[1024];
static int curl_pool_count = 0;
static int debug = 0;
static int verify_ssl = 1;
static int rhel5_mode = 0;

#ifdef HAVE_OPENSSL
#include <openssl/crypto.h>
static pthread_mutex_t *ssl_lockarray;
static void lock_callback(int mode, int type, char *file, int line)
{
  if (mode & CRYPTO_LOCK)
    pthread_mutex_lock(&(ssl_lockarray[type]));
  else
    pthread_mutex_unlock(&(ssl_lockarray[type]));
}

static unsigned long thread_id()
{
  return (unsigned long)pthread_self();
}
#endif

static void rewrite_url_snet(char *url)
{
  char protocol[MAX_URL_SIZE];
  char rest[MAX_URL_SIZE];
  sscanf(url, "%[a-z]://%s", protocol, rest);
  if (strncasecmp(rest, "snet-", 5))
    sprintf(url, "%s://snet-%s", protocol, rest);
}

static size_t xml_dispatch(void *ptr, size_t size, size_t nmemb, void *stream)
{
  xmlParseChunk((xmlParserCtxtPtr)stream, (char *)ptr, size * nmemb, 0);
  return size * nmemb;
}

static CURL *get_connection(const char *path)
{
  pthread_mutex_lock(&pool_mut);
  CURL *curl = curl_pool_count ? curl_pool[--curl_pool_count] : curl_easy_init();
  if (!curl)
  {
    debugf("curl alloc failed");
    abort();
  }
  pthread_mutex_unlock(&pool_mut);
  return curl;
}

static void return_connection(CURL *curl)
{
  pthread_mutex_lock(&pool_mut);
  curl_pool[curl_pool_count++] = curl;
  pthread_mutex_unlock(&pool_mut);
}

static void add_header(curl_slist **headers, const char *name,
                       const char *value)
{
  char x_header[MAX_HEADER_SIZE];
  snprintf(x_header, sizeof(x_header), "%s: %s", name, value);
  *headers = curl_slist_append(*headers, x_header);
}

static int send_request(char *method, const char *path, FILE *fp,
                        xmlParserCtxtPtr xmlctx, curl_slist *extra_headers)
{
  char url[MAX_URL_SIZE];
  char *slash;
  long response = -1;
  int tries = 0;

  if (!storage_url[0])
  {
    debugf("send_request with no storage_url?");
    abort();
  }

  while ((slash = strstr(path, "%2F")) || (slash = strstr(path, "%2f")))
  {
    *slash = '/';
    memmove(slash+1, slash+3, strlen(slash+3)+1);
  }
  while (*path == '/')
    path++;
  snprintf(url, sizeof(url), "%s/%s", storage_url, path);

  // retry on failures
  for (tries = 0; tries < REQUEST_RETRIES; tries++)
  {
    CURL *curl = get_connection(path);
    if (rhel5_mode)
      curl_easy_setopt(curl, CURLOPT_CAINFO, RHEL5_CERTIFICATE_FILE);
    curl_slist *headers = NULL;
    curl_easy_setopt(curl, CURLOPT_URL, url);
    curl_easy_setopt(curl, CURLOPT_HEADER, 0);
    curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
    curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 1);
    curl_easy_setopt(curl, CURLOPT_USERAGENT, USER_AGENT);
    curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, verify_ssl);
    curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 10);
    curl_easy_setopt(curl, CURLOPT_VERBOSE, debug);
    add_header(&headers, "X-Auth-Token", storage_token);
    if (!strcasecmp(method, "MKDIR"))
    {
      curl_easy_setopt(curl, CURLOPT_UPLOAD, 1);
      curl_easy_setopt(curl, CURLOPT_INFILESIZE, 0);
      add_header(&headers, "Content-Type", "application/directory");
    }
    else if (!strcasecmp(method, "PUT") && fp)
    {
      rewind(fp);
      curl_easy_setopt(curl, CURLOPT_UPLOAD, 1);
      curl_easy_setopt(curl, CURLOPT_INFILESIZE, cloudfs_file_size(fileno(fp)));
      curl_easy_setopt(curl, CURLOPT_READDATA, fp);
    }
    else if (!strcasecmp(method, "GET"))
    {
      if (fp)
      {
        rewind(fp); // make sure the file is ready for a-writin'
        fflush(fp);
        if (ftruncate(fileno(fp), 0) < 0)
        {
          debugf("ftruncate failed.  I don't know what to do about that.");
          abort();
        }
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
      }
      else if (xmlctx)
      {
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, xmlctx);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &xml_dispatch);
      }
    }
    else
      curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, method);
    /* add the headers from extra_headers if any */
    curl_slist *extra;
    for (extra = extra_headers; extra; extra = extra->next)
    {
      debugf("adding header: %s", extra->data);
      headers = curl_slist_append(headers, extra->data);
    }
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
    curl_easy_perform(curl);
    curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response);
    curl_slist_free_all(headers);
    curl_easy_reset(curl);
    return_connection(curl);
    if (response >= 200 && response < 400)
      return response;
    sleep(8 << tries); // backoff
    if (response == 401 && !cloudfs_connect()) // re-authenticate on 401s
      return response;
    if (xmlctx)
      xmlCtxtResetPush(xmlctx, NULL, 0, NULL, NULL);
  }
  return response;
}

static size_t header_dispatch(void *ptr, size_t size, size_t nmemb, void *stream)
{
  char *header = (char *)alloca(size * nmemb + 1);
  char *head = (char *)alloca(size * nmemb + 1);
  char *value = (char *)alloca(size * nmemb + 1);
  memcpy(header, (char *)ptr, size * nmemb);
  header[size * nmemb] = '\0';
  if (sscanf(header, "%[^:]: %[^\r\n]", head, value) == 2)
  {
    if (!strncasecmp(head, "x-auth-token", size * nmemb))
      strncpy(storage_token, value, sizeof(storage_token));
    if (!strncasecmp(head, "x-storage-url", size * nmemb))
      strncpy(storage_url, value, sizeof(storage_url));
  }
  return size * nmemb;
}

int write_iter;
pthread_mutex_t write_iter_lock;

void set_write_iter() {
  pthread_mutex_lock(&write_iter_lock);
  int ret = write_iter++;
  pthread_mutex_unlock(&write_iter_lock);
}

int get_write_iter() {
  pthread_mutex_lock(&write_iter_lock);
  int ret = write_iter;
  pthread_mutex_unlock(&write_iter_lock);
  return ret;
}

void* write_splits(void* in) {
  t_thread_pass *data = (t_thread_pass *) in;
  const char* store_path = data->path;
  int blocks = data->blocks;

  intptr_t result = 1;
  int i = get_write_iter();
  t_fifo_elem *elem = pop_fifo();

  while (i < blocks) {
    if(elem != NULL) {
      FILE *tmp = elem->data;
      i = elem->index;

      char iStr[10];
      sprintf(iStr, "%d", i);

      curl_slist *headers = NULL;
      add_header(&headers, "X-Chunk-Index", iStr);

      char *encoded = curl_escape(store_path, 0);
      int response = send_request("PUT", encoded, tmp, NULL, headers);
      result = (response >= 200 && response < 300) && result;
      curl_free(encoded);
      fclose(tmp);

      set_write_iter();
    }
    i = get_write_iter();
    elem = pop_fifo();
  }

  pthread_exit((void*) result);

  return 0;
}

void* create_splits(void* in) {
  t_thread_pass *data = (t_thread_pass *) in;
  char *file = data->data;
  int blocks = data->blocks;
  long size = data->size;

  int i;

  reset_level();

  for (i = 0; i < blocks; i++) {
    int fifo_size_at_start = fifo_size();

    char *buf = (char*)calloc(CHUNK+1,sizeof(char));
    FILE *tmp = tmpfile();
    FILE *store = tmpfile();

    long begin = i*CHUNK;
    long end = (i*CHUNK+CHUNK-1 > size ? size : i*CHUNK+CHUNK);

    fwrite(&file[i*CHUNK], sizeof(char), end-begin, tmp);
    fflush(tmp);
    fseek(tmp, 0L, SEEK_SET);

    adaptive_deflate(tmp, store);
    fclose(tmp);
    push_fifo(i, store);

    free(buf);

    int fifo_diff = fifo_size() - fifo_size_at_start;
    update_level(fifo_diff);
  }

  return 0;
}

int split_file_and_put(const char* path, FILE* fp, FILE* temp, long size) {
  int blocks;
  pthread_t create_thread, write_thread, write_thread_2;
  pthread_t *write_threads = (pthread_t*) malloc(NUM_THREADS*sizeof(pthread_t));

  blocks = ceil((float)size/CHUNK);
  char* file = (char*) calloc(1, CHUNK*blocks);

  fprintf(temp, "%d", blocks);

  if(fread(file, sizeof(char), size, fp) != size)
    return 0;

  t_thread_pass *pass_splits = (t_thread_pass *) malloc(sizeof(t_thread_pass));
  t_thread_pass *pass_write = (t_thread_pass *) malloc(sizeof(t_thread_pass));

  pass_splits->data = file;
  pass_splits->blocks = blocks;
  pass_splits->size = size;

  pass_write->path = path;
  pass_write->blocks = blocks;

  int result = 1;

  pthread_mutex_init(&write_iter_lock, NULL);
  write_iter = 0;
  int i = 0;

  pthread_create(&create_thread, NULL, create_splits, pass_splits);
  for(i = 0; i < NUM_THREADS; i++) {
    pthread_create(&write_threads[i], NULL, write_splits, pass_write);
  }

  pthread_join(create_thread, NULL);
  for(i = 0; i < NUM_THREADS; i++) {
    int res;
    pthread_join(write_threads[i], (void **)&res);
    result = result && res;
  }

  pthread_mutex_destroy(&write_iter_lock);

  return result;
}

/*
 * Public interface
 */

void cloudfs_init()
{
  LIBXML_TEST_VERSION
  xmlXPathInit();
  curl_global_init(CURL_GLOBAL_ALL);
  pthread_mutex_init(&pool_mut, NULL);
  curl_version_info_data *cvid = curl_version_info(CURLVERSION_NOW);

  // CentOS/RHEL 5 get stupid mode, because they have a broken libcurl
  if (cvid->version_num == RHEL5_LIBCURL_VERSION)
  {
    debugf("RHEL5 mode enabled.");
    rhel5_mode = 1;
  }

  if (!strncasecmp(cvid->ssl_version, "openssl", 7))
  {
    #ifdef HAVE_OPENSSL
    int i;
    ssl_lockarray = (pthread_mutex_t *)OPENSSL_malloc(CRYPTO_num_locks() *
                                              sizeof(pthread_mutex_t));
    for (i = 0; i < CRYPTO_num_locks(); i++)
      pthread_mutex_init(&(ssl_lockarray[i]), NULL);
    CRYPTO_set_id_callback((unsigned long (*)())thread_id);
    CRYPTO_set_locking_callback((void (*)())lock_callback);
    #endif
  }
  else if (!strncasecmp(cvid->ssl_version, "nss", 3))
  {
    // allow https to continue working after forking (for RHEL/CentOS 6)
    setenv("NSS_STRICT_NOFORK", "DISABLED", 1);
  }
}

int cloudfs_object_read_fp(const char *path, FILE *fp)
{
  fflush(fp);
  rewind(fp);

  FILE *tmp = tmpfile();

  fseek(fp, 0L, SEEK_END);
  long size = ftell(fp);
  rewind(fp);

  split_file_and_put(path, fp, tmp, size);

  curl_slist *headers = NULL;
  add_header(&headers, "X-Write-To-Core", "true");
  add_header(&headers, "Expect", "");

  char *encoded = curl_escape(path, 0);
  int response = send_request("PUT", encoded, tmp, NULL, headers);
  fclose(tmp);
  curl_free(encoded);
  return (response >= 200 && response < 300);
}

int cloudfs_object_write_fp(const char *path, FILE *fp)
{
  char *encoded = curl_escape(path, 0);
  FILE *tmp = tmpfile();
  curl_slist *headers = NULL;
  add_header(&headers, "X-Get-Compressed", "true");
  int response = send_request("GET", encoded, tmp, NULL, headers);
  curl_free(encoded);
  fflush(tmp);
  rewind(tmp);
  adaptive_inflate(tmp, fp);
  fflush(fp);
  if ((response >= 200 && response < 300) || ftruncate(fileno(fp), 0))
    return 1;
  rewind(fp);
  return 0;
}

int cloudfs_object_truncate(const char *path, off_t size)
{
  char *encoded = curl_escape(path, 0);
  int response;
  if (size == 0)
  {
    FILE *fp = fopen("/dev/null", "r");
    response = send_request("PUT", encoded, fp, NULL, NULL);
    fclose(fp);
  }
  else
  {//TODO: this is busted
    response = send_request("GET", encoded, NULL, NULL, NULL);
  }
  curl_free(encoded);
  return (response >= 200 && response < 300);
}

int cloudfs_list_directory(const char *path, dir_entry **dir_list)
{
  char container[MAX_PATH_SIZE * 3] = "";
  char object[MAX_PATH_SIZE] = "";
  char last_subdir[MAX_PATH_SIZE] = "";
  int prefix_length = 0;
  int response = 0;
  int retval = 0;
  int entry_count = 0;

  *dir_list = NULL;
  xmlNode *onode = NULL, *anode = NULL, *text_node = NULL;
  xmlParserCtxtPtr xmlctx = xmlCreatePushParserCtxt(NULL, NULL, "", 0, NULL);
  if (!strcmp(path, "") || !strcmp(path, "/"))
  {
    path = "";
    strncpy(container, "/?format=xml", sizeof(container));
  }
  else
  {
    sscanf(path, "/%[^/]/%[^\n]", container, object);
    char *encoded_container = curl_escape(container, 0);
    char *encoded_object = curl_escape(object, 0);

    // The empty path doesn't get a trailing slash, everything else does
    char *trailing_slash;
    prefix_length = strlen(object);
    if (object[0] == 0)
      trailing_slash = "";
    else
    {
      trailing_slash = "/";
      prefix_length++;
    }

    snprintf(container, sizeof(container), "%s?format=xml&delimiter=/&prefix=%s%s",
              encoded_container, encoded_object, trailing_slash);
    curl_free(encoded_container);
    curl_free(encoded_object);
  }

  response = send_request("GET", container, NULL, xmlctx, NULL);
  xmlParseChunk(xmlctx, "", 0, 1);
  if (xmlctx->wellFormed && response >= 200 && response < 300)
  {
    xmlNode *root_element = xmlDocGetRootElement(xmlctx->myDoc);
    for (onode = root_element->children; onode; onode = onode->next)
    {
      if (onode->type != XML_ELEMENT_NODE) continue;

      char is_object = !strcasecmp((const char *)onode->name, "object");
      char is_container = !strcasecmp((const char *)onode->name, "container");
      char is_subdir = !strcasecmp((const char *)onode->name, "subdir");

      if (is_object || is_container || is_subdir)
      {
        entry_count++;

        dir_entry *de = (dir_entry *)malloc(sizeof(dir_entry));
        de->next = NULL;
        de->size = 0;
        de->last_modified = time(NULL);
        if (is_container || is_subdir)
          de->content_type = strdup("application/directory");
        for (anode = onode->children; anode; anode = anode->next)
        {
          char *content = "<?!?>";
          for (text_node = anode->children; text_node; text_node = text_node->next)
            if (text_node->type == XML_TEXT_NODE)
              content = (char *)text_node->content;
          if (!strcasecmp((const char *)anode->name, "name"))
          {
            de->name = strdup(content + prefix_length);

            // Remove trailing slash
            char *slash = strrchr(de->name, '/');
            if (slash && (0 == *(slash + 1)))
              *slash = 0;

            if (asprintf(&(de->full_name), "%s/%s", path, de->name) < 0)
              de->full_name = NULL;
          }
          if (!strcasecmp((const char *)anode->name, "bytes"))
            de->size = strtoll(content, NULL, 10);
          if (!strcasecmp((const char *)anode->name, "content_type"))
          {
            de->content_type = strdup(content);
            char *semicolon = strchr(de->content_type, ';');
            if (semicolon)
              *semicolon = '\0';
          }
          if (!strcasecmp((const char *)anode->name, "last_modified"))
          {
            struct tm last_modified;
            strptime(content, "%FT%T", &last_modified);
            de->last_modified = mktime(&last_modified);
          }
        }
        de->isdir = de->content_type &&
            ((strstr(de->content_type, "application/folder") != NULL) ||
             (strstr(de->content_type, "application/directory") != NULL));
        if (de->isdir)
        {
          if (!strncasecmp(de->name, last_subdir, sizeof(last_subdir)))
          {
            cloudfs_free_dir_list(de);
            continue;
          }
          strncpy(last_subdir, de->name, sizeof(last_subdir));
        }
        de->next = *dir_list;
        *dir_list = de;
      }
      else
      {
        debugf("unknown element: %s", onode->name);
      }
    }
    retval = 1;
  }

  debugf("entry count: %d", entry_count);

  xmlFreeDoc(xmlctx->myDoc);
  xmlFreeParserCtxt(xmlctx);
  return retval;
}

void cloudfs_free_dir_list(dir_entry *dir_list)
{
  while (dir_list)
  {
    dir_entry *de = dir_list;
    dir_list = dir_list->next;
    free(de->name);
    free(de->full_name);
    free(de->content_type);
    free(de);
  }
}

int cloudfs_delete_object(const char *path)
{
  char *encoded = curl_escape(path, 0);
  int response = send_request("DELETE", encoded, NULL, NULL, NULL);
  curl_free(encoded);
  return (response >= 200 && response < 300);
}

int cloudfs_copy_object(const char *src, const char *dst)
{
  char *dst_encoded = curl_escape(dst, 0);
  curl_slist *headers = NULL;
  add_header(&headers, "X-Copy-From", src);
  add_header(&headers, "Content-Length", "0");
  int response = send_request("PUT", dst_encoded, NULL, NULL, headers);
  curl_free(dst_encoded);
  curl_slist_free_all(headers);
  return (response >= 200 && response < 300);
}

int cloudfs_create_directory(const char *path)
{
  char *encoded = curl_escape(path, 0);
  int response = send_request("MKDIR", encoded, NULL, NULL, NULL);
  curl_free(encoded);
  return (response >= 200 && response < 300);
}

off_t cloudfs_file_size(int fd)
{
  struct stat buf;
  fstat(fd, &buf);
  return buf.st_size;
}

void cloudfs_debug(int dbg)
{
  debug = dbg;
}

void cloudfs_verify_ssl(int vrfy)
{
  verify_ssl = vrfy;
}

static struct {
  char username[MAX_HEADER_SIZE], password[MAX_HEADER_SIZE],
      tenant[MAX_HEADER_SIZE], authurl[MAX_URL_SIZE], region[MAX_URL_SIZE],
      use_snet, auth_version;
} reconnect_args;

void cloudfs_set_credentials(char *username, char *tenant, char *password,
                             char *authurl, char *region, int use_snet)
{
  strncpy(reconnect_args.username, username, sizeof(reconnect_args.username));
  strncpy(reconnect_args.tenant, tenant, sizeof(reconnect_args.tenant));
  strncpy(reconnect_args.password, password, sizeof(reconnect_args.password));
  strncpy(reconnect_args.authurl, authurl, sizeof(reconnect_args.authurl));
  strncpy(reconnect_args.region, region, sizeof(reconnect_args.region));
  if (strstr(authurl, "v2.0"))
  {
    reconnect_args.auth_version = 2;
    if (!strcmp(authurl + strlen(authurl) - 5, "/v2.0"))
      strcat(reconnect_args.authurl, "/tokens");
    else if (!strcmp(authurl + strlen(authurl) - 6, "/v2.0/"))
      strcat(reconnect_args.authurl, "tokens");
  }
  else
    reconnect_args.auth_version = 1;
  reconnect_args.use_snet = use_snet;
}

int cloudfs_connect()
{
  long response = -1;
  curl_slist *headers = NULL;
  CURL *curl = curl_easy_init();
  char postdata[8192] = "";
  xmlNode *top_node = NULL, *service_node = NULL, *endpoint_node = NULL;
  xmlParserCtxtPtr xmlctx = NULL;

  if(!init_fifo()) {
    return 0;
  }

  pthread_mutex_lock(&pool_mut);

  storage_token[0] = storage_url[0] = '\0';

  if (reconnect_args.auth_version == 2)
  {
    if (reconnect_args.username[0] && reconnect_args.tenant[0] && reconnect_args.password[0])
    {
      snprintf(postdata, sizeof(postdata), "<?xml version=\"1.0\" encoding"
          "=\"UTF-8\"?><auth xmlns=\"http://docs.openstack.org/identity/ap"
          "i/v2.0\" tenantName=\"%s\"><passwordCredentials username=\"%s\""
          " password=\"%s\"/></auth>", reconnect_args.tenant,
          reconnect_args.username, reconnect_args.password);
    }
    else if (reconnect_args.username[0] && reconnect_args.password[0])
    {
      snprintf(postdata, sizeof(postdata), "<?xml version=\"1.0\" encoding"
          "=\"UTF-8\"?><auth><apiKeyCredentials xmlns=\"http://docs.racksp"
          "ace.com/identity/api/ext/RAX-KSKEY/v1.0\" username=\"%s\" apiKe"
          "y=\"%s\"/></auth>", reconnect_args.username, reconnect_args.password);
    }
    else
    {
      debugf("Unable to determine auth scheme.");
      abort();
    }
    debugf("%s", postdata);

    add_header(&headers, "Content-Type", "application/xml");
    add_header(&headers, "Accept", "application/xml");

    curl_easy_setopt(curl, CURLOPT_POST, 1);
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postdata);
    curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, strlen(postdata));

    xmlctx = xmlCreatePushParserCtxt(NULL, NULL, "", 0, NULL);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, xmlctx);
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &xml_dispatch);
  }
  else
  {
    add_header(&headers, "X-Auth-User", reconnect_args.username);
    add_header(&headers, "X-Auth-Key", reconnect_args.password);
    curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, &header_dispatch);
  }

  curl_easy_setopt(curl, CURLOPT_VERBOSE, debug);
  curl_easy_setopt(curl, CURLOPT_URL, reconnect_args.authurl);
  curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  curl_easy_setopt(curl, CURLOPT_USERAGENT, USER_AGENT);
  curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
  curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, verify_ssl);
  curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, verify_ssl);
  curl_easy_setopt(curl, CURLOPT_TIMEOUT, 10);
  curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 10);
  curl_easy_setopt(curl, CURLOPT_FORBID_REUSE, 1);

  debugf("Sending authentication request.");
  curl_easy_perform(curl);
  curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response);
  curl_slist_free_all(headers);
  curl_easy_cleanup(curl);

  if (reconnect_args.auth_version == 2)
  {
    xmlParseChunk(xmlctx, "", 0, 1);
    if (xmlctx->wellFormed && response >= 200 && response < 300)
    {
      xmlXPathContextPtr xpctx = xmlXPathNewContext(xmlctx->myDoc);
      xmlXPathRegisterNs(xpctx, "id", "http://docs.openstack.org/identity/api/v2.0");
      xmlXPathObjectPtr obj;

      /* Determine default region if not configured */
      if (!reconnect_args.region[0])
      {
        obj = xmlXPathEval("/id:access/id:user", xpctx);
        if (obj && obj->nodesetval && obj->nodesetval->nodeNr > 0)
        {
          xmlChar *default_region = xmlGetProp(obj->nodesetval->nodeTab[0], "defaultRegion");
          if (default_region && *default_region)
          {
            strncpy(reconnect_args.region, default_region, sizeof(reconnect_args.region));
            xmlFree(default_region);
          }
        }
        xmlXPathFreeNodeSetList(obj);
      }
      debugf("Using region: %s", reconnect_args.region);

      if (reconnect_args.region[0])
      {
        char path[1024];
        snprintf(path, sizeof(path), "/id:access/id:serviceCatalog/id:service"
            "[@type='object-store']/id:endpoint[@region='%s']",
            reconnect_args.region);
        obj = xmlXPathEval(path, xpctx);
      }
      else
        obj = xmlXPathEval("/id:access/id:serviceCatalog/id:service"
            "[@type='object-store']/id:endpoint", xpctx);
      if (obj->nodesetval && obj->nodesetval->nodeNr > 0)
      {
        xmlChar *url;
        if (reconnect_args.use_snet)
          url = xmlGetProp(obj->nodesetval->nodeTab[0], "internalURL");
        else
          url = xmlGetProp(obj->nodesetval->nodeTab[0], "publicURL");
        strncpy(storage_url, url, sizeof(storage_url));
        xmlFree(url);
      }
      else
        debugf("Unable to find endpoint");
      xmlXPathFreeNodeSetList(obj);

      obj = xmlXPathEval("/id:access/id:token", xpctx);
      if (obj->nodesetval && obj->nodesetval->nodeNr > 0)
      {
        xmlChar *token_id = xmlGetProp(obj->nodesetval->nodeTab[0], "id");
        strncpy(storage_token, token_id, sizeof(storage_token));
        xmlFree(token_id);
      }
      xmlXPathFreeNodeSetList(obj);
      xmlXPathFreeContext(xpctx);
      debugf("storage_url: %s", storage_url);
      debugf("storage_token: %s", storage_token);
    }
    xmlFreeParserCtxt(xmlctx);
  }
  else if (reconnect_args.use_snet && storage_url[0])
    rewrite_url_snet(storage_url);
  pthread_mutex_unlock(&pool_mut);
  return (response >= 200 && response < 300 && storage_token[0] && storage_url[0]);
}

void debugf(char *fmt, ...)
{
  if (debug)
  {
    va_list args;
    va_start(args, fmt);
    fputs("!!! ", stderr);
    vfprintf(stderr, fmt, args);
    va_end(args);
    putc('\n', stderr);
  }
}


text:
import './shared/multi-select-list/main.js';
import './shared/route-extensions/main.js';

redpajama_set_name: RedPajamaGithub


text:
package portalsoup.component;

/**
 * This is used to simply declare a component as a core component, as in, a component that is required by one or
 * more other components.
 *
 * User: jcleary
 * Date: 2/24/14
 */
public interface CoreComponent {
}


text:
/*!
 * Start Bootstrap - 1 Col Portfolio HTML Template (http://startbootstrap.com)
 * Code licensed under the Apache License v2.0.
 * For details, see http://www.apache.org/licenses/LICENSE-2.0.
 */

/*.navbar navbar-inverse navbar-fixed-top .container .a {
    float: right;
}

.navbar navbar-inverse navbar-fixed-top .container .collapse navbar-collapse .li {
    float: right;
}*/

body {
    padding-top: 70px; /* Required padding for .navbar-fixed-top. Remove if using .navbar-static-top. Change if height of navigation changes. */

}

footer {
    margin: 50px 0;
}


text:
namespace wgt
{
const RefObjectId& RefObjectIds::current() const
{
	TF_ASSERT(ids_.size() > current_);
	return ids_.at(current_);
}

const RefObjectId& RefObjectIds::next()
{
	if (++current_ >= ids_.size())
	{
		ids_.emplace_back(RefObjectId::generate());
	}
	return current();
}

void RefObjectIds::begin()
{
	current_ = -1;
}

} // end namespace wgt


text:
import { Mongoose } from 'mongoose';
import * as express from 'express';
import * as resource from './resource';
import { Resource } from './resource';
import * as bodyParser from 'body-parser';
import UserResource from './userResource';
import * as authorizedResource from './authorizedResource';
import { default as AuthorizedResource, ROLES } from './authorizedResource';
import SubResource from './subResource';
import AuthorizedSubResource from './authorizedSubResource';
const autoloader = require('auto-loader');

export default class RestIO {
  static authorizedResource = authorizedResource;
  static UserResource = UserResource;
  static AuthorizedResource = AuthorizedResource;
  static SubResource = SubResource;
  static AuthorizedSubResource = AuthorizedSubResource;
  static Resource = Resource;
  static ROLES = ROLES;

  constructor(app: express.Application, config?: IRestIOConfig) {
    app.use(bodyParser.json());
    resource.registerApp(app, config.db);
    if (!!config) {
      const resources: Object = autoloader.load(config.resources);
      for (let i in resources) {
        if (resources.hasOwnProperty(i)) {
          // access to trigger getter of auto-loader
          resources[i];
        }
      }
    }
    return resource;
  }
}

export interface IRestIOConfig {
  resources: string;
  db?: Mongoose;
}


text:
Using cap

```
bundle exec cap production monit:exec["-g postgresql restart"]
```

From sever

```
monit -g postgresql restart
```

### How do I find where is pg_hba.conf file

Login as root and then execute following command.

```
find \ -name "pg_hba.conf"
```


text: window.Delivery = require('../src/js/app.js');


text:
def Session(request):
    """
    Restore session based on Cookie session_id.

    Set `request.session` with LazySession to fetch data from
    database when we access it.
    """
    pass


text:
DELIMITER /
ALTER TABLE COI_DISCLOSURE_NOTEPAD ADD CONSTRAINT COI_DISCLOSURE_ID_FK FOREIGN KEY (COI_DISCLOSURE_ID_FK) REFERENCES COI_DISCLOSURE (COI_DISCLOSURE_ID)
/

DELIMITER ;


text:
.pointer {
  cursor: pointer;
  /* Disabled double click selection */
  -moz-user-select: none;
  -webkit-user-select: none;
  -ms-user-select: none;
  user-select: none;
}


text:
namespace cobalt {
namespace media {

DataSource::DataSource() {}

DataSource::~DataSource() {}

}  // namespace media
}  // namespace cobalt


text:
import sys
from PyObjCTools.TestSupport import *
from PyObjCTest.voidpointer import OC_TestVoidPointer

class TestVoidPointer (TestCase):
    def testVoidPointerMethods(self):
        o = OC_TestVoidPointer.alloc().init()
        self.assertEqual(o.getvalue(), 0)

        o.setvalue_(523532)
        self.assertEqual(o.getvalue(), 523532)

        o.setvalue_(sys.maxsize + 1)
        self.assertEqual(o.getvalue(), sys.maxsize + 1)

if __name__ == "__main__":
    main()


text:
using namespace simplex;

static void append(std::vector<std::string>& vec, std::vector<std::string> other) {
  vec.insert(vec.end(), other.begin(), other.end());
}

static std::vector<std::string> whitespaceVariations(std::vector<std::string> input) {
  // inserts whitespace before, after, and before/after
  std::vector<std::string> ret;
  for (const auto& str : input) {
    ret.push_back(str);
    ret.push_back("  " + str);
    ret.push_back(str + "  ");
    ret.push_back(" " + str + " ");
  }
  return ret;
}

TEST_CASE("ASTNode") {
  std::vector<std::string> identifiers = {
      "identifier",
      "foo",
      "@#*&%&$#",
      "...",
      "💩"
  };

  std::vector<std::string> strings = {
      "'foo bar'",
      "'&\"\\'+~💩$'"
  };

  std::vector<std::string> integers = {
      "0",
      "1",
      "928453821"
  };

  std::vector<std::string> floats = {
      "0.23592",
      "29384."
  };

  std::vector<std::string> literals;
  append(literals, strings);
  append(literals, integers);
  append(literals, floats);

  std::vector<std::string> expressions = {
    "( + 3 4)",
    " (  +  3  4  ) ",
    "(- 1.5)",
    "(* (- 1.5) 2)",
  };
  append(expressions, whitespaceVariations(identifiers));
  append(expressions, whitespaceVariations(literals));

  std::vector<std::string> programs = expressions;
  for (size_t i=0; i<expressions.size() - 1; i++) {
    // test multiple expressions with or without whitespace between
    programs.push_back(expressions[0] + expressions[1]);
  }

  SECTION("parseProgram") {
    for (const auto& str : programs) {
      ASTInput input("TODO-filename", str.c_str(), str.size());
      ASTNode result;
      CHECK_NOTHROW(result = ASTNode::parseProgram(input));
      CHECK(result.kind() == NodeKind::program);
    }
  }

  SECTION("parseExpression") {
    for (const auto& str : expressions) {
      ASTInput input("TODO-filename", str.c_str(), str.size());
      ASTNode result;
      CHECK_NOTHROW(result = ASTNode::parseExpression(input));
      // resulting NodeKind could be any of:
      // * expression
      // * literal
      // * identifier
      // due to simplified parse tree structure (useless expressions are skipped).
    }
  }

  SECTION("parseIdentifier") {
    for (const auto& str : identifiers) {
      ASTInput input("TODO-filename", str.c_str(), str.size());
      ASTNode result;
      CHECK_NOTHROW(result = ASTNode::parseIdentifier(input));
      CHECK(result.kind() == NodeKind::identifier);
    }
  }

  SECTION("parseLiteral") {
    for (const auto& str : literals) {
      ASTInput input("TODO-filename", str.c_str(), str.size());
      ASTNode result;
      CHECK_NOTHROW(result = ASTNode::parseLiteral(input));
      CHECK(result.kind() == NodeKind::literal);
    }
  }

  SECTION("parseString") {
    for (const auto& str : strings) {
      ASTInput input("TODO-filename", str.c_str(), str.size());
      ASTNode result;
      CHECK_NOTHROW(result = ASTNode::parseString(input));
      CHECK(result.kind() == NodeKind::string);
    }
  }

  SECTION("parseNumber") {
    for (const auto& str : floats) {
      ASTInput input("TODO-filename", str.c_str(), str.size());
      ASTNode result;
      CHECK_NOTHROW(result = ASTNode::parseNumber(input));
      CHECK(result.kind() == NodeKind::floatingPoint);
    }
    for (const auto& str : integers) {
      ASTInput input("TODO-filename", str.c_str(), str.size());
      ASTNode result;
      CHECK_NOTHROW(result = ASTNode::parseNumber(input));
      CHECK(result.kind() == NodeKind::integer);
    }
  }
}


text:
package io.grpc.internal;

/**
 * A listener to a server for transport creation events. The listener need not be thread-safe, so
 * notifications must be properly synchronized externally.
 */
public interface ServerListener {

  /**
   * Called upon the establishment of a new client connection.
   *
   * @param transport the new transport to be observed.
   * @return a listener for stream creation events on the transport.
   */
  ServerTransportListener transportCreated(ServerTransport transport);

  /**
   * The server is shutting down. No new transports will be processed, but existing transports may
   * continue. Shutdown is only caused by a call to {@link InternalServer#shutdown()}. All
   * resources have been released.
   */
  void serverShutdown();
}


text:
package com.zongtui.filter.utils;

import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

/**
 *
* @ClassName: MapValueComparator
* @Description: 在map中按照value的值大小排序
* @author yifan
* @date 2015年6月11日 上午10:13:08
*
 */
public class MapValueComparator  implements Comparator<String>{

    Map<String, Integer> base;
    public MapValueComparator(HashMap<String, Integer> map) {
        this.base = map;
    }

    // Note: this comparator imposes orderings that are inconsistent with equals.
    public int compare(String a, String b) {
        if (base.get(a) >= base.get(b)) {
            return -1;
        } else {
            return 1;
        } // returning 0 would merge keys
    }

	public static void main(String[] args) {
		StringBuffer s = new StringBuffer("中国,华东地区,山东省,烟台市:10;");
		StringBuffer allValueNum = new StringBuffer();
		//System.out.println(s.subSequence(0, s.length()-1));
		HashMap<String,Integer> map = new HashMap<String,Integer>();
		MapValueComparator vc = new MapValueComparator(map);
		TreeMap<String, Integer> sorted_map = new TreeMap<String,Integer>(vc);
		//20:0;22:0;15:943;13:2845;14:0;
		map.put("20",  0);
		map.put("22", 0);
		map.put("15", 943);
		map.put("13", 2845);
		map.put("14", 0);

		sorted_map.putAll(map);

		System.out.println(sorted_map);

		Set<String> keys = sorted_map.keySet();
		for (Iterator iterator = keys.iterator(); iterator.hasNext();) {
			String key = (String) iterator.next();
			allValueNum = allValueNum.append(key).append(":").append(map.get(key)).append(";");
		}

		System.out.println(allValueNum.substring(0, allValueNum.length()-1));

	}
}


text:
<?php

namespace Symfony\Component\EventDispatcher\Tests;

use Symfony\Component\EventDispatcher\GenericEvent;

/**
 * Test class for Event.
 */
class GenericEventTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var GenericEvent
     */
    private $event;

    private $subject;

    /**
     * Prepares the environment before running a test.
     */
    protected function setUp()
    {
        parent::setUp();

        $this->subject = new \stdClass();
        $this->event = new GenericEvent($this->subject, array('name' => 'Event'));
    }

    /**
     * Cleans up the environment after running a test.
     */
    protected function tearDown()
    {
        $this->subject = null;
        $this->event = null;

        parent::tearDown();
    }

    public function testConstruct()
    {
        $this->assertEquals($this->event, new GenericEvent($this->subject, array('name' => 'Event')));
    }

    /**
     * Tests Event->getArgs().
     */
    public function testGetArguments()
    {
        // test getting all
        $this->assertSame(array('name' => 'Event'), $this->event->getArguments());
    }

    public function testSetArguments()
    {
        $result = $this->event->setArguments(array('foo' => 'bar'));
        $this->assertAttributeSame(array('foo' => 'bar'), 'arguments', $this->event);
        $this->assertSame($this->event, $result);
    }

    public function testSetArgument()
    {
        $result = $this->event->setArgument('foo2', 'bar2');
        $this->assertAttributeSame(array('name' => 'Event', 'foo2' => 'bar2'), 'arguments', $this->event);
        $this->assertEquals($this->event, $result);
    }

    public function testGetArgument()
    {
        // test getting key
        $this->assertEquals('Event', $this->event->getArgument('name'));
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testGetArgException()
    {
        $this->event->getArgument('nameNotExist');
    }

    public function testOffsetGet()
    {
        // test getting key
        $this->assertEquals('Event', $this->event['name']);

        // test getting invalid arg
        $this->setExpectedException('InvalidArgumentException');
        $this->assertFalse($this->event['nameNotExist']);
    }

    public function testOffsetSet()
    {
        $this->event['foo2'] = 'bar2';
        $this->assertAttributeSame(array('name' => 'Event', 'foo2' => 'bar2'), 'arguments', $this->event);
    }

    public function testOffsetUnset()
    {
        unset($this->event['name']);
        $this->assertAttributeSame(array(), 'arguments', $this->event);
    }

    public function testOffsetIsset()
    {
        $this->assertTrue(isset($this->event['name']));
        $this->assertFalse(isset($this->event['nameNotExist']));
    }

    public function testHasArgument()
    {
        $this->assertTrue($this->event->hasArgument('name'));
        $this->assertFalse($this->event->hasArgument('nameNotExist'));
    }

    public function testGetSubject()
    {
        $this->assertSame($this->subject, $this->event->getSubject());
    }

    public function testHasIterator()
    {
        $data = array();
        foreach ($this->event as $key => $value) {
            $data[$key] = $value;
        }
        $this->assertEquals(array('name' => 'Event'), $data);
    }
}


text:
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
/* global NOTIFY_WARNING, NOTIFY_INFO */
/* eslint-disable no-unused-vars */

/**
 * A autosave function for the Atto editor.
 *
 * @module     moodle-editor_atto-autosave
 * @submodule  autosave-base
 * @package    editor_atto
 * @copyright  2014 Damyon Wiese
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */

var SUCCESS_MESSAGE_TIMEOUT = 5000,
    RECOVER_MESSAGE_TIMEOUT = 60000,
    LOGNAME_AUTOSAVE = 'moodle-editor_atto-editor-autosave';

function EditorAutosave() {}

EditorAutosave.ATTRS= {
    /**
     * Enable/Disable auto save for this instance.
     *
     * @attribute autosaveEnabled
     * @type Boolean
     * @writeOnce
     */
    autosaveEnabled: {
        value: true,
        writeOnce: true
    },

    /**
     * The time between autosaves (in seconds).
     *
     * @attribute autosaveFrequency
     * @type Number
     * @default 60
     * @writeOnce
     */
    autosaveFrequency: {
        value: 60,
        writeOnce: true
    },

    /**
     * Unique hash for this page instance. Calculated from $PAGE->url in php.
     *
     * @attribute pageHash
     * @type String
     * @writeOnce
     */
    pageHash: {
        value: '',
        writeOnce: true
    }
};

EditorAutosave.prototype = {

    /**
     * The text that was auto saved in the last request.
     *
     * @property lastText
     * @type string
     */
    lastText: "",

    /**
     * Autosave instance.
     *
     * @property autosaveInstance
     * @type string
     */
    autosaveInstance: null,

    /**
     * Autosave Timer.
     *
     * @property autosaveTimer
     * @type object
     */
    autosaveTimer: null,

    /**
     * Initialize the autosave process
     *
     * @method setupAutosave
     * @chainable
     */
    setupAutosave: function() {
        var draftid = -1,
            form,
            optiontype = null,
            options = this.get('filepickeroptions'),
            params;

        if (!this.get('autosaveEnabled')) {
            // Autosave disabled for this instance.
            return;
        }

        this.autosaveInstance = Y.stamp(this);
        for (optiontype in options) {
            if (typeof options[optiontype].itemid !== "undefined") {
                draftid = options[optiontype].itemid;
            }
        }

        // First see if there are any saved drafts.
        // Make an ajax request.
        params = {
            contextid: this.get('contextid'),
            action: 'resume',
            draftid: draftid,
            elementid: this.get('elementid'),
            pageinstance: this.autosaveInstance,
            pagehash: this.get('pageHash')
        };

        this.autosaveIo(params, this, {
            success: function(response) {
                if (response === null) {
                    // This can happen when there is nothing to resume from.
                    return;
                } else if (!response) {
                    Y.log('Invalid response received.', 'debug', LOGNAME_AUTOSAVE);
                    return;
                }

                // Revert untouched editor contents to an empty string.
                // Check for FF and Chrome.
                if (response.result === '

' || response.result === '

' ||
                    response.result === '
') {
                    response.result = '';
                }

                // Check for IE 9 and 10.
                if (response.result === '

' || response.result === '

') {
                    response.result = '';
                }

                if (response.error || typeof response.result === 'undefined') {
                    Y.log('Error occurred recovering draft text: ' + response.error, 'debug', LOGNAME_AUTOSAVE);
                    this.showMessage(M.util.get_string('errortextrecovery', 'editor_atto'),
                            NOTIFY_WARNING, RECOVER_MESSAGE_TIMEOUT);
                } else if (response.result !== this.textarea.get('value') &&
                        response.result !== '') {
                    Y.log('Autosave text found - recover it.', 'debug', LOGNAME_AUTOSAVE);
                    this.recoverText(response.result);
                }
                this._fireSelectionChanged();

            },
            failure: function() {
                this.showMessage(M.util.get_string('errortextrecovery', 'editor_atto'),
                        NOTIFY_WARNING, RECOVER_MESSAGE_TIMEOUT);
            }
        });

        // Now setup the timer for periodic saves.
        var delay = parseInt(this.get('autosaveFrequency'), 10) * 1000;
        this.autosaveTimer = Y.later(delay, this, this.saveDraft, false, true);

        // Now setup the listener for form submission.
        form = this.textarea.ancestor('form');
        if (form) {
            this.autosaveIoOnSubmit(form, {
                action: 'reset',
                contextid: this.get('contextid'),
                elementid: this.get('elementid'),
                pageinstance: this.autosaveInstance,
                pagehash: this.get('pageHash')
            });
        }
        return this;
    },

    /**
     * Recover a previous version of this text and show a message.
     *
     * @method recoverText
     * @param {String} text
     * @chainable
     */
    recoverText: function(text) {
        this.editor.setHTML(text);
        this.saveSelection();
        this.updateOriginal();
        this.lastText = text;

        this.showMessage(M.util.get_string('textrecovered', 'editor_atto'),
                NOTIFY_INFO, RECOVER_MESSAGE_TIMEOUT);

        // Fire an event that the editor content has changed.
        require(['core/event'], function(event) {
            event.notifyEditorContentRestored();
        });

        return this;
    },

    /**
     * Save a single draft via ajax.
     *
     * @method saveDraft
     * @chainable
     */
    saveDraft: function() {
        var url, params;

        if (!this.editor.getDOMNode()) {
            // Stop autosaving if the editor was removed from the page.
            this.autosaveTimer.cancel();
            return;
        }
        // Only copy the text from the div to the textarea if the textarea is not currently visible.
        if (!this.editor.get('hidden')) {
            this.updateOriginal();
        }
        var newText = this.textarea.get('value');

        if (newText !== this.lastText) {
            Y.log('Autosave text', 'debug', LOGNAME_AUTOSAVE);

            // Make an ajax request.
            url = M.cfg.wwwroot + this.get('autosaveAjaxScript');
            params = {
                sesskey: M.cfg.sesskey,
                contextid: this.get('contextid'),
                action: 'save',
                drafttext: newText,
                elementid: this.get('elementid'),
                pagehash: this.get('pageHash'),
                pageinstance: this.autosaveInstance
            };

            // Reusable error handler - must be passed the correct context.
            var ajaxErrorFunction = function(response) {
                var errorDuration = parseInt(this.get('autosaveFrequency'), 10) * 1000;
                Y.log('Error while autosaving text', 'warn', LOGNAME_AUTOSAVE);
                Y.log(response, 'warn', LOGNAME_AUTOSAVE);
                this.showMessage(M.util.get_string('autosavefailed', 'editor_atto'), NOTIFY_WARNING, errorDuration);
            };

            this.autosaveIo(params, this, {
                failure: ajaxErrorFunction,
                success: function(response) {
                    if (response && response.error) {
                        Y.soon(Y.bind(ajaxErrorFunction, this, [response]));
                    } else {
                        // All working.
                        this.lastText = newText;
                        this.showMessage(M.util.get_string('autosavesucceeded', 'editor_atto'),
                                NOTIFY_INFO, SUCCESS_MESSAGE_TIMEOUT);
                    }
                }
            });
        }
        return this;
    }
};

Y.Base.mix(Y.M.editor_atto.Editor, [EditorAutosave]);


text: some spring boot demos


text:
//-----------------------------------NOTICE----------------------------------//
// Some of this file is automatically filled in by a Python script.  Only    //
// add custom code in the designated areas or it will be overwritten during  //
// the next update.                                                          //
//-----------------------------------NOTICE----------------------------------//

//--BEGIN FILE HEAD CUSTOM CODE--//
//--END CUSTOM CODE--//

#include "../../include/FixLink.h"
#include "../../include/ObjectRegistry.h"
#include "../../include/NIF_IO.h"
#include "../../include/obj/NiPSysColliderManager.h"
#include "../../include/obj/NiPSysCollider.h"
using namespace Niflib;

//Definition of TYPE constant
const Type NiPSysColliderManager::TYPE("NiPSysColliderManager", &NiPSysModifier::TYPE);

NiPSysColliderManager::NiPSysColliderManager() : collider(NULL)
{
	//--BEGIN CONSTRUCTOR CUSTOM CODE--//
	//--END CUSTOM CODE--//
}

NiPSysColliderManager::~NiPSysColliderManager()
{
	//--BEGIN DESTRUCTOR CUSTOM CODE--//
	//--END CUSTOM CODE--//
}

const Type & NiPSysColliderManager::GetType() const
{
	return TYPE;
}

NiObject * NiPSysColliderManager::Create()
{
	return new NiPSysColliderManager;
}

void NiPSysColliderManager::Read(istream& in, list<unsigned int> & link_stack, const NifInfo & info)
{
	//--BEGIN PRE-READ CUSTOM CODE--//
	//--END CUSTOM CODE--//

	unsigned int block_num;
	NiPSysModifier::Read(in, link_stack, info);
	NifStream(block_num, in, info);
	link_stack.push_back(block_num);

	//--BEGIN POST-READ CUSTOM CODE--//
	//--END CUSTOM CODE--//
}

void NiPSysColliderManager::Write(ostream& out, const map<NiObjectRef, unsigned int> & link_map, list<NiObject *> & missing_link_stack, const NifInfo & info) const
{
	//--BEGIN PRE-WRITE CUSTOM CODE--//
	//--END CUSTOM CODE--//

	NiPSysModifier::Write(out, link_map, missing_link_stack, info);
	if(info.version < VER_3_3_0_13)
	{
		WritePtr32(&(*collider), out);
	}
	else
	{
		if(collider != NULL)
		{
			map<NiObjectRef, unsigned int>::const_iterator it = link_map.find(StaticCast<NiObject>(collider));
			if(it != link_map.end())
			{
				NifStream(it->second, out, info);
				missing_link_stack.push_back(NULL);
			}
			else
			{
				NifStream(0xFFFFFFFF, out, info);
				missing_link_stack.push_back(collider);
			}
		}
		else
		{
			NifStream(0xFFFFFFFF, out, info);
			missing_link_stack.push_back(NULL);
		}
	}

	//--BEGIN POST-WRITE CUSTOM CODE--//
	//--END CUSTOM CODE--//
}

std::string NiPSysColliderManager::asString(bool verbose) const
{
	//--BEGIN PRE-STRING CUSTOM CODE--//
	//--END CUSTOM CODE--//

	stringstream out;
	out << NiPSysModifier::asString(verbose);
	out << "  Collider:  " << collider << endl;
	return out.str();

	//--BEGIN POST-STRING CUSTOM CODE--//
	//--END CUSTOM CODE--//
}

void NiPSysColliderManager::FixLinks(const map<unsigned int, NiObjectRef> & objects, list<unsigned int> & link_stack, list<NiObjectRef> & missing_link_stack, const NifInfo & info)
{
	//--BEGIN PRE-FIXLINKS CUSTOM CODE--//
	//--END CUSTOM CODE--//

	NiPSysModifier::FixLinks(objects, link_stack, missing_link_stack, info);
	collider = FixLink<NiPSysCollider>(objects, link_stack, missing_link_stack, info);

	//--BEGIN POST-FIXLINKS CUSTOM CODE--//
	//--END CUSTOM CODE--//
}

std::list<NiObjectRef> NiPSysColliderManager::GetRefs() const
{
	list<Ref<NiObject> > refs;
	refs = NiPSysModifier::GetRefs();
	if(collider != NULL)
		refs.push_back(StaticCast<NiObject>(collider));
	return refs;
}

std::list<NiObject *> NiPSysColliderManager::GetPtrs() const
{
	list<NiObject *> ptrs;
	ptrs = NiPSysModifier::GetPtrs();
	return ptrs;
}

/***Begin Example Naive Implementation****

Ref<NiPSysCollider > NiPSysColliderManager::GetCollider() const {
return collider;
}

void NiPSysColliderManager::SetCollider( Ref<NiPSysCollider > value ) {
collider = value;
}

****End Example Naive Implementation***/

//--BEGIN MISC CUSTOM CODE--//
//--END CUSTOM CODE--//


text:
// Code generated by client-gen. DO NOT EDIT.

package v1alpha1

type CronExpansion interface{}


text:
var fs = require('fs'),
	http = require('http'),
	WebSocket = require('ws');

if (process.argv.length < 3) {
	console.log(
		'Usage: \n' +
		'node websocket-relay.js <secret> [<stream-port> <websocket-port>]'
	);
	process.exit();
}

var STREAM_SECRET = process.argv[2],
	STREAM_PORT = process.argv[3] || 8081,
	WEBSOCKET_PORT = process.argv[4] || 8082,
	RECORD_STREAM = false;

// Websocket Server
var socketServer = new WebSocket.Server({port: WEBSOCKET_PORT, perMessageDeflate: false});
socketServer.connectionCount = 0;
socketServer.on('connection', function(socket) {
	socketServer.connectionCount++;
	console.log(
		'New WebSocket Connection: ',
		socket.upgradeReq.socket.remoteAddress,
		socket.upgradeReq.headers['user-agent'],
		'('+socketServer.connectionCount+' total)'
	);
	socket.on('close', function(code, message){
		socketServer.connectionCount--;
		console.log(
			'Disconnected WebSocket ('+socketServer.connectionCount+' total)'
		);
	});
});
socketServer.broadcast = function(data) {
	socketServer.clients.forEach(function each(client) {
		if (client.readyState === WebSocket.OPEN) {
			client.send(data);
		}
	});
};

// HTTP Server to accept incomming MPEG-TS Stream from ffmpeg
var streamServer = http.createServer( function(request, response) {
	var params = request.url.substr(1).split('/');

	if (params[0] !== STREAM_SECRET) {
		console.log(
			'Failed Stream Connection: '+ request.socket.remoteAddress + ':' +
			request.socket.remotePort + ' - wrong secret.'
		);
		response.end();
	}

	response.connection.setTimeout(0);
	console.log(
		'Stream Connected: ' +
		request.socket.remoteAddress + ':' +
		request.socket.remotePort
	);
	request.on('data', function(data){
		socketServer.broadcast(data);
		if (request.socket.recording) {
			request.socket.recording.write(data);
		}
	});
	request.on('end',function(){
		console.log('close');
		if (request.socket.recording) {
			request.socket.recording.close();
		}
	});

	// Record the stream to a local file?
	if (RECORD_STREAM) {
		var path = 'recordings/' + Date.now() + '.ts';
		request.socket.recording = fs.createWriteStream(path);
	}
}).listen(STREAM_PORT);

console.log('Listening for incomming MPEG-TS Stream on http://127.0.0.1:'+STREAM_PORT+'/<secret>');
console.log('Awaiting WebSocket connections on ws://127.0.0.1:'+WEBSOCKET_PORT+'/');


text:
package tw.invictus.tventhusiast.view.event;

/**
 * Created by ivan on 11/21/15.
 */
public class GetPaletteEvent {
    private int darkColor;
    private int lightColor;
    private int backgroundColor;

    public GetPaletteEvent(int darkColor, int lightColor, int backgroundColor) {
        this.darkColor = darkColor;
        this.lightColor = lightColor;
        this.backgroundColor = backgroundColor;
    }

    public int getDarkColor() {
        return darkColor;
    }

    public void setDarkColor(int darkColor) {
        this.darkColor = darkColor;
    }

    public int getLightColor() {
        return lightColor;
    }

    public void setLightColor(int lightColor) {
        this.lightColor = lightColor;
    }

    public int getBackgroundColor() {
        return backgroundColor;
    }

    public void setBackgroundColor(int backgroundColor) {
        this.backgroundColor = backgroundColor;
    }
}


text:
import React, { Component } from 'react'

import {
    StyleSheet,
    View
} from 'react-native'

import TabBarComp from './TabBar'
import NavbarComp from './NavBar'

export default class IndexView extends Component{
    constructor(props) {
        super(props)
        this.state = {}
    }

		render() {
        return (
            <View style={styles.container}>
                <NavbarComp route={this.props.route} navigator={this.props.navigator}/>
                <TabBarComp navigator={this.props.navigator}/>
            </View>
        )
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1
    }
})


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE module PUBLIC "-//Google Inc.//DTD Google Web Toolkit trunk//EN" "http://google-web-toolkit.googlecode.com/svn/trunk/distro-source/core/src/gwt-module.dtd">
<module>
	<source path="pay" />
	<inherits name='com.badlogic.gdx.pay' />
</module>


text:
package org.usc.demo.wechat.util;

import com.google.common.base.Charsets;
import com.google.common.base.Joiner;
import com.google.common.base.Joiner.MapJoiner;
import com.google.common.base.Predicate;
import com.google.common.collect.Maps;
import com.google.common.hash.Hashing;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.usc.demo.wechat.vo.AbstractRequest;
import org.usc.demo.wechat.vo.PayRequest;

import java.lang.reflect.InvocationTargetException;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeMap;

/**
 *
 * @author Shunli
 */
public class SignUtil {
    private static final MapJoiner mapJoiner = Joiner.on("&").useForNull("").withKeyValueSeparator("=");
    private static final Predicate<String> notBlank = input -> StringUtils.isNotBlank(input);

    public static void main(String[] args) throws Exception {
        PayRequest payRequest = new PayRequest("NONCE_STR", "MCH_BILLNO", "MCH_ID", "WXAPPID", "");

        appendRequestSign(payRequest, "KEY");

        System.out.println(payRequest);
    }

    private static void appendRequestSign(AbstractRequest payRequest, String key) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
        Map<String, String> paramMap = BeanUtils.describe(payRequest);
        paramMap.remove("class");

        // sort
        TreeMap<String, String> newTreeMap = Maps.newTreeMap();
        newTreeMap.putAll(paramMap);

        // last append key
        LinkedHashMap<String, String> newLinkedHashMap = Maps.newLinkedHashMap();
        newLinkedHashMap.putAll(newTreeMap);
        newLinkedHashMap.put("key", key);

        String join = mapJoiner.join(Maps.filterValues(newLinkedHashMap, notBlank));
        // System.out.println(join);
        payRequest.setSign(StringUtils.upperCase(Hashing.md5().hashString(join, Charsets.UTF_8).toString()));
    }
}


text:
using WebKit::WebDocument;
using WebKit::WebFrame;
using WebKit::WebInputElement;
using WebKit::WebString;
using webkit::forms::FormData;
using webkit::forms::FormField;

namespace autofill {

TEST_F(ChromeRenderViewTest, SendForms) {
  // Don't want any delay for form state sync changes. This will still post a
  // message so updates will get coalesced, but as soon as we spin the message
  // loop, it will generate an update.
  SendContentStateImmediately();

  LoadHTML("<form method=\"POST\">"
           "  <input type=\"text\" id=\"firstname\"/>"
           "  <input type=\"text\" id=\"middlename\"/>"
           "  <input type=\"text\" id=\"lastname\" autoComplete=\"off\"/>"
           "  <input type=\"hidden\" id=\"email\"/>"
           "  <select id=\"state\"/>"
           "    <option>?</option>"
           "    <option>California</option>"
           "    <option>Texas</option>"
           "  </select>"
           "</form>");

  // Verify that "FormsSeen" sends the expected number of fields.
  ProcessPendingMessages();
  const IPC::Message* message = render_thread_->sink().GetFirstMessageMatching(
      AutofillHostMsg_FormsSeen::ID);
  ASSERT_NE(static_cast<IPC::Message*>(NULL), message);
  AutofillHostMsg_FormsSeen::Param params;
  AutofillHostMsg_FormsSeen::Read(message, &params);
  const std::vector<FormData>& forms = params.a;
  ASSERT_EQ(1UL, forms.size());
  ASSERT_EQ(4UL, forms[0].fields.size());

  FormField expected;

  expected.name = ASCIIToUTF16("firstname");
  expected.value = string16();
  expected.form_control_type = ASCIIToUTF16("text");
  expected.max_length = WebInputElement::defaultMaxLength();
  EXPECT_FORM_FIELD_EQUALS(expected, forms[0].fields[0]);

  expected.name = ASCIIToUTF16("middlename");
  expected.value = string16();
  expected.form_control_type = ASCIIToUTF16("text");
  expected.max_length = WebInputElement::defaultMaxLength();
  EXPECT_FORM_FIELD_EQUALS(expected, forms[0].fields[1]);

  expected.name = ASCIIToUTF16("lastname");
  expected.value = string16();
  expected.form_control_type = ASCIIToUTF16("text");
  expected.max_length = WebInputElement::defaultMaxLength();
  EXPECT_FORM_FIELD_EQUALS(expected, forms[0].fields[2]);

  expected.name = ASCIIToUTF16("state");
  expected.value = ASCIIToUTF16("?");
  expected.form_control_type = ASCIIToUTF16("select-one");
  expected.max_length = 0;
  EXPECT_FORM_FIELD_EQUALS(expected, forms[0].fields[3]);

  // Verify that |didAcceptAutofillSuggestion()| sends the expected number of
  // fields.
  WebFrame* web_frame = GetMainFrame();
  WebDocument document = web_frame->document();
  WebInputElement firstname =
      document.getElementById("firstname").to<WebInputElement>();

  // Make sure to query for Autofill suggestions before selecting one.
  autofill_agent_->QueryAutofillSuggestions(firstname, false);

  // Accept suggestion that contains a label.  Labeled items indicate Autofill
  // as opposed to Autocomplete.  We're testing this distinction below with
  // the |AutofillHostMsg_FillAutofillFormData::ID| message.
  autofill_agent_->didAcceptAutofillSuggestion(
      firstname,
      WebKit::WebString::fromUTF8("Johnny"),
      WebKit::WebString::fromUTF8("Home"),
      1,
      -1);

  ProcessPendingMessages();
  const IPC::Message* message2 =
      render_thread_->sink().GetUniqueMessageMatching(
          AutofillHostMsg_FillAutofillFormData::ID);
  ASSERT_NE(static_cast<IPC::Message*>(NULL), message2);
  AutofillHostMsg_FillAutofillFormData::Param params2;
  AutofillHostMsg_FillAutofillFormData::Read(message2, &params2);
  const FormData& form2 = params2.b;
  ASSERT_EQ(3UL, form2.fields.size());

  expected.name = ASCIIToUTF16("firstname");
  expected.value = string16();
  expected.form_control_type = ASCIIToUTF16("text");
  expected.max_length = WebInputElement::defaultMaxLength();
  EXPECT_FORM_FIELD_EQUALS(expected, form2.fields[0]);

  expected.name = ASCIIToUTF16("middlename");
  expected.value = string16();
  expected.form_control_type = ASCIIToUTF16("text");
  expected.max_length = WebInputElement::defaultMaxLength();
  EXPECT_FORM_FIELD_EQUALS(expected, form2.fields[1]);

  expected.name = ASCIIToUTF16("state");
  expected.value = ASCIIToUTF16("?");
  expected.form_control_type = ASCIIToUTF16("select-one");
  expected.max_length = 0;
  EXPECT_FORM_FIELD_EQUALS(expected, form2.fields[2]);
}

TEST_F(ChromeRenderViewTest, FillFormElement) {
  // Don't want any delay for form state sync changes. This will still post a
  // message so updates will get coalesced, but as soon as we spin the message
  // loop, it will generate an update.
  SendContentStateImmediately();

  LoadHTML("<form method=\"POST\">"
           "  <input type=\"text\" id=\"firstname\"/>"
           "  <input type=\"text\" id=\"middlename\"/>"
           "</form>");

  // Verify that "FormsSeen" isn't sent, as there are too few fields.
  ProcessPendingMessages();
  const IPC::Message* message = render_thread_->sink().GetFirstMessageMatching(
      AutofillHostMsg_FormsSeen::ID);
  ASSERT_EQ(static_cast<IPC::Message*>(NULL), message);

  // Verify that |didAcceptAutofillSuggestion()| sets the value of the expected
  // field.
  WebFrame* web_frame = GetMainFrame();
  WebDocument document = web_frame->document();
  WebInputElement firstname =
      document.getElementById("firstname").to<WebInputElement>();
  WebInputElement middlename =
      document.getElementById("middlename").to<WebInputElement>();
  middlename.setAutofilled(true);

  // Make sure to query for Autofill suggestions before selecting one.
  autofill_agent_->QueryAutofillSuggestions(firstname, false);

  // Accept a suggestion in a form that has been auto-filled.  This triggers
  // the direct filling of the firstname element with value parameter.
  autofill_agent_->didAcceptAutofillSuggestion(firstname,
                                               WebString::fromUTF8("David"),
                                               WebString(),
                                               0,
                                               0);

  ProcessPendingMessages();
  const IPC::Message* message2 =
      render_thread_->sink().GetUniqueMessageMatching(
          AutofillHostMsg_FillAutofillFormData::ID);

  // No message should be sent in this case.  |firstname| is filled directly.
  ASSERT_EQ(static_cast<IPC::Message*>(NULL), message2);
  EXPECT_EQ(firstname.value(), WebKit::WebString::fromUTF8("David"));
}

}  // namespace autofill


text:
import React from 'react';
import ReactDOM from 'react-dom';
import createLogger from 'redux-logger';
import { Router, browserHistory } from 'react-router';
import { createStore, compose, applyMiddleware, combineReducers } from 'redux';
import { Provider } from 'react-redux';
import thunkMiddleware from 'redux-thunk';

// imports needed for for Convy.
import { convyRoute, convyReducers, convyConfig } from './convy';

// convyConfig.stateName = 'convy';
// convyConfig.urlPrefix = 'convy';
// convyConfig.adapter = new SlackAdapter();

const loggerMiddleware = createLogger({
  predicate: (getState, action) => true,
});

function configureStore() {
  const enhancer = compose(
    applyMiddleware(
      thunkMiddleware,
      loggerMiddleware
    )
  );

  const reducers = combineReducers({
    // will store the state in object convy.
    [convyConfig.stateName]: convyReducers,
    // define other reducers for your store
    // products: productsReducer
  });

  return createStore(reducers, enhancer);
}

ReactDOM.render(
  <Provider store={ configureStore() }>
    <Router history={ browserHistory }>
      { convyRoute() }
    </Router>
  </Provider>,

  document.querySelector('.s-application')
);


text:
<?

print <<< EOF

			$showMessage

Contact Form

			$showContactForm

			For general inquiries, please fill out the contact form to your left.
			[ALTERNATIVE_CONTACT_INFO]

EOF;

?>


text:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

/**
 * Profiles
 *
 * This model represents user autologin data. It can be used
 * for user verification when user claims his autologin passport.
 *
 * @package	models
 * @author	Young Gyu Park (http://kauc.net/)
 */
class Profiles extends CI_Model
{
	private $table_name			= 'user_profiles';

	function __construct()
	{
		parent::__construct();
	}

	/**
	 * Get user data for auto-logged in user.
	 * Return NULL if given key or user ID is invalid.
	 *
	 */
	function isRegistered($user_id)
	{
		$query = $this->db->get_where($this->table_name, array('user_id' => $user_id));
		if ($query->num_rows() > 0) return $query->result();
		return NULL;
	}

	/**
	 * Save data for user's autologin
	 *
	 * @param	array
	 * @return	bool
	 */
	function create($data)
	{
		return $this->db->insert($this->table_name, $data);
	}

	/**
	 * Get user data for auto-logged in user.
	 * Return NULL if given key or user ID is invalid.
	 *
	 */
	function retrieve($user_id)
	{
		$query = $this->db->get_where($this->table_name, array('user_id' => $user_id));
		if ($query->num_rows() == 1) return $query->result();
		return NULL;
	}

	/**
	 * Update profile record
	 *
	 * @param	array
	 * @return	array
	 */
	function update($data, $id)
	{
		return $this->db->update($this->table_name, $data, array('id' => $id));
	}

}

/* End of file user_autologin.php */
/* Location: ./application/models/auth/user_autologin.php */


text:
require 'capybara-webkit'

Evergreen.configure do |config|
  config.driver = :webkit
  config.public_dir = 'app/assets/javascripts'
end


text:
# Process overview
The following shows the process boundaries

![](https://raw.githubusercontent.com/alm-tools/alm-tools.github.io/master/screens/design/process.png)

We have two libraries to manage this (designed for simple RPC) and both of them follow the same principle of `QueryResponse` async programming.

# Async programming

There are NPM libraries for such stuff but none written with the requirements of TypeScript in mind.
* DRY: A contract should only be defined once and any edits to that should result in compile errors in all places that need to change.
* Understanding Code: Doing a *find reference* on a contract should show both callers and implementation.

## Basic principle
Consider a function that takes a JavaScript object `Query` and returns a *promise* to a JavaScript object `Response`. If we have such an function (`QRFunction<Query,Response>`) it is trivial to take *the same code* (as long as its runtime dependencies allow it) and:
* mutate it on the *calling side* to simply pass the Query it over a JSON layer (e.g. a socket connection OR Inter Process Communication `ipc` for node workers) and wait for a response, creating a Promise in the meantime to pass back, and resolve this promise when the JSON layer comes back with the *actual* response.
* use it as is on the *called side*, but just register with the JSON layer as a responder for the query (detected by `name`).

## Contract
On thing to note is the *as long as its runtime dependencies allow it* gotcha (e.g. some function might depend on `fs` and you don't want to import such a module on the client). This is not always true, so we just create a *pseudo* object and call it `contract`. The calling side needs to do nothing with this object (except mutate it as documented), but the *called side* needs to provide a concrete implementation.
* We just let TypeScript verify the overall implementation on the *called side* by a line like `var _checkTypes: typeof contract.worker = Worker;`).
* Additionally individual function implementations use the contract too (e.g. `export var fileListUpdated: typeof contract.master.fileListUpdated = (q) => {`) and let TypeScript do the necessary type inference (`Query`) and validation `Promise<Qesponse>`.

## Two way
The contract can be two way by *just having two contracts*. E.g. for a socket : `client -> server` and `server -> client`. Having a contracts separated from implementations also means that we don't have to deal with cyclic dependencies when writing the implementations.

## Libraries
To take the contract + implementation and work the magic we have two libraries, `socketLib` and `simpleWorker`, that work over sockets and IPC respectively.

## More than just Promises
Basically anything that is *async* in its contract can be used under the same principle. Our `socketLib` allows us to convert *events* raised from the server become *events* that are emitted (`cast`) to all the clients. Great for stuff like an up to date error list, file changes etc.

## Example FrontEnd

We use socketio in the frontend. Checkout the [`socket` folder][socket] which contains the socket contract + server + client :rose:

# `simpleWorker`
Checkout the example [fileListing worker][fileListing]. Here is are the snippets you need to create a new worker:

## Contract
```ts
import * as sw from "../../utils/simpleWorker";

/**
 * There are two contracts
 * A contract on how the master --calls--> worker
 * A contract on how the worker --calls--> master
 */
export const worker = {
    // TODO: Put your own
    echo: {} as sw.QRFunction<{ text: string, num: number }, { text: string, num: number }>,
}

export const master = {
    // TODO: Put your own
    increment: {} as sw.QRFunction<{ num: number }, { num: number }>,
}
```

## Master
```ts
import * as sw from "../../utils/simpleWorker";
import * as contract from "./fileListingContract";

namespace Master {
    export const increment: typeof contract.master.increment = (q) => {
        return Promise.resolve({
            num: ++q.num
        });
    }
}

// Ensure that the namespace follows the contract
const _checkTypes: typeof contract.master = Master;
// launch worker
export const {worker} = sw.startWorker({
    workerPath: __dirname + '/fileListingWorker',
    workerContract: contract.worker,
    masterImplementation: Master
});
export function start() {
    // Any optional initilization on worker;
}
```

## Worker
```ts
import * as sw from "../../utils/simpleWorker";
import * as contract from "./fileListingContract";

namespace Worker {
    export const echo: typeof contract.worker.echo = (q) => {
        return master.increment(q).then((res) => {
            return {
                text: q.text,
                num: res.num
            };
        });
    }
}

// Ensure that the namespace follows the contract
const _checkTypes: typeof contract.worker = Worker;
// run worker
export const {master} = sw.runWorker({
    workerImplementation: Worker,
    masterContract: contract.master
});
```

You generally want to export a `start` function in the master and just call that to ensure that `master` file is loaded (hence worker started).

[socket]: https://github.com/alm-tools/alm/tree/e34bbf9cb6227f3cd150737fef5a47f212e2ad7a/src/socket
[fileListing]: https://github.com/alm-tools/alm/tree/master/src/server/workers/fileListing


text:
import {
  Component,
  OnInit,
  trigger,
  HostListener,
  state,
  style,
  transition,
  animate,
  Input,
  Output,
  EventEmitter
} from '@angular/core';

@Component({
  selector: 'size-input',
  moduleId: module.id,
  template: `
<label class="size-label">{{inputName}}:</label>
<input class="size-input-number" [(ngModel)]="myDataWihtoutUnit" type="number" (change)="changeData()" (keyup)="changeData()" >
<select class="size-input-unit" (change)='changeData()' [(ngModel)]="selectedValue">
    <option *ngFor="let u of unitArray" [ngValue]="u">{{u}}</option>
</select>
`,
  styleUrls: ['input-elements.stylesheet.css']

})

export class SizeInput implements OnInit{
@Input('data') data:any;
@Input('name') name:string;
@Input('index') index:any;
@Input('inputName') inputName:string;
done:boolean = false;
selectedValue:string ;
dataSplitted:string[];
myDataWihtoutUnit:number;
unitArray:string[] = ['px','%','vh','cm','mm'];

  private getUnit(text:string){
    return text.replace(/\d/g,'')
  }

  private changeData(){
    let newSize:string = this.myDataWihtoutUnit+this.selectedValue;
    this.dataSplitted[this.index] = newSize;
    let newData:string = '';
    for(let j=0;j<this.dataSplitted.length;j++) newData += this.dataSplitted[j]+' ';
    this.data[this.name] = newData;
  }

 ngOnInit(){
    this.dataSplitted = this.data[this.name].split(' ');
    let myData:string = this.dataSplitted[this.index];
    let unit:string = this.getUnit(myData);
    this.myDataWihtoutUnit = parseInt(myData);
    this.selectedValue = unit;
    this.done = true;
 }
}


text:
namespace ash {

ManagedDeviceTrayItemView::ManagedDeviceTrayItemView(Shelf* shelf)
    : TrayItemView(shelf) {
  Shell::Get()->session_controller()->AddObserver(this);
  Shell::Get()->system_tray_model()->enterprise_domain()->AddObserver(this);
  CreateImageView();
  Update();
}

ManagedDeviceTrayItemView::~ManagedDeviceTrayItemView() {
  Shell::Get()->system_tray_model()->enterprise_domain()->RemoveObserver(this);
  Shell::Get()->session_controller()->RemoveObserver(this);
}

void ManagedDeviceTrayItemView::OnLoginStatusChanged(LoginStatus status) {
  Update();
}

void ManagedDeviceTrayItemView::OnDeviceEnterpriseInfoChanged() {
  Update();
}

void ManagedDeviceTrayItemView::OnEnterpriseAccountDomainChanged() {}

const char* ManagedDeviceTrayItemView::GetClassName() const {
  return "ManagedDeviceTrayItemView";
}

void ManagedDeviceTrayItemView::OnThemeChanged() {
  TrayItemView::OnThemeChanged();
  UpdateIcon();
}

void ManagedDeviceTrayItemView::HandleLocaleChange() {
  UpdateTooltipText();
}

void ManagedDeviceTrayItemView::Update() {
  SessionControllerImpl* session = Shell::Get()->session_controller();
  if (!session->IsUserPublicAccount() && !session->IsUserChild()) {
    SetVisible(false);
    return;
  }

  UpdateIcon();
  UpdateTooltipText();
  SetVisible(true);
}

void ManagedDeviceTrayItemView::UpdateIcon() {
  const gfx::VectorIcon* icon = nullptr;
  SessionControllerImpl* session = Shell::Get()->session_controller();
  if (session->IsUserPublicAccount())
    icon = &kSystemTrayManagedIcon;
  else if (session->IsUserChild())
    icon = &kSystemTraySupervisedUserIcon;

  if (icon) {
    image_view()->SetImage(
        ui::ImageModel::FromVectorIcon(*icon, kColorAshIconColorPrimary));
  }
}

void ManagedDeviceTrayItemView::UpdateTooltipText() {
  SessionControllerImpl* session = Shell::Get()->session_controller();
  if (session->IsUserPublicAccount()) {
    std::string enterprise_domain_manager = Shell::Get()
                                                ->system_tray_model()
                                                ->enterprise_domain()
                                                ->enterprise_domain_manager();
    if (!enterprise_domain_manager.empty()) {
      image_view()->SetTooltipText(l10n_util::GetStringFUTF16(
          IDS_ASH_ENTERPRISE_DEVICE_MANAGED_BY, ui::GetChromeOSDeviceName(),
          base::UTF8ToUTF16(enterprise_domain_manager)));
    } else {
      image_view()->SetTooltipText(std::u16string());
      LOG(WARNING)
          << "Public account user, but device not enterprise-enrolled.";
    }
  } else if (session->IsUserChild()) {
    image_view()->SetTooltipText(
        l10n_util::GetStringUTF16(IDS_ASH_STATUS_TRAY_FAMILY_LINK_LABEL));
  }
}

}  // namespace ash


text:
[![Build Status](https://travis-ci.org/ToniaDemchuk/EMSimulation.svg?branch=master)](https://travis-ci.org/ToniaDemchuk/EMSimulation)

This is a software packages for electromagnetic simulations.

### What is this repository for? ###

* The package includes the implementation of computational electromagnetic methods:
 - discrete dipole approximation (DDA)
 - finite-difference time-domain (FDTD)

* The methods calculate optical spectra of nanoparticles in the dielectric medium.

## Table of Contents

- [Prerequisites](#prerequisites)
- [Install](#install)
- [Usage](#usage)
- [Contribute](#contribute)
- [License](#license)

## Prerequisites
The console applications use the [*gnuplot*](http://gnuplot.sourceforge.net/).

[Download](http://gnuplot.sourceforge.net/download.html) the gnuplot installer  and install it with the standard steps.

## Install

```
```

## Usage

```
```

## Contribute

Feel free to open an issue or submit a PR.

## License

See the [LICENSE](LICENSE.md) file for license rights and limitations (MIT).


text:
namespace Zu.ChromeDevTools.Memory
{
    using Newtonsoft.Json;

    /// <summary>
    /// Stop collecting native memory profile.
    /// </summary>
    public sealed class StopSamplingCommand : ICommand
    {
        private const string ChromeRemoteInterface_CommandName = "Memory.stopSampling";

        [JsonIgnore]
        public string CommandName
        {
            get { return ChromeRemoteInterface_CommandName; }
        }

    }

    public sealed class StopSamplingCommandResponse : ICommandResponse<StopSamplingCommand>
    {
    }
}


text:
package com.tamic.jswebview.browse;

import android.graphics.Bitmap;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

/**
 * Created by bruce on 10/28/15.
 */
public class BridgeWebViewClient extends WebViewClient {
    private BridgeWebView webView;

    public BridgeWebViewClient(BridgeWebView webView) {
        this.webView = webView;
    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        try {
            url = URLDecoder.decode(url, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        if (url.startsWith(BridgeUtil.YY_RETURN_DATA)) { // 如果是返回数据
            webView.handlerReturnData(url);
            return true;
        } else if (url.startsWith(BridgeUtil.YY_OVERRIDE_SCHEMA)) { //
            webView.flushMessageQueue();
            return true;
        } else {
            return super.shouldOverrideUrlLoading(view, url);
        }
    }

    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        super.onPageStarted(view, url, favicon);
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);

        if (BridgeWebView.toLoadJs != null) {
            BridgeUtil.webViewLoadLocalJs(view, BridgeWebView.toLoadJs);
        }

        //
        if (webView.getStartupMessage() != null) {
            for (Message m : webView.getStartupMessage()) {
                webView.dispatchMessage(m);
            }
            webView.setStartupMessage(null);
        }
    }

    @Override
    public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
        super.onReceivedError(view, errorCode, description, failingUrl);
    }
}


text:
all posts
 by most recent

				{% for post in site.posts %}

 {{ forloop.index }}
{{ post.title }}{{ post.date | date_to_string | date: "%b %-d, %Y"  }}

				{% endfor %}


text:
/**
 * The launcher is responsible for parsing the capabilities from the
 * input configuration and launching test runners.
 */
import * as q from 'q';
import {Config, ConfigParser} from './configParser';
import {Logger} from './logger2';
import {Runner} from './runner';
import {TaskRunner} from './taskRunner';
import {TaskScheduler} from './taskScheduler';
import * as helper from './util';

let logger = new Logger('launcher');
let RUNNERS_FAILED_EXIT_CODE = 100;

/**
 * Keeps track of a list of task results. Provides method to add a new
 * result, aggregate the results into a summary, count failures,
 * and save results into a JSON file.
 */
class TaskResults {
  // TODO: set a type for result
  results_: any[] = [];

  add(result: any): void { this.results_.push(result); }

  totalSpecFailures(): number {
    return this.results_.reduce((specFailures, result) => {
      return specFailures + result.failedCount;
    }, 0);
  }

  totalProcessFailures(): number {
    return this.results_.reduce((processFailures, result) => {
      return !result.failedCount && result.exitCode !== 0 ?
          processFailures + 1 :
          processFailures;
    }, 0);
  }

  saveResults(filepath: string): void {
    let jsonOutput = this.results_.reduce((jsonOutput, result) => {
      return jsonOutput.concat(result.specResults);
    }, []);

    let json = JSON.stringify(jsonOutput, null, '  ');
    let fs = require('fs');
    fs.writeFileSync(filepath, json);
  }

  reportSummary(): void {
    let specFailures = this.totalSpecFailures();
    let processFailures = this.totalProcessFailures();
    this.results_.forEach((result: any) => {
      let capabilities = result.capabilities;
      let shortName =
          (capabilities.browserName) ? capabilities.browserName : '';
      shortName = (capabilities.logName) ?
          capabilities.logName :
          (capabilities.browserName) ? capabilities.browserName : '';
      shortName += (capabilities.version) ? capabilities.version : '';
      shortName += (capabilities.logName && capabilities.count < 2) ?
          '' :
          ' #' + result.taskId;
      if (result.failedCount) {
        logger.info(shortName + ' failed ' + result.failedCount + ' test(s)');
      } else if (result.exitCode !== 0) {
        logger.info(shortName + ' failed with exit code: ' + result.exitCode);
      } else {
        logger.info(shortName + ' passed');
      }
    });

    if (specFailures && processFailures) {
      logger.info(
          'overall: ' + specFailures + ' failed spec(s) and ' +
          processFailures + ' process(es) failed to complete');
    } else if (specFailures) {
      logger.info('overall: ' + specFailures + ' failed spec(s)');
    } else if (processFailures) {
      logger.info(
          'overall: ' + processFailures + ' process(es) failed to complete');
    }
  }
}

let taskResults_ = new TaskResults();

/**
 * Initialize and run the tests.
 * Exits with 1 on test failure, and RUNNERS_FAILED_EXIT_CODE on unexpected
 * failures.
 *
 * @param {string=} configFile
 * @param {Object=} additionalConfig
 */
let initFn = function(configFile: string, additionalConfig: Config) {
  let configParser = new ConfigParser();
  if (configFile) {
    configParser.addFileConfig(configFile);
  }
  if (additionalConfig) {
    configParser.addConfig(additionalConfig);
  }
  let config = configParser.getConfig();

  logger.debug('Running with --troubleshoot');
  logger.debug('Protractor version: ' + require('../package.json').version);
  logger.debug('Your base url for tests is ' + config.baseUrl);

  // Run beforeLaunch
  helper.runFilenameOrFn_(config.configDir, config.beforeLaunch)
      .then(() => {

        return q
            .Promise<any>((resolve: Function) => {
              // 1) If getMultiCapabilities is set, resolve that as
              // `multiCapabilities`.
              if (config.getMultiCapabilities &&
                  typeof config.getMultiCapabilities === 'function') {
                if (config.multiCapabilities.length || config.capabilities) {
                  logger.warn(
                      'getMultiCapabilities() will override both capabilities ' +
                      'and multiCapabilities');
                }
                // If getMultiCapabilities is defined and a function, use this.
                q.when(config.getMultiCapabilities(), (multiCapabilities) => {
                   config.multiCapabilities = multiCapabilities;
                   config.capabilities = null;
                 }).then((resolve) => {});
              } else {
                resolve();
              }
            })
            .then(() => {
              // 2) Set `multicapabilities` using `capabilities`,
              // `multicapabilities`,
              // or default
              if (config.capabilities) {
                if (config.multiCapabilities.length) {
                  logger.warn(
                      'You have specified both capabilities and ' +
                      'multiCapabilities. This will result in capabilities being ' +
                      'ignored');
                } else {
                  // Use capabilities if multiCapabilities is empty.
                  config.multiCapabilities = [config.capabilities];
                }
              } else if (!config.multiCapabilities.length) {
                // Default to chrome if no capabilities given
                config.multiCapabilities = [{browserName: 'chrome'}];
              }
            });
      })
      .then(() => {
        // 3) If we're in `elementExplorer` mode, run only that.
        if (config.elementExplorer || config.framework === 'explorer') {
          if (config.multiCapabilities.length != 1) {
            throw new Error(
                'Must specify only 1 browser while using elementExplorer');
          } else {
            config.capabilities = config.multiCapabilities[0];
          }
          config.framework = 'explorer';

          let runner = new Runner(config);
          return runner.run().then(
              (exitCode: number) => { process.exit(exitCode); },
              (err: Error) => {
                logger.error(err);
                process.exit(1);
              });
        }
      })
      .then(() => {
        // 4) Run tests.
        let scheduler = new TaskScheduler(config);

        process.on('exit', (code: number) => {
          if (code) {
            logger.error('Process exited with error code ' + code);
          } else if (scheduler.numTasksOutstanding() > 0) {
            logger.error(
                'BUG: launcher exited with ' + scheduler.numTasksOutstanding() +
                ' tasks remaining');
            process.exit(RUNNERS_FAILED_EXIT_CODE);
          }
        });

        // Run afterlaunch and exit
        let cleanUpAndExit = (exitCode: number) => {
          return helper
              .runFilenameOrFn_(
                  config.configDir, config.afterLaunch, [exitCode])
              .then(
                  (returned) => {
                    if (typeof returned === 'number') {
                      process.exit(returned);
                    } else {
                      process.exit(exitCode);
                    }
                  },
                  (err: Error) => {
                    logger.error('Error:', err);
                    process.exit(1);
                  });
        };

        let totalTasks = scheduler.numTasksOutstanding();
        let forkProcess = false;
        if (totalTasks >
            1) {  // Start new processes only if there are >1 tasks.
          forkProcess = true;
          if (config.debug) {
            throw new Error(
                'Cannot run in debug mode with ' +
                'multiCapabilities, count > 1, or sharding');
          }
        }

        let deferred = q.defer<any>();  // Resolved when all tasks are completed
        let createNextTaskRunner = () => {
          var task = scheduler.nextTask();
          if (task) {
            let taskRunner =
                new TaskRunner(configFile, additionalConfig, task, forkProcess);
            taskRunner.run()
                .then((result) => {
                  if (result.exitCode && !result.failedCount) {
                    logger.error(
                        'Runner process exited unexpectedly with error code: ' +
                        result.exitCode);
                  }
                  taskResults_.add(result);
                  task.done();
                  createNextTaskRunner();
                  // If all tasks are finished
                  if (scheduler.numTasksOutstanding() === 0) {
                    deferred.resolve();
                  }
                  logger.info(
                      scheduler.countActiveTasks() +
                      ' instance(s) of WebDriver still running');
                })
                .catch((err: Error) => {
                  logger.error('Error:', err.stack || err.message || err);
                  cleanUpAndExit(RUNNERS_FAILED_EXIT_CODE);
                });
          }
        };
        // Start `scheduler.maxConcurrentTasks()` workers for handling tasks in
        // the beginning. As a worker finishes a task, it will pick up the next
        // task
        // from the scheduler's queue until all tasks are gone.
        for (var i = 0; i < scheduler.maxConcurrentTasks(); ++i) {
          createNextTaskRunner();
        }
        logger.info(
            'Running ' + scheduler.countActiveTasks() +
            ' instances of WebDriver');

        // By now all runners have completed.
        deferred.promise
            .then(function() {
              // Save results if desired
              if (config.resultJsonOutputFile) {
                taskResults_.saveResults(config.resultJsonOutputFile);
              }

              taskResults_.reportSummary();
              let exitCode = 0;
              if (taskResults_.totalProcessFailures() > 0) {
                exitCode = RUNNERS_FAILED_EXIT_CODE;
              } else if (taskResults_.totalSpecFailures() > 0) {
                exitCode = 1;
              }
              return cleanUpAndExit(exitCode);
            })
            .done();
      })
      .done();
};

export let init = initFn;


text:
require 'ffi'

module PyBind
  class PyObjectStruct < FFI::Struct
    layout ob_refcnt: :ssize_t,
           ob_type:   PyObjectStruct.by_ref

    def self.null
      new(FFI::Pointer::NULL)
    end

    def none?
      PyBind.None.to_ptr == to_ptr
    end

    def kind_of?(klass)
      case klass
      when PyBind::PyObjectStruct
        value = LibPython.PyObject_IsInstance(self, klass)
        raise PyError.fetch if value == -1
        value == 1
      else
        super
      end
    end

    def incref
      LibPython.Py_IncRef(self)
    end

    def decref
      LibPython.Py_DecRef(self)
      self.pointer = FFI::Pointer::NULL
    end

    def to_ruby_object
      PyObject.new(self)
    end

    def to_python_struct
      self
    end
    alias_method :to_python, :to_python_struct
  end
end


text:
namespace CoinNews.Northwind {
    export interface CustomerRepresentativesRow {
        RepresentativeId?: number;
        CustomerId?: number;
        EmployeeId?: number;
    }

    export namespace CustomerRepresentativesRow {
        export const idProperty = 'RepresentativeId';
        export const localTextPrefix = 'Northwind.CustomerRepresentatives';

        export declare const enum Fields {
            RepresentativeId = "RepresentativeId",
            CustomerId = "CustomerId",
            EmployeeId = "EmployeeId"
        }
    }
}


text:
package edu.cmu.minorthird.classify.sequential;

import java.util.Iterator;
import java.util.Vector;

import edu.cmu.minorthird.classify.ClassLabel;
import edu.cmu.minorthird.classify.Classifier;
import edu.cmu.minorthird.classify.Example;
import edu.cmu.minorthird.classify.ExampleSchema;
import edu.cmu.minorthird.classify.Instance;
import edu.cmu.minorthird.util.ProgressCounter;

/**
 * Sequential learner based on the perceptron algorithm that takes the
 * top-k viterbi paths and subtracts those within a margin of beta of
 * the correct.
 *
 * @author Sunita Sarawagi */

public class MarginPerceptronLearner extends CollinsPerceptronLearner
{
	float beta = (float)0.05;
	int topK = 10;
	public MarginPerceptronLearner()
	{
		this(3,5,(float)0.05);
	}
	public MarginPerceptronLearner(int numberOfEpochs)
	{
		this(3,numberOfEpochs,(float)0.05);
	}
	public MarginPerceptronLearner(int historySize,int numberOfEpochs, float beta) {
		this(historySize, numberOfEpochs,beta,10);
	}
	public MarginPerceptronLearner(int historySize,int numberOfEpochs, float beta, int topK)
	{
		super(historySize, numberOfEpochs);
		this.beta = beta;
		this.topK = topK;
	}
	@Override
	public SequenceClassifier batchTrain(SequenceDataset dataset)
	{
		ExampleSchema schema = dataset.getSchema();
		MultiClassVPClassifier c = new MultiClassVPClassifier(schema);

		ProgressCounter pc =
	    new ProgressCounter("training sequence perceptron","sequence",getNumberOfEpochs()*dataset.numberOfSequences());

		Vector<ClassLabel[]> viterbiS = new Vector<ClassLabel[]>();
		for (int epoch=0; epoch<getNumberOfEpochs(); epoch++)
		{
			// statistics for curious researchers
			int sequenceErrors = 0;
			int transitionErrors = 0;
			int transitions = 0;

			for (Iterator<Example[]> i=dataset.sequenceIterator(); i.hasNext(); )
			{
				Example[] sequence = i.next();
				BeamSearcher beam = new BeamSearcher(c,getHistorySize(),schema);
				beam.doSearch(sequence);

				float corrScore = getScore(sequence, c);
				if (DEBUG) log.debug("corrScore: " + corrScore);
				viterbiS.clear();
				int maxNum = Math.min(beam.getNumberOfSolutionsFound(),topK);
				for (int k = 0; k < maxNum; k++) {
			    ClassLabel[] viterbi = beam.viterbi(k);
			    float thisScore = beam.score(k);
			    if (DEBUG) log.debug("viterbi: "+k + " score " + thisScore);
			    if (DEBUG) log.debug(sequenceToString(viterbi));
			    if (thisScore < corrScore*(1-beta))
						break;
			    if (!isCorrect(viterbi,sequence)) {
						viterbiS.add(viterbi);
			    }

				}
				if (DEBUG) log.debug("added: " + viterbiS.size());
				boolean errorOnThisSequence=false;
				if (viterbiS.size() > 0) {
					for (int j=0; j<sequence.length; j++) {
						boolean differenceAtJ = false;
						for (int s = 0; s < viterbiS.size(); s++) {
							ClassLabel[] viterbi = viterbiS.elementAt(s);
							differenceAtJ = !viterbi[j].isCorrect( sequence[j].getLabel() );
							for (int k=1; j-k>=0 && !differenceAtJ && k<=getHistorySize(); k++) {
								if (!viterbi[j-k].isCorrect( sequence[j-k].getLabel() )) {
									differenceAtJ = true;
								}
							}
							if (differenceAtJ) break;
						}

						if (differenceAtJ) { // i.e., if phi(sequence,j) != phi(viterbi,j)
							transitionErrors++;
							errorOnThisSequence=true;
							InstanceFromSequence.fillHistory( history, sequence, j );
							Instance correctXj = new InstanceFromSequence( sequence[j], history );
							c.update( sequence[j].getLabel().bestClassName(), correctXj, 1.0 );
							for (int s = 0; s < viterbiS.size(); s++) {
								ClassLabel[] viterbi = viterbiS.elementAt(s);
								InstanceFromSequence.fillHistory( history, viterbi, j );
								Instance wrongXj = new InstanceFromSequence( sequence[j], history );
								c.update( viterbi[j].bestClassName(), wrongXj, -1.0/viterbiS.size());
							}
						}
					} // example sequence j
				}
				// for voted perceptron needs this...
				c.completeUpdate();

				if (errorOnThisSequence) sequenceErrors++;
				transitions += sequence.length;

				pc.progress();
			} // sequence i

			System.out.println("Epoch "+epoch+": sequenceErr="+sequenceErrors
												 +" transitionErrors="+transitionErrors+"/"+transitions);

			if (transitionErrors==0) break;

		} // epoch
		pc.finished();
		c.setVoteMode(true);
		// we can use a CMM here, since the classifier is constructed to the same
		// beam search will work
		return new CMM(c, getHistorySize(), schema );
	}
	float getScore(Example[] sequence, Classifier classifier) {
		float score = 0;
		for (int j=0; j<sequence.length; j++) {
	    InstanceFromSequence.fillHistory( history, sequence, j );
	    Instance correctXj = new InstanceFromSequence( sequence[j], history );
	    score += classifier.classification(correctXj).getWeight(sequence[j].getLabel().bestClassName());
		}
		return score;
	}
	boolean isCorrect(ClassLabel[] viterbi, Example[] sequence) {
		for (int j=0; j<sequence.length; j++) {
	    if (!viterbi[j].isCorrect( sequence[j].getLabel()))
				return false;
		}
		return true;
	}
	String sequenceToString(ClassLabel[] viterbi) {
		String path="";
		for (int j=0; j<viterbi.length; j++) {
	    path += (viterbi[j].bestClassName() + " ");
		}
		return path;
	}
}