text:
#ifdef WIN32
#define WIN32_LEAN_AND_MEAN
#define PSAPI_VERSION 1
#include <windows.h>
#include <psapi.h>
#include <Ws2tcpip.h>
#endif

#define APR_WANT_STRFUNC
#include <apr_want.h>

#include <apr_lib.h>
#include <apr_pools.h>
#include <apr_file_info.h>
#include <apr_signal.h>
#include <apr_strings.h>
#include <apr_thread_proc.h>
#include <apr_version.h>
#include <apu_version.h>

#include "svn_pools.h"
#include "svn_ctype.h"
#include "svn_dirent_uri.h"
#include "svn_error.h"
#include "svn_io.h"
#include "svn_string.h"
#include "svn_utf.h"
#include "svn_version.h"

#include "private/svn_sqlite.h"

#include "sysinfo.h"
#include "svn_private_config.h"

#if HAVE_SYS_UTSNAME_H
#include <sys/utsname.h>
#endif

#ifdef SVN_HAVE_MACOS_PLIST
#include <CoreFoundation/CoreFoundation.h>
#endif

#ifdef SVN_HAVE_MACHO_ITERATE
#include <mach-o/dyld.h>
#include <mach-o/loader.h>
#endif

#if HAVE_UNAME
static const char *canonical_host_from_uname(apr_pool_t *pool);
# ifndef SVN_HAVE_MACOS_PLIST
static const char *release_name_from_uname(apr_pool_t *pool);
# endif
#endif

#ifdef WIN32
static const char *win32_canonical_host(apr_pool_t *pool);
static const char *win32_release_name(apr_pool_t *pool);
static const apr_array_header_t *win32_shared_libs(apr_pool_t *pool);
#endif /* WIN32 */

#ifdef SVN_HAVE_MACOS_PLIST
static const char *macos_release_name(apr_pool_t *pool);
#endif

#ifdef SVN_HAVE_MACHO_ITERATE
static const apr_array_header_t *macos_shared_libs(apr_pool_t *pool);
#endif

#if __linux__
static const char *linux_release_name(apr_pool_t *pool);
#endif

const char *
svn_sysinfo__canonical_host(apr_pool_t *pool)
{
#ifdef WIN32
  return win32_canonical_host(pool);
#elif HAVE_UNAME
  return canonical_host_from_uname(pool);
#else
  return "unknown-unknown-unknown";
#endif
}

const char *
svn_sysinfo__release_name(apr_pool_t *pool)
{
#ifdef WIN32
  return win32_release_name(pool);
#elif defined(SVN_HAVE_MACOS_PLIST)
  return macos_release_name(pool);
#elif __linux__
  return linux_release_name(pool);
#elif HAVE_UNAME
  return release_name_from_uname(pool);
#else
  return NULL;
#endif
}

const apr_array_header_t *
svn_sysinfo__linked_libs(apr_pool_t *pool)
{
  svn_version_ext_linked_lib_t *lib;
  apr_array_header_t *array = apr_array_make(pool, 3, sizeof(*lib));

  lib = &APR_ARRAY_PUSH(array, svn_version_ext_linked_lib_t);
  lib->name = "APR";
  lib->compiled_version = APR_VERSION_STRING;
  lib->runtime_version = apr_pstrdup(pool, apr_version_string());

/* Don't list APR-Util if it isn't linked in, which it may not be if
 * we're using APR 2.x+ which combined APR-Util into APR. */
#ifdef APU_VERSION_STRING
  lib = &APR_ARRAY_PUSH(array, svn_version_ext_linked_lib_t);
  lib->name = "APR-Util";
  lib->compiled_version = APU_VERSION_STRING;
  lib->runtime_version = apr_pstrdup(pool, apu_version_string());
#endif

  lib = &APR_ARRAY_PUSH(array, svn_version_ext_linked_lib_t);
  lib->name = "SQLite";
  lib->compiled_version = apr_pstrdup(pool, svn_sqlite__compiled_version());
#ifdef SVN_SQLITE_INLINE
  lib->runtime_version = NULL;
#else
  lib->runtime_version = apr_pstrdup(pool, svn_sqlite__runtime_version());
#endif

  return array;
}

const apr_array_header_t *
svn_sysinfo__loaded_libs(apr_pool_t *pool)
{
#ifdef WIN32
  return win32_shared_libs(pool);
#elif defined(SVN_HAVE_MACHO_ITERATE)
  return macos_shared_libs(pool);
#else
  return NULL;
#endif
}

#if HAVE_UNAME
static const char*
canonical_host_from_uname(apr_pool_t *pool)
{
  const char *machine = "unknown";
  const char *vendor = "unknown";
  const char *sysname = "unknown";
  const char *sysver = "";
  struct utsname info;

  if (0 <= uname(&info))
    {
      svn_error_t *err;
      const char *tmp;

      err = svn_utf_cstring_to_utf8(&tmp, info.machine, pool);
      if (err)
        svn_error_clear(err);
      else
        machine = tmp;

      err = svn_utf_cstring_to_utf8(&tmp, info.sysname, pool);
      if (err)
        svn_error_clear(err);
      else
        {
          char *lwr = apr_pstrdup(pool, tmp);
          char *it = lwr;
          while (*it)
            {
              if (svn_ctype_isupper(*it))
                *it = apr_tolower(*it);
              ++it;
            }
          sysname = lwr;
        }

      if (0 == strcmp(sysname, "darwin"))
        vendor = "apple";
      if (0 == strcmp(sysname, "linux"))
        sysver = "-gnu";
      else
        {
          err = svn_utf_cstring_to_utf8(&tmp, info.release, pool);
          if (err)
            svn_error_clear(err);
          else
            {
              apr_size_t n = strspn(tmp, ".0123456789");
              if (n > 0)
                {
                  char *ver = apr_pstrdup(pool, tmp);
                  ver[n] = 0;
                  sysver = ver;
                }
              else
                sysver = tmp;
            }
        }
    }

  return apr_psprintf(pool, "%s-%s-%s%s", machine, vendor, sysname, sysver);
}

# ifndef SVN_HAVE_MACOS_PLIST
/* Generate a release name from the uname(3) info, effectively
   returning "`uname -s` `uname -r`". */
static const char *
release_name_from_uname(apr_pool_t *pool)
{
  struct utsname info;
  if (0 <= uname(&info))
    {
      svn_error_t *err;
      const char *sysname;
      const char *sysver;

      err = svn_utf_cstring_to_utf8(&sysname, info.sysname, pool);
      if (err)
        {
          sysname = NULL;
          svn_error_clear(err);
        }

      err = svn_utf_cstring_to_utf8(&sysver, info.release, pool);
      if (err)
        {
          sysver = NULL;
          svn_error_clear(err);
        }

      if (sysname || sysver)
        {
          return apr_psprintf(pool, "%s%s%s",
                              (sysname ? sysname : ""),
                              (sysver ? (sysname ? " " : "") : ""),
                              (sysver ? sysver : ""));
        }
    }
  return NULL;
}
# endif  /* !SVN_HAVE_MACOS_PLIST */
#endif  /* HAVE_UNAME */

#if __linux__
/* Split a stringbuf into a key/value pair.
   Return the key, leaving the striped value in the stringbuf. */
static const char *
stringbuf_split_key(svn_stringbuf_t *buffer, char delim)
{
  char *key;
  char *end;

  end = strchr(buffer->data, delim);
  if (!end)
    return NULL;

  svn_stringbuf_strip_whitespace(buffer);

  /* Now we split the currently allocated buffer in two parts:
      - a const char * HEAD
      - the remaining stringbuf_t. */

  /* Create HEAD as '\0' terminated const char * */
  key = buffer->data;
  end = strchr(key, delim);
  *end = '\0';

  /* And update the TAIL to be a smaller, but still valid stringbuf */
  buffer->data = end + 1;
  buffer->len -= 1 + end - key;
  buffer->blocksize -= 1 + end - key;

  svn_stringbuf_strip_whitespace(buffer);

  return key;
}

/* Parse `/usr/bin/lsb_rlease --all` */
static const char *
lsb_release(apr_pool_t *pool)
{
  static const char *const args[3] =
    {
      "/usr/bin/lsb_release",
      "--all",
      NULL
    };

  const char *distributor = NULL;
  const char *description = NULL;
  const char *release = NULL;
  const char *codename = NULL;

  apr_proc_t lsbproc;
  svn_stream_t *lsbinfo;
  svn_error_t *err;

  /* Run /usr/bin/lsb_release --all < /dev/null 2>/dev/null */
  {
    apr_file_t *stdin_handle;
    apr_file_t *stdout_handle;

    err = svn_io_file_open(&stdin_handle, SVN_NULL_DEVICE_NAME,
                           APR_READ, APR_OS_DEFAULT, pool);
    if (!err)
      err = svn_io_file_open(&stdout_handle, SVN_NULL_DEVICE_NAME,
                             APR_WRITE, APR_OS_DEFAULT, pool);
    if (!err)
      err = svn_io_start_cmd3(&lsbproc, NULL, args[0], args, NULL, FALSE,
                              FALSE, stdin_handle,
                              TRUE, NULL,
                              FALSE, stdout_handle,
                              pool);
    if (err)
      {
        svn_error_clear(err);
        return NULL;
      }
  }

  /* Parse the output and try to populate the  */
  lsbinfo = svn_stream_from_aprfile2(lsbproc.out, TRUE, pool);
  if (lsbinfo)
    {
      for (;;)
        {
          svn_boolean_t eof = FALSE;
          svn_stringbuf_t *line;
          const char *key;

          err = svn_stream_readline(lsbinfo, &line, "\n", &eof, pool);
          if (err || eof)
            break;

          key = stringbuf_split_key(line, ':');
          if (!key)
            continue;

          if (0 == svn_cstring_casecmp(key, "Distributor ID"))
            distributor = line->data;
          else if (0 == svn_cstring_casecmp(key, "Description"))
            description = line->data;
          else if (0 == svn_cstring_casecmp(key, "Release"))
            release = line->data;
          else if (0 == svn_cstring_casecmp(key, "Codename"))
            codename = line->data;
        }
      err = svn_error_compose_create(err,
                                     svn_stream_close(lsbinfo));
      if (err)
        {
          svn_error_clear(err);
          apr_proc_kill(&lsbproc, SIGKILL);
          return NULL;
        }
    }

  /* Reap the child process */
  err = svn_io_wait_for_cmd(&lsbproc, "", NULL, NULL, pool);
  if (err)
    {
      svn_error_clear(err);
      return NULL;
    }

  if (description)
    return apr_psprintf(pool, "%s%s%s%s", description,
                        (codename ? " (" : ""),
                        (codename ? codename : ""),
                        (codename ? ")" : ""));
  if (distributor)
    return apr_psprintf(pool, "%s%s%s%s%s%s", distributor,
                        (release ? " " : ""),
                        (release ? release : ""),
                        (codename ? " (" : ""),
                        (codename ? codename : ""),
                        (codename ? ")" : ""));

  return NULL;
}

/* Read the whole contents of a file. */
static svn_stringbuf_t *
read_file_contents(const char *filename, apr_pool_t *pool)
{
  svn_error_t *err;
  svn_stringbuf_t *buffer;

  err = svn_stringbuf_from_file2(&buffer, filename, pool);
  if (err)
    {
      svn_error_clear(err);
      return NULL;
    }

  return buffer;
}

/* Strip everything but the first line from a stringbuf. */
static void
stringbuf_first_line_only(svn_stringbuf_t *buffer)
{
  char *eol = strchr(buffer->data, '\n');
  if (eol)
    {
      *eol = '\0';
      buffer->len = 1 + eol - buffer->data;
    }
  svn_stringbuf_strip_whitespace(buffer);
}

/* Look at /etc/redhat_release to detect RHEL/Fedora/CentOS. */
static const char *
redhat_release(apr_pool_t *pool)
{
  svn_stringbuf_t *buffer = read_file_contents("/etc/redhat-release", pool);
  if (buffer)
    {
      stringbuf_first_line_only(buffer);
      return buffer->data;
    }
  return NULL;
}

/* Look at /etc/SuSE-release to detect non-LSB SuSE. */
static const char *
suse_release(apr_pool_t *pool)
{
  const char *release = NULL;
  const char *codename = NULL;

  svn_stringbuf_t *buffer = read_file_contents("/etc/SuSE-release", pool);
  svn_stringbuf_t *line;
  svn_stream_t *stream;
  svn_boolean_t eof;
  svn_error_t *err;
  if (!buffer)
      return NULL;

  stream = svn_stream_from_stringbuf(buffer, pool);
  err = svn_stream_readline(stream, &line, "\n", &eof, pool);
  if (err || eof)
    {
      svn_error_clear(err);
      return NULL;
    }

  svn_stringbuf_strip_whitespace(line);
  release = line->data;

  for (;;)
    {
      const char *key;

      err = svn_stream_readline(stream, &line, "\n", &eof, pool);
      if (err || eof)
        {
          svn_error_clear(err);
          break;
        }

      key = stringbuf_split_key(line, '=');
      if (!key)
        continue;

      if (0 == strncmp(key, "CODENAME", 8))
        codename = line->data;
    }

  return apr_psprintf(pool, "%s%s%s%s",
                      release,
                      (codename ? " (" : ""),
                      (codename ? codename : ""),
                      (codename ? ")" : ""));
}

/* Look at /etc/debian_version to detect non-LSB Debian. */
static const char *
debian_release(apr_pool_t *pool)
{
  svn_stringbuf_t *buffer = read_file_contents("/etc/debian_version", pool);
  if (!buffer)
      return NULL;

  stringbuf_first_line_only(buffer);
  return apr_pstrcat(pool, "Debian ", buffer->data, NULL);
}

/* Try to find the Linux distribution name, or return info from uname. */
static const char *
linux_release_name(apr_pool_t *pool)
{
  const char *uname_release = release_name_from_uname(pool);

  /* Try anything that has /usr/bin/lsb_release.
     Covers, for example, Debian, Ubuntu and SuSE.  */
  const char *release_name = lsb_release(pool);

  /* Try RHEL/Fedora/CentOS */
  if (!release_name)
    release_name = redhat_release(pool);

  /* Try Non-LSB SuSE */
  if (!release_name)
    release_name = suse_release(pool);

  /* Try non-LSB Debian */
  if (!release_name)
    release_name = debian_release(pool);

  if (!release_name)
    return uname_release;

  if (!uname_release)
    return release_name;

  return apr_psprintf(pool, "%s [%s]", release_name, uname_release);
}
#endif /* __linux__ */

#ifdef WIN32
typedef DWORD (WINAPI *FNGETNATIVESYSTEMINFO)(LPSYSTEM_INFO);
typedef BOOL (WINAPI *FNENUMPROCESSMODULES) (HANDLE, HMODULE*, DWORD, LPDWORD);

/* Get system and version info, and try to tell the difference
   between the native system type and the runtime environment of the
   current process. Populate results in SYSINFO, LOCAL_SYSINFO
   (optional) and OSINFO. */
static BOOL
system_info(SYSTEM_INFO *sysinfo,
            SYSTEM_INFO *local_sysinfo,
            OSVERSIONINFOEXW *osinfo)
{
  FNGETNATIVESYSTEMINFO GetNativeSystemInfo_ = (FNGETNATIVESYSTEMINFO)
    GetProcAddress(GetModuleHandleA("kernel32.dll"), "GetNativeSystemInfo");

  ZeroMemory(sysinfo, sizeof *sysinfo);
  if (local_sysinfo)
    {
      ZeroMemory(local_sysinfo, sizeof *local_sysinfo);
      GetSystemInfo(local_sysinfo);
      if (GetNativeSystemInfo_)
        GetNativeSystemInfo_(sysinfo);
      else
        memcpy(sysinfo, local_sysinfo, sizeof *sysinfo);
    }
  else
    GetSystemInfo(sysinfo);

  ZeroMemory(osinfo, sizeof *osinfo);
  osinfo->dwOSVersionInfoSize = sizeof *osinfo;
  if (!GetVersionExW((LPVOID)osinfo))
    return FALSE;

  return TRUE;
}

/* Map the proccessor type from SYSINFO to a string. */
static const char *
processor_name(SYSTEM_INFO *sysinfo)
{
  switch (sysinfo->wProcessorArchitecture)
    {
    case PROCESSOR_ARCHITECTURE_AMD64:         return "x86_64";
    case PROCESSOR_ARCHITECTURE_IA64:          return "ia64";
    case PROCESSOR_ARCHITECTURE_INTEL:         return "x86";
    case PROCESSOR_ARCHITECTURE_MIPS:          return "mips";
    case PROCESSOR_ARCHITECTURE_ALPHA:         return "alpha32";
    case PROCESSOR_ARCHITECTURE_PPC:           return "powerpc";
    case PROCESSOR_ARCHITECTURE_SHX:           return "shx";
    case PROCESSOR_ARCHITECTURE_ARM:           return "arm";
    case PROCESSOR_ARCHITECTURE_ALPHA64:       return "alpha";
    case PROCESSOR_ARCHITECTURE_MSIL:          return "msil";
    case PROCESSOR_ARCHITECTURE_IA32_ON_WIN64: return "x86_wow64";
    default: return "unknown";
    }
}

/* Return the Windows-specific canonical host name. */
static const char *
win32_canonical_host(apr_pool_t *pool)
{
  SYSTEM_INFO sysinfo;
  SYSTEM_INFO local_sysinfo;
  OSVERSIONINFOEXW osinfo;

  if (system_info(&sysinfo, &local_sysinfo, &osinfo))
    {
      const char *arch = processor_name(&local_sysinfo);
      const char *machine = processor_name(&sysinfo);
      const char *vendor = "microsoft";
      const char *sysname = "windows";
      const char *sysver = apr_psprintf(pool, "%u.%u.%u",
                                        (unsigned int)osinfo.dwMajorVersion,
                                        (unsigned int)osinfo.dwMinorVersion,
                                        (unsigned int)osinfo.dwBuildNumber);

      if (sysinfo.wProcessorArchitecture
          == local_sysinfo.wProcessorArchitecture)
        return apr_psprintf(pool, "%s-%s-%s%s",
                            machine, vendor, sysname, sysver);
      return apr_psprintf(pool, "%s/%s-%s-%s%s",
                          arch, machine, vendor, sysname, sysver);
    }

  return "unknown-microsoft-windows";
}

/* Convert a Unicode string to UTF-8. */
static char *
wcs_to_utf8(const wchar_t *wcs, apr_pool_t *pool)
{
  const int bufsize = WideCharToMultiByte(CP_UTF8, 0, wcs, -1,
                                          NULL, 0, NULL, NULL);
  if (bufsize > 0)
    {
      char *const utf8 = apr_palloc(pool, bufsize + 1);
      WideCharToMultiByte(CP_UTF8, 0, wcs, -1, utf8, bufsize, NULL, NULL);
      return utf8;
    }
  return NULL;
}

/* Query the value called NAME of the registry key HKEY. */
static char *
registry_value(HKEY hkey, wchar_t *name, apr_pool_t *pool)
{
  DWORD size;
  wchar_t *value;

  if (RegQueryValueExW(hkey, name, NULL, NULL, NULL, &size))
    return NULL;

  value = apr_palloc(pool, size + sizeof *value);
  if (RegQueryValueExW(hkey, name, NULL, NULL, (void*)value, &size))
    return NULL;
  value[size / sizeof *value] = 0;
  return wcs_to_utf8(value, pool);
}

/* Try to glean the Windows release name and associated info from the
   registry. Failing that, construct a release name from the version
   info. */
static const char *
win32_release_name(apr_pool_t *pool)
{
  SYSTEM_INFO sysinfo;
  OSVERSIONINFOEXW osinfo;
  HKEY hkcv;

  if (!system_info(&sysinfo, NULL, &osinfo))
    return NULL;

  if (!RegOpenKeyExW(HKEY_LOCAL_MACHINE,
                     L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion",
                     0, KEY_QUERY_VALUE, &hkcv))
    {
      const char *release = registry_value(hkcv, L"ProductName", pool);
      const char *spack = registry_value(hkcv, L"CSDVersion", pool);
      const char *curver = registry_value(hkcv, L"CurrentVersion", pool);
      const char *curtype = registry_value(hkcv, L"CurrentType", pool);
      const char *install = registry_value(hkcv, L"InstallationType", pool);
      const char *curbuild = registry_value(hkcv, L"CurrentBuildNumber", pool);

      if (!spack && *osinfo.szCSDVersion)
        spack = wcs_to_utf8(osinfo.szCSDVersion, pool);

      if (!curbuild)
        curbuild = registry_value(hkcv, L"CurrentBuild", pool);

      if (release || spack || curver || curtype || curbuild)
        {
          const char *bootinfo = "";
          if (curver || install || curtype)
            {
              bootinfo = apr_psprintf(pool, "[%s%s%s%s%s]",
                                      (curver ? curver : ""),
                                      (install ? (curver ? " " : "") : ""),
                                      (install ? install : ""),
                                      (curtype
                                       ? (curver||install ? " " : "")
                                       : ""),
                                      (curtype ? curtype : ""));
            }

          return apr_psprintf(pool, "%s%s%s%s%s%s%s",
                              (release ? release : ""),
                              (spack ? (release ? ", " : "") : ""),
                              (spack ? spack : ""),
                              (curbuild
                               ? (release||spack ? ", build " : "build ")
                               : ""),
                              (curbuild ? curbuild : ""),
                              (bootinfo
                               ? (release||spack||curbuild ? " " : "")
                               : ""),
                              (bootinfo ? bootinfo : ""));
        }
    }

  if (*osinfo.szCSDVersion)
    {
      const char *servicepack = wcs_to_utf8(osinfo.szCSDVersion, pool);

      if (servicepack)
        return apr_psprintf(pool, "Windows NT %u.%u, %s, build %u",
                            (unsigned int)osinfo.dwMajorVersion,
                            (unsigned int)osinfo.dwMinorVersion,
                            servicepack,
                            (unsigned int)osinfo.dwBuildNumber);

      /* Assume wServicePackMajor > 0 if szCSDVersion is not empty */
      if (osinfo.wServicePackMinor)
        return apr_psprintf(pool, "Windows NT %u.%u SP%u.%u, build %u",
                            (unsigned int)osinfo.dwMajorVersion,
                            (unsigned int)osinfo.dwMinorVersion,
                            (unsigned int)osinfo.wServicePackMajor,
                            (unsigned int)osinfo.wServicePackMinor,
                            (unsigned int)osinfo.dwBuildNumber);

      return apr_psprintf(pool, "Windows NT %u.%u SP%u, build %u",
                          (unsigned int)osinfo.dwMajorVersion,
                          (unsigned int)osinfo.dwMinorVersion,
                          (unsigned int)osinfo.wServicePackMajor,
                          (unsigned int)osinfo.dwBuildNumber);
    }

  return apr_psprintf(pool, "Windows NT %u.%u, build %u",
                      (unsigned int)osinfo.dwMajorVersion,
                      (unsigned int)osinfo.dwMinorVersion,
                      (unsigned int)osinfo.dwBuildNumber);
}

/* Get a list of handles of shared libs loaded by the current
   process. Returns a NULL-terminated array alocated from POOL. */
static HMODULE *
enum_loaded_modules(apr_pool_t *pool)
{
  HMODULE psapi_dll = 0;
  HANDLE current = GetCurrentProcess();
  HMODULE dummy[1];
  HMODULE *handles;
  DWORD size;
  FNENUMPROCESSMODULES EnumProcessModules_;

  psapi_dll = GetModuleHandleA("psapi.dll");

  if (!psapi_dll)
    {
      /* Load and never unload, just like static linking */
      psapi_dll = LoadLibraryA("psapi.dll");
    }

  if (!psapi_dll)
      return NULL;

  EnumProcessModules_ = (FNENUMPROCESSMODULES)
                              GetProcAddress(psapi_dll, "EnumProcessModules");

  /* Before Windows XP psapi was an optional module */
  if (! EnumProcessModules_)
    return NULL;

  if (!EnumProcessModules_(current, dummy, sizeof(dummy), &size))
    return NULL;

  handles = apr_palloc(pool, size + sizeof *handles);
  if (! EnumProcessModules_(current, handles, size, &size))
    return NULL;
  handles[size / sizeof *handles] = NULL;
  return handles;
}

/* Find the version number, if any, embedded in FILENAME. */
static const char *
file_version_number(const wchar_t *filename, apr_pool_t *pool)
{
  VS_FIXEDFILEINFO info;
  unsigned int major, minor, micro, nano;
  void *data;
  DWORD data_size = GetFileVersionInfoSizeW(filename, NULL);
  void *vinfo;
  UINT vinfo_size;

  if (!data_size)
    return NULL;

  data = apr_palloc(pool, data_size);
  if (!GetFileVersionInfoW(filename, 0, data_size, data))
    return NULL;

  if (!VerQueryValueW(data, L"\\", &vinfo, &vinfo_size))
    return NULL;

  if (vinfo_size != sizeof info)
    return NULL;

  memcpy(&info, vinfo, sizeof info);
  major = (info.dwFileVersionMS >> 16) & 0xFFFF;
  minor = info.dwFileVersionMS & 0xFFFF;
  micro = (info.dwFileVersionLS >> 16) & 0xFFFF;
  nano = info.dwFileVersionLS & 0xFFFF;

  if (!nano)
    {
      if (!micro)
        return apr_psprintf(pool, "%u.%u", major, minor);
      else
        return apr_psprintf(pool, "%u.%u.%u", major, minor, micro);
    }
  return apr_psprintf(pool, "%u.%u.%u.%u", major, minor, micro, nano);
}

/* List the shared libraries loaded by the current process. */
static const apr_array_header_t *
win32_shared_libs(apr_pool_t *pool)
{
  apr_array_header_t *array = NULL;
  wchar_t buffer[MAX_PATH + 1];
  HMODULE *handles = enum_loaded_modules(pool);
  HMODULE *module;

  for (module = handles; module && *module; ++module)
    {
      const char *filename;
      const char *version;
      if (GetModuleFileNameW(*module, buffer, MAX_PATH))
        {
          buffer[MAX_PATH] = 0;

          version = file_version_number(buffer, pool);
          filename = wcs_to_utf8(buffer, pool);
          if (filename)
            {
              svn_version_ext_loaded_lib_t *lib;

              if (!array)
                {
                  array = apr_array_make(pool, 32, sizeof(*lib));
                }
              lib = &APR_ARRAY_PUSH(array, svn_version_ext_loaded_lib_t);
              lib->name = svn_dirent_local_style(filename, pool);
              lib->version = version;
            }
        }
    }

  return array;
}
#endif /* WIN32 */

#ifdef SVN_HAVE_MACOS_PLIST
/* Load the SystemVersion.plist or ServerVersion.plist file into a
   property list. Set SERVER to TRUE if the file read was
   ServerVersion.plist. */
static CFDictionaryRef
system_version_plist(svn_boolean_t *server, apr_pool_t *pool)
{
  static const UInt8 server_version[] =
    "/System/Library/CoreServices/ServerVersion.plist";
  static const UInt8 system_version[] =
    "/System/Library/CoreServices/SystemVersion.plist";

  CFPropertyListRef plist = NULL;
  CFDataRef resource = NULL;
  CFStringRef errstr = NULL;
  CFURLRef url = NULL;
  SInt32 errcode;

  url = CFURLCreateFromFileSystemRepresentation(kCFAllocatorDefault,
                                                server_version,
                                                sizeof(server_version) - 1,
                                                FALSE);
  if (!url)
    return NULL;

  if (!CFURLCreateDataAndPropertiesFromResource(kCFAllocatorDefault,
                                                url, &resource,
                                                NULL, NULL, &errcode))
    {
      CFRelease(url);
      url = CFURLCreateFromFileSystemRepresentation(kCFAllocatorDefault,
                                                    system_version,
                                                    sizeof(system_version) - 1,
                                                    FALSE);
      if (!url)
        return NULL;

      if (!CFURLCreateDataAndPropertiesFromResource(kCFAllocatorDefault,
                                                    url, &resource,
                                                    NULL, NULL, &errcode))
        {
          CFRelease(url);
          return NULL;
        }
      else
        {
          CFRelease(url);
          *server = FALSE;
        }
    }
  else
    {
      CFRelease(url);
      *server = TRUE;
    }

  /* ### CFPropertyListCreateFromXMLData is obsolete, but its
         replacement CFPropertyListCreateWithData is only available
         from Mac OS 1.6 onward. */
  plist = CFPropertyListCreateFromXMLData(kCFAllocatorDefault, resource,
                                          kCFPropertyListImmutable,
                                          &errstr);
  if (resource)
    CFRelease(resource);
  if (errstr)
    CFRelease(errstr);

  if (CFDictionaryGetTypeID() != CFGetTypeID(plist))
    {
      /* Oops ... this really should be a dict. */
      CFRelease(plist);
      return NULL;
    }

  return plist;
}

/* Return the value for KEY from PLIST, or NULL if not available. */
static const char *
value_from_dict(CFDictionaryRef plist, CFStringRef key, apr_pool_t *pool)
{
  CFStringRef valref;
  CFIndex bufsize;
  const void *valptr;
  const char *value;

  if (!CFDictionaryGetValueIfPresent(plist, key, &valptr))
    return NULL;

  valref = valptr;
  if (CFStringGetTypeID() != CFGetTypeID(valref))
    return NULL;

  value = CFStringGetCStringPtr(valref, kCFStringEncodingUTF8);
  if (value)
    return apr_pstrdup(pool, value);

  bufsize =  5 * CFStringGetLength(valref) + 1;
  value = apr_palloc(pool, bufsize);
  if (!CFStringGetCString(valref, (char*)value, bufsize,
                          kCFStringEncodingUTF8))
    value = NULL;

  return value;
}

/* Return the commercial name of the OS, given the version number in
   a format that matches the regular expression /^10\.\d+(\..*)?$/ */
static const char *
release_name_from_version(const char *osver)
{
  char *end = NULL;
  unsigned long num = strtoul(osver, &end, 10);

  if (!end || *end != '.' || num != 10)
    return NULL;

  osver = end + 1;
  end = NULL;
  num = strtoul(osver, &end, 10);
  if (!end || (*end && *end != '.'))
    return NULL;

  /* See http://en.wikipedia.org/wiki/History_of_OS_X#Release_timeline */
  switch(num)
    {
    case 0: return "Cheetah";
    case 1: return "Puma";
    case 2: return "Jaguar";
    case 3: return "Panther";
    case 4: return "Tiger";
    case 5: return "Leopard";
    case 6: return "Snow Leopard";
    case 7: return "Lion";
    case 8: return "Mountain Lion";
    case 9: return "Mavericks";
    }

  return NULL;
}

/* Construct the release name from information stored in the Mac OS X
   "SystemVersion.plist" file (or ServerVersion.plist, for Mac Os
   Server. */
static const char *
macos_release_name(apr_pool_t *pool)
{
  svn_boolean_t server;
  CFDictionaryRef plist = system_version_plist(&server, pool);

  if (plist)
    {
      const char *osname = value_from_dict(plist, CFSTR("ProductName"), pool);
      const char *osver = value_from_dict(plist,
                                          CFSTR("ProductUserVisibleVersion"),
                                          pool);
      const char *build = value_from_dict(plist,
                                          CFSTR("ProductBuildVersion"),
                                          pool);
      const char *release;

      if (!osver)
        osver = value_from_dict(plist, CFSTR("ProductVersion"), pool);
      release = release_name_from_version(osver);

      CFRelease(plist);
      return apr_psprintf(pool, "%s%s%s%s%s%s%s%s",
                          (osname ? osname : ""),
                          (osver ? (osname ? " " : "") : ""),
                          (osver ? osver : ""),
                          (release ? (osname||osver ? " " : "") : ""),
                          (release ? release : ""),
                          (build
                           ? (osname||osver||release ? ", " : "")
                           : ""),
                          (build
                           ? (server ? "server build " : "build ")
                           : ""),
                          (build ? build : ""));
    }

  return NULL;
}
#endif  /* SVN_HAVE_MACOS_PLIST */

#ifdef SVN_HAVE_MACHO_ITERATE
/* List the shared libraries loaded by the current process.
   Ignore frameworks and system libraries, they're just clutter. */
static const apr_array_header_t *
macos_shared_libs(apr_pool_t *pool)
{
  static const char slb_prefix[] = "/usr/lib/system/";
  static const char fwk_prefix[] = "/System/Library/Frameworks/";
  static const char pfk_prefix[] = "/System/Library/PrivateFrameworks/";

  const size_t slb_prefix_len = strlen(slb_prefix);
  const size_t fwk_prefix_len = strlen(fwk_prefix);
  const size_t pfk_prefix_len = strlen(pfk_prefix);

  apr_array_header_t *result = NULL;
  apr_array_header_t *dylibs = NULL;

  uint32_t i;
  for (i = 0;; ++i)
    {
      const struct mach_header *header = _dyld_get_image_header(i);
      const char *filename = _dyld_get_image_name(i);
      const char *version;
      char *truename;
      svn_version_ext_loaded_lib_t *lib;

      if (!(header && filename))
        break;

      switch (header->cputype)
        {
        case CPU_TYPE_I386:      version = _("Intel"); break;
        case CPU_TYPE_X86_64:    version = _("Intel 64-bit"); break;
        case CPU_TYPE_POWERPC:   version = _("PowerPC"); break;
        case CPU_TYPE_POWERPC64: version = _("PowerPC 64-bit"); break;
        default:
          version = NULL;
        }

      if (0 == apr_filepath_merge(&truename, "", filename,
                                  APR_FILEPATH_NATIVE
                                  | APR_FILEPATH_TRUENAME,
                                  pool))
        filename = truename;
      else
        filename = apr_pstrdup(pool, filename);

      if (0 == strncmp(filename, slb_prefix, slb_prefix_len)
          || 0 == strncmp(filename, fwk_prefix, fwk_prefix_len)
          || 0 == strncmp(filename, pfk_prefix, pfk_prefix_len))
        {
          /* Ignore frameworks and system libraries. */
          continue;
        }

      if (header->filetype == MH_EXECUTE)
        {
          /* Make sure the program filename is first in the list */
          if (!result)
            {
              result = apr_array_make(pool, 32, sizeof(*lib));
            }
          lib = &APR_ARRAY_PUSH(result, svn_version_ext_loaded_lib_t);
        }
      else
        {
          if (!dylibs)
            {
              dylibs = apr_array_make(pool, 32, sizeof(*lib));
            }
          lib = &APR_ARRAY_PUSH(dylibs, svn_version_ext_loaded_lib_t);
        }

      lib->name = filename;
      lib->version = version;
    }

  /* Gather results into one array. */
  if (dylibs)
    {
      if (result)
        apr_array_cat(result, dylibs);
      else
        result = dylibs;
    }

  return result;
}
#endif  /* SVN_HAVE_MACHO_ITERATE */


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

import java.util.List;

import org.camunda.bpm.engine.authorization.Permission;
import org.camunda.bpm.engine.authorization.Permissions;
import org.camunda.bpm.engine.authorization.Resource;
import org.camunda.bpm.engine.authorization.Resources;
import org.camunda.bpm.engine.identity.Group;
import org.camunda.bpm.engine.identity.GroupQuery;
import org.camunda.bpm.engine.identity.User;
import org.camunda.bpm.engine.identity.UserQuery;
import org.camunda.bpm.engine.impl.AbstractQuery;
import org.camunda.bpm.engine.impl.UserQueryImpl;
import org.camunda.bpm.engine.impl.context.Context;
import org.camunda.bpm.engine.impl.identity.ReadOnlyIdentityProvider;
import org.camunda.bpm.engine.impl.interceptor.CommandContext;
import org.camunda.bpm.engine.impl.persistence.AbstractManager;
import org.camunda.bpm.engine.impl.persistence.entity.GroupEntity;
import org.camunda.bpm.engine.impl.persistence.entity.UserEntity;

/**
 *
Read only implementation of DB-backed identity service

 *
 * @author Daniel Meyer
 * @author nico.rehwaldt
 */
@SuppressWarnings("unchecked")
public class DbReadOnlyIdentityServiceProvider extends AbstractManager implements ReadOnlyIdentityProvider {

  // users /////////////////////////////////////////

  public UserEntity findUserById(String userId) {
    checkAuthorization(Permissions.READ, Resources.USER, userId);
    return getDbSqlSession().selectById(UserEntity.class, userId);
  }

  public UserQuery createUserQuery() {
    return new DbUserQueryImpl(Context.getProcessEngineConfiguration().getCommandExecutorTxRequired());
  }

  public UserQueryImpl createUserQuery(CommandContext commandContext) {
    return new DbUserQueryImpl(commandContext);
  }

  public long findUserCountByQueryCriteria(DbUserQueryImpl query) {
    configureQuery(query, Resources.USER);
    return (Long) getDbSqlSession().selectOne("selectUserCountByQueryCriteria", query);
  }

  public List<User> findUserByQueryCriteria(DbUserQueryImpl query) {
    configureQuery(query, Resources.USER);
    return getDbSqlSession().selectList("selectUserByQueryCriteria", query);
  }

  public boolean checkPassword(String userId, String password) {
    User user = findUserById(userId);
    if ((user != null) && (password != null) && matchPassword(password, user)) {
      return true;
    } else {
      return false;
    }
  }

  protected boolean matchPassword(String password, User user) {
    return Context.getProcessEngineConfiguration()
      .getPasswordEncryptor()
      .check(password, user.getPassword());
  }

  protected String encryptPassword(String password) {
    if (password == null) {
      return null;
    } else {
      return Context.getProcessEngineConfiguration()
        .getPasswordEncryptor()
        .encrypt(password);
    }
  }

  // groups //////////////////////////////////////////

  public GroupEntity findGroupById(String groupId) {
    checkAuthorization(Permissions.READ, Resources.GROUP, groupId);
    return getDbSqlSession().selectById(GroupEntity.class, groupId);
  }

  public GroupQuery createGroupQuery() {
    return new DbGroupQueryImpl(Context.getProcessEngineConfiguration().getCommandExecutorTxRequired());
  }

  public GroupQuery createGroupQuery(CommandContext commandContext) {
    return new DbGroupQueryImpl(commandContext);
  }

  public long findGroupCountByQueryCriteria(DbGroupQueryImpl query) {
    configureQuery(query, Resources.GROUP);
    return (Long) getDbSqlSession().selectOne("selectGroupCountByQueryCriteria", query);
  }

  public List<Group> findGroupByQueryCriteria(DbGroupQueryImpl query) {
    configureQuery(query, Resources.GROUP);
    return getDbSqlSession().selectList("selectGroupByQueryCriteria", query);
  }

  //authorizations ////////////////////////////////////////////////////

  protected void configureQuery(@SuppressWarnings("rawtypes") AbstractQuery query, Resource resource) {
    Context.getCommandContext()
      .getAuthorizationManager()
      .configureQuery(query, resource);
  }

  protected void checkAuthorization(Permission permission, Resource resource, String resourceId) {
    Context.getCommandContext()
      .getAuthorizationManager()
      .checkAuthorization(permission, resource, resourceId);
 }

}

redpajama_set_name: RedPajamaGithub


text:
package org.eclipse.gef.commands;

import java.util.EventObject;

/**
 * A CommandStackListener is notified whenever the {@link CommandStack}'s state
 * has changed.
 *
 * @deprecated Use {@link CommandStackEventListener} instead and filter for
 *             post-events using {@link CommandStack#POST_MASK}.
 */
public interface CommandStackListener {

    /**
     * Called when the {@link CommandStack}'s state has changed.
     *
     * @param event
     *            the event
     */
    void commandStackChanged(EventObject event);

}


text:
package org.openkilda.testing.service.elastic.model;

public final class KildaTags {
    public static final String NORTHBOUND = "kilda-northbound";
    public static final String STORM_WORKER = "storm-worker_log";
    public static final String TOPOLOGY_ENGINE = "kilda-tpe";
    public static final String FLOODLIGHT = "kilda-floodlight";

    private KildaTags() {
        throw new UnsupportedOperationException();
    }

}


text:
:mod:`certbot.hooks`
------------------------

.. automodule:: certbot.hooks
   :members:


text:
namespace blink {

class Document;
class Event;

class CORE_EXPORT DeviceSingleWindowEventController : public GarbageCollectedFinalized<DeviceSingleWindowEventController>, public PlatformEventController, public DOMWindowLifecycleObserver {
public:
    virtual ~DeviceSingleWindowEventController();

    // Inherited from DeviceEventControllerBase.
    void didUpdateData() override;
    DECLARE_VIRTUAL_TRACE();

    // Inherited from DOMWindowLifecycleObserver.
    void didAddEventListener(LocalDOMWindow*, const AtomicString&) override;
    void didRemoveEventListener(LocalDOMWindow*, const AtomicString&) override;
    void didRemoveAllEventListeners(LocalDOMWindow*) override;

protected:
    explicit DeviceSingleWindowEventController(Document&);

    Document& document() const { return *m_document; }

    void dispatchDeviceEvent(Event*);

    virtual Event* lastEvent() const = 0;
    virtual const AtomicString& eventTypeName() const = 0;
    virtual bool isNullEvent(Event*) const = 0;

private:
    bool m_needsCheckingNullEvents;
    Member<Document> m_document;
};

} // namespace blink

#endif // DeviceSingleWindowEventController_h


text:
//
//  CTFeedbackViewController.h
//  CTFeedbackDemo
//
//  Created by 和泉田 領一 on 2013/10/31.
//  Copyright (c) 2013年 CAPH. All rights reserved.
//

#import <UIKit/UIKit.h>
#import <MessageUI/MessageUI.h>

@class CTFeedbackTopicCellItem;
@class CTFeedbackContentCellItem;

@protocol CTFeedbackViewControllerDelegate;

@interface CTFeedbackViewController : UITableViewController <MFMailComposeViewControllerDelegate>

@property (weak) id <CTFeedbackViewControllerDelegate> delegate;

@property (nonatomic, strong) NSArray *topics;
@property (nonatomic, strong) NSArray *localizedTopics;

/*
 * selectedTopic's default value is first item of topics.
 */
@property (nonatomic, strong) NSString *selectedTopic;

@property (nonatomic, assign) BOOL hidesAppNameCell;
@property (nonatomic, assign) BOOL hidesAppVersionCell;
@property (nonatomic, assign) BOOL hidesAppBuildCell;

@property (nonatomic, readonly) NSString *platformString;
@property (nonatomic, readonly) NSString *systemVersion;
@property (nonatomic, readonly) NSString *appName;
@property (nonatomic, readonly) NSString *appVersion;
@property (nonatomic, readonly) NSString *appBuild;

@property (nonatomic, strong) NSArray *toRecipients;

@property (nonatomic, strong) NSArray *ccRecipients;

@property (nonatomic, strong) NSArray *bccRecipients;

@property (nonatomic, strong) NSString *additionalDiagnosticContent;
@property (assign) BOOL useHTML;

+ (CTFeedbackViewController *)controllerWithTopics:(NSArray *)topics localizedTopics:(NSArray *)localizedTopics;

- (instancetype)initWithTopics:(NSArray *)topics localizedTopics:(NSArray *)localizedTopics;

@end

@protocol CTFeedbackViewControllerDelegate <NSObject>
@optional
- (void)feedbackViewController:(CTFeedbackViewController *)controller didFinishWithMailComposeResult:(MFMailComposeResult)result error:(NSError *)error;

@end


text:
package com.amazonaws.services.translate.model.transform;

import java.math.*;

import javax.annotation.Generated;

import com.amazonaws.services.translate.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;

import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;

/**
 * Language JSON Unmarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class LanguageJsonUnmarshaller implements Unmarshaller<Language, JsonUnmarshallerContext> {

    public Language unmarshall(JsonUnmarshallerContext context) throws Exception {
        Language language = new Language();

        int originalDepth = context.getCurrentDepth();
        String currentParentElement = context.getCurrentParentElement();
        int targetDepth = originalDepth + 1;

        JsonToken token = context.getCurrentToken();
        if (token == null)
            token = context.nextToken();
        if (token == VALUE_NULL) {
            return null;
        }

        while (true) {
            if (token == null)
                break;

            if (token == FIELD_NAME || token == START_OBJECT) {
                if (context.testExpression("LanguageName", targetDepth)) {
                    context.nextToken();
                    language.setLanguageName(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("LanguageCode", targetDepth)) {
                    context.nextToken();
                    language.setLanguageCode(context.getUnmarshaller(String.class).unmarshall(context));
                }
            } else if (token == END_ARRAY || token == END_OBJECT) {
                if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
                    if (context.getCurrentDepth() <= originalDepth)
                        break;
                }
            }
            token = context.nextToken();
        }

        return language;
    }

    private static LanguageJsonUnmarshaller instance;

    public static LanguageJsonUnmarshaller getInstance() {
        if (instance == null)
            instance = new LanguageJsonUnmarshaller();
        return instance;
    }
}


text:
if platform?('centos','redhat','fedora','amazon')
  apache_module 'log_config'
else
  include_recipe 'apache2'
end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace scat
{
    public class PhpSqlInjectionRule : IRule
    {
        public List<FileLoader> Loaders
        {
            get;
            set;
        }

        private ITemplate template;

        public PhpSqlInjectionRule(List<FileLoader> loaders, ITemplate template)
        {
            this.Loaders = loaders;
            this.Vulnerabilities = new List<BaseVulnerability>();
            this.template = template;
        }

        private List<BaseVulnerability> Vulnerabilities;

        public IEnumerable<BaseVulnerability> GetVulnerabilities()
        {
            return this.Vulnerabilities;
        }

        public string GetRuleName()
        {
            return this.template.GetRuleName();
        }

        public class PhpFileInclusionAnalyzer
        {
            public List<BaseVulnerability> vulns;
            public FileLoader fileLoader;
            private ITemplate template;

            public PhpFileInclusionAnalyzer(FileLoader l, ITemplate template)
            {
                this.fileLoader = l;
                this.vulns = new List<BaseVulnerability>();
                this.template = template;
            }

            public void Analyze()
            {
                if (this.fileLoader.Filename.EndsWith(".php"))
                {
                    //
                    //  test the basecase first.
                    //

                    foreach (var line in this.fileLoader.Lines)
                    {
                        if (line.Contains("mysql_query(") && PhpUtil.ContainsUserInput(line))
                        {
                            this.vulns.Add(this.template.GetVulnerability(this.fileLoader.Filename, "Php Sql Injection", line));
                        }
                    }

                    //
                    // ok, now see if we get all the tainted variables and see if those are used in a mysql line.
                    //

                    List<Tuple<string,string>> taintedVariables = PhpUtil.EnumerateTaintedVariables(this.fileLoader.Lines);
                    foreach (var taintedLove in taintedVariables)
                    {
                        foreach (var line in this.fileLoader.Lines)
                        {
                            if (line.Contains("mysql_query(") && line.Contains(taintedLove.Item1))
                            {
                                this.vulns.Add(this.template.GetVulnerability(this.fileLoader.Filename, "Php Sql Injection", line + "<-->" + taintedLove.Item2));
                            }
                        }
                    }

                }

            }

        }

        public void Evaluate()
        {
            List<PhpFileInclusionAnalyzer> analyzers = new List<PhpFileInclusionAnalyzer>();

            foreach (var l in this.Loaders)
            {
                analyzers.Add( new PhpFileInclusionAnalyzer(l, this.template));
            }

            Parallel.ForEach(analyzers, a =>
            {
                a.Analyze();
            });

            //
            // aggregate the vulnerabilities.
            //
            foreach(var a in analyzers)
            {
                if(a.vulns.Count > 0)
                {
                    foreach (var v in a.vulns)
                    {
                        this.Vulnerabilities.Add(v);
                    }
                }
            }

        }
    }
}


text:
'use strict';

var _interopRequireDefault = require('babel-runtime/helpers/interop-require-default')['default'];

Object.defineProperty(exports, '__esModule', {
  value: true
});
exports['default'] = resolveToValue;

var _recast = require('recast');

var _recast2 = _interopRequireDefault(_recast);

var _recast$types = _recast2['default'].types;
var NodePath = _recast$types.NodePath;
var builders = _recast$types.builders;
var types = _recast$types.namedTypes;

function buildMemberExpressionFromPattern(_x) {
  var _again = true;

  _function: while (_again) {
    var path = _x;
    node = objPath = undefined;
    _again = false;

    var node = path.node;
    if (types.Property.check(node)) {
      var objPath = buildMemberExpressionFromPattern(path.parent);
      if (objPath) {
        return new NodePath(builders.memberExpression(objPath.node, node.key, types.Literal.check(node.key)), objPath);
      }
    } else if (types.ObjectPattern.check(node)) {
      _x = path.parent;
      _again = true;
      continue _function;
    } else if (types.VariableDeclarator.check(node)) {
      return path.get('init');
    }
    return null;
  }
}

/**
 * If the path is an identifier, it is resolved in the scope chain.
 * If it is an assignment expression, it resolves to the right hand side.
 *
 * Else the path itself is returned.
 */

function resolveToValue(_x2) {
  var _again2 = true;

  _function2: while (_again2) {
    var path = _x2;
    node = scope = bindings = resultPath = parentPath = memberExpressionPath = undefined;
    _again2 = false;

    var node = path.node;
    if (types.VariableDeclarator.check(node)) {
      if (node.init) {
        _x2 = path.get('init');
        _again2 = true;
        continue _function2;
      }
    } else if (types.ImportDefaultSpecifier.check(node) || types.ImportSpecifier.check(node)) {
      return path.parentPath;
    } else if (types.AssignmentExpression.check(node)) {
      if (node.operator === '=') {
        _x2 = node.get('right');
        _again2 = true;
        continue _function2;
      }
    } else if (types.Identifier.check(node)) {
      if ((types.ClassDeclaration.check(path.parentPath.node) || types.ClassExpression.check(path.parentPath.node) || types.Function.check(path.parentPath.node)) && path.parentPath.get('id') === path) {
        return path.parentPath;
      }

      var scope = path.scope.lookup(node.name);
      if (scope) {
        var bindings = scope.getBindings()[node.name];
        if (bindings.length > 0) {
          var resultPath = scope.getBindings()[node.name][0];
          var parentPath = resultPath.parent;
          if (types.ImportDefaultSpecifier.check(parentPath.node) || types.ImportSpecifier.check(parentPath.node) || types.VariableDeclarator.check(parentPath.node)) {
            resultPath = parentPath;
          } else if (types.Property.check(parentPath.node)) {
            // must be inside a pattern
            var memberExpressionPath = buildMemberExpressionFromPattern(parentPath);
            if (memberExpressionPath) {
              return memberExpressionPath;
            }
          }
          if (resultPath.node !== path.node) {
            _x2 = resultPath;
            _again2 = true;
            continue _function2;
          } else {
            return path;
          }
        }
      }
    }
    return path;
  }
}

module.exports = exports['default'];


text:
import React, { PropTypes, Component } from 'react'
import { ListView } from 'react-native'
import { Leaderboard } from '~/components'
import { connect } from 'react-redux'
import { fetchAndSetScoresListener } from '~/redux/modules/scores'
import Leader from '~/components/Leaderboard/Leader'

class LeaderboardContainer extends Component {
  static propTypes = {
    listenerSet: PropTypes.bool.isRequired,
    leaders: PropTypes.array.isRequired,
    openDrawer: PropTypes.func,
    navigator: PropTypes.object.isRequired,
  }
  constructor (props) {
    super(props)
    this.ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2})
    this.state = {
      dataSource: this.ds.cloneWithRows(this.props.leaders)
    }
  }
  componentDidMount () {
    if (this.props.listenerSet === false) {
      this.props.dispatch(fetchAndSetScoresListener())
    }
  }
  componentWillReceiveProps (nextProps) {
    if (nextProps.leaders !== this.props.leaders) {
      this.setState({
        dataSource: this.ds.cloneWithRows(nextProps.leaders)
      })
    }
  }
  renderRow = ({displayName, photoURL, score}) => {
    return <Leader name={displayName} avatar={photoURL} score={score} />
  }
  render () {
    return (
      <Leaderboard
        dataSource={this.state.dataSource}
        renderRow={this.renderRow}
        listenerSet={this.props.listenerSet}
        openDrawer={this.props.openDrawer} />
    )
  }
}

function mapStateToProps ({scores, users}) {
  return {
    listenerSet: scores.listenerSet,
    leaders: scores.leaderboardUids.map((uid) => {
      return {
        score: scores.usersScores[uid],
        ...users[uid],
      }
    })
  }
}

export default connect(
  mapStateToProps
)(LeaderboardContainer)


text:
package com.quollwriter.data.comparators;

import java.util.*;

import com.quollwriter.data.*;

public class OutlineItemSorter implements Comparator<OutlineItem>
{

    public int compare (OutlineItem o1,
                        OutlineItem o2)
    {

        return o1.getPosition () - o2.getPosition ();

    }

    public boolean equals (Object o)
    {

        return this == o;

    }

}


text:
#ifndef SAMPLEAPPLICATION_INCLUDE_SAMPLEAPPLICATION_AUDIOMANAGER_WAKEWORD_WAKEWORDENGINEINTERFACE_H_
#define SAMPLEAPPLICATION_INCLUDE_SAMPLEAPPLICATION_AUDIOMANAGER_WAKEWORD_WAKEWORDENGINEINTERFACE_H_

#include <memory>
#include <ostream>
#include <string>
#include <set>

#include <MultiAgentExperience/Utils/Data/DataObserverInterface.h>
#include <MultiAgentExperience/Application/WakeWordObserverInterface.h>

#include "SampleApplication/AgentManager/GestureHandlerInterface.h"
#include "SampleApplication/AudioManager/Wakeword/CrosswakeDetector/SimpleCrosswakeDetector.h"

namespace multiAgentExperience {
namespace sampleApplication {
namespace audioManager {
namespace wakeword {

namespace MAX = multiAgentExperience;

/**
 * The Wakeword Engine interface to be used by MAX Application engines.
 */
class WakewordEngine : public MAX::utils::data::DataObserverInterface {
public:
    /// Methods by which a @c WakewordEngine may be created.
    enum class CreateMethod {
        /// Create via an AVS SDK Library.
        AVS_SDK,
        /// Create by some other method as defined within this application.
        CUSTOM
    };

    /**
     * Constructor.
     *
     * @param crosswakeDetector The detector to prevent cross wakes.
     * @param observer The MAX Observer to be notified when a wakeword is detected.
     */
    WakewordEngine(
        std::shared_ptr<crosswake::SimpleCrosswakeDetector> crosswakeDetector,
        std::shared_ptr<MAX::application::WakeWordObserverInterface> observer);

    /**
     * Destructor.
     */
    virtual ~WakewordEngine() = default;

    /**
     * Return the name of the wakeword engine.
     *
     * @return The name of the wakeword engine.
     */
    virtual std::string getName() = 0;

    /**
     * Return the create method of the wakeword engine.
     *
     * @return The create method of the wakeword engine.
     */
    virtual CreateMethod getCreateMethod() = 0;

    /**
     * Return the set of wakewords this engine may detect.
     *
     * @return The set of wakewords this engine may detect.
     */
    virtual std::set<std::string> getWakewords() = 0;

    /**
     * Sets the gesture handler to be used.
     *
     * @param gestureHandler The gesture handler to be used.
     */
    virtual void setGestureHandler(std::shared_ptr<agentManager::GestureHandlerInterface> gestureHandler);

protected:
    /// Our MAX wakeword observer.
    std::shared_ptr<crosswake::SimpleCrosswakeDetector> m_crosswakeDetector;
    std::shared_ptr<MAX::application::WakeWordObserverInterface> m_observer;
};

/**
 * Write a @c createMethod value to an @c ostream as a string.
 *
 * @param stream The stream to write the value to.
 * @param state The createMethod value to write to the @c ostream as a string.
 * @return The @c ostream that was passed in and written to.
 */
inline std::ostream& operator<<(std::ostream& stream, const WakewordEngine::CreateMethod createMethod) {
    switch (createMethod) {
        case WakewordEngine::CreateMethod::AVS_SDK:
            return stream << "AVS_SDK";
        case WakewordEngine::CreateMethod::CUSTOM:
            return stream << "CUSTOM";
    }

    return stream << "Unknown WakewordEngine::CreateMethod.";
}

}  // namespace wakeword
}  // namespace audioManager
}  // namespace sampleApplication
}  // namespace multiAgentExperience

#endif  // SAMPLEAPPLICATION_INCLUDE_SAMPLEAPPLICATION_AUDIOMANAGER_WAKEWORD_WAKEWORDENGINEINTERFACE_H_


text:
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\Schema;

class CreateCountriesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('countries', function(Blueprint $table)
        {
            $table->increments('id');
            $table->string('name', 255)->default('');
            $table->string('full_name', 255)->nullable();
            $table->string('capital', 255)->nullable();
            $table->string('citizenship', 255)->nullable();
            $table->string('currency', 255)->nullable();
            $table->string('currency_code', 255)->nullable();
            $table->string('currency_sub_unit', 255)->nullable();
            $table->string('currency_symbol', 3)->nullable();
            $table->string('country_code', 3)->default('');
            $table->string('region_code', 3)->default('');
            $table->string('sub_region_code', 3)->default('');
            $table->boolean('eea')->default(0);
            $table->string('calling_code', 3)->nullable();
            $table->string('iso_3166_2', 2)->default('');
            $table->string('iso_3166_3', 3)->default('');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('countries');
    }
}


text:
import re
from typing import List

import numpy as np

# pylint: disable=too-few-public-methods

ID_SEP = re.compile(r"[-:]")

class WordAlignmentPreprocessor(object):
    """A preprocessor for word alignments in a text format.

    One of the following formats is expected:

        s1-t1 s2-t2 ...

        s1:1/w1 s2:t2/w2 ...

    where each `s` and `t` is the index of a word in the source and target
    sentence, respectively, and `w` is the corresponding weight. If the weight
    is not given, it is assumend to be 1. The separators `-` and `:` are
    interchangeable.

    The output of the preprocessor is an alignment matrix of the fixed shape
    (target_len, source_len) for each sentence.
    """

    def __init__(self, source_len, target_len, dtype=np.float32,
                 normalize=True, zero_based=True):
        self._source_len = source_len
        self._target_len = target_len
        self._dtype = dtype
        self._normalize = normalize
        self._zero_based = zero_based

    def __call__(self, sentence: List[str]):
        result = np.zeros((self._target_len, self._source_len), self._dtype)

        for ali in sentence:
            ids, _, str_weight = ali.partition('/')
            i, j = map(int, ID_SEP.split(ids))
            weight = float(str_weight) if str_weight != '' else 1.

            if not self._zero_based:
                i -= 1
                j -= 1

            if i < self._source_len and j < self._target_len:
                result[j][i] = weight

        if self._normalize:
            with np.errstate(divide='ignore', invalid='ignore'):
                result /= result.sum(axis=1, keepdims=True)
                result[np.isnan(result)] = 0

        return result


text:
using Microsoft.Graphics.Canvas;
using Microsoft.Graphics.Canvas.UI.Xaml;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Foundation;

namespace DrawingCore.Interfaces
{
    public interface IDrawCommand
    {
        void Draw(double canvasWidth, double canvasHeight, CanvasDrawingSession session, Rect rect);
    }
}


text:
using NUnit.Framework;
using System.Collections.Generic;
using CallfireApiClient.Api.Common.Model;
using CallfireApiClient.Api.CallsTexts.Model;
using CallfireApiClient.Api.CallsTexts.Model.Request;
using RestSharp;
using System.Linq;

namespace CallfireApiClient.Tests.Api.CallsTexts
{
    [TestFixture]
    public class TextsApiTest : AbstractApiTest
    {
        [Test]
        public void SendTexts()
        {
            string requestJson = GetJsonPayload("/callstexts/textsApi/request/sendTexts.json");
            string responseJson = GetJsonPayload("/callstexts/textsApi/response/sendTexts.json");
            var restRequest = MockRestResponse(responseJson);

            TextRecipient r1 = new TextRecipient { PhoneNumber = "12135551100", Message = "Hello World!" };
            TextRecipient r2 = new TextRecipient { PhoneNumber = "12135551101", Message = "Testing 1 2 3", FromNumber = "12135551102" };

            IList<CallfireApiClient.Api.CallsTexts.Model.Text> texts = Client.TextsApi.Send(new List<TextRecipient> { r1, r2 });

            Assert.That(Serializer.Serialize(new ListHolder<CallfireApiClient.Api.CallsTexts.Model.Text>(texts)), Is.EqualTo(responseJson));
            Assert.AreEqual(Method.POST, restRequest.Value.Method);
            var requestBodyParam = restRequest.Value.Parameters.FirstOrDefault(p => p.Type == ParameterType.RequestBody);
            Assert.That(Serializer.Serialize(requestBodyParam.Value), Is.EqualTo(requestJson));

            texts = Client.TextsApi.Send(new List<TextRecipient> { r1, r2 }, 100, FIELDS);
            Assert.That(restRequest.Value.Parameters, Has.Some.Matches<Parameter>(p => p.Name.Equals("fields") && p.Value.Equals(FIELDS)));
            Assert.That(restRequest.Value.Parameters, Has.Some.Matches<Parameter>(p => p.Name.Equals("campaignId") && p.Value.Equals("100")));
        }

        [Test]
        public void SendTextsUsingRequest()
        {
            string requestJson = GetJsonPayload("/callstexts/textsApi/request/sendTexts.json");
            string responseJson = GetJsonPayload("/callstexts/textsApi/response/sendTexts.json");
            var restRequest = MockRestResponse(responseJson);

            TextRecipient r1 = new TextRecipient { PhoneNumber = "12135551100", Message = "Hello World!" };
            TextRecipient r2 = new TextRecipient { PhoneNumber = "12135551101", Message = "Testing 1 2 3", FromNumber = "12135551102" };

            var request = new SendTextsRequest
            {
               Recipients = new List<TextRecipient> { r1, r2 },
               CampaignId = 100,
               Fields = FIELDS,
               DefaultMessage = "defaultMessage",
               StrictValidation = true
            };

            IList<CallfireApiClient.Api.CallsTexts.Model.Text> texts = Client.TextsApi.Send(request);

            Assert.That(Serializer.Serialize(new ListHolder<CallfireApiClient.Api.CallsTexts.Model.Text>(texts)), Is.EqualTo(responseJson));
            Assert.AreEqual(Method.POST, restRequest.Value.Method);
            var requestBodyParam = restRequest.Value.Parameters.FirstOrDefault(p => p.Type == ParameterType.RequestBody);
            Assert.That(Serializer.Serialize(requestBodyParam.Value), Is.EqualTo(requestJson));
            Assert.That(restRequest.Value.Parameters, Has.Some.Matches<Parameter>(p => p.Name.Equals("fields") && p.Value.Equals(FIELDS)));
            Assert.That(restRequest.Value.Parameters, Has.Some.Matches<Parameter>(p => p.Name.Equals("campaignId") && p.Value.Equals("100")));
            Assert.That(restRequest.Value.Parameters, Has.Some.Matches<Parameter>(p => p.Name.Equals("defaultMessage") && p.Value.Equals("defaultMessage")));
            Assert.That(restRequest.Value.Parameters, Has.Some.Matches<Parameter>(p => p.Name.Equals("strictValidation") && p.Value.Equals("True")));
        }

        [Test]
        public void FindTexts()
        {
            string expectedJson = GetJsonPayload("/callstexts/textsApi/response/findTexts.json");
            var restRequest = MockRestResponse(expectedJson);
            var request = new FindTextsRequest
            {
                Limit = 5,
                Offset = 0,
                States = new List<StateType> { StateType.CALLBACK, StateType.DISABLED },
                Id = new List<long> { 1, 2, 3 },
                BatchId = 1001
            };

            Page<CallfireApiClient.Api.CallsTexts.Model.Text> texts = Client.TextsApi.Find(request);

            Assert.That(Serializer.Serialize(texts), Is.EqualTo(expectedJson));
            Assert.AreEqual(Method.GET, restRequest.Value.Method);
            Assert.That(restRequest.Value.Parameters, Has.Some.Matches<Parameter>(p => p.Name.Equals("limit") && p.Value.Equals("5")));
            Assert.That(restRequest.Value.Parameters, Has.Some.Matches<Parameter>(p => p.Name.Equals("offset") && p.Value.Equals("0")));
            Assert.That(restRequest.Value.Parameters, Has.Some.Matches<Parameter>(p => p.Name.Equals("batchId") && p.Value.Equals("1001")));
            Assert.That(restRequest.Value.Parameters, Has.Some.Matches<Parameter>(p => p.Name.Equals("id") && p.Value.Equals("1")));
            Assert.That(restRequest.Value.Parameters, Has.Some.Matches<Parameter>(p => p.Name.Equals("id") && p.Value.Equals("2")));
            Assert.That(restRequest.Value.Parameters, Has.Some.Matches<Parameter>(p => p.Name.Equals("id") && p.Value.Equals("3")));
            Assert.That(restRequest.Value.Parameters, Has.Some.Matches<Parameter>(p => p.Name.Equals("states") && p.Value.Equals("CALLBACK")));
            Assert.That(restRequest.Value.Parameters, Has.Some.Matches<Parameter>(p => p.Name.Equals("states") && p.Value.Equals("DISABLED")));
        }

        [Test]
        public void GetText()
        {
            string expectedJson = GetJsonPayload("/callstexts/textsApi/response/getText.json");
            var restRequest = MockRestResponse(expectedJson);

            CallfireApiClient.Api.CallsTexts.Model.Text text = Client.TextsApi.Get(1);
            Assert.That(restRequest.Value.Parameters, Has.None.Matches<Parameter>(p => p.Name.Equals("fields")));

            text = Client.TextsApi.Get(1, FIELDS);
            Assert.That(Serializer.Serialize(text), Is.EqualTo(expectedJson));
            Assert.AreEqual(Method.GET, restRequest.Value.Method);
            Assert.That(restRequest.Value.Parameters, Has.Some.Matches<Parameter>(p => p.Name.Equals("fields") && p.Value.Equals(FIELDS)));
        }
    }
}


text:
require 'rexml/document'
require File.expand_path('../../../../spec_helper', __FILE__)

describe "REXML::Element#[]" do

  before :each do
    @doc = REXML::Document.new("<root foo='bar'></root>")
    @child = REXML::Element.new("child")
    @doc.root.add_element @child
  end

  ruby_version_is "2.4" do
    it "return attribute value if argument is string or symbol" do
      @doc.root[:foo].should == 'bar'
      @doc.root['foo'].should == 'bar'
    end

    it "return nth element if argument is int" do
      @doc.root[0].should == @child
    end
  end
end


text:
/**
 * @file MulTimeLongDouble.c    Task to create two long double numbers for muliplication.
 * @brief
 *    Execute for a fixed number of iterations the multiplication of two random long double numbers.
 *
 * @author George Heineman
 * @date 6/15/08
 */

#include <stdlib.h>
#include "problem.h"

/** First random long double. */
static long double m;

/** Second random short. */
static long double n;

/** Number of times to compute multiplication. */
static int psize;

/** Select two random numbers in the range 1..2^32. */
void prepareInput(int inputSize) {
  m = 1 + (int) (2147483648 * (rand() / (RAND_MAX + 1.0)));
  m = 0.5 + 1 + (int) (2147483648 * (rand() / (RAND_MAX + 1.0)));
  psize = inputSize;
}

/** Execute by invoking multiplication 'psize' number of times. */
int execute() {
  int i;
  long double res = 0.0;

  /* change the m,n each time to thwart potential optimizers. */
  for (i = 0; i < psize; i++) {
    res = m*n;
    m++;
    n++;
    res = res -1;
  }

  return (int) res;
}

/** No postprocessing needed. */
void postInputProcessing() {
}

/** No specific problem usage. */
void problemUsage() {
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FLCLib.Chunks
{
    class FLCChunkFrameType : FLCChunk
    {
        public ushort Chunks { get; private set; }          // Number of subchunks
        public ushort Delay { get; private set; }           // Delay in milliseconds
        public short Reserved { get; private set; }         // Always zero
        public ushort Width { get; private set; }           // Frame width override (if non-zero)
        public ushort Height { get; private set; }          // Frame height override (if non-zero)

        public FLCChunkFrameType(FLCFile setOwnerFile)
            : base(setOwnerFile)
        {
        }

        protected override void ReadFromStream(System.IO.BinaryReader reader)
        {
            base.ReadFromStream(reader);

            Chunks = reader.ReadUInt16();
            Delay = reader.ReadUInt16();
            Reserved = reader.ReadInt16();
            Width = reader.ReadUInt16();
            Height = reader.ReadUInt16();

            if (Width != 0 || Height != 0)
                throw new NotImplementedException("Overlay width or height is not supported yet.");

            ReadSubChunks(reader, Chunks);
        }
    }
}


text:
SHELL := /bin/bash

PATH := ${GOPATH}/bin:$(PATH)

ENV := env
PYTHON := python3.5
PYTHON_PROJECTS := cbagent perfdaily perfrunner scripts spring

.PHONY: docker

all:
	virtualenv --quiet --python ${PYTHON} ${ENV}
	${ENV}/bin/pip install --upgrade --quiet pip wheel
	${ENV}/bin/pip install --quiet --no-warn-script-location -r requirements.txt
	${ENV}/bin/python setup.py --quiet install
	pwd > ${ENV}/lib/${PYTHON}/site-packages/perfrunner.pth

clean:
	rm -fr build perfrunner.egg-info dist cachestat dcptest kvgen cbindexperf rachell loader *.db *.log .coverage *.pid celery
	find . -name '*.pyc' -o -name '*.pyo' -o -name __pycache__ | xargs rm -fr

pep8:
	${ENV}/bin/flake8 --statistics ${PYTHON_PROJECTS}
	${ENV}/bin/isort --quiet --check-only --recursive ${PYTHON_PROJECTS}
	${ENV}/bin/pydocstyle ${PYTHON_PROJECTS}

test:
	${ENV}/bin/nosetests -v --with-coverage --cover-package=cbagent,perfrunner,spring unittests.py

misspell:
	go get -u github.com/client9/misspell/cmd/misspell
	find go ${PYTHON_PROJECTS} -type f -not -name "*.txt" | xargs misspell -error

gofmt:
	gofmt -e -d -s go && ! gofmt -l go | read

check: pep8 misspell gofmt test

vendor-sync:
	go version
	go get -u github.com/kardianos/govendor
	govendor sync

cachestat:
	go build ./go/cachestats

dcptest: vendor-sync
	go build ./go/dcptest

buildquery: vendor-sync
	go get -u golang.org/x/tools/cmd/goyacc
	cd vendor/github.com/couchbase/query/parser/n1ql && sh build.sh

cbindexperf: buildquery
	go build ./go/cbindexperf

kvgen: vendor-sync
	go build ./go/kvgen

rachell:
	go build ./go/rachell

loader:
	go build ./go/loader

docker:
	docker build -t docker.io/perflab/perfrunner docker


text:
window.$ = window.jQuery = require('jquery');
var angular = require('angular');

require('opentok-angular');
require('opentok-whiteboard');
require('opentok-whiteboard/opentok-whiteboard.css');

angular.module('opentok-meet', ['opentok', 'opentok-whiteboard'])
.controller('WhiteboardCtrl', ['$scope', 'RoomService', 'OTSession', function ($scope, RoomService, OTSession) {
    $scope.connected = false;
    // A bit cheeky: Forcing checkSystemRequirements to pass so that this works on mobile
    TB.checkSystemRequirements = function () {
        return true;
    };

    RoomService.getRoom().then(function (roomData) {
        OTSession.init(roomData.apiKey, roomData.sessionId, roomData.token, function (err) {
            if (!err) {
                $scope.$apply(function () {
                    $scope.connected = true;
                });
            }
        });
    });
}]);

require('../services.js');
require('../../css/whiteboard.css');


text:
#include <aws/elasticloadbalancingv2/model/CreateLoadBalancerRequest.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>

using namespace Aws::ElasticLoadBalancingv2::Model;
using namespace Aws::Utils;

CreateLoadBalancerRequest::CreateLoadBalancerRequest() :
    m_nameHasBeenSet(false),
    m_subnetsHasBeenSet(false),
    m_subnetMappingsHasBeenSet(false),
    m_securityGroupsHasBeenSet(false),
    m_scheme(LoadBalancerSchemeEnum::NOT_SET),
    m_schemeHasBeenSet(false),
    m_tagsHasBeenSet(false),
    m_type(LoadBalancerTypeEnum::NOT_SET),
    m_typeHasBeenSet(false),
    m_ipAddressType(IpAddressType::NOT_SET),
    m_ipAddressTypeHasBeenSet(false),
    m_customerOwnedIpv4PoolHasBeenSet(false)
{
}

Aws::String CreateLoadBalancerRequest::SerializePayload() const
{
  Aws::StringStream ss;
  ss << "Action=CreateLoadBalancer&";
  if(m_nameHasBeenSet)
  {
    ss << "Name=" << StringUtils::URLEncode(m_name.c_str()) << "&";
  }

  if(m_subnetsHasBeenSet)
  {
    unsigned subnetsCount = 1;
    for(auto& item : m_subnets)
    {
      ss << "Subnets.member." << subnetsCount << "="
          << StringUtils::URLEncode(item.c_str()) << "&";
      subnetsCount++;
    }
  }

  if(m_subnetMappingsHasBeenSet)
  {
    unsigned subnetMappingsCount = 1;
    for(auto& item : m_subnetMappings)
    {
      item.OutputToStream(ss, "SubnetMappings.member.", subnetMappingsCount, "");
      subnetMappingsCount++;
    }
  }

  if(m_securityGroupsHasBeenSet)
  {
    unsigned securityGroupsCount = 1;
    for(auto& item : m_securityGroups)
    {
      ss << "SecurityGroups.member." << securityGroupsCount << "="
          << StringUtils::URLEncode(item.c_str()) << "&";
      securityGroupsCount++;
    }
  }

  if(m_schemeHasBeenSet)
  {
    ss << "Scheme=" << LoadBalancerSchemeEnumMapper::GetNameForLoadBalancerSchemeEnum(m_scheme) << "&";
  }

  if(m_tagsHasBeenSet)
  {
    unsigned tagsCount = 1;
    for(auto& item : m_tags)
    {
      item.OutputToStream(ss, "Tags.member.", tagsCount, "");
      tagsCount++;
    }
  }

  if(m_typeHasBeenSet)
  {
    ss << "Type=" << LoadBalancerTypeEnumMapper::GetNameForLoadBalancerTypeEnum(m_type) << "&";
  }

  if(m_ipAddressTypeHasBeenSet)
  {
    ss << "IpAddressType=" << IpAddressTypeMapper::GetNameForIpAddressType(m_ipAddressType) << "&";
  }

  if(m_customerOwnedIpv4PoolHasBeenSet)
  {
    ss << "CustomerOwnedIpv4Pool=" << StringUtils::URLEncode(m_customerOwnedIpv4Pool.c_str()) << "&";
  }

  ss << "Version=2015-12-01";
  return ss.str();
}

void  CreateLoadBalancerRequest::DumpBodyToUrl(Aws::Http::URI& uri ) const
{
  uri.SetQueryString(SerializePayload());
}


text:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;

[System.Serializable]
public class AxleInfo {

	public WheelCollider leftWheel;
	public WheelCollider rightWheel;
	// is this wheel attached to motor?
	public bool hasMotor;
	// does this wheel apply steer angle?
	public bool hasSteering;

}

public class MonsterTruckControllerScript : MonoBehaviour {

	// the information about each individual axle
	public List<AxleInfo> axleInfos;
	// maximum torque the motor can apply to wheel
	public float maxMotorTorque;
	// maximum steer angle the wheel can have
	public float maxSteeringAngle;

	public float downForce;

	private float motorTorque = 0.0f;
	private float steeringAngle = 0.0f;

	private Vector3 homePosition;
	private Quaternion homeRotation;

	public void Start(){
		homePosition = transform.position;
		homeRotation = transform.rotation;
	}

	public void Update(){

		if(Input.GetKeyUp(KeyCode.R)){

			transform.position = homePosition;
			transform.rotation = homeRotation;
			motorTorque = 0.0f;
			steeringAngle = 0.0f;
			gameObject.GetComponent<Rigidbody>().velocity = Vector3.zero;

		}

	}

	public void FixedUpdate(){

		motorTorque = maxMotorTorque * Input.GetAxis("Vertical");
		steeringAngle = maxSteeringAngle * Input.GetAxis("Horizontal");

		foreach(AxleInfo axleInfo in axleInfos){

			if(axleInfo.hasSteering){

				axleInfo.leftWheel.steerAngle = steeringAngle;
				axleInfo.rightWheel.steerAngle = steeringAngle;

			}

			if(axleInfo.hasMotor) {

				axleInfo.leftWheel.motorTorque = motorTorque;
				axleInfo.rightWheel.motorTorque = motorTorque;

			}

			// Only apply visuals to wheels with steering
			ApplyLocalPositionToVisuals(axleInfo.leftWheel);
			ApplyLocalPositionToVisuals(axleInfo.rightWheel);

		}

		AddDownForce();

	}

	public void ApplyLocalPositionToVisuals(WheelCollider collider){

		if(collider.transform.childCount == 0){
			return;
		}

		Transform visualWheel = collider.transform.GetChild(0);

		Vector3 position;// = collider.transform.position;
		Quaternion rotation;// = collider.transform.rotation;
		collider.GetWorldPose(out position, out rotation);

		visualWheel.transform.position = position;
		visualWheel.transform.rotation = rotation;
		// Note: since we're hacking this together with z=90 rotated cylinders, rotate by 90 for now
		visualWheel.transform.Rotate(new Vector3(0.0f,0.0f,90.0f));

	}

	private void AddDownForce(){

		//TODO: make downforce configurable based on spoilers or whatever

		//m_WheelColliders[0].attachedRigidbody.AddForce(-transform.up*m_Downforce*m_WheelColliders[0].attachedRigidbody.velocity.magnitude);
		foreach(AxleInfo axleInfo in axleInfos){

			axleInfo.leftWheel.attachedRigidbody.AddForce(-transform.up*downForce*axleInfo.leftWheel.attachedRigidbody.velocity.magnitude);
			axleInfo.rightWheel.attachedRigidbody.AddForce(-transform.up*downForce*axleInfo.rightWheel.attachedRigidbody.velocity.magnitude);

		}

	}

	void OnGUI(){

		GUI.contentColor = Color.black;
		GUI.Label (new Rect (2, 2, 256, 64), "motor=" + motorTorque + ",steerAngle=" + steeringAngle);

	}

}


text:
import { normalizeUnits } from '../units/aliases';
import { hooks } from '../utils/hooks';
import isFunction from '../utils/is-function';

export function makeGetSet (unit, keepTime) {
    return function (value) {
        if (value != null) {
            set(this, unit, value);
            hooks.updateOffset(this, keepTime);
            return this;
        } else {
            return get(this, unit);
        }
    };
}

export function get (mom, unit) {
    return mom.isValid() ?
        mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit]() : NaN;
}

export function set (mom, unit, value) {
    if (mom.isValid()) {
        mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value);
    }
}

// MOMENTS

export function getSet (units, value) {
    var unit;
    if (typeof units === 'object') {
        for (unit in units) {
            this.set(unit, units[unit]);
        }
    } else {
        units = normalizeUnits(units);
        if (isFunction(this[units])) {
            return this[units](value);
        }
    }
    return this;
}


text:
#include "OgreRTShaderSystem.h"

namespace Ogre {

//-----------------------------------------------------------------------
template<>
RTShader::RTShaderSystem* Singleton<RTShader::RTShaderSystem>::msSingleton = 0;

namespace RTShader {

/************************************************************************/
/*                                                                      */
/************************************************************************/

Ogre::Technique* RTShaderSystem::ShaderGeneratorTechniqueResolverListener::handleSchemeNotFound( unsigned short schemeIndex, const Ogre::String& schemeName, Ogre::Material* originalMaterial, unsigned short lodIndex, const Ogre::Renderable* rend )
{
  Ogre::Technique* generatedTech = NULL;

  // Case this is the default shader generator scheme.
  if (schemeName == ShaderGenerator::DEFAULT_SCHEME_NAME)
  {
    bool techniqueCreated;

    // Create shader generated technique for this material.
    techniqueCreated = mShaderGenerator->createShaderBasedTechnique(
      originalMaterial->getName(),
      Ogre::MaterialManager::DEFAULT_SCHEME_NAME,
      schemeName);

    // Case technique registration succeeded.
    if (techniqueCreated)
    {
      // Force creating the shaders for the generated technique.
      mShaderGenerator->validateMaterial(schemeName, originalMaterial->getName());

      // Grab the generated technique.
      Ogre::Material::TechniqueIterator itTech = originalMaterial->getTechniqueIterator();

      while (itTech.hasMoreElements())
      {
        Ogre::Technique* curTech = itTech.getNext();

        if (curTech->getSchemeName() == schemeName)
        {
          generatedTech = curTech;
          break;
        }
      }
    }
  }

  return generatedTech;
}

//-----------------------------------------------------------------------
RTShaderSystem::ShaderGeneratorTechniqueResolverListener::ShaderGeneratorTechniqueResolverListener( ShaderGenerator* pShaderGenerator )
{
  mShaderGenerator = pShaderGenerator;
}

//-----------------------------------------------------------------------
RTShaderSystem::RTShaderSystem()
  : mShaderGenerator(0), mMaterialMgrListener(0)
{

}

//-----------------------------------------------------------------------
RTShaderSystem::~RTShaderSystem()
{

}

//-----------------------------------------------------------------------
size_t RTShaderSystem::getVertexShaderCount() const
{
  return mShaderGenerator->getVertexShaderCount();
}

//-----------------------------------------------------------------------
size_t RTShaderSystem::getFragmentShaderCount() const
{
  return mShaderGenerator->getFragmentShaderCount();
}

//-----------------------------------------------------------------------
bool RTShaderSystem::initializeRTShaderSystem( Ogre::SceneManager* sceneMgr )
{
  if (ShaderGenerator::initialize())
  {
    mShaderGenerator = ShaderGenerator::getSingletonPtr();

    mShaderGenerator->addSceneManager(sceneMgr);

    // Setup core libraries and shader cache path.
    Ogre::StringVector groupVector = Ogre::ResourceGroupManager::getSingleton().getResourceGroups();
    Ogre::StringVector::iterator itGroup = groupVector.begin();
    Ogre::StringVector::iterator itGroupEnd = groupVector.end();
    Ogre::String shaderCoreLibsPath;
    Ogre::String shaderCachePath;

    for (; itGroup != itGroupEnd; ++itGroup)
    {
      Ogre::ResourceGroupManager::LocationList resLocationsList = Ogre::ResourceGroupManager::getSingleton().getResourceLocationList(*itGroup);
      Ogre::ResourceGroupManager::LocationList::iterator it = resLocationsList.begin();
      Ogre::ResourceGroupManager::LocationList::iterator itEnd = resLocationsList.end();
      bool coreLibsFound = false;

      // Try to find the location of the core shader lib functions and use it
      // as shader cache path as well - this will reduce the number of generated files
      // when running from different directories.
      for (; it != itEnd; ++it)
      {
        if ((*it)->archive->getName().find("RTShaderLib") != Ogre::String::npos)
        {
          shaderCoreLibsPath = (*it)->archive->getName() + "/";
          shaderCachePath = shaderCoreLibsPath;
          coreLibsFound = true;
          break;
        }
      }
      // Core libs path found in the current group.
      if (coreLibsFound)
        break;
    }

    // Core shader libs not found -> shader generating will fail.
    if (shaderCoreLibsPath.empty())
      return false;

#ifdef _RTSS_WRITE_SHADERS_TO_DISK
    // Set shader cache path.
#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS
    shaderCachePath = Ogre::macCachePath();
#endif
    mShaderGenerator->setShaderCachePath(shaderCachePath);
#endif
    // Create and register the material manager listener.
    mMaterialMgrListener = new ShaderGeneratorTechniqueResolverListener(mShaderGenerator);
    Ogre::MaterialManager::getSingleton().addListener(mMaterialMgrListener);
  }

  return true;
}

//-----------------------------------------------------------------------
void RTShaderSystem::finalizeRTShaderSystem()
{
  // Restore default scheme.
  Ogre::MaterialManager::getSingleton().setActiveScheme(Ogre::MaterialManager::DEFAULT_SCHEME_NAME);

  // Unregister the material manager listener.
  if (mMaterialMgrListener != NULL)
  {
    Ogre::MaterialManager::getSingleton().removeListener(mMaterialMgrListener);
    delete mMaterialMgrListener;
    mMaterialMgrListener = NULL;
  }

  // Finalize RTShader system.
  if (mShaderGenerator != NULL)
  {
    ShaderGenerator::finalize();
    mShaderGenerator = NULL;
  }
}

//-----------------------------------------------------------------------
RTShaderSystem& RTShaderSystem::getSingleton()
{
	assert( msSingleton );
	return ( *msSingleton );
}

//-----------------------------------------------------------------------
RTShaderSystem* RTShaderSystem::getSingletonPtr()
{
	assert( msSingleton );
	return msSingleton;
}

}
}


text:
package hudson.plugins.ec2;

import hudson.Extension;
import hudson.util.FormValidation;

import java.io.IOException;
import java.net.URL;
import java.util.List;

import javax.servlet.ServletException;

import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerResponse;

/**
 * Eucalyptus.
 *
 * @author Kohsuke Kawaguchi
 */
public class Eucalyptus extends EC2Cloud {
    public final URL ec2endpoint;
    public final URL s3endpoint;

    @DataBoundConstructor
    public Eucalyptus(URL ec2endpoint, URL s3endpoint, boolean useInstanceProfileForCredentials, String accessId, String secretKey, String privateKey, String instanceCapStr, List<SlaveTemplate> templates) throws IOException {
        super("eucalyptus", useInstanceProfileForCredentials, accessId, secretKey, privateKey, instanceCapStr, templates);
        this.ec2endpoint = ec2endpoint;
        this.s3endpoint = s3endpoint;
    }

    @Override
    public URL getEc2EndpointUrl() throws IOException {
        return this.ec2endpoint;
    }

    @Override
    public URL getS3EndpointUrl() throws IOException {
        return this.s3endpoint;
    }

    @Extension
    public static class DescriptorImpl extends EC2Cloud.DescriptorImpl {
        @Override
        public String getDisplayName() {
            return "Eucalyptus";
        }

        @Override
        public FormValidation doTestConnection(
                @QueryParameter URL ec2endpoint,
                @QueryParameter boolean useInstanceProfileForCredentials,
                @QueryParameter String accessId,
                @QueryParameter String secretKey,
                @QueryParameter String privateKey) throws IOException, ServletException {
            return super.doTestConnection(ec2endpoint, useInstanceProfileForCredentials, accessId, secretKey, privateKey);
        }

        @Override
        public FormValidation doGenerateKey(
                StaplerResponse rsp, @QueryParameter URL url, @QueryParameter boolean useInstanceProfileForCredentials, @QueryParameter String accessId, @QueryParameter String secretKey) throws IOException, ServletException {
            return super.doGenerateKey(rsp, url, useInstanceProfileForCredentials, accessId, secretKey);
        }
    }
}


text:
package wireless

import (
	"github.com/influxdata/telegraf"
	"github.com/influxdata/telegraf/plugins/inputs"
)

func (w *Wireless) Init() error {
	w.Log.Warn("Current platform is not supported")
	return nil
}

func (w *Wireless) Gather(acc telegraf.Accumulator) error {
	return nil
}

func init() {
	inputs.Add("wireless", func() telegraf.Input {
		return &Wireless{}
	})
}


text:
using System;
using System.Reflection.Emit;
using CodeBuilder.Context;
using CodeBuilder.Helpers;

namespace CodeBuilder.Expressions
{
    public class NegateExpression : Expression
    {
        private static readonly Type[] _intTypes = new[] { typeof(byte), typeof(sbyte), typeof(short), typeof(ushort), typeof(int), typeof(char) };
        private static readonly Type[] _preserveTypes = new[] { typeof(long), typeof(double), typeof(float) };
        private readonly Expression _value;

        public NegateExpression(Expression value)
            : base(DetermineResultType(Validators.NullCheck(value, "value")))
        {
            _value = value;
        }

        private static Type DetermineResultType(Expression value)
        {
            Validators.NumericPrimitiveCheck(value.ExpressionType, "value");

            foreach (var type in _intTypes)
                if (type == value.ExpressionType)
                    return typeof(int);

            foreach (var type in _preserveTypes)
                if (type == value.ExpressionType)
                    return value.ExpressionType;

            throw new ArgumentException(string.Format("Unsupported operation for type {0}. Please try to cast them first to type allowing negation without overflow.", value.ExpressionType), "value");
        }

        internal override void Compile(IBuildContext ctx, int expressionId)
        {
            ctx.Compile(_value);
            ctx.MarkSequencePointFor(expressionId);
            ctx.Generator.Emit(OpCodes.Neg);
        }

        internal override CodeBlock WriteDebugCode(IMethodSymbolGenerator symbolGenerator)
        {
            return symbolGenerator.GetCurrentPosition().BlockTo(symbolGenerator.Write("-").Write(_value).GetCurrentPosition());
        }
    }
}


text:
PatternSpotter::PatternSpotter(Template const& ref, SpotterParams const& p):
	mTime(0),
	mLabel(ref.label),
	M(ref.nSamples),
	dMin(INFINITY),
	ts(kINVALID),
	te(kINVALID),
	mSameClassMeansOptimal(false),
	mReportCriteria(p.reportCriteria)
{
	refData = new data_t[M];
	array_copy(&ref.data[0], refData, M);
}

PatternSpotter::PatternSpotter(const PatternSpotter& other):
	mTime(other.mTime),
	mLabel(other.mLabel),
	M(other.M),
	dMin(other.dMin),
	ts(other.ts),
	te(other.te),
	mSameClassMeansOptimal(other.mSameClassMeansOptimal),
	mReportCriteria(other.mReportCriteria)
{
	refData = new data_t[M];
	array_copy(other.refData, refData, M);
}

//PatternSpotter& PatternSpotter::operator=(const PatternSpotter& other) {
//	if (this == &other) return *this;
//
//	if (M != other.M) {
//		refData = (data_t *)realloc(refData, other.M*sizeof(data_t));
//	}
//	array_copy(other.refData, refData, other.M);
//
//	mLabel = other.mLabel;
//	M = other.M;
//	nDims = other.nDims;
//	dMin = other.dMin;
//	ts = other.ts;
//	te = other.te;
//	mDistCalls = other.mDistCalls;
//	return *this;
//}

//void swap(PatternSpotter& first, PatternSpotter& second) {
//	using std::swap;
//
//	swap(
//}

PatternSpotter::~PatternSpotter() {
	delete [] refData;
}

PatternSpotter* createPatternSpotter(Template const& seq, SpotterParams const& params) {
	PatternSpotter *ps;

	//TODO have all the constructors take in a SpotterParams so we can avoid
	// 1) constructing and *then* giving them the right values
	// 2) duplicating the reportCriteria code in each case

	SpotterParams p = params;

	switch(p.spotType) {
		case EDW_OPTIMAL:
			p.reportCriteria = CAUTIOUS;	//TODO should be OPTIMAL
			ps = new EuclideanSpotter(seq, p);
			break;
		case EDW_AGGRESSIVE:
			p.reportCriteria = AGGRESSIVE;
			ps = new EuclideanSpotter(seq, p);
			break;
		case DDW_OPTIMAL:
			p.reportCriteria = CAUTIOUS;	//TODO should be OPTIMAL
			ps = new DDWSpotter(seq, p);
			break;
		case DDW_AGGRESSIVE:
			p.reportCriteria = AGGRESSIVE;
			ps = new DDWSpotter(seq, p);
			break;
		case ED_AGGRESSIVE:
			p.reportCriteria = AGGRESSIVE;
			ps = new EuclideanSearcher(seq, p);
			break;
		case ED_CAUTIOUS:
			p.reportCriteria = CAUTIOUS;
			ps = new EuclideanSearcher(seq, p);
			break;
		case DTW_AGGRESSIVE:
			p.reportCriteria = AGGRESSIVE;
			ps = new DtwSearcher(seq, p);
			break;
		case DTW_CAUTIOUS:
			p.reportCriteria = CAUTIOUS;
			ps = new DtwSearcher(seq, p);
			break;
		case US_AGGRESSIVE:
			p.reportCriteria = AGGRESSIVE;
			ps = new USEuclideanSearcher(seq, p);
			break;
		case US_CAUTIOUS:
			p.reportCriteria = CAUTIOUS;
			ps = new USEuclideanSearcher(seq, p);
			break;
		case SWM_AGGRESSIVE:
			p.reportCriteria = AGGRESSIVE;
			ps = new SwmSearcher(seq, p);
			break;
		case SWM_CAUTIOUS:
			p.reportCriteria = CAUTIOUS;
			ps = new SwmSearcher(seq, p);
			break;
		case SPRING_OPTIMAL:
			p.reportCriteria = OPTIMAL;
			ps = new SpringSpotter(seq, p);
			break;
		case SPRING_AGGRESSIVE:
			p.reportCriteria = AGGRESSIVE;
			ps = new SpringSpotter(seq, p);
			break;
		default:
			printf("ERROR: SignalMonitor: invalid SpotType; not adding Template\n");
			return nullptr;
	}

	return ps;
}


text:
package com.yogee.zhebuy.modules.ebuy.entity;

import org.hibernate.validator.constraints.Length;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonFormat;

import com.yogee.zhebuy.common.persistence.EbuyEntity;

/**
 * 平台发放消息用户关系表Entity
 * @author sunye
 * @version 2017-09-08
 */
public class EbuyMessageUser extends EbuyEntity<EbuyMessageUser> {

	private static final long serialVersionUID = 1L;
	private String messageId;		// 消息Id
	private String businessId;		// 消息接收人id

	public EbuyMessageUser() {
		super();
	}

	public EbuyMessageUser(String id){
		super(id);
	}

	@Length(min=0, max=128, message="消息Id长度必须介于 0 和 128 之间")
	public String getMessageId() {
		return messageId;
	}

	public void setMessageId(String messageId) {
		this.messageId = messageId;
	}

	public String getBusinessId() {
		return businessId;
	}

	public void setBusinessId(String businessId) {
		this.businessId = businessId;
	}

}


text:
package tr.com.muzo.entity;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;

import org.hibernate.annotations.Type;

@Entity
@Table(name="KULLANICI" , schema="MUZO")
public class Kullanici implements Serializable{

	private static final long serialVersionUID = -7066603469390149854L;

	private Long kullaniciId;
	private String kullaniciAdi;
	private String sifre;
	private Boolean aktif;

	@Id
	@Column(name="KULLANICI_ID")
	@GeneratedValue(generator="S_KULLANICI" , strategy=GenerationType.SEQUENCE)
	@SequenceGenerator(name="S_KULLANICI" , schema="MUZO" , sequenceName="S_KULLANICI")
	public Long getKullaniciId() {
		return kullaniciId;
	}
	public void setKullaniciId(Long kullaniciId) {
		this.kullaniciId = kullaniciId;
	}

	@Column(name="KULLANICI_ADI")
	public String getKullaniciAdi() {
		return kullaniciAdi;
	}
	public void setKullaniciAdi(String kullaniciAdi) {
		this.kullaniciAdi = kullaniciAdi;
	}

	@Column(name="SIFRE")
	public String getSifre() {
		return sifre;
	}
	public void setSifre(String sifre) {
		this.sifre = sifre;
	}

	@Type(type="numeric_boolean")
	@Column(name="AKTIF")
	public Boolean getAktif() {
		return aktif;
	}
	public void setAktif(Boolean aktif) {
		this.aktif = aktif;
	}

}


text:
package app.location;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(value = "/api/locations")
public class LocationController {

    private LocationService locationService;

    @Autowired
    public void setLocationService(LocationService locationService) {
        this.locationService = locationService;
    }

    @RequestMapping(method = RequestMethod.GET)
    public Iterable<Location> findAll() {
        return locationService.findAll();
    }
}