text:
/*
 * This is the hamsterdb Database Server.
 *
 * On Unix it's implemented as a daemon, on Windows it's a Win32 Service.
 * The configuration file has json format - see example.config.
 * The Win32 implementation is based on
 * http://www.devx.com/cplus/Article/9857/1954
 */

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <stdarg.h>
#ifndef WIN32
#  include <unistd.h>
#  include <signal.h>
#  include <sys/signal.h>
#  include <sys/ioctl.h>
#  include <sys/stat.h>
#  include <sys/types.h>
#  include <fcntl.h>
#  include <syslog.h>
#  define STRTOK_SAFE strtok_r
#  define EXENAME "hamzilla"
#  define MAX_PATH_LENGTH   FILENAME_MAX
#else
#  include <process.h> /* _getpid() */
#  include <tchar.h>
#  include <winsock2.h>
#  include <windows.h>
#  include <winioctl.h>
#  define STRTOK_SAFE strtok_s
#  define EXENAME "hamzilla.exe"
#  define MAX_PATH_LENGTH   _MAX_PATH
static TCHAR *serviceName = TEXT("hamsterdb Database Server");
static TCHAR *serviceDescription = TEXT("Provides network access to hamsterdb Databases.");
#endif
#include <signal.h>
#include <errno.h>

#include <ham/hamsterdb.h>
#include <ham/hamsterdb_srv.h>

#include "getopts.h"
#include "common.h"
#include "config.h"

#define ARG_HELP                1
#define ARG_FOREGROUND          2
#define ARG_CONFIG              3
#define ARG_PIDFILE             4
#define ARG_INSTALL             5
#define ARG_UNINSTALL           6
#define ARG_STOP                7
#define ARG_START               8
#define ARG_RUN                 9
#define ARG_LOG_LEVEL           10

/*
 * command line parameters
 */
static option_t opts[] = {
  {
    ARG_HELP,         // symbolic name of this option
    "h",          // short option
    "help",         // long option
    "this help screen",   // help string
    0 },          // no flags
  {
    ARG_FOREGROUND,
    "f",
    "foreground",
    "run in foreground",
    0 },
  {
    ARG_CONFIG,
    "c",
    "config",
    "specify config file",
    GETOPTS_NEED_ARGUMENT },
  {
    ARG_PIDFILE,
    "p",
    "pid",
    "store pid in file",
    GETOPTS_NEED_ARGUMENT },
#ifdef WIN32
  {
    ARG_INSTALL,
    "i",
    "install",
    "(only Win32) installs the Service",
    0 },
  {
    ARG_UNINSTALL,
    "u",
    "uninstall",
    "(only Win32) uninstalls the Service",
    0 },
  {
    ARG_START,
    "s",
    "start",
    "(only Win32) starts the Service",
    0 },
  {
    ARG_STOP,
    "x",
    "stop",
    "(only Win32) stops the Service",
    0 },
#endif
  {
    ARG_LOG_LEVEL,
    "l",
    "log_level",
    "sets the logging level (0: Debug; 1: Info; 2: Warnings; 3: Fatal)",
    GETOPTS_NEED_ARGUMENT },
  { 0, 0, 0, 0, 0 } /* terminating element */
};

#define LOG_DBG     0
#define LOG_NORMAL  1
#define LOG_WARN    2
#define LOG_FATAL   3

static sig_atomic_t running  = 1;
static int foreground = 0;
static int log_level  = LOG_NORMAL;

static void
init_syslog() {
#ifndef WIN32
  openlog(EXENAME, LOG_PID, LOG_DAEMON);
#endif
}

static void
close_syslog() {
#ifndef WIN32
  closelog();
#endif
}

extern "C" {
void
hlog(int level, const char *format, ...) {
  va_list ap;
  char buffer[1024];

  if (level < log_level)
    return;

  va_start(ap, format);
  vsprintf(buffer, format, ap);
  va_end(ap);

  if (foreground) {
    fprintf(stderr, "%s", &buffer[0]);
  }
  else {
#ifdef WIN32
    TCHAR msg[1024];

    mbstowcs(msg, buffer, 1024);

    switch(level) {
      case LOG_DBG:
        OutputDebugString(TEXT("DBG "));
        break;
      case LOG_NORMAL:
        OutputDebugString(TEXT("INFO "));
        break;
      case LOG_WARN:
        OutputDebugString(TEXT("WARN "));
        break;
      default:
        OutputDebugString(TEXT("ERROR "));
        break;
    }

    OutputDebugString(msg);
#else
    unsigned code;

    switch (level) {
      case LOG_DBG:
        code = LOG_DEBUG;
        break;
      case LOG_NORMAL:
        code = LOG_INFO;
        break;
      case LOG_WARN:
        code = LOG_WARNING;
        break;
      default: /* LOG_FATAL */
        code = LOG_EMERG;
        break;
    }
    syslog(code, "%s", buffer);
#endif
  }
}
}

static void
signal_handler(int sig) {
  (void)sig;
  running = 0;
}

#ifndef WIN32

static void
daemonize() {
  int fd;

  switch(fork()) {
  case 0:  /* i'm the child */
    break;
  case -1:
    hlog(LOG_FATAL, "fork failed: %s\n", strerror(errno));
    break;
  default: /* i'm the parent */
    exit(0);
  }

  /* go to root directory */
  /* chdir("/"); */

  /* reset umask */
  /* umask(0); */

  /* disassociate from process group */
  setpgrp();

  /* disassociate from control terminal */
  if ((fd = open("dev/tty", O_RDWR)) >= 0) {
    ioctl(fd, TIOCNOTTY, NULL);
    close(fd);
  }
}
#endif

void
read_config(const char *configfile, config_table_t **params) {
  ham_status_t st;
  char *buf;
  FILE *fp;
  long len;
  size_t r;

  hlog(LOG_DBG, "Parsing configuration file %s\n", configfile);

  /* read the whole file into 'buf' */
  fp = fopen(configfile, "rt");
  if (!fp) {
    hlog(LOG_FATAL, "Failed to open config file %s: %s\n",
        configfile, strerror(errno));
    exit(-1);
  }
  fseek(fp, 0, SEEK_END);
  len = ftell(fp);
  fseek(fp, 0, SEEK_SET);
  buf = (char *)malloc(len + 1); /* for zero-terminating byte */
  r = fread(buf, 1, len, fp);
  fclose(fp);

  if (r != (size_t)len) {
    hlog(LOG_FATAL, "failed to read configuration file: %s\n",
                    strerror(errno));
    exit(-1);
  }

  buf[len] = '\0';

  /* parse the file */
  st = config_parse_string(buf, params);
  if (st) {
    hlog(LOG_FATAL, "failed to read configuration file: %s\n",
        ham_strerror(st));
    exit(-1);
  }

  /* clean up */
  free(buf);
}

void
write_pidfile(const char *pidfile) {
  FILE *fp = fopen(pidfile, "wt");
  if (!fp) {
    hlog(LOG_FATAL, "failed to write pidfile: %s\n", strerror(errno));
    exit(-1);
  }
#ifdef WIN32
  fprintf(fp, "%u", (unsigned)_getpid());
#else
  fprintf(fp, "%u", (unsigned)getpid());
#endif
  fclose(fp);
}

#define COMPARE_FLAG(n)       if (!strcmp(#n, p)) f|=n

uint32_t
format_flags(char *flagstr) {
  uint32_t f = 0;
  char *saveptr = 0;
  char *p;

  if (!flagstr || flagstr[0] == '\0')
    return (0);
  p = STRTOK_SAFE(flagstr, "|", &saveptr);
  while (p) {
    COMPARE_FLAG(HAM_ENABLE_FSYNC);
    else COMPARE_FLAG(HAM_DISABLE_MMAP);
    else COMPARE_FLAG(HAM_CACHE_UNLIMITED);
    else COMPARE_FLAG(HAM_ENABLE_RECOVERY);
    else COMPARE_FLAG(HAM_ENABLE_TRANSACTIONS);
    else COMPARE_FLAG(HAM_READ_ONLY);
    else COMPARE_FLAG(HAM_ENABLE_DUPLICATE_KEYS);
    else COMPARE_FLAG(HAM_RECORD_NUMBER);
    else {
      hlog(LOG_WARN, "Ignoring unknown flag %s\n", p);
    }
    p = STRTOK_SAFE(0, "|", &saveptr);
  }

  return (f);
}

void
initialize_server(ham_srv_t *srv, config_table_t *params) {
  unsigned e, d;
  ham_env_t *env;
  ham_status_t st;

  for (e = 0; e < params->env_count; e++) {
    uint32_t flags = format_flags(params->envs[e].flags);
    ham_bool_t created_env = HAM_FALSE;

    /* First try to open the Environment */
    hlog(LOG_DBG, "Opening Environment %s (flags 0x%x)\n",
        params->envs[e].path, flags);
    st = ham_env_open(&env, params->envs[e].path, flags, 0);
    if (st) {
      /* Not found? if open_exclusive is false then we create the
       * Environment */
      if (st == HAM_FILE_NOT_FOUND && !params->envs[e].open_exclusive) {
        hlog(LOG_DBG, "Env was not found; trying to create it\n");
        st = ham_env_create(&env, params->envs[e].path, flags, 0644, 0);
        if (st) {
          hlog(LOG_FATAL, "Failed to create Env %s: %s\n",
              params->envs[e].path, ham_strerror(st));
          exit(-1);
        }
        hlog(LOG_DBG, "Env %s created successfully\n",
              params->envs[e].path);
        created_env = HAM_TRUE;
      }
      else {
        hlog(LOG_FATAL, "Failed to open Environment %s: %s\n",
              params->envs[e].path, ham_strerror(st));
        exit(-1);
      }
    }

    /* Now create each of the Databases if the Environment was
     * created */
    if (created_env) {
      ham_db_t *db;

      for (d = 0; d < params->envs[e].db_count; d++) {
        uint32_t flags = format_flags(params->envs[e].dbs[d].flags);

        hlog(LOG_DBG, "Creating Database %u\n",
            params->envs[e].dbs[d].name);
        st = ham_env_create_db(env, &db, params->envs[e].dbs[d].name,
                  flags, 0);
        if (st) {
          hlog(LOG_FATAL, "Failed to create Database %u: %s\n",
            params->envs[e].dbs[d].name, ham_strerror(st));
          exit(-1);
        }

        hlog(LOG_DBG, "Created Database %u successfully\n",
            params->envs[e].dbs[d].name);

        ham_db_close(db, 0);
      }
    }

    hlog(LOG_DBG, "Attaching Env to Server (url %s)\n",
        params->envs[e].url);

    /* Add the Environment to the server */
    st = ham_srv_add_env(srv, env, params->envs[e].url);
    if (st) {
      hlog(LOG_FATAL, "Failed to attach Env to Server: %s\n",
          ham_strerror(st));
      exit(-1);
    }

    /* Store env in configuration object */
    params->envs[e].env = env;
  }
}

#ifdef WIN32
static void
win32_service_install() {
  SC_HANDLE scm = OpenSCManager(0, 0, SC_MANAGER_CREATE_SERVICE);

  if (scm) {
    TCHAR path[MAX_PATH_LENGTH+1];
    if (GetModuleFileName(0, path, sizeof(path)/sizeof(path[0])) > 0) {
      SC_HANDLE service = CreateService(scm,
              serviceName, serviceName,
              SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS,
              SERVICE_AUTO_START, SERVICE_ERROR_IGNORE, path,
              0, 0, 0, 0, 0 );
      if (service) {
        SERVICE_DESCRIPTION sd;
        sd.lpDescription=serviceDescription;
        ChangeServiceConfig2(service, SERVICE_CONFIG_DESCRIPTION, &sd);
        CloseServiceHandle(service);
        hlog(LOG_DBG, "Service was installed successfully.\n");
      }
      else
      switch(GetLastError()) {
      case ERROR_ACCESS_DENIED:
        hlog(LOG_FATAL, "The handle to the SCM database does not "
            "have the SC_MANAGER_CREATE_SERVICE access right.\n");
        break;
      case ERROR_CIRCULAR_DEPENDENCY:
        hlog(LOG_FATAL, "A circular service dependency was "
            "specified.\n");
        break;
      case ERROR_DUPLICATE_SERVICE_NAME:
        hlog(LOG_FATAL, "The display name already exists in the "
            "service control manager database either as a "
            "service name or as another display name.\n");
        break;
      case ERROR_INVALID_NAME:
        hlog(LOG_FATAL, "The specified service name is invalid.\n");
        break;
      case ERROR_INVALID_PARAMETER:
        hlog(LOG_FATAL, "A parameter that was specified is invalid.\n");
        break;
      case ERROR_INVALID_SERVICE_ACCOUNT:
        hlog(LOG_FATAL, "The user account name specified in the "
            "lpServiceStartName parameter does not exist.\n");
        break;
      case ERROR_SERVICE_EXISTS:
        hlog(LOG_FATAL, "The specified service already exists in "
            "this database.\n");
        break;
      default:
        hlog(LOG_FATAL, "Failed to install the service (error %u)\n",
            GetLastError());
        break;
      }
    }
    else
      hlog(LOG_FATAL, "GetModuleFileName failed\n");

    CloseServiceHandle(scm);
  }
  else
    hlog(LOG_FATAL, "OpenSCManager failed\n");
}

static void
win32_service_uninstall() {
  SC_HANDLE scm = OpenSCManager(0, 0, SC_MANAGER_CONNECT);

  if (scm) {
    SC_HANDLE service = OpenService(scm, serviceName,
          SERVICE_QUERY_STATUS | DELETE);
    if (service) {
      SERVICE_STATUS sst;
      if (QueryServiceStatus(service, &sst )) {
        if (sst.dwCurrentState == SERVICE_STOPPED) {
          DeleteService(service);
          hlog(LOG_DBG, "Service was uninstalled.\n");
        }
        else
          hlog(LOG_FATAL, "Failed to uninstall - service was "
              "not stopped\n");
      }
      else
        hlog(LOG_FATAL, "QueryServiceStatus failed\n");

      CloseServiceHandle(service);
    }
    else
      hlog(LOG_FATAL, "OpenService failed\n");

    CloseServiceHandle(scm);
  }
  else
    hlog(LOG_FATAL, "OpenSCManager failed\n");
}

static SERVICE_STATUS sst;
static SERVICE_STATUS_HANDLE ssth = 0;
static HANDLE stop_me = 0;

void WINAPI
ServiceControlHandler(DWORD controlCode) {
  switch (controlCode) {
    case SERVICE_CONTROL_INTERROGATE:
      break;

    case SERVICE_CONTROL_SHUTDOWN:
    case SERVICE_CONTROL_STOP:
      hlog(LOG_DBG, "Service received STOP request\n");
      sst.dwCurrentState = SERVICE_STOP_PENDING;
      SetServiceStatus(ssth, &sst);

      SetEvent(stop_me);
      return;

    case SERVICE_CONTROL_PAUSE:
      break;

    case SERVICE_CONTROL_CONTINUE:
      break;

    default:
      if ((controlCode>=128) && (controlCode<=255))
        // user defined control code
        break;
      else
        // unrecognized control code
        break;
  }

  SetServiceStatus(ssth, &sst);
}

static void
win32_service_stop() {
  SC_HANDLE scm = OpenSCManager(0, 0, SC_MANAGER_CONNECT);

  if (scm) {
    SC_HANDLE service = OpenService(scm, serviceName,
          SERVICE_QUERY_STATUS | DELETE | SERVICE_STOP);
    if (service) {
      SERVICE_STATUS sst;
      if (QueryServiceStatus(service, &sst )) {
        if (sst.dwCurrentState == SERVICE_STOPPED) {
          hlog(LOG_NORMAL, "Service is already stopped\n");
        }
        else {
          if (!ControlService(service, SERVICE_CONTROL_STOP, &sst)) {
            hlog(LOG_FATAL, "ControlService failed (%d)\n",
                GetLastError());
          }
        }
      }
      else
        hlog(LOG_FATAL, "QueryServiceStatus failed\n");

      CloseServiceHandle(service);
    }
    else
      hlog(LOG_FATAL, "OpenService failed\n");

    CloseServiceHandle(scm);
  }
  else
    hlog(LOG_FATAL, "OpenSCManager failed\n");
}

static void
win32_service_start() {
  SC_HANDLE scm = OpenSCManager(0, 0, SC_MANAGER_CONNECT);

  if (scm) {
    SC_HANDLE service = OpenService(scm, serviceName,
          SERVICE_QUERY_STATUS | SERVICE_START | DELETE);
    if (service) {
      SERVICE_STATUS sst;
      if (QueryServiceStatus(service, &sst )) {
        if (sst.dwCurrentState != SERVICE_STOPPED
            && sst.dwCurrentState != SERVICE_STOP_PENDING) {
          hlog(LOG_NORMAL, "Service is already running\n");
        }
        else {
          if (!StartService(service, 0, NULL)) {
            hlog(LOG_FATAL, "StartService failed (%d)\n",
                GetLastError());
          }
        }
      }
      else
        hlog(LOG_FATAL, "QueryServiceStatus failed\n");

      CloseServiceHandle(service);
    }
    else
      hlog(LOG_FATAL, "OpenService failed\n");

    CloseServiceHandle(scm);
  }
  else
    hlog(LOG_FATAL, "OpenSCManager failed\n");
}

void WINAPI
ServiceMain(DWORD argc, TCHAR *argv[]) {
  ssth = RegisterServiceCtrlHandler(serviceName, ServiceControlHandler);
  if (ssth) {
    // do initialisation here
    stop_me = CreateEvent(0, FALSE, FALSE, 0);

    // running
    sst.dwControlsAccepted |= (SERVICE_ACCEPT_STOP
                  | SERVICE_ACCEPT_SHUTDOWN);
    sst.dwCurrentState = SERVICE_RUNNING;
    SetServiceStatus(ssth, &sst);

    hlog(LOG_DBG, "Service is entering main loop\n");

    do {
      /* this is the main loop */;
    } while (WaitForSingleObject(stop_me, 5000)==WAIT_TIMEOUT);

    // service was stopped
    hlog(LOG_DBG, "Service is leaving main loop\n");
    sst.dwCurrentState = SERVICE_STOP_PENDING;
    SetServiceStatus(ssth, &sst);

    // do cleanup here
    CloseHandle(stop_me);
    stop_me = 0;

    // service is now stopped
    sst.dwControlsAccepted &= ~(SERVICE_ACCEPT_STOP
                | SERVICE_ACCEPT_SHUTDOWN);
    sst.dwCurrentState = SERVICE_STOPPED;
    SetServiceStatus(ssth, &sst);
  }
  else
    hlog(LOG_FATAL, "RegisterServiceCtrlHandler failed\n");
}

static void
win32_service_run_fg() {
  hlog(LOG_DBG, "Service is entering main loop\n");
  while (running)
    Sleep(1000);
  hlog(LOG_DBG, "Service is leaving main loop\n");
}

static void
win32_service_run() {
  DWORD ret;
  SERVICE_TABLE_ENTRY serviceTable[] = {
    { serviceName, ServiceMain },
    { 0, 0 }
  };

  // initialize service status
  sst.dwServiceType = SERVICE_WIN32;
  sst.dwCurrentState = SERVICE_STOPPED;
  sst.dwControlsAccepted = 0;
  sst.dwWin32ExitCode = NO_ERROR;
  sst.dwServiceSpecificExitCode = NO_ERROR;
  sst.dwCheckPoint = 0;
  sst.dwWaitHint = 0;

  // service is starting
  sst.dwCurrentState = SERVICE_START_PENDING;
  SetServiceStatus(ssth, &sst);

  ret=StartServiceCtrlDispatcher(serviceTable);
  if (!ret) {
    /* This fails if hamzilla is started from the console. */
    printf("Please run `hamzilla.exe -s` to start the service.\n");
  }
}
#endif

int
main(int argc, char **argv) {
  unsigned opt;
  char *param = 0, *configfile = 0, *pidfile = 0;
  unsigned e;
  ham_srv_t *srv = 0;
  ham_srv_config_t cfg;
  config_table_t *params = 0;
  char configbuffer[MAX_PATH_LENGTH * 2];
#ifdef WIN32
  int win32_action = ARG_RUN;
#endif

  memset(&cfg, 0, sizeof(cfg));
  getopts_init(argc, argv, EXENAME);
  strcpy(configbuffer, argv[0]);

  while ((opt = getopts(&opts[0], &param))) {
    switch (opt) {
      case ARG_FOREGROUND:
        hlog(LOG_DBG, "Paramter: Running in foreground\n");
        foreground = 1;
        break;
      case ARG_CONFIG:
        configfile = param;
        hlog(LOG_DBG, "Paramter: configuration file is %s\n",
            configfile);
        break;
      case ARG_PIDFILE:
        pidfile = param;
        hlog(LOG_DBG, "Paramter: pid file is %s\n", pidfile);
        break;
      case ARG_HELP:
        print_banner(EXENAME);

        printf("usage: %s [-f] -c configfile\n", EXENAME);
        printf("usage: %s -h\n", EXENAME);
        printf("     -h:     this help screen (alias: --help)\n");
        printf("     -f:     run in foreground\n");
        printf("     configfile: path of configuration file\n");
        return (0);
#ifdef WIN32
      case ARG_INSTALL:
        hlog(LOG_DBG, "Paramter: Installing service\n");
        win32_action=ARG_INSTALL;
        break;
      case ARG_UNINSTALL:
        hlog(LOG_DBG, "Paramter: Uninstalling service\n");
        win32_action = ARG_UNINSTALL;
        break;
      case ARG_STOP:
        hlog(LOG_DBG, "Paramter: Stopping service\n");
        win32_action = ARG_STOP;
        break;
      case ARG_START:
        hlog(LOG_DBG, "Paramter: Starting service\n");
        win32_action = ARG_START;
        break;
#endif
      case ARG_LOG_LEVEL:
        log_level = strtoul(param, 0, 0);
        if (log_level > LOG_FATAL)
          log_level = LOG_FATAL;
        hlog(LOG_DBG, "Paramter: Log level is %u\n", log_level);
        break;
      default:
        printf("Invalid or unknown parameter `%s'. "
             "Enter `./hamzilla --help' for usage.", param);
        return (-1);
    }
  }

  /* daemon/win32 service: initialize syslog/Eventlog */
  if (!foreground)
    init_syslog();

  /* if there's no configuration file then load a default one:
   * Just look for a configuration file with the same name (but a
   * different extension ".config") in the same directory
   * as hamsvc[.exe] */
  if (!configfile) {
#ifdef WIN32
    char *p = configbuffer + strlen(configbuffer) - 1;
    while (*p != '.')
      p--;
    *p = '\0';
#endif
    strcat(configbuffer, ".config");
    configfile = &configbuffer[0];
    hlog(LOG_DBG, "Parameter: No config file specified - using %s\n",
        configfile);
  }

  /* now read and parse the configuration file */
  if (configfile)
    read_config(configfile, &params);

  /* register signals; these are the signals that will terminate the daemon */
  hlog(LOG_DBG, "Registering signal handlers\n");
#ifndef WIN32
  signal(SIGHUP, signal_handler);
  signal(SIGQUIT, signal_handler);
  signal(SIGKILL, signal_handler);
#endif
  signal(SIGABRT, signal_handler);
  signal(SIGINT, signal_handler);
  signal(SIGTERM, signal_handler);

#ifdef WIN32
  switch (win32_action) {
    case ARG_INSTALL:
      hlog(LOG_NORMAL, "hamzilla is installing...\n");
      win32_service_install();
      goto cleanup;
    case ARG_UNINSTALL:
      hlog(LOG_NORMAL, "hamzilla is uninstalling...\n");
      win32_service_uninstall();
      goto cleanup;
    case ARG_STOP:
      hlog(LOG_NORMAL, "hamzilla is stopping...\n");
      win32_service_stop();
      goto cleanup;
    case ARG_START:
      hlog(LOG_NORMAL, "hamzilla is starting...\n");
      win32_service_start();
      goto cleanup;
  }
#else
  hlog(LOG_NORMAL, "hamzilla is starting...\n");
#endif

  if (params) {
    cfg.port = params->globals.port;
    hlog(LOG_DBG, "Config: port is %u\n", cfg.port);
    if (params->globals.enable_access_log) {
      cfg.access_log_path = params->globals.access_log;
      hlog(LOG_DBG, "Config: http access hlog is %s\n",
          cfg.access_log_path);
    }
    if (params->globals.enable_error_log) {
      cfg.error_log_path = params->globals.error_log;
      hlog(LOG_DBG, "Config: http error hlog is %s\n",
          cfg.error_log_path);
    }
  }

  /* on Unix we first daemonize, then write the pidfile (otherwise we do
   * not know the pid of the daemon process). On Win32, we first write
   * the pidfile and then call the service startup routine later. */
#ifndef WIN32
  if (!foreground) {
    hlog(LOG_DBG, "Running in background...\n");
    daemonize();
  }
#endif
  if (pidfile) {
    hlog(LOG_DBG, "Writing pid file\n");
    write_pidfile(pidfile);
  }

  /* Initialize the server */
  if ((0 != ham_srv_init(&cfg, &srv))) {
    hlog(LOG_FATAL, "Failed to initialize the server; terminating\n");
    exit(-1);
  }
  if (params)
    initialize_server(srv, params);

  /* This is the unix "main loop" which waits till the server is terminated.
   * Any registered signal will terminate the server by setting the
   * 'running' flag to 0. (The Win32 main loop is hidden in
   * win32_service_run()). */
#ifndef WIN32
  hlog(LOG_DBG, "Daemon is entering main loop\n");
  while (running)
    sleep(1);
  hlog(LOG_DBG, "Daemon is leaving main loop\n");
#else
  if (win32_action == ARG_RUN) {
    if (foreground) {
      hlog(LOG_DBG, "Running in foreground\n");
      win32_service_run_fg();
    }
    else {
      hlog(LOG_DBG, "Running in background (Win32 service)\n");
      win32_service_run();
    }
  }
#endif

  hlog(LOG_NORMAL, "hamzilla is stopping...\n");

  /* avoid warning on linux that the cleanup label is never used */
  goto cleanup;

cleanup:
  /* clean up */
  hlog(LOG_DBG, "Cleaning up\n");
  if (srv)
    ham_srv_close(srv);
  if (params) {
    for (e = 0; e < params->env_count; e++) {
      if (params->envs[e].env)
        (void)ham_env_close(params->envs[e].env, HAM_AUTO_CLEANUP);
    }
    config_clear_table(params);
  }

  hlog(LOG_DBG, "Terminating process\n");

  /* daemon/win32 service: close syslog/Eventlog */
  if (!foreground)
    close_syslog();

  return (0);
}


text:
package org.broadinstitute.hellbender.utils.read;

import htsjdk.samtools.SAMRecord;
import htsjdk.samtools.SamReader;
import htsjdk.samtools.SamReaderFactory;
import org.broadinstitute.hellbender.GATKBaseTest;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

public final class ArtificialBAMBuilderUnitTest extends GATKBaseTest {

    @DataProvider(name = "ArtificialBAMBuilderUnitTestProvider")
    public Object[][] makeArtificialBAMBuilderUnitTestProvider() {
        final List<Object[]> tests = new LinkedList<>();

        final List<Integer> starts = Arrays.asList(
                1 // very start of the chromosome
        );

        for ( final int readLength : Arrays.asList(10, 20) ) {
            for ( final int skips : Arrays.asList(0, 1, 10) ) {
                for ( final int start : starts ) {
                    for ( final int nSamples : Arrays.asList(1, 2) ) {
                        for ( final int nReadsPerLocus : Arrays.asList(1, 10) ) {
                            for ( final int nLoci : Arrays.asList(10, 100, 1000) ) {
                                final ArtificialBAMBuilder bamBuilder = new ArtificialBAMBuilder(nReadsPerLocus, nLoci);
                                bamBuilder.setReadLength(readLength);
                                bamBuilder.setSkipNLoci(skips);
                                bamBuilder.setAlignmentStart(start);
                                bamBuilder.createAndSetHeader(nSamples);
                                tests.add(new Object[]{bamBuilder, readLength, skips, start, nSamples, nReadsPerLocus, nLoci});
                            }
                        }
                    }
                }
            }
        }

        return tests.toArray(new Object[][]{});
    }

    @Test(dataProvider = "ArtificialBAMBuilderUnitTestProvider")
    public void testBamProvider(final ArtificialBAMBuilder bamBuilder, int readLength, int skips, int start, int nSamples, int nReadsPerLocus, int nLoci) throws IOException {
        Assert.assertEquals(bamBuilder.getReadLength(), readLength);
        Assert.assertEquals(bamBuilder.getSkipNLoci(), skips);
        Assert.assertEquals(bamBuilder.getAlignmentStart(), start);
        Assert.assertEquals(bamBuilder.getAlignmentEnd(), start + nLoci * (skips + 1) + readLength);
        Assert.assertEquals(bamBuilder.getNSamples(), nSamples);
        Assert.assertEquals(bamBuilder.getnReadsPerLocus(), nReadsPerLocus);
        Assert.assertEquals(bamBuilder.getnLoci(), nLoci);

        Assert.assertEquals(bamBuilder.getSamples().size(), bamBuilder.getNSamples());
        Assert.assertNull(bamBuilder.getReference());

        final List<GATKRead> reads = bamBuilder.makeReads();
        Assert.assertEquals(reads.size(), bamBuilder.expectedNumberOfReads());
        for ( final GATKRead read : reads ) {
            assertGoodRead(read.convertToSAMRecord(bamBuilder.getHeader()), bamBuilder);
        }

        final File bam = bamBuilder.makeTemporaryBAMFile();
        final SamReader reader = SamReaderFactory.makeDefault().open(bam);
        Assert.assertTrue(reader.hasIndex());
        final Iterator<SAMRecord> bamIt = reader.iterator();
        int nReadsFromBam = 0;
        int lastStart = -1;
        while ( bamIt.hasNext() ) {
            final SAMRecord read = bamIt.next();
            assertGoodRead(read, bamBuilder);
            nReadsFromBam++;
            Assert.assertTrue(read.getAlignmentStart() >= lastStart);
            lastStart = read.getAlignmentStart();
        }
        Assert.assertEquals(nReadsFromBam, bamBuilder.expectedNumberOfReads());
    }

    private void assertGoodRead(final SAMRecord read, final ArtificialBAMBuilder bamBuilder) {
        Assert.assertEquals(read.getReadLength(), bamBuilder.getReadLength());
        Assert.assertEquals(read.getReadBases().length, bamBuilder.getReadLength());
        Assert.assertEquals(read.getBaseQualities().length, bamBuilder.getReadLength());
        Assert.assertTrue(read.getStart() >= bamBuilder.getAlignmentStart());
        Assert.assertNotNull(read.getReadGroup());
    }
}

redpajama_set_name: RedPajamaGithub


text:
print("Hi there. \nUse this tool to find out if you can drink alcohol legally in your state.")
print("You will be asked to enter your state of residence, birth year, and birth month.")
print("If you are inquiring about another state's drinking laws, you may do so.")
print("That's enough talking for now... let's get started!\n\n")

"""Variables"""
#WA_resident = input to determine if one is a WA resident or not.
#state_name = user's state of residence or state of inquiry.
#birth_year = user's year of birth.
#birth_month = user's month of birth.

def main():

    ## This portion of the program collects user-input ##
    WA_resident = str(input("Are you inquiring about Washington laws? Enter YES or NO: "))

    ## Section of code to determine non-WA residents' ability to consume alcohol legally. ##
    ## Some states have exceptions to the "21 and over" law. ##
    if WA_resident == "NO":

        ##Getting birth year/month from the user##
        birth_year = int(input("What is your birth year? (e.g. 1975): "))
        birth_month = int(input("What is your birth month? (e.g. 4 for April): "))
        if birth_month == 0 or birth_month > 12:
            print("Please enter in a valid month. ")
            birth_month = int(input("What is your birth month? (e.g. 4 for April): "))

        ##California has laws that allow people <21 to drink a small amount of alcohol for religious purposes##
        california = str(input("Are you inquiring about California? Enter YES or NO: "))
        if california == "YES":
            state_name = "California"
            exception = str(input("Are you consuming alcohol for RELIGIOUS PURPOSES?\n(It must be a SMALL amount!) Enter YES or NO: "))
            if exception == "NO":
                if birth_year == 1993 and birth_month == 3 or birth_year <= 1993 and birth_month <= 3:
                    print("\nIt doesn't matter why you're consuming alcohol!\nYou can drink in the entire United States!\nCongrats!")
                if birth_year >= 1993 and birth_month > 3 or birth_year > 1993:
                    print("\nSorry, you won't be able to consume any alcohol... anywhere...")
            if exception == "YES":
                if birth_year == 1993 and birth_month == 3 or birth_year <= 1993 and birth_month <= 3:
                    print("\nIt doesn't matter why you're consuming alcohol!\nYou can drink in the entire United States!\nCongrats!")
                if birth_year >= 1993 and birth_month > 3 or birth_year > 1993:
                    print("\nYou can consume alcohol in this way in the state of California.\nJust don't do it anywhere else.\nBecause that'd be illegal...")

        if california == "NO":
            ##Kansas allows people <21 to drink on one's own property##
            kansas = str(input("Are you inquiring about Kansas? Enter YES or NO: "))
            if kansas == "NO":
                ##In Georgia and Wisconsin people <21 can drink if their parent(s)/legal guardian(s) or spouse is present##
                georgia_wisconsin = str(input("Are you inquiring about Georgia or Wisconsin? Enter YES or NO: "))
                if georgia_wisconsin == "YES":
                    exception_2 = str(input("Are your parents, legal guardians, and/or spouse present? Enter YES or NO: "))
                    if exception_2 == "YES":
                        state_name = "Georgia and Wisconsin"
                        if birth_year == 1993 and birth_month == 3 or birth_year <= 1993 and birth_month <= 3:
                            print("\nYou can actively enjoy your alcohol in the ENTIRE United States!")
                            print("Congrats on your accomplishment!")
                        if birth_year >= 1993 and birth_month > 3 or birth_year > 1993:
                            print("\nCool-- you can legally consume alcohol in Wisconsin and Georgia.\nBut not in any other US state.\nSorry :(")
                    if exception_2 == "NO":
                        state_name = "Georgia and Wisconsin"
                        if birth_year == 1993 and birth_month == 3 or birth_year <= 1993 and birth_month <= 3:
                            print("\nYou can actively enjoy your alcohol in the ENTIRE United States!")
                            print("Congrats on your accomplishment!")
                        if birth_year >= 1993 and birth_month > 3 or birth_year > 1993:
                            print("\nI am sorry, you cannot legally consume alcohol in " +str(state_name)+ ".")
                            print("Be patient and give it some time.")
                            print("Sorry :(")

                if georgia_wisconsin == "NO":
                    ##This block of code is solely to determine the user's eligibity in remaining states##
                    state_name = str(input("What state are you inquiring about? "))
                    if birth_year == 1993 and birth_month == 3 or birth_year <= 1993 and birth_month <= 3:
                        print("\nYou can actively enjoy your alcohol in the ENTIRE United States!")
                        print("Congrats on your accomplishment!")
                    if birth_year >= 1993 and birth_month > 3 or birth_year > 1993:
                        print("\nI am sorry, you cannot legally consume alcohol in " +str(state_name)+ ".")
                        print("Be patient and give it some time.")
                        print("Sorry :(")

            if kansas == "YES":
                exception_3 = str(input("Will you be consuming alcohol on your own property? Enter YES or NO: "))
                if exception_3 == "YES":
                    if birth_year == 1993 and birth_month == 3 or birth_year <= 1993 and birth_month <= 3:
                        print("\nIt doesn't matter why you're consuming alcohol!\nYou can drink in the entire United States!\nCongrats!")
                    if birth_year >= 1993 and birth_month > 3 or birth_year > 1993:
                        print("\nYou can drink alcohol as long as it's on your personal property.\nBut only in Kansas, it's illegal for you in all other states.")

    ## This portion of the program determines legality based upon birth year/month for WA. ##
    if WA_resident == "YES":
        state_name = "Washington"
        birth_year = int(input("What is your birth year? (e.g. 1975): "))
        birth_month = int(input("What is your birth month? (e.g. 4 for April): "))
        if birth_month == 0 or birth_month > 12:
            print("Please enter in a valid month. ")
            birth_month = int(input("What is your birth month? (e.g. 4 for April): "))
        if birth_year == 1993 and birth_month == 3 or birth_year <= 1993 and birth_month <= 3:
            print("\nYou can actively enjoy your alcohol in the ENTIRE United States!")
            print("Congrats on your accomplishment!")
        if birth_year >= 1993 and birth_month > 3 or birth_year > 1993:
            print("\nI am sorry, you cannot legally consume alcohol in " +str(state_name)+ ".")
            print("Be patient and give it some time.")
            print("Sorry :(")
main()

## Short function to end the program ##
def endTool():
    print("___________________")
    print("\nThank you for using this tool.")
    input("Press enter to quit... goodbye.")

endTool()


text:
angular.module('module_watchlist')

.directive('watchlistDirective', function() {
    return {
        restrict: 'E',
        scope: {
        },
        controller: "Module_WatchlistController",
        templateUrl: 'frontend/app/module/watchlist/template/watchlist.tpl.html',
        link: function(scope) {

        }
    };
});


text:
/**
 * Work
 */
export class Work {
    constructor(
        public id: number,
        public employer: string,
        public title: string,
        public domain: string,
        public from: string,
        public to: string) { }
}


text:
class StandingsController < ApplicationController
  before_action only: [:show] do
    contest = Contest.find(params[:contest_id])
    contestant_user(contest) if !contest.past?
  end

  def show
    @contest = Contest.find(params[:contest_id])
    @users = User.all
  end
end


text:
import threading
import unittest
from flexmock import flexmock
from nose.tools import raises
import time
from tinys3.auth import S3Auth
from tinys3.pool import Pool
from .test_conn import TEST_SECRET_KEY, TEST_ACCESS_KEY
from concurrent.futures import ThreadPoolExecutor, Future
import concurrent.futures

DUMMY_OBJECT = 'DUMMY'

class TestPool(unittest.TestCase):
    def test_pool_creation(self):
        """
        Test creating a pool
        """

        # Test new pool with auth
        pool = Pool(TEST_ACCESS_KEY, TEST_SECRET_KEY, default_bucket='bucket', tls=True)

        self.assertEquals(pool.tls, True)
        self.assertEquals(pool.default_bucket, 'bucket')
        self.assertTrue(isinstance(pool.auth, S3Auth))
        self.assertTrue(isinstance(pool.executor, ThreadPoolExecutor))

        # Test new pool with different size
        pool = Pool(TEST_ACCESS_KEY, TEST_SECRET_KEY, size=25)
        self.assertEquals(pool.executor._max_workers, 25)

    def test_as_completed(self):
        """
        Test the as_completed method
        """

        # Create mock futures
        futures = [Future(), Future(), Future()]

        # Create a default pool
        pool = Pool(TEST_ACCESS_KEY, TEST_SECRET_KEY)

        # Resolve futures with a simple object
        for i in futures:
            i.set_result(DUMMY_OBJECT)

        # Make sure all the results are dummy objects
        for i in pool.as_completed(futures):
            self.assertEquals(i, DUMMY_OBJECT)

    def test_all_completed(self):
        """
        Test the all completed
        """
        # Create mock futures
        futures = [Future(), Future(), Future()]

        # Create a default pool
        pool = Pool(TEST_ACCESS_KEY, TEST_SECRET_KEY)

        # Resolve futures with a simple object
        for i in futures:
            i.set_result(DUMMY_OBJECT)

        # Make sure all the results are dummy objects
        for i in pool.all_completed(futures):
            self.assertEquals(i, DUMMY_OBJECT)

    def test_pool_as_context_manager(self):
        """
        Test the pool's context_management ability
        """

        pool = Pool(TEST_ACCESS_KEY, TEST_SECRET_KEY)

        flexmock(pool).should_receive('close').once()

        with pool as p:
            # do nothing
            pass


text:
class CreateUsers < ActiveRecord::Migration
  def self.up
    create_table :users do |t|
      t.string :login
      t.string :crypted_password
      t.string :salt
      t.integer :profile_id
      t.integer :updated_by

      t.timestamps
    end
  end

  def self.down
    drop_table :users
  end
end


text:
package org.apache.nifi.registry.service.mapper;

import org.apache.nifi.registry.db.entity.KeyEntity;
import org.apache.nifi.registry.security.key.Key;

/**
 * Mappings between key DB entities and data model.
 */
public class KeyMappings {

    public static Key map(final KeyEntity keyEntity) {
        final Key key = new Key();
        key.setId(keyEntity.getId());
        key.setIdentity(keyEntity.getTenantIdentity());
        key.setKey(keyEntity.getKeyValue());
        return key;
    }

    public static KeyEntity map(final Key key) {
        final KeyEntity keyEntity = new KeyEntity();
        keyEntity.setId(key.getId());
        keyEntity.setTenantIdentity(key.getIdentity());
        keyEntity.setKeyValue(key.getKey());
        return keyEntity;
    }

}


text:
class Smoothmouse < Cask
  url 'http://smoothmouse.com/download/latest'
  homepage 'http://smoothmouse.com'
  version 'latest'
  sha256 :no_check
  install 'SmoothMouse.pkg'
  uninstall :launchctl => [
                           'com.cyberic.smoothmouse',
                           'com.cyberic.smoothmouseupdater',
                          ],
            :quit      => 'com.test.SmoothMouseDaemon',
            :kext      => 'com.cyberic.SmoothMouse',
            :pkgutil   => [
                           'com.cyberic.pkg.SmoothMousePrefPane',
                           'com.cyberic.pkg.SmoothMouseKext2',
                          ],
            :files     => '/usr/bin/smoothmouse'
end


text:
<!DOCTYPE html>
<meta charset="utf-8">

    <title>Hybrid Cloud Demo</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

hcr.k8s.io

            <button id="play" class="sendRequest">Send Request</button>

Kubernetes


text:
//-----------------------------------------------------------------------
// <copyright file="ClusterEvent.cs" company="Akka.NET Project">
//     Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com>
//     Copyright (C) 2013-2015 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Runtime.InteropServices;
using Akka.Actor;
using Akka.Event;
using Akka.Util.Internal;

namespace Akka.Cluster
{
    /// <summary>
    /// Domain events published to the event bus.
    /// Subscribe with:
    /// {{{
    /// Cluster(system).subscribe(actorRef, classOf[ClusterDomainEvent])
    /// }}}
    /// </summary>
    public class ClusterEvent
    {
        public enum SubscriptionInitialStateMode
        {
            //TODO: Sort out xml doc references
            /// <summary>
            /// When using this subscription mode a snapshot of
            /// [[akka.cluster.ClusterEvent.CurrentClusterState]] will be sent to the
            /// subscriber as the first message.
            /// </summary>
            InitialStateAsSnapshot,
            /// <summary>
            /// When using this subscription mode the events corresponding
            /// to the current state will be sent to the subscriber to mimic what you would
            /// have seen if you were listening to the events when they occurred in the past.
            /// </summary>
            InitialStateAsEvents
        }

        public static readonly SubscriptionInitialStateMode InitialStateAsSnapshot =
            SubscriptionInitialStateMode.InitialStateAsSnapshot;

        public static readonly SubscriptionInitialStateMode InitialStateAsEvents =
            SubscriptionInitialStateMode.InitialStateAsEvents;

        /// <summary>
        /// Marker interface for cluster domain events
        /// </summary>
        public interface IClusterDomainEvent { }

        public sealed class CurrentClusterState
        {
            private readonly ImmutableSortedSet<Member> _members;
            private readonly ImmutableHashSet<Member> _unreachable;
            private readonly ImmutableHashSet<Address> _seenBy;
            private readonly Address _leader;
            private readonly ImmutableDictionary<string, Address> _roleLeaderMap;

            public CurrentClusterState() : this(
                ImmutableSortedSet.Create<Member>(),
                ImmutableHashSet.Create<Member>(),
                ImmutableHashSet.Create<Address>(),
                null,
                ImmutableDictionary.Create<string, Address>()
                )
            {}

            public CurrentClusterState(
                ImmutableSortedSet<Member> members,
                ImmutableHashSet<Member> unreachable,
                ImmutableHashSet<Address> seenBy,
                Address leader,
                ImmutableDictionary<string, Address> roleLeaderMap)
            {
                _members = members;
                _unreachable = unreachable;
                _seenBy = seenBy;
                _leader = leader;
                _roleLeaderMap = roleLeaderMap;
            }

            /// <summary>
            /// Get current member list
            /// </summary>
            public ImmutableSortedSet<Member> Members
            {
                get { return _members; }
            }

            /// <summary>
            /// Get current unreachable set
            /// </summary>
            public ImmutableHashSet<Member> Unreachable
            {
                get { return _unreachable; }
            }

            /// <summary>
            /// Get current "seen-by" set
            /// </summary>
            public ImmutableHashSet<Address> SeenBy
            {
                get { return _seenBy; }
            }

            /// <summary>
            /// Get address of current leader, or null if noe
            /// </summary>
            public Address Leader
            {
                get { return _leader; }
            }

            //TODO: Cache ToImmutableHashSet?
            /// <summary>
            /// All node roles in the cluster
            /// </summary>
            public ImmutableHashSet<string> AllRoles
            {
                get { return _roleLeaderMap.Keys.ToImmutableHashSet(); }
            }

            /// <summary>
            /// Needed internally inside the <see cref="ClusterReadView"/>
            /// </summary>
            internal ImmutableDictionary<string, Address> RoleLeaderMap
            {
                get { return _roleLeaderMap; }
            }

            /// <summary>
            /// Get address of current leader, if any, within the role set
            /// </summary>
            public Address RoleLeader(string role)
            {
                return _roleLeaderMap.GetOrElse(role, null);
            }

            /// <summary>
            /// Creates a deep copy of the <see cref="CurrentClusterState"/> and optionally allows you
            /// to specify different values for the outgoing objects
            /// </summary>
            public CurrentClusterState Copy(ImmutableSortedSet<Member> members = null,
                ImmutableHashSet<Member> unreachable = null,
                ImmutableHashSet<Address> seenBy = null,
                Address leader = null,
                ImmutableDictionary<string, Address> roleLeaderMap = null)
            {
                return new CurrentClusterState(members ?? _members,
                    unreachable ?? _unreachable,
                    seenBy ?? _seenBy,
                    leader ?? (_leader != null ? (Address)_leader.Clone() : null),
                    roleLeaderMap ?? _roleLeaderMap);
            }
        }

        /// <summary>
        /// Marker interface for membership events.
        /// Published when the state change is first seen on a node.
        /// The state change was performed by the leader when there was
        /// convergence on the leader node, i.e. all members had seen previous
        /// state.
        /// </summary>
        public interface IMemberEvent : IClusterDomainEvent
        {
            Member Member { get; }
        }

        public abstract class MemberStatusChange : IMemberEvent
        {
            protected readonly Member _member;

            protected MemberStatusChange(Member member, MemberStatus validStatus)
            {
                if (member.Status != validStatus)
                    throw new ArgumentException(String.Format("Expected {0} state, got: {1}", validStatus, member));
                _member = member;
            }

            public Member Member
            {
                get { return _member; }
            }

            public override bool Equals(object obj)
            {
                var other = obj as MemberStatusChange;
                if (other == null) return false;
                return _member.Equals(other._member);
            }

            public override int GetHashCode()
            {
                unchecked
                {
                    var hash = 17;
                    hash = hash*23 + _member.GetHashCode();
                    return hash;
                }
            }
        }

        /// <summary>
        /// Member status changed to Up.
        /// </summary>
        public sealed class MemberUp : MemberStatusChange
        {
            public MemberUp(Member member)
                : base(member, MemberStatus.Up) { }
        }

        //TODO: Sort out xml doc references
        /// <summary>
        /// Member status changed to [[MemberStatus.Exiting]] and will be removed
        /// when all members have seen the `Exiting` status.
        /// </summary>
        public sealed class MemberExited : MemberStatusChange
        {
            public MemberExited(Member member)
                : base(member, MemberStatus.Exiting)
            {
            }
        }

        /// <summary>
        /// Member completely removed from the cluster.
        /// When `previousStatus` is `MemberStatus.Down` the node was removed
        /// after being detected as unreachable and downed.
        /// When `previousStatus` is `MemberStatus.Exiting` the node was removed
        /// after graceful leaving and exiting.
        /// </summary>
        public sealed class MemberRemoved : MemberStatusChange
        {
            readonly MemberStatus _previousStatus;

            public MemberStatus PreviousStatus
            {
                get { return _previousStatus; }
            }

            public MemberRemoved(Member member, MemberStatus previousStatus)
                : base(member, MemberStatus.Removed)
            {
                //TODO: Akka exception?
                if(member.Status != MemberStatus.Removed) throw new ArgumentException(String.Format("Expected Removed status, got {0}", member));
                _previousStatus = previousStatus;
            }

            public override bool Equals(object obj)
            {
                var other = obj as MemberRemoved;
                if (other == null) return false;
                return _member.Equals(other._member) && _previousStatus == other._previousStatus;
            }

            public override int GetHashCode()
            {
                unchecked
                {
                    var hash = 17;
                    hash = hash*23 + base.GetHashCode();
                    hash = hash*23 + _previousStatus.GetHashCode();
                    return hash;
                }
            }
        }

        /// <summary>
        /// Leader of the cluster members changed. Published when the state change
        /// is first seen on a node.
        /// </summary>
        public sealed class LeaderChanged : IClusterDomainEvent
        {
            private readonly Address _leader;

            public LeaderChanged(Address leader)
            {
                _leader = leader;
            }

            /// <summary>
            /// Address of current leader, or null if none
            /// </summary>
            public Address Leader
            {
                get { return _leader; }
            }

            public override bool Equals(object obj)
            {
                var other = obj as LeaderChanged;
                if (other == null) return false;
                return (_leader == null && other._leader == null) || (_leader != null && _leader.Equals(other._leader));
            }

            public override int GetHashCode()
            {
                unchecked
                {
                    var hash = 17;
                    hash = hash * 23 + (_leader == null ? 0 : _leader.GetHashCode());
                    return hash;
                }
            }
        }

        /// <summary>
        /// First member (leader) of the members within a role set changed.
        /// Published when the state change is first seen on a node.
        /// </summary>
        public sealed class RoleLeaderChanged : IClusterDomainEvent
        {
            //TODO: While I'm here Address needs to be immutable
            private readonly Address _leader;
            private readonly string _role;

            public RoleLeaderChanged(string role, Address leader)
            {
                _role = role;
                _leader = leader;
            }

            /// <summary>
            /// Address of current leader, or null if none
            /// </summary>
            public Address Leader
            {
                get { return _leader; }
            }

            public string Role
            {
                get { return _role; }
            }

            public override int GetHashCode()
            {
                unchecked
                {
                    var hash = 17;
                    hash = hash * 23 + _role.GetHashCode();
                    hash = hash * 23 + (_leader == null ? 0 : _leader.GetHashCode());
                    return hash;
                }
            }

            public override bool Equals(object obj)
            {
                //TODO: Messy
                var other = obj as RoleLeaderChanged;
                if (other == null) return false;
                return _role.Equals(other._role) &&
                    ((_leader == null && other._leader == null) || (_leader != null && _leader.Equals(other._leader)));
            }
        }

        //TODO: xml doc
        /// <summary>
        /// Marker interface to facilitate subscription of
        /// both [[UnreachableMember]] and [[ReachableMember]].
        /// </summary>
        public interface IReachabilityEvent : IClusterDomainEvent
        {
        }

        public abstract class ReachabilityEvent : IReachabilityEvent
        {
            private readonly Member _member;

            protected ReachabilityEvent(Member member)
            {
                _member = member;
            }

            public Member Member
            {
                get { return _member; }
            }

            public override bool Equals(object obj)
            {
                var other = obj as ReachabilityEvent;
                if (other == null) return false;
                return _member.Equals(other._member);
            }

            public override int GetHashCode()
            {
                unchecked
                {
                    var hash = 17;
                    hash = hash * 23 + _member.GetHashCode();
                    return hash;
                }
            }
        }

        /// <summary>
        /// A member is considered as unreachable by the failure detector.
        /// </summary>
        public sealed class UnreachableMember : ReachabilityEvent
        {
            public UnreachableMember(Member member)
                : base(member)
            {
            }
        }

        //TODO: xml doc
        /// <summary>
        /// A member is considered as reachable by the failure detector
        /// after having been unreachable.
        /// @see [[UnreachableMember]]
        /// </summary>
        public sealed class ReachableMember : ReachabilityEvent
        {
            public ReachableMember(Member member)
                : base(member)
            {
            }
        }

        /// <summary>
        /// Current snapshot of cluster node metrics. Published to subscribers.
        /// </summary>
        public class ClusterMetricsChanged : IClusterDomainEvent
        {
            private readonly ImmutableHashSet<NodeMetrics> _nodeMetrics;

            public ClusterMetricsChanged(ImmutableHashSet<NodeMetrics> nodeMetrics)
            {
                _nodeMetrics = nodeMetrics;
            }

            public ImmutableHashSet<NodeMetrics> NodeMetrics
            {
                get { return _nodeMetrics; }
            }
        }

        /// <summary>
        /// The nodes that have seen current version of the Gossip.
        /// </summary>
        internal sealed class SeenChanged : IClusterDomainEvent
        {
            private readonly bool _convergence;
            private readonly ImmutableHashSet<Address> _seenBy;

            public SeenChanged(bool convergence, ImmutableHashSet<Address> seenBy)
            {
                _convergence = convergence;
                _seenBy = seenBy;
            }

            public bool Convergence
            {
                get { return _convergence; }
            }

            public ImmutableHashSet<Address> SeenBy
            {
                get { return _seenBy; }
            }

            public override bool Equals(object obj)
            {
                var other = obj as SeenChanged;
                if (other == null) return false;
                return _convergence.Equals(other._convergence) && _seenBy.SequenceEqual(other._seenBy);
            }

            //TODO: Override GetHashCode? What to do about collection?
        }

        internal sealed class ReachabilityChanged : IClusterDomainEvent
        {
            private readonly Reachability _reachability;

            public ReachabilityChanged(Reachability reachability)
            {
                _reachability = reachability;
            }

            public Reachability Reachability
            {
                get { return _reachability; }
            }

            public override bool Equals(object obj)
            {
                var other = obj as ReachabilityChanged;
                if (other == null) return false;
                return _reachability.Equals(other._reachability);
            }

            public override int GetHashCode()
            {
                unchecked
                {
                    var hash = 17;
                    hash = hash*23 + _reachability.GetHashCode();
                    return hash;
                }
            }
        }

        internal sealed class CurrentInternalStats : IClusterDomainEvent
        {
            private readonly GossipStats _gossipStats;
            private readonly VectorClockStats _vclockStats;

            public CurrentInternalStats(GossipStats gossipStats, VectorClockStats vclockStats)
            {
                _gossipStats = gossipStats;
                _vclockStats = vclockStats;
            }

            public GossipStats GossipStats
            {
                get { return _gossipStats; }
            }

            public VectorClockStats SeenBy
            {
                get { return _vclockStats; }
            }

            public override int GetHashCode()
            {
                unchecked
                {
                    var hash = 17;
                    hash = hash*23 + _gossipStats.GetHashCode();
                    hash = hash*23 + _vclockStats.GetHashCode();
                    return hash;
                }
            }

            public override bool Equals(object obj)
            {
                var other = obj as CurrentInternalStats;
                if (other == null) return false;
                return _gossipStats.Equals(other._gossipStats) && _vclockStats.Equals(other._vclockStats);
            }
        }

        internal static ImmutableList<UnreachableMember> DiffUnreachable(Gossip oldGossip, Gossip newGossip)
        {
            if (newGossip.Equals(oldGossip)) return ImmutableList.Create<UnreachableMember>();
            var oldUnreachableNodes = oldGossip.Overview.Reachability.AllUnreachableOrTerminated;
            return
                newGossip.Overview.Reachability.AllUnreachableOrTerminated
                    .Where(a => !oldUnreachableNodes.Contains(a))
                    .Select(a => new UnreachableMember(newGossip.GetMember(a)))
                    .ToImmutableList();
        }

        internal static ImmutableList<ReachableMember> DiffReachable(Gossip oldGossip, Gossip newGossip)
        {
            if (newGossip.Equals(oldGossip)) return ImmutableList.Create<ReachableMember>();
            return
                oldGossip.Overview.Reachability.AllUnreachable
                    .Where(a => newGossip.HasMember(a) && newGossip.Overview.Reachability.IsReachable(a))
                    .Select(a => new ReachableMember(newGossip.GetMember(a)))
                    .ToImmutableList();
        }

        internal static ImmutableList<IMemberEvent> DiffMemberEvents(Gossip oldGossip, Gossip newGossip)
        {
            if (newGossip.Equals(oldGossip)) return ImmutableList.Create<IMemberEvent>();
            var newMembers = newGossip.Members.Except(oldGossip.Members);

            var membersGroupedByAddress = newGossip.Members
                .Concat(oldGossip.Members)
                .GroupBy(m => m.UniqueAddress);
            var changedMembers = membersGroupedByAddress
                .Where(g => g.Count() == 2 && g.First().Status != g.Skip(1).First().Status)
                .Select(g => g.First());
            var memberEvents = CollectMemberEvents(newMembers.Union(changedMembers));

            var removedMembers = oldGossip.Members.Except(newGossip.Members);
            var removedEvents = removedMembers.Select(m => new MemberRemoved(m.Copy(status: MemberStatus.Removed), m.Status));

            return memberEvents.Concat(removedEvents).ToImmutableList();
        }

        private static IEnumerable<IMemberEvent> CollectMemberEvents(IEnumerable<Member> members)
        {
            foreach (var member in members)
            {
                if (member.Status == MemberStatus.Up) yield return new MemberUp(member);
                if (member.Status == MemberStatus.Exiting) yield return new MemberExited(member);
            }
        }

        internal static ImmutableList<LeaderChanged> DiffLeader(Gossip oldGossip, Gossip newGossip)
        {
            var newLeader = newGossip.Leader;
            if ((newLeader == null && oldGossip.Leader == null) || newLeader != null && newLeader.Equals(oldGossip.Leader)) return ImmutableList.Create<LeaderChanged>();
            if (newLeader == null) return ImmutableList.Create(new LeaderChanged(null));
            return ImmutableList.Create(new LeaderChanged(newLeader.Address));
        }

        internal static ImmutableHashSet<RoleLeaderChanged> DiffRolesLeader(Gossip oldGossip, Gossip newGossip)
        {
            return InternalDiffRolesLeader(oldGossip, newGossip).ToImmutableHashSet();
        }

        private static IEnumerable<RoleLeaderChanged> InternalDiffRolesLeader(Gossip oldGossip, Gossip newGossip)
        {
            foreach (var role in oldGossip.AllRoles.Union(newGossip.AllRoles))
            {
                var newLeader = newGossip.RoleLeader(role);
                if(newLeader == null && oldGossip.RoleLeader(role) != null)
                    yield return new RoleLeaderChanged(role, null);
                if(newLeader != null && !newLeader.Equals(oldGossip.RoleLeader(role)))
                    yield return new RoleLeaderChanged(role, newLeader.Address);
            }
        }

        internal static ImmutableList<SeenChanged> DiffSeen(Gossip oldGossip, Gossip newGossip)
        {
            if (newGossip.Equals(oldGossip)) return ImmutableList.Create<SeenChanged>();

            var newConvergence = newGossip.Convergence;
            var newSeenBy = newGossip.SeenBy;
            if (newConvergence != oldGossip.Convergence || newSeenBy != oldGossip.SeenBy)
                return ImmutableList.Create(new SeenChanged(newConvergence,
                        newSeenBy.Select(s => s.Address).ToImmutableHashSet()));
            return ImmutableList.Create<SeenChanged>();
        }

        internal static ImmutableList<ReachabilityChanged> DiffReachability(Gossip oldGossip, Gossip newGossip)
        {
            if (newGossip.Overview.Reachability.Equals(oldGossip.Overview.Reachability))
                return ImmutableList.Create<ReachabilityChanged>();

            return ImmutableList.Create(new ReachabilityChanged(newGossip.Overview.Reachability));
        }
    }

    //TODO: IRequiresMessageQueue?
    sealed class ClusterDomainEventPublisher : UntypedActor
    {
        Gossip _latestGossip;

        public ClusterDomainEventPublisher()
        {
            _latestGossip = Gossip.Empty;
            _eventStream = Context.System.EventStream;
        }

        protected override void PreRestart(Exception reason, object message)
        {
            // don't postStop when restarted, no children to stop
        }

        protected override void PostStop()
        {
            // publish the final removed state before shutting down
            PublishChanges(Gossip.Empty);
        }

        protected override void OnReceive(object message)
        {
            if (message is InternalClusterAction.PublishChanges)
            {
                var p = message as InternalClusterAction.PublishChanges;
                PublishChanges(p.NewGossip);
            }
            else if (message is ClusterEvent.CurrentInternalStats)
            {
                var i = message as ClusterEvent.CurrentInternalStats;
                PublishInternalStats(i);
            }
            else if (message is InternalClusterAction.SendCurrentClusterState)
            {
                var sc = message as InternalClusterAction.SendCurrentClusterState;
                SendCurrentClusterState(sc.Receiver);
            }
            else if (message is InternalClusterAction.Subscribe)
            {
                var sub = message as InternalClusterAction.Subscribe;
                Subscribe(sub.Subscriber, sub.InitialStateMode, sub.To);
            }
            else if (message is InternalClusterAction.PublishEvent)
            {
                var pub = message as InternalClusterAction.PublishEvent;
                Publish(pub);
            }
            else if (message is InternalClusterAction.Unsubscribe)
            {
                var unsub = message as InternalClusterAction.Unsubscribe;
                Unsubscribe(unsub.Subscriber, unsub.To);
            }
            else
            {
                Unhandled(message);
            }
        }

        readonly EventStream _eventStream;

        /// <summary>
        /// The current snapshot state corresponding to latest gossip
        /// to mimic what you would have seen if you were listening to the events.
        /// </summary>
        private void SendCurrentClusterState(IActorRef receiver)
        {
            var state = new ClusterEvent.CurrentClusterState(
                _latestGossip.Members,
                _latestGossip.Overview.Reachability.AllUnreachableOrTerminated.Select(_latestGossip.GetMember)
                    .ToImmutableHashSet(),
                _latestGossip.SeenBy.Select(s => s.Address).ToImmutableHashSet(),
                _latestGossip.Leader == null ? null : _latestGossip.Leader.Address,
                _latestGossip.AllRoles.ToImmutableDictionary(r => r, r =>
                {
                    var leader = _latestGossip.RoleLeader(r);
                    return leader == null ? null : leader.Address;
                }));
            receiver.Tell(state);
        }

        private void Subscribe(IActorRef subscriber, ClusterEvent.SubscriptionInitialStateMode initMode,
            IEnumerable<Type> to)
        {
            if (initMode == ClusterEvent.SubscriptionInitialStateMode.InitialStateAsEvents)
            {
                Action<object> pub = @event =>
                {
                    var eventType = @event.GetType();
                    //TODO: IsAssignableFrom same as in scala?
                    if (to.Any(o => o.IsAssignableFrom(eventType)))
                        subscriber.Tell(@event);
                };
                PublishDiff(Gossip.Empty, _latestGossip, pub);
            }
            else if(initMode == ClusterEvent.SubscriptionInitialStateMode.InitialStateAsSnapshot)
            {
                SendCurrentClusterState(subscriber);
            }

            foreach (var t in to) _eventStream.Subscribe(subscriber, t);
        }

        private void Unsubscribe(IActorRef subscriber, Type to)
        {
            if (to == null) _eventStream.Unsubscribe(subscriber);
            else _eventStream.Unsubscribe(subscriber, to);
        }

        private void PublishChanges(Gossip newGossip)
        {
            var oldGossip = _latestGossip;
            _latestGossip = newGossip;
            PublishDiff(oldGossip, newGossip, Publish);
        }

        private void PublishDiff(Gossip oldGossip, Gossip newGossip, Action<object> pub)
        {
            foreach (var @event in ClusterEvent.DiffMemberEvents(oldGossip, newGossip)) pub(@event);
            foreach (var @event in ClusterEvent.DiffUnreachable(oldGossip, newGossip)) pub(@event);
            foreach (var @event in ClusterEvent.DiffReachable(oldGossip, newGossip)) pub(@event);
            foreach (var @event in ClusterEvent.DiffLeader(oldGossip, newGossip)) pub(@event);
            foreach (var @event in ClusterEvent.DiffRolesLeader(oldGossip, newGossip)) pub(@event);
            // publish internal SeenState for testing purposes
            foreach (var @event in ClusterEvent.DiffSeen(oldGossip, newGossip)) pub(@event);
            foreach (var @event in ClusterEvent.DiffReachability(oldGossip, newGossip)) pub(@event);
        }

        private void PublishInternalStats(ClusterEvent.CurrentInternalStats currentStats)
        {
            Publish(currentStats);
        }

        private void Publish(object @event)
        {
            _eventStream.Publish(@event);
        }

        private void ClearState()
        {
            _latestGossip = Gossip.Empty;
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace Revit.SDK.Samples.ImportExport.CS
{
    /// <summary>
    /// Provide a dialog which provides the options for exporting dgn format
    /// </summary>
    public partial class ExportDGNOptionsForm : System.Windows.Forms.Form
    {
        /// <summary>
        /// data class
        /// </summary>
        private ExportDGNData m_data;

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="data">Data class object</param>
        public ExportDGNOptionsForm(ExportDGNData data)
        {
            m_data = data;
            InitializeComponent();
            InitializeControl();
        }

        /// <summary>
        /// Initialize values and status of controls
        /// </summary>
        private void InitializeControl()
        {
            comboBoxLayerSettings.DataSource = m_data.LayerMapping;
            comboBoxLayerSettings.SelectedIndex = 0;
            checkBoxEnableTemplateFile.Checked = false;
            textBoxTemplateFile.Enabled = false;
            buttonBrowserTemplate.Enabled = false;
        }

        /// <summary>
        /// Whether to use dgn template file
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void checkBoxEnableTemplateFile_CheckedChanged(object sender, EventArgs e)
        {
            textBoxTemplateFile.Enabled = checkBoxEnableTemplateFile.Checked;
            buttonBrowserTemplate.Enabled = checkBoxEnableTemplateFile.Checked;
        }

        /// <summary>
        /// Select dgn template
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonBrowserTemplate_Click(object sender, EventArgs e)
        {
            String fileName = String.Empty;

            using (OpenFileDialog openDialog = new OpenFileDialog())
            {
                openDialog.CheckPathExists = true;
                openDialog.DefaultExt = ".dgn";
                openDialog.Title = m_data.Title;
                openDialog.InitialDirectory = m_data.ExportFolder;

                DialogResult result = openDialog.ShowDialog();
                if (result != DialogResult.Cancel)
                {
                    textBoxTemplateFile.Text = openDialog.FileName;
                }
            }
        }

        /// <summary>
        /// OK button click event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonOK_Click(object sender, EventArgs e)
        {
            m_data.ExportLayerMapping =
                m_data.EnumLayerMapping[comboBoxLayerSettings.SelectedIndex];

            if (checkBoxEnableTemplateFile.Checked)
            {
                if (ValidateTemplateFile())
                {
                    this.Close();
                }
            }
            else
            {
                this.Close();
            }
        }

        /// <summary>
        /// Check whether the template file is valid
        /// </summary>
        /// <returns></returns>
        private Boolean ValidateTemplateFile()
        {
            String fileNameFull = textBoxTemplateFile.Text;
            //If the textBoxTemplateFile is empty
            if (String.IsNullOrEmpty(fileNameFull))
            {
                MessageBox.Show("Please specify the template file name!", "Information",
                    MessageBoxButtons.OK, MessageBoxIcon.Information);
                textBoxTemplateFile.Focus();
                return false;
            }

            //Whether the template file exists
            if (!File.Exists(fileNameFull))
            {
                MessageBox.Show("The specified template file does not exist!", "Information",
                    MessageBoxButtons.OK, MessageBoxIcon.Information);
                textBoxTemplateFile.Focus();
                return false;
            }

            m_data.TemplateFile = fileNameFull;
            return true;
        }
    }
}


text:
namespace Renci.SshNet.Messages.Transport
{
    /// <summary>
    /// Represents SSH_MSG_NEWKEYS message.
    /// </summary>
    [Message("SSH_MSG_NEWKEYS", 21)]
    public class NewKeysMessage : Message, IKeyExchangedAllowed
    {
        /// <summary>
        /// Called when type specific data need to be loaded.
        /// </summary>
        protected override void LoadData()
        {
        }

        /// <summary>
        /// Called when type specific data need to be saved.
        /// </summary>
        protected override void SaveData()
        {
        }

        internal override void Process(Session session)
        {
            session.OnNewKeysReceived(this);
        }
    }
}


text:
namespace iox
{
namespace runtime
{
class PoshRuntimeSingleProcess : public PoshRuntimeImpl
{
  public:
    PoshRuntimeSingleProcess(const RuntimeName_t& name) noexcept;
    ~PoshRuntimeSingleProcess();
};
} // namespace runtime
} // namespace iox

#endif


text:
/**
 * Created by Aus on 2017/7/14.
 */
import ListTitle from './components/ListTitle'

export default ListTitle;


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE reference PUBLIC "-//IXIA//DTD IXIA DITA Composite//EN" "../../system/dtd/ixia/IxiaDitabase.dtd">
<reference id="blackberry_pim_contacts_ContactField_type" xml:lang="en-us">
    <title><apiname>type</apiname></title>
    <shortdesc>Specifies the type of ContactField.</shortdesc>
    <refbody>

            <title>Synopsis:</title>

{String}

    </refbody>
</reference>


text:
package com.thoughtworks.go.server.database.migration;

import com.google.gson.Gson;
import org.apache.commons.lang3.StringUtils;

import java.sql.*;

class M001 {
    private static final String ID = "id";
    private static final String SELECTIONS = "selections";
    private static final String TO_BE_EXCLUDED = "isblacklist";
    private static final int SCHEMA = 1;
    private static final Gson GSON = new Gson();

    static Migration convertPipelineSelectionsToFilters() {
        return (cxn) -> {
            if (!required(cxn)) return;

            try (Statement s = cxn.createStatement()) {
                final ResultSet rs = s.executeQuery("SELECT id, selections, isblacklist FROM pipelineselections WHERE version = 0");
                while (rs.next()) {
                    perform(cxn, rs.getLong(ID), rs.getString(SELECTIONS), rs.getBoolean(TO_BE_EXCLUDED));
                }
            }
        };
    }

    static void perform(Connection cxn, long id, String selections, boolean isBlacklist) throws SQLException {
        try (PreparedStatement ps = cxn.prepareStatement("UPDATE pipelineselections SET selections = NULL, version = ?, filters = ? WHERE id = ?")) {
            ps.setInt(1, SCHEMA);
            ps.setString(2, asJson(selections, isBlacklist));
            ps.setLong(3, id);
            ps.executeUpdate();
        }
    }

    static String asJson(String selections, boolean isBlacklist) {
        return GSON.toJson(new FilterSet(selections, isBlacklist));
    }

    static boolean required(Connection cxn) throws SQLException {
        try (Statement s = cxn.createStatement()) {
            try (ResultSet rs = s.executeQuery("SELECT COUNT(*) as remaining FROM PIPELINESELECTIONS WHERE version = 0")) {
                rs.next();
                return rs.getInt("remaining") > 0;
            }
        }
    }

    private static class FilterSet {
        Filter[] filters;

        public FilterSet(String selections, boolean isToBeExcluded) {
            this.filters = new Filter[]{new Filter(selections, isToBeExcluded)};
        }
    }

    private static class Filter {
        String name;
        String type;
        String[] pipelines;

        public Filter(String selections, boolean isToBeExcluded) {
            name = "Default";
            pipelines = StringUtils.isBlank(selections) ? new String[]{} : StringUtils.split(selections, ",");
            type = isToBeExcluded ? "blacklist" : "whitelist";
        }
    }
}


text:
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>FormField Demo Page</title>
  <script src="../../dist/main.js"></script>
  <link href="../../dist/main.css" rel="stylesheet" />
</head>
<body>
<script type="text/javascript">
  window.onload = function() {
    var field = new tnt.FormField({ label: '姓名', hintMessage: '给我一个Hint', hintType: 'error' });

    field.render(document.body);
  };
</script>
</body>
</html>


text:
ifndef BUILD_ROOT
$(error Variable BUILD_ROOT was not defined.)
endif

ifndef ENV_ROOT
$(error Variable ENV_ROOT was not defined.)
endif

################################################################################
# Sanity check since and SRP environment is quite different.
################################################################################
ifndef SRP
$(error SRP not defined for SRP environment)
endif

################################################################################
# Setup any build related flags, such as CC, AS, LDFLAGS, CFLAGS etc.
################################################################################

CC		:= gcc
CFLAGS	:= -DENV_POSIX_SRP=1 -Wall -O2 -I$(ENV_ROOT) $(CFLAGS)
LDFLAGS	:= -lpthread -lrt $(LDFLAGS)

################################################################################
# Setup the rules for building the required object files from the source.
################################################################################

$(BUILD_ROOT)/env.o: $(ENV_ROOT)/$(ENV)/env.c
	$(CC) $(CFLAGS) $< -c -o $@

################################################################################
# Setup the required objects for the enviroment sources.
################################################################################

ENV_OBJECTS := $(BUILD_ROOT)/env.o


text:
package ru.job4j.max;

import org.junit.Test;

import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;

/**
 * JUnit Тест нахождения максимума.
 * @author Nickolai Matveev.
 * @since 25.09.2017
 * @version 0.1
 */
public class MaxTest {

	/**
	* Тестирование поиска максимума, где second больше first.
	*/
	@Test
	public void whenFirstLessSecond() {
		Max maximum = new Max();
		int result = maximum.max(1, 2);
		assertThat(result, is(2));
	}

	/**
	* Тестирование поиска максимума из трех.
	*/
	@Test
	public void whenSecondIsBigger() {
		Max maximum = new Max();
		int result = maximum.max(5, 8, 2);
		assertThat(result, is(8));
	}

	/**
	* Тестирование поиска максимума из трех.
	*/
	@Test
	public void whenFirstIsBigger() {
		Max maximum = new Max();
		int result = maximum.max(10, 1, 4);
		assertThat(result, is(10));
	}

	/**
	* Тестирование поиска максимума из трех.
	*/
	@Test
	public void whenThirdIsBigger() {
		Max maximum = new Max();
		int result = maximum.max(1, 4, 28);
		assertThat(result, is(28));
	}

}


text:
<?php
require_once('xml_functions.php');

class BobCat_Embed
{

	private $config_file = "config/settings.xml";
	private $metalib_url = null;
	private $metalib_user = null;
	private $metalib_pass = null;
	private $metalib_inst = null;

	protected $config_xml = null;
	protected $page_xml = null;
	protected $base_url = null;
	protected $primo_search_url = null;
	protected $primo_dlsearch_url = null;
	protected $primo_nui_search_url = null;
	protected $xerxes_search_url = null;
	protected $umlaut_search_url = null;

  /**
   * Turn the page into an XML document based on the config
   * settings so it can be translated by XSLT
   */
	public function __construct() {

    // Find environment specific settings file, if config/settings is not present
    if (isset($_SERVER['PHP_ENV']) && file_exists("config/settings." . $_SERVER['PHP_ENV'] . ".xml")) {
      $this->config_file = "config/settings." . $_SERVER['PHP_ENV'] . ".xml";
	  } elseif (!file_exists($this->config_file)) {
	    $this->config_file = "settings.local.xml";
	  }

		//Retrieve config file and validate that it is in the proper format
		if ( ! $this->config_xml instanceof SimpleXMLElement ) {
			try {
				if ( file_exists($this->config_file) ) {
					$this->config_xml = simplexml_load_file($this->config_file);
				} else {
					throw new Exception("__construct: could not find configuration file");
				}
			} catch (Exception $e) {
				print "Error: " . $e->getMessage();
				exit ;
			}
		}

		//Initialize private vars
		$this->metalib_url = $this->getConfigOption('metalib_url');
		$this->metalib_user = $this->getConfigOption('metalib_user');
		$this->metalib_pass = $this->getConfigOption('metalib_pass');
		$this->metalib_inst = $this->getConfigOption('metalib_inst');

		//Initialize this page's XML
		$this->page_xml = new SimpleXMLElement("<bobcat_embed />");

		//Add all config variables
		$this->page_xml->addChild('config','');
		if (count($this->config_xml->xpath("//config[not(@pass) or @pass='true']")) > 0) {
			foreach ($this->config_xml->xpath("//config[not(@pass) or @pass='true']") as $config) {
				$this->page_xml->config->addChild($this->getAttributeValue($config, "name"), $config);
			}
		}

		//Populate additional global vars for sub class use
		$this->primo_search_url = $this->getConfigOption('primo_search_url');
		$this->primo_dlsearch_url = $this->getConfigOption('primo_dlsearch_url');
		$this->primo_nui_search_url = $this->getConfigOption('primo_nui_search_url');
		$this->xerxes_search_url = $this->getConfigOption('xerxes_search_url');
		$this->umlaut_search_url = $this->getConfigOption('umlaut_search_url');
		$this->libguides_search_url = $this->getConfigOption('libguides_search_url');

		$this->page_xml->config->addChild("base_url", $this->getServerName() . "/bobcat");

		//$this->page_xml->addChild('metalib_config','');
		//$this->page_xml->metalib_config->addChild('session_id',$this->retrieveMetaLibSessionId());

		//Add query string options to XML
		$this->page_xml->addChild('request','');
		$this->page_xml->request->addChild('unique_key',$this->getUniqueKey(10));

    if (isset($_SERVER["QUERY_STRING"])) {
  		$request_params = explode('&',$_SERVER["QUERY_STRING"]);
  		if (count($request_params) > 0) {
  			$this->page_xml->request->addChild('querystring', urlencode($_SERVER["QUERY_STRING"]));
  			foreach ($request_params as $p) {
  				if ($p != "") {
  				$p_parts = explode('=',$p);
  				$this->page_xml->request->addChild($p_parts[0],$p_parts[1]);
  				}
  			}
  		}
	  }

	}

	/**
	 * getConfigOption: retrieve config option value from config file
	 *
	 * @param $option			[string] containing the title of the value to retrieve form the config file
	 * @return 					[string] containing the value of $option
	 */
	protected function getConfigOption($option) {
		try {
			$option_container = $this->config_xml->xpath("//config[@name='".$option."']");
			if ($option_container[0] instanceof SimpleXMLElement) {
			 	return $option_container[0][0];
			} else {
				throw new Exception("getConfigOption: could not retrieve config option");
			}
		} catch (Exception $e) {
			print "Error: " . $e->getMessage();
			exit ;
		}
	}

	/**
	 * getAttributeValue retrieve attribute value from config file
	 *
	 * @param $el				[string] SimplXMLElement with the attribute
	 * @param $attr			[string] Attribute to extract
	 * @return 					[string] containing the value of $option
	 */
	protected function getAttributeValue($el, $attr) {
		try {
			if ($el instanceof SimpleXMLElement) {
				foreach($el->attributes() as $a => $b) {
					if ($a == $attr)
						return $b;
				}
			 	return null;
			} else {
				throw new Exception("getAttributeValue: element is not SimpleXMLElement");
			}
		} catch (Exception $e) {
			print "Error: " . $e->getMessage();
			exit ;
		}
	}

	/**
	 * getViews: retrieve an object containing all the views specified in the config file
	 *
	 * @return 			[SimpleXMLElement] object containing objects of views
	 */
	protected function getViews() {
		try {
			if (isset($_REQUEST['action']) && $_REQUEST['action'] == "embed" && isset($_REQUEST['disp_select_view'])) {
				$views_container = $this->config_xml->xpath("//views/view[@id='".$_REQUEST['disp_select_view']."']");
			} else {
				$views_container = $this->config_xml->xpath("//views");
			}
			if ($views_container[0] instanceof SimpleXMLElement) {
			 	return $views_container;
			} else {
				throw new Exception("getViews: could not retrieve view information");
			}
		} catch (Exception $e) {
			print "Error: " . $e->getMessage();
			exit ;
		}
	}

	/**
	 * retrieveMetaLibSessionId: retrieve a MetaLib session ID for making other x-service calls
	 *
	 * @return 			[string] containing session ID
	 */
	private function retrieveMetaLibSessionId() {
		try {
			//Retrieve ML session id
			$ml_auth = simplexml_load_string(getXML($this->metalib_url."/X?op=login_request&user_name=".$this->metalib_user."&user_password=".$this->metalib_pass));
			$ml_auth_path = $ml_auth->xpath("//session_id");

			if ($ml_auth_path[0] instanceof SimpleXMLElement) {
			 	return $ml_auth_path[0][0];
			} else {
				throw new Exception("retrieveMetaLibSessionId: could not retrieve metalib session");
			}
		} catch (Exception $e) {
			print "Error: " . $e->getMessage();
			exit ;
		}
	}

	/**
	 * retrieveMetaLibQuickSets: retrieve an object with all the PRIMO user quicksets from MetaLib
	 *
	 * @return 			[SimpleXMLElement] object containing all PRIMO user quicksets
	 */
	private function retrieveMetaLibQuickSets() {
		//Retrieve MLQuickSets
		$ml_qs = simplexml_load_string(getXML("$this->metalib_url/X?op=retrieve_quick_sets_request&verification=$this->metalib_pass&source_id=$this->metalib_user&institute=$this->metalib_inst&session_id=".$this->page_xml->metalib_config->session_id));
		$ml_qs_path = $ml_qs->xpath("//retrieve_quick_sets_response");
		return $ml_qs_path;
	}

	/**
	 * populateViews: generate an XML subtree for each view in the config table
	 */
	protected function populateViews() {
		//load up subtree of views from config file
		$views = $this->getViews();

		// Create new DOMElements from the two SimpleXMLElements
		$dom_master = dom_import_simplexml($this->page_xml);
		$dom_sub  = dom_import_simplexml($views[0]);

		// Import the views into the page xml document
		$dom_sub  = $dom_master->ownerDocument->importNode($dom_sub, TRUE);

		// Append the view tree to page xml in the dictionary
		$dom_master->appendChild($dom_sub);
	}

	/**
	 * getUniqueKey: generate a unique key of size $length
	 */
  private function getUniqueKey($length = 0) {
    $code = md5(uniqid(rand(), true));
    if ($length > 0) return substr($code, 0, $length);
    else return $code;
  }

  /**
   * getServerName: Retrieve and format server name
  */
  protected function getServerName() {
    # Get server name for generating embed urls
		if (isset($_SERVER["SERVER_NAME"])) {
		  $server_name = (preg_match("/^http(s)?:\/\//i", $_SERVER["SERVER_NAME"])) ? $_SERVER["SERVER_NAME"] : "https://".$_SERVER["SERVER_NAME"];
	  } elseif (isset($_SERVER["ServerName"])) {
	    $server_name = (preg_match("/^http(s)?:\/\//i", $_SERVER["ServerName"])) ? $_SERVER["ServerName"] : "https://".$_SERVER["ServerName"];
	  } else {
	    $server_name = "";
	  }
	  return $server_name;
  }

}


text:
<!DOCTYPE html>

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

    <link rel="icon" type="image/png" href="https://just2us.com/img/favicon-180.png" />
    <link rel="apple-touch-icon" href="https://just2us.com/img/favicon-192.png"/>

    <link rel="stylesheet" href="/css/bootstrap.min.css">
    <link rel="stylesheet" href="/css/clean-blog.min.css">
    <link rel="stylesheet" href="/css/syntax.css">

    <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href='https://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic&display=swap' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800&display=swap' rel='stylesheet' type='text/css'>

    <link type="application/atom+xml" rel="alternate" href="https://just2me.com/feed.xml" title="Just2me" />

<title>Page 20 of 22 for Just2me | Personal blog on anything Singapore and my life</title>
<meta name="generator" content="Jekyll v4.0.0" />
<meta property="og:title" content="Just2me" />
<meta property="og:locale" content="en_US" />
<meta name="description" content="¯_(ツ)_/¯" />
<meta property="og:description" content="¯_(ツ)_/¯" />
<link rel="canonical" href="https://just2me.com/page20/" />
<meta property="og:url" content="https://just2me.com/page20/" />
<meta property="og:site_name" content="Just2me" />
<meta property="og:image" content="https://just2me.com/img/jewel-fountain.jpeg" />
<link rel="prev" href="https://just2me.com/page19" />
<link rel="next" href="https://just2me.com/page21" />
<meta name="twitter:card" content="summary" />
<meta property="twitter:image" content="https://just2me.com/img/jewel-fountain.jpeg" />
<meta property="twitter:title" content="Just2me" />
<meta name="twitter:site" content="@samwize" />
<meta name="twitter:creator" content="@samwize" />
<meta property="fb:admins" content="704185456" />

            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                Toggle navigation

            </button>
            Just2me

                  Stories

                  Apps

                  Quotes

                  About

                    ¯\_(ツ)_/¯

          Mobile Web Site

          Mobile web site development. Some call it WAP development. In mobile devices, there are many different markup languages: XHTML MP (WAP 2.x), CHTML, WML...

Published on December 26, 2007

          just2me.com, a  Christmas present for myself

          Its Christmas season once again, a period of giving and receiving gifts! I agree, but I hate to buy gifts as it is so...

Published on December 25, 2007

          Navteq Map Data

          Mobile is about mobility. Mobility is about location, and it can't do without good maps. The giant in the map data of the world...

Published on December 23, 2007

          Python on S60

          Python is an interpreted , object oriented, and has remarkable power with clear syntax. It claims to be a programming language on the rise....

Published on December 22, 2007

          Web Development Framework - SEAM

          For those who are interested in picking up an enterprise web development framework, you may want to try JBoss Seam. It is a fairly...

Published on December 17, 2007

          Gundam stop motion video

          My first stop motion video with my Gundam toy model..

And it won me a Panasonic laptop, courtesy of PlayNetEarth :)

Published on December 14, 2007

          Tomcat Apache 5.5

          Some technicalities about Tomcat. You can unrar a war file in an external hard disk, and have Tomcat point to it. The simpler way...

Published on December 13, 2007

          Code Versioning with SVN

          SVN is a code versioning tool, which has being gaining popularity over the more well known CVS. Some SVN commands for server To run...

Published on December 12, 2007

          Porting to different platforms

          Mobile fragmentation has led to difficulties when it comes to porting an application across platforms. We are not talking about 3 or 5 platforms,...

Published on December 11, 2007

          Symbian Signing

          Symbian signing is pretty smooth and fast. This post explain on the full process of getting a TrustCenter publisher ID, signing a developer's version...

Published on December 11, 2007

          Location Based Service (LBS)

          Location Based Service could be next big thing for mobile application. There are 2 ways to localize your phone: GPS - Requires special hardware...

Published on November 30, 2007

          Random Exploration/Ideas

Some random stuff that could be worth exploring:

  Barcode Reader: ZXing (Opensource, Andriod), popular Kaywa Reader in Japan
  More to come…

Published on November 30, 2007

          Mobile Statistics

          Statistics on the surfing: Admob Metric - most used phone models on WAP Bango Live - Live mobile usage Symbian 2007 Roundup Report -...

Published on November 22, 2007

          Random Resources

          Randomly Numbering Plan - About your phone number Sprint Developer Guide - Sprint, a telco operator, has its own developer APIs for J2ME too!...

Published on November 19, 2007

          'Secret' Codes for Nokia phones

          Tips to check some (secret) information and unlocking on your phones. Works for Nokia phones only. Press the numbers as if you are dialing....

Published on November 15, 2007

          Developer Libraries

          Popular libraries used by developers: log4j - Logger, needy tool for debugging. Tip: Put the configuration file "log4j.properties" in /Tomcat 5.5/common/classes/ to be shared...

Published on November 15, 2007

          GPRS Configuration Settings

          Setting up GPRS for a phone is always a problem for mobile. This problem is usually diverted to mobile developer when an application does...

Published on November 13, 2007

          News Video Summarization - my HYP

          My HYP - Honours Year Project - is to do a news video summarization system. A typical scenario is a user searching for a...

Published on November 11, 2007

          Developing WAP/XHTML MP (mobile web pages)

          Good Guides: Developers Home Steps to Getting Started: Install a WAP server - Tomcat Apache Configure MIME Types for WAP server Install a WAP...

Published on November 6, 2007

          Symbian Development

          This development guide is geared towards Symbian S60 3rd Ed, but it would be similar for others like UIQ or MOAP. Components to install...

Published on October 28, 2007

        ← Older Posts

      Page 20 of 22

        Newer Posts →

Copyright © Junda Ong 1983-2021


text:
<!-- Copyright (c) Microsoft. All rights reserved. --><!-- Licensed under the MIT license. See LICENSE file in the project root for full license information. --><project>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>iothub-java-client</artifactId>
    <name>IoT Hub Java Client</name>
    <description>The Microsoft Azure IoT Device SDK for Java</description>
    <developers>
        <developer>
            <id>microsoft</id>
            <name>Microsoft</name>
        </developer>
    </developers>
    <parent>
        <groupId>com.microsoft.azure.iothub-java-client</groupId>
        <artifactId>iothub-java-client-with-samples</artifactId>
        <version>1.0.14</version>
    </parent>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <skipITs>true</skipITs>
    </properties>
    <dependencies>
        <dependency>
            <groupId>com.microsoft.azure.iot</groupId>
            <artifactId>proton-j-azure-iot-dev</artifactId>
            <version>0.12.3</version>
            <type>jar</type>
        </dependency>
        <dependency>
            <groupId>org.bouncycastle</groupId>
            <artifactId>bcpkix-jdk15on</artifactId>
            <version>1.47</version>
        </dependency>
        <dependency>
            <groupId>org.eclipse.paho</groupId>
            <artifactId>org.eclipse.paho.client.mqttv3</artifactId>
            <version>1.0.2</version>
        </dependency>
        <!-- test dependencies -->
        <dependency>
            <groupId>org.jmockit</groupId>
            <artifactId>jmockit</artifactId>
            <version>1.22</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit-dep</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.hamcrest</groupId>
            <artifactId>hamcrest-all</artifactId>
            <version>1.3</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.microsoft.azure.iothub-java-client</groupId>
            <artifactId>iothub-java-service-client</artifactId>
            <version>1.0.4</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.10</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.19.1</version>
                <configuration>
                    <forkCount>1</forkCount>
                    <reuseForks>true</reuseForks>
                    <argLine>
                        -javaagent:${settings.localRepository}/org/jmockit/jmockit/1.22/jmockit-1.22.jar
                    </argLine>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-failsafe-plugin</artifactId>
                <version>2.19.1</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>integration-test</goal>
                            <goal>verify</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <forkCount>1</forkCount>
                    <reuseForks>true</reuseForks>
                    <skipITs>${skipITs}</skipITs>
                    <argLine>
                        -javaagent:${settings.localRepository}/org/jmockit/jmockit/1.22/jmockit-1.22.jar
                    </argLine>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-shade-plugin</artifactId>
                <version>2.4</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <shadedArtifactAttached>true</shadedArtifactAttached>
                            <shadedClassifierName>with-deps</shadedClassifierName>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>