text:
// These are weird things we need to do to get this compiling on
// random systems (and on SWIG).

#ifndef BASE_PORT_H_
#define BASE_PORT_H_

#include <limits.h>         // So we can set the bounds of our types
#include <string.h>         // for memcpy()
#include <stdlib.h>         // for free()

#if defined(OS_MACOSX)
#include <unistd.h>         // for getpagesize() on mac
#elif defined(OS_CYGWIN) || defined(OS_NACL)
#include <malloc.h>         // for memalign()
#endif

#include "base/integral_types.h"

// Must happens before inttypes.h inclusion */
#if defined(OS_MACOSX)
/* From MacOSX's inttypes.h:
 * "C++ implementations should define these macros only when
 *  __STDC_FORMAT_MACROS is defined before <inttypes.h> is included." */
#ifndef __STDC_FORMAT_MACROS
#define __STDC_FORMAT_MACROS
#endif  /* __STDC_FORMAT_MACROS */
#endif  /* OS_MACOSX */

/* Default for most OSes */
/* We use SIGPWR since that seems unlikely to be used for other reasons. */
#define GOOGLE_OBSCURE_SIGNAL  SIGPWR

#if defined OS_LINUX || defined OS_CYGWIN || defined __ANDROID__

// _BIG_ENDIAN
#include <endian.h>

// The uint mess:
// mysql.h sets _GNU_SOURCE which sets __USE_MISC in <features.h>
// sys/types.h typedefs uint if __USE_MISC
// mysql typedefs uint if HAVE_UINT not set
// The following typedef is carefully considered, and should not cause
//  any clashes
#if !defined(__USE_MISC)
#if !defined(HAVE_UINT)
#define HAVE_UINT 1
typedef unsigned int uint;
#endif
#if !defined(HAVE_USHORT)
#define HAVE_USHORT 1
typedef unsigned short ushort;
#endif
#if !defined(HAVE_ULONG)
#define HAVE_ULONG 1
typedef unsigned long ulong;
#endif
#endif

#if defined(__cplusplus)
#include <cstddef>              // For _GLIBCXX macros
#endif

#if !defined(HAVE_TLS) && defined(_GLIBCXX_HAVE_TLS) && defined(ARCH_K8)
#define HAVE_TLS 1
#endif

// using namespace std so we can compile google3 codes
namespace std {} // Avoid error if we didn't see std
using namespace std;

#elif defined OS_FREEBSD

// _BIG_ENDIAN
#include <machine/endian.h>

#elif defined OS_SOLARIS

// _BIG_ENDIAN
#include <sys/isa_defs.h>

// Solaris doesn't define sig_t (function taking an int, returning void)
typedef void (*sig_t)(int);

// Solaris only defines strtoll, not strtoq
#define strtoq  strtoll
#define strtouq strtoull

// It doesn't define the posix-standard(?) u_int_16
#include <sys/int_types.h>
typedef uint16_t u_int16_t;

#elif defined OS_MACOSX

#if !defined(HAVE_UINT)
#define HAVE_UINT 1
typedef unsigned int uint;
#endif
#if !defined(HAVE_USHORT)
#define HAVE_USHORT 1
typedef unsigned short ushort;
#endif
#if !defined(HAVE_ULONG)
#define HAVE_ULONG 1
typedef unsigned long ulong;
#endif

#endif  // OS_MACOSX

#if defined(OS_MACOSX) || defined(OS_NACL)
// BIG_ENDIAN
#include <machine/endian.h>
/* Let's try and follow the Linux convention */
#define __BYTE_ORDER  BYTE_ORDER
#define __LITTLE_ENDIAN LITTLE_ENDIAN
#define __BIG_ENDIAN BIG_ENDIAN
#endif  // OS_MACOSX || OS_NACL

// The following guarenty declaration of the byte swap functions, and
// define __BYTE_ORDER for MSVC
#ifdef COMPILER_MSVC
#include <stdlib.h>
#define __BYTE_ORDER __LITTLE_ENDIAN
#define bswap_16(x) _byteswap_ushort(x)
#define bswap_32(x) _byteswap_ulong(x)
#define bswap_64(x) _byteswap_uint64(x)

#elif defined(OS_MACOSX)
// Mac OS X / Darwin features
#include <libkern/OSByteOrder.h>
#define bswap_16(x) OSSwapInt16(x)
#define bswap_32(x) OSSwapInt32(x)
#define bswap_64(x) OSSwapInt64(x)

#elif defined(OS_NACL)
#include "i18n/input/engine/stubs/nacl/newlib_port/byteswap.h"
#define bswap_16(x) i18n_input::engine::stubs::byteswap_16(x)
#define bswap_32(x) i18n_input::engine::stubs::byteswap_32(x)
#define bswap_64(x) i18n_input::engine::stubs::byteswap_64(x)
#define __bswap_constant_16(x) bswap_16(x)
#define __bswap_constant_32(x) bswap_32(x)
#define __bswap_constant_64(x) bswap_64(x)

#else
#include <byteswap.h>  // IWYU pragma: export
#endif

// define the macros IS_LITTLE_ENDIAN or IS_BIG_ENDIAN
// using the above endian defintions from endian.h if
// endian.h was included
#ifdef __BYTE_ORDER
#if __BYTE_ORDER == __LITTLE_ENDIAN
#define IS_LITTLE_ENDIAN
#endif

#if __BYTE_ORDER == __BIG_ENDIAN
#define IS_BIG_ENDIAN
#endif

#else

#if defined(__LITTLE_ENDIAN__)
#define IS_LITTLE_ENDIAN
#elif defined(__BIG_ENDIAN__)
#define IS_BIG_ENDIAN
#endif

// there is also PDP endian ...

#endif  // __BYTE_ORDER

// Define the OS's path separator
#ifdef __cplusplus  // C won't merge duplicate const variables at link time
// Some headers provide a macro for this (GCC's system.h), remove it so that we
// can use our own.
#undef PATH_SEPARATOR
#if OS_WINDOWS
const char PATH_SEPARATOR = '\\';
#else
const char PATH_SEPARATOR = '/';
#endif
#endif

// Windows has O_BINARY as a flag to open() (like "b" for fopen).
// Linux doesn't need make this distinction.
#if defined OS_LINUX && !defined O_BINARY
#define O_BINARY 0
#endif

// va_copy portability definitions
#if defined(COMPILER_MSVC) && !defined(va_copy)
// MSVC doesn't have va_copy yet.
// This is believed to work for 32-bit msvc.  This may not work at all for
// other platforms.
// If va_list uses the single-element-array trick, you will probably get
// a compiler error here.
//
#include <stdarg.h>
inline void va_copy(va_list& a, va_list& b) {
  a = b;
}

// Nor does it have uid_t
typedef int uid_t;

#endif

// Mac OS X / Darwin features

#if defined(OS_MACOSX)

#include <errno.h>

// For mmap, Linux defines both MAP_ANONYMOUS and MAP_ANON and says MAP_ANON is
// deprecated. In Darwin, MAP_ANON is all there is.
#if !defined MAP_ANONYMOUS
#define MAP_ANONYMOUS MAP_ANON
#endif

// Linux has this in <sys/cdefs.h>
#define __ptr_t void *

// Linux has this in <linux/errno.h>
#define EXFULL      ENOMEM  // not really that great a translation...

// Mach-O supports sections (albeit with small names), but doesn't have
// vars at the beginning and end.  Instead you should call the function
// getsectdata("__DATA", name, &size).
#define HAVE_ATTRIBUTE_SECTION 1

// Any function with ATTRIBUTE_SECTION must not be inlined, or it will
// be placed into whatever section its caller is placed into.
#define ATTRIBUTE_SECTION(name) \
  __attribute__ ((section ("__DATA, " #name))) __attribute__ ((noinline))

#define ENUM_DYLD_BOOL  // so that we don't pollute the global namespace
extern "C" {
  #include <mach-o/getsect.h>
  #include <mach-o/dyld.h>
}
class AssignAttributeStartEnd {
 public:
  AssignAttributeStartEnd(const char* name, char** pstart, char** pend) {
    // Find out what dynamic library name is defined in
    for (int i = _dyld_image_count() - 1; i >= 0; --i) {
      const mach_header* hdr = _dyld_get_image_header(i);
      uint32_t len;
      *pstart = getsectdatafromheader(hdr, "__DATA", name, &len);
      if (*pstart) {   // NULL if not defined in this dynamic library
        *pstart += _dyld_get_image_vmaddr_slide(i);   // correct for reloc
        *pend = *pstart + len;
        return;
      }
    }
    // If we get here, not defined in a dll at all.  See if defined statically.
    unsigned long len;    // don't ask me why this type isn't uint32_t too...
    *pstart = getsectdata("__DATA", name, &len);
    *pend = *pstart + len;
  }
};

// 1) DEFINE_ATTRIBUTE_SECTION_VARS: must be called once per unique
//    name.  You want to make sure this is executed before any
//    DECLARE_ATTRIBUTE_SECTION_VARS; the easiest way is to put them
//    in the same .cc file.  Put this call at the global level.
// 2) INIT_ATTRIBUTE_SECTION_VARS: you can scatter calls to this in
//    multiple places to help ensure execution before any
//    DECLARE_ATTRIBUTE_SECTION_VARS.  You must have at least one
//    DEFINE, but you can have many INITs.  Put each in its own scope.
// 3) DECLARE_ATTRIBUTE_SECTION_VARS: must be called before using
//    ATTRIBUTE_SECTION_START or ATTRIBUTE_SECTION_STOP on a name.
//    Put this call at the global level.
#define DECLARE_ATTRIBUTE_SECTION_VARS(name) \
  extern char* __start_##name; \
  extern char* __stop_##name;

#define INIT_ATTRIBUTE_SECTION_VARS(name)               \
  DECLARE_ATTRIBUTE_SECTION_VARS(name);                 \
  static const AssignAttributeStartEnd __assign_##name( \
    #name, &__start_##name, &__stop_##name)

#define DEFINE_ATTRIBUTE_SECTION_VARS(name)             \
  char* __start_##name, *__stop_##name;                 \
  INIT_ATTRIBUTE_SECTION_VARS(name)

// Darwin doesn't have strnlen. No comment.
inline size_t strnlen(const char *s, size_t maxlen) {
  const char* end = (const char *)memchr(s, '\0', maxlen);
  if (end)
    return end - s;
  return maxlen;
}

namespace std {}  // Avoid error if we didn't see std.
using namespace std;  // Just like VC++, we need a using here.

// Doesn't exist on OSX; used in google.cc for send() to mean "no flags".
#define MSG_NOSIGNAL 0

// No SIGPWR on MacOSX.  SIGINFO seems suitably obscure.
#undef GOOGLE_OBSCURE_SIGNAL
#define GOOGLE_OBSCURE_SIGNAL  SIGINFO

#elif defined(OS_CYGWIN)  // Cygwin-specific behavior.

#if defined(__CYGWIN32__)
#define __WORDSIZE 32
#else
// It's probably possible to support 64-bit, but the #defines will need checked.
#error "Cygwin is currently only 32-bit."
#endif

// No signalling on Windows.
#undef GOOGLE_OBSCURE_SIGNAL
#define GOOGLE_OBSCURE_SIGNAL 0

struct stack_t {
  void* ss_sp;
  int ss_flags;
  size_t ss_size;
};
inline int sigaltstack(stack_t* ss, stack_t* oss) { return 0; }

#define PTHREAD_STACK_MIN 0  // Not provided by cygwin

// Scans memory for a character.
// memrchr is used in a few places, but it's linux-specific.
inline void* memrchr(const void* bytes, int find_char, size_t len) {
  const unsigned char* cursor =
      reinterpret_cast<const unsigned char*>(bytes) + len - 1;
  unsigned char actual_char = find_char;
  for (; cursor >= bytes; --cursor) {
    if (*cursor == actual_char) {
      return const_cast<void*>(reinterpret_cast<const void*>(cursor));
    }
  }
  return NULL;
}

#endif

// Klocwork static analysis tool's C/C++ complier kwcc
#if defined(__KLOCWORK__)
#define STATIC_ANALYSIS
#endif // __KLOCWORK__

// GCC-specific features

#if (defined(COMPILER_GCC3) || defined(COMPILER_ICC) || \
     defined(OS_MACOSX) || defined(__ANDROID__)) && !defined(SWIG)

//
// Tell the compiler to do printf format string checking if the
// compiler supports it; see the 'format' attribute in
// <http://gcc.gnu.org/onlinedocs/gcc-4.3.0/gcc/Function-Attributes.html>.
//
// N.B.: As the GCC manual states, "[s]ince non-static C++ methods
// have an implicit 'this' argument, the arguments of such methods
// should be counted from two, not one."
//

#if defined(__clang__)
// Clang sucks anyway
#define PRINTF_ATTRIBUTE(string_index, first_to_check)
#define SCANF_ATTRIBUTE(string_index, first_to_check)
#else
#define PRINTF_ATTRIBUTE(string_index, first_to_check) \
    __attribute__((__format__ (__printf__, string_index, first_to_check)))
#define SCANF_ATTRIBUTE(string_index, first_to_check) \
    __attribute__((__format__ (__scanf__, string_index, first_to_check)))
#endif

//
// Prevent the compiler from padding a structure to natural alignment
//
#define PACKED __attribute__ ((packed))

// Cache line alignment
#if defined(__i386__) || defined(__x86_64__)
#define CACHELINE_SIZE 64
#define CACHELINE_ALIGNED __attribute__((aligned(CACHELINE_SIZE)))
#elif defined(__arm__)
// Cache line sizes for ARM: These values are not strictly correct since
// cache line sizes depend on implementations, not architectures.  There
// are even implementations with cache line sizes configurable at boot
// time.
#if defined(__ARM_ARCH_5T__)
#define CACHELINE_SIZE 32
#elif defined(__ARM_ARCH_7A__)
#define CACHELINE_SIZE 64
#endif
#define CACHELINE_ALIGNED
#else
#define CACHELINE_ALIGNED
#endif

//
// Prevent the compiler from complaining about or optimizing away variables
// that appear unused
// (careful, others e.g. third_party/libxml/xmlversion.h also define this)
#undef ATTRIBUTE_UNUSED
#define ATTRIBUTE_UNUSED __attribute__ ((unused))

//
// For functions we want to force inline or not inline.
// Introduced in gcc 3.1.
#define ATTRIBUTE_ALWAYS_INLINE  __attribute__ ((always_inline))
#define HAVE_ATTRIBUTE_ALWAYS_INLINE 1
#define ATTRIBUTE_NOINLINE __attribute__ ((noinline))
#define HAVE_ATTRIBUTE_NOINLINE 1

// For weak functions
#undef ATTRIBUTE_WEAK
#define ATTRIBUTE_WEAK __attribute__ ((weak))
#define HAVE_ATTRIBUTE_WEAK 1

// Tell the compiler to use "initial-exec" mode for a thread-local variable.
// See http://people.redhat.com/drepper/tls.pdf for the gory details.
#define ATTRIBUTE_INITIAL_EXEC __attribute__ ((tls_model ("initial-exec")))

//
// Tell the compiler that some function parameters should be non-null pointers.
// Note: As the GCC manual states, "[s]ince non-static C++ methods
// have an implicit 'this' argument, the arguments of such methods
// should be counted from two, not one."
//
#define ATTRIBUTE_NONNULL(arg_index) __attribute__((nonnull(arg_index)))

//
// Tell the compiler that a given function never returns
//
#define ATTRIBUTE_NORETURN __attribute__((noreturn))

#ifndef HAVE_ATTRIBUTE_SECTION  // may have been pre-set to 0, e.g. for Darwin
#define HAVE_ATTRIBUTE_SECTION 1
#endif

#if HAVE_ATTRIBUTE_SECTION  // define section support for the case of GCC

//
// Tell the compiler/linker to put a given function into a section and define
// "__start_ ## name" and "__stop_ ## name" symbols to bracket the section.
// Sections can not span more than none compilation unit.
// This functionality is supported by GNU linker.
// Any function with ATTRIBUTE_SECTION must not be inlined, or it will
// be placed into whatever section its caller is placed into.
//
#ifndef ATTRIBUTE_SECTION
#define ATTRIBUTE_SECTION(name) \
  __attribute__ ((section (#name))) __attribute__ ((noinline))
#endif

//
// Weak section declaration to be used as a global declaration
// for ATTRIBUTE_SECTION_START|STOP(name) to compile and link
// even without functions with ATTRIBUTE_SECTION(name).
// DEFINE_ATTRIBUTE_SECTION should be in the exactly one file; it's
// a no-op on ELF but not on Mach-O.
//
#ifndef DECLARE_ATTRIBUTE_SECTION_VARS
#define DECLARE_ATTRIBUTE_SECTION_VARS(name) \
  extern char __start_##name[] ATTRIBUTE_WEAK; \
  extern char __stop_##name[] ATTRIBUTE_WEAK
#endif
#ifndef DEFINE_ATTRIBUTE_SECTION_VARS
#define INIT_ATTRIBUTE_SECTION_VARS(name)
#define DEFINE_ATTRIBUTE_SECTION_VARS(name)
#endif

//
// Return void* pointers to start/end of a section of code with
// functions having ATTRIBUTE_SECTION(name).
// Returns 0 if no such functions exits.
// One must DECLARE_ATTRIBUTE_SECTION_VARS(name) for this to compile and link.
//
#define ATTRIBUTE_SECTION_START(name) (reinterpret_cast<void*>(__start_##name))
#define ATTRIBUTE_SECTION_STOP(name) (reinterpret_cast<void*>(__stop_##name))

#endif  // HAVE_ATTRIBUTE_SECTION

// Support for aligning the stack on 32-bit x86.  See http://b/issue?id=798841
//
// The legacy prod71 libc does not provide the stack alignment required for use
// of SSE intrinsics.  In order to properly use the intrinsics you need to use
// a trampoline function which aligns the stack prior to calling your code,
// or as of crosstool v10 with gcc 4.2.0 there is an attribute which asks
// gcc to do this for you.
//
// It has also been discovered that crosstool up to and including v10 does not
// provide proper alignment for pthread_once() functions in x86-64 code either.
// Unfortunately gcc does not provide force_align_arg_pointer as an option in
// x86-64 code, so this requires us to always have a trampoline.
//
// For an example of using this see util/hash/adler32*

#if defined(__i386__) && \
  (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 2))
#define ATTRIBUTE_STACK_ALIGN_FOR_OLD_LIBC \
  __attribute__((force_align_arg_pointer))
#define REQUIRE_STACK_ALIGN_TRAMPOLINE (0)
#elif defined(__i386__) || defined(__x86_64__)
#define REQUIRE_STACK_ALIGN_TRAMPOLINE (1)
#define ATTRIBUTE_STACK_ALIGN_FOR_OLD_LIBC
#else
#define REQUIRE_STACK_ALIGN_TRAMPOLINE (0)
#define ATTRIBUTE_STACK_ALIGN_FOR_OLD_LIBC
#endif

//
// Tell the compiler to warn about unused return values for functions declared
// with this macro.  The macro should be used on function declarations
// following the argument list:
//
//   Sprocket* AllocateSprocket() MUST_USE_RESULT;
//
#undef MUST_USE_RESULT
#if (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) \
  && !defined(COMPILER_ICC)
#define MUST_USE_RESULT __attribute__ ((warn_unused_result))
#else
#define MUST_USE_RESULT
#endif

#if (defined(COMPILER_ICC) || defined(COMPILER_GCC3) || defined(__llvm__))
// Defined behavior on some of the uarchs:
// PREFETCH_HINT_T0:
//   prefetch to all levels of the hierarchy (except on p4: prefetch to L2)
// PREFETCH_HINT_NTA:
//   p4: fetch to L2, but limit to 1 way (out of the 8 ways)
//   core: skip L2, go directly to L1
//   k8 rev E and later: skip L2, can go to either of the 2-ways in L1
enum PrefetchHint {
  PREFETCH_HINT_T0 = 3,  // More temporal locality
  PREFETCH_HINT_T1 = 2,
  PREFETCH_HINT_T2 = 1,  // Less temporal locality
  PREFETCH_HINT_NTA = 0  // No temporal locality
};
#else
// prefetch is a no-op for this target. Feel free to add more sections above.
#endif

extern inline void prefetch(const char *x, int hint) {
#if defined(COMPILER_ICC) || defined(__llvm__)
  // In the gcc version of prefetch(), hint is only a constant _after_ inlining
  // (assumed to have been successful).  icc views things differently, and
  // checks constant-ness _before_ inlining.  This leads to compilation errors
  // with the gcc version in icc.
  //
  // One way round this is to use a switch statement to explicitly match
  // prefetch hint enumerations, and invoke __builtin_prefetch for each valid
  // value.  icc's optimization removes the switch and unused case statements
  // after inlining, so that this boils down in the end to the same as for gcc;
  // that is, a single inlined prefetchX instruction.  Demonstrate by compiling
  // with icc options -xK -O2 and viewing assembly language output.
  //
  // Note that this version of prefetch() cannot verify constant-ness of hint.
  // If client code calls prefetch() with a variable value for hint, it will
  // receive the full expansion of the switch below, perhaps also not inlined.
  // This should however not be a problem in the general case of well behaved
  // caller code that uses the supplied prefetch hint enumerations.
  switch (hint) {
    case PREFETCH_HINT_T0:
      __builtin_prefetch(x, 0, PREFETCH_HINT_T0);
      break;
    case PREFETCH_HINT_T1:
      __builtin_prefetch(x, 0, PREFETCH_HINT_T1);
      break;
    case PREFETCH_HINT_T2:
      __builtin_prefetch(x, 0, PREFETCH_HINT_T2);
      break;
    case PREFETCH_HINT_NTA:
      __builtin_prefetch(x, 0, PREFETCH_HINT_NTA);
      break;
    default:
      __builtin_prefetch(x);
      break;
  }
#elif defined(COMPILER_GCC3)
 #if !defined(ARCH_PIII) || defined(__SSE__)
  if (__builtin_constant_p(hint)) {
    __builtin_prefetch(x, 0, hint);
  } else {
    // Defaults to PREFETCH_HINT_T0
    __builtin_prefetch(x);
  }
#else
  // We want a __builtin_prefetch, but we build with the default -march=i386
  // where __builtin_prefetch quietly turns into nothing.
  // Once we crank up to -march=pentium3 or higher the __SSE__
  // clause above will kick in with the builtin.
  // -- mec 2006-06-06
  if (hint == PREFETCH_HINT_NTA)
    __asm__ __volatile__("prefetchnta (%0)" : : "r"(x));
 #endif
#else
  // You get no effect.  Feel free to add more sections above.
#endif
}

#ifdef __cplusplus
// prefetch intrinsic (bring data to L1 without polluting L2 cache)
extern inline void prefetch(const char *x) {
  return prefetch(x, 0);
}
#endif  // ifdef __cplusplus

//
// GCC can be told that a certain branch is not likely to be taken (for
// instance, a CHECK failure), and use that information in static analysis.
// Giving it this information can help it optimize for the common case in
// the absence of better information (ie. -fprofile-arcs).
//
#if defined(COMPILER_GCC3)
#define PREDICT_FALSE(x) (__builtin_expect(x, 0))
#define PREDICT_TRUE(x) (__builtin_expect(!!(x), 1))
#else
#define PREDICT_FALSE(x) x
#define PREDICT_TRUE(x) x
#endif

#define FTELLO ftello
#define FSEEKO fseeko

#if !defined(__cplusplus) && !defined(OS_MACOSX) && !defined(OS_CYGWIN) && \
    !defined(__ANDROID__)
// stdlib.h only declares this in C++, not in C, so we declare it here.
// Also make sure to avoid declaring it on platforms which don't support it.
extern int posix_memalign(void **memptr, size_t alignment, size_t size);
#endif

inline void *aligned_malloc(size_t size, int minimum_alignment) {
#if defined(OS_MACOSX)
  // mac lacks memalign(), posix_memalign(), however, according to
  // http://stackoverflow.com/questions/196329/osx-lacks-memalign
  // mac allocs are already 16-byte aligned.
  if (minimum_alignment <= 16)
    return malloc(size);
  // next, try to return page-aligned memory. perhaps overkill
  if (minimum_alignment <= getpagesize())
    return valloc(size);
  // give up
  return NULL;
#elif defined(OS_CYGWIN) || defined(__ANDROID__) || defined(OS_NACL)
  return memalign(minimum_alignment, size);
#else  // !OS_MACOSX && !OS_CYGWIN
  void *ptr = NULL;
  if (posix_memalign(&ptr, minimum_alignment, size) != 0)
    return NULL;
  else
    return ptr;
#endif
}

inline void aligned_free(void *aligned_memory) {
  free(aligned_memory);
}

#else   // not GCC

#define PRINTF_ATTRIBUTE(string_index, first_to_check)
#define SCANF_ATTRIBUTE(string_index, first_to_check)
#define PACKED
#define CACHELINE_ALIGNED
#define ATTRIBUTE_UNUSED
#define ATTRIBUTE_ALWAYS_INLINE
#define ATTRIBUTE_NOINLINE
#define ATTRIBUTE_WEAK
#define HAVE_ATTRIBUTE_WEAK 0
#define ATTRIBUTE_INITIAL_EXEC
#define ATTRIBUTE_NONNULL(arg_index)
#define ATTRIBUTE_NORETURN
#define HAVE_ATTRIBUTE_SECTION 0
#define ATTRIBUTE_STACK_ALIGN_FOR_OLD_LIBC
#define REQUIRE_STACK_ALIGN_TRAMPOLINE (0)
#define MUST_USE_RESULT
extern inline void prefetch(const char *x) {}
#define PREDICT_FALSE(x) x
#define PREDICT_TRUE(x) x

// These should be redefined appropriately if better alternatives to
// ftell/fseek exist in the compiler
#define FTELLO ftell
#define FSEEKO fseek

#endif  // GCC

//
// Provides a char array with the exact same alignment as another type. The
// first parameter must be a complete type, the second parameter is how many
// of that type to provide space for.
//
//   ALIGNED_CHAR_ARRAY(struct stat, 16) storage_;
//
#if defined(__cplusplus)
#undef ALIGNED_CHAR_ARRAY
// Because MSVC and older GCCs require that the argument to their alignment
// construct to be a literal constant integer, we use a template instantiated
// at all the possible powers of two.
#ifndef SWIG
template<int alignment, int size> struct AlignType { };
template<int size> struct AlignType<0, size> { typedef char result[size]; };
#if defined(COMPILER_MSVC)
#define BASE_PORT_H_ALIGN_ATTRIBUTE(X) __declspec(align(X))
#define BASE_PORT_H_ALIGN_OF(T) __alignof(T)
#elif defined(COMPILER_GCC3) || defined(COMPILER_ICC)
#define BASE_PORT_H_ALIGN_ATTRIBUTE(X) __attribute__((aligned(X)))
#define BASE_PORT_H_ALIGN_OF(T) __alignof__(T)
#endif

#if defined(BASE_PORT_H_ALIGN_ATTRIBUTE)

#define BASE_PORT_H_ALIGNTYPE_TEMPLATE(X) \
  template<int size> struct AlignType<X, size> { \
    typedef BASE_PORT_H_ALIGN_ATTRIBUTE(X) char result[size]; \
  }

BASE_PORT_H_ALIGNTYPE_TEMPLATE(1);
BASE_PORT_H_ALIGNTYPE_TEMPLATE(2);
BASE_PORT_H_ALIGNTYPE_TEMPLATE(4);
BASE_PORT_H_ALIGNTYPE_TEMPLATE(8);
BASE_PORT_H_ALIGNTYPE_TEMPLATE(16);
BASE_PORT_H_ALIGNTYPE_TEMPLATE(32);
BASE_PORT_H_ALIGNTYPE_TEMPLATE(64);
BASE_PORT_H_ALIGNTYPE_TEMPLATE(128);
BASE_PORT_H_ALIGNTYPE_TEMPLATE(256);
BASE_PORT_H_ALIGNTYPE_TEMPLATE(512);
BASE_PORT_H_ALIGNTYPE_TEMPLATE(1024);
BASE_PORT_H_ALIGNTYPE_TEMPLATE(2048);
BASE_PORT_H_ALIGNTYPE_TEMPLATE(4096);
BASE_PORT_H_ALIGNTYPE_TEMPLATE(8192);
// Any larger and MSVC++ will complain.

#define ALIGNED_CHAR_ARRAY(T, Size) \
  typename AlignType<BASE_PORT_H_ALIGN_OF(T), sizeof(T) * Size>::result

#undef BASE_PORT_H_ALIGNTYPE_TEMPLATE
#undef BASE_PORT_H_ALIGN_ATTRIBUTE

#else  // defined(BASE_PORT_H_ALIGN_ATTRIBUTE)
#define ALIGNED_CHAR_ARRAY \
    you_must_define_ALIGNED_CHAR_ARRAY_for_your_compiler_in_base_port_h
#endif // defined(BASE_PORT_H_ALIGN_ATTRIBUTE)

#else  // !SWIG

// SWIG can't represent alignment and doesn't care about alignment on data
// members (it works fine without it).
template<typename Size>
struct AlignType { typedef char result[Size]; };
#define ALIGNED_CHAR_ARRAY(T, Size) AlignType<Size * sizeof(T)>::result

#endif // !SWIG
#else  // __cpluscplus
#define ALIGNED_CHAR_ARRAY ALIGNED_CHAR_ARRAY_is_not_available_without_Cplusplus
#endif // __cplusplus

#if !HAVE_ATTRIBUTE_SECTION  // provide dummy definitions

#define ATTRIBUTE_SECTION(name)
#define INIT_ATTRIBUTE_SECTION_VARS(name)
#define DEFINE_ATTRIBUTE_SECTION_VARS(name)
#define DECLARE_ATTRIBUTE_SECTION_VARS(name)
#define ATTRIBUTE_SECTION_START(name) (reinterpret_cast<void*>(0))
#define ATTRIBUTE_SECTION_STOP(name) (reinterpret_cast<void*>(0))

#endif  // !HAVE_ATTRIBUTE_SECTION

#ifdef COMPILER_MSVC     /* if Visual C++ */

// This compiler flag can be easily overlooked on MSVC.
// _CHAR_UNSIGNED gets set with the /J flag.
#ifndef _CHAR_UNSIGNED
#error chars must be unsigned!  Use the /J flag on the compiler command line.
#endif

// MSVC is a little hyper-active in its warnings
// Signed vs. unsigned comparison is ok.
#pragma warning(disable : 4018 )
// We know casting from a long to a char may lose data
#pragma warning(disable : 4244 )
// Don't need performance warnings about converting ints to bools
#pragma warning(disable : 4800 )
// Integral constant overflow is apparently ok too
// for example:
//  short k;  int n;
//  k = k + n;
#pragma warning(disable : 4307 )
// It's ok to use this* in constructor
// Example:
//  class C {
//   Container cont_;
//   C() : cont_(this) { ...
#pragma warning(disable : 4355 )
// Truncating from double to float is ok
#pragma warning(disable : 4305 )

#include <assert.h>
#include <windows.h>
#undef ERROR

#include <float.h>  // for nextafter functionality on windows
#define _USE_MATH_DEFINES
#include <math.h>  // for HUGE_VAL
#ifdef STL_MSVC
inline double log2(double n) {
  return log(n) / log(2.);
}
inline double log(int n) {
  return log(static_cast<double>(n));
}
inline bool isblank(char c) {
  return c == ' ' || c == '\t';
}
#endif  // STL_MSVC

#ifndef HUGE_VALF
#define HUGE_VALF (static_cast<float>(HUGE_VAL))
#endif

namespace std {}  // Avoid error if we didn't see std.
using namespace std;

// VC++ doesn't understand "uint"
#ifndef HAVE_UINT
#define HAVE_UINT 1
typedef unsigned int uint;
#endif  // HAVE_UINT

#ifndef HAVE_USHORT
#define HAVE_USHORT 1
typedef unsigned short ushort;
#endif  // HAVE_USHORT

#ifndef HAVE_ULONG
#define HAVE_ULONG 1
typedef unsigned long ulong;
#endif  // HAVE_ULONG

// VC++ doesn't understand "ssize_t"
// <windows.h> from above includes <BaseTsd.h> and <BaseTsd.h> defines SSIZE_T
#ifndef HAVE_SSIZET
#define HAVE_SSIZET 1
typedef SSIZE_T ssize_t;
#endif  // HAVE_SSIZET

#define strtof(a,b)   stof((a), reinterpret_cast<size_t*>(b))
#define strtoq   _strtoi64
#define strtouq  _strtoui64
#define strtoll  _strtoi64
#define strtoull _strtoui64
#define atoll    _atoi64

// You say tomato, I say atotom
#define PATH_MAX MAX_PATH

// You say tomato, I say _tomato
#if (_MSC_VER < 1600)
#define vsnprintf _vsnprintf
#endif  // _MSC_VER < 1600
#define snprintf _snprintf
#define strcasecmp _stricmp
#define strncasecmp _strnicmp

#define nextafter _nextafter

#define hypot _hypot
#define hypotf _hypotf

#define strdup _strdup
#define tempnam _tempnam
#define chdir  _chdir
#define putenv  _putenv

#undef gmtime_r
#define gmtime_r(x, y) gmtime_s((y), (x))

// You say tomato, I say toma
#define srandom(x) srand(x)

// You say juxtapose, I say transpose
#define bcopy(s, d, n) memcpy(d, s, n)

inline void *aligned_malloc(size_t size, int minimum_alignment) {
  return _aligned_malloc(size, minimum_alignment);
}

inline void aligned_free(void *aligned_memory) {
  _aligned_free(aligned_memory);
}

// ----- BEGIN VC++ STUBS & FAKE DEFINITIONS ---------------------------------

// See http://en.wikipedia.org/wiki/IEEE_754 for details of
// floating point format.
#if !defined(COMPILER_MSVC) || _MSC_VER < 1800
enum {
  FP_NAN,  //  is "Not a Number"
  FP_INFINITE,  //  is either plus or minus infinity.
  FP_ZERO,
  FP_SUBNORMAL,  // is too small to be represented in normalized format.
  FP_NORMAL  // if nothing of the above is correct that it must be a
  // normal floating-point number.
};
#endif

inline int fpclassify_double(double x) {
  const int float_point_class =_fpclass(x);
  int c99_class;
  switch  (float_point_class) {
  case _FPCLASS_SNAN:  // Signaling NaN
  case _FPCLASS_QNAN:  // Quiet NaN
    c99_class = FP_NAN;
    break;
  case _FPCLASS_NZ:  // Negative zero ( -0)
  case _FPCLASS_PZ:  // Positive 0 (+0)
    c99_class = FP_ZERO;
    break;
  case _FPCLASS_NINF:  // Negative infinity ( -INF)
  case _FPCLASS_PINF:  // Positive infinity (+INF)
    c99_class = FP_INFINITE;
    break;
  case _FPCLASS_ND:  // Negative denormalized
  case _FPCLASS_PD:  // Positive denormalized
    c99_class = FP_SUBNORMAL;
    break;
  case _FPCLASS_NN:  // Negative normalized non-zero
  case _FPCLASS_PN:  // Positive normalized non-zero
    c99_class = FP_NORMAL;
    break;
  default:
    c99_class = FP_NAN;  // Should never happen
    break;
  }
  return  c99_class;
}

// This function handle the special subnormal case for float; it will
// become a normal number while casting to double.
// bit_cast is avoided to simplify dependency and to create a code that is
// easy to deploy in C code
inline int fpclassify_float(float x) {
  uint32 bitwise_representation;
  memcpy(&bitwise_representation, &x, 4);
  if ((bitwise_representation & 0x7f800000) == 0 &&
      (bitwise_representation & 0x007fffff) != 0)
    return FP_SUBNORMAL;
  return fpclassify_double(x);
}
//
// This define takes care of the denormalized float; the casting to
// double make it a normal number
#define fpclassify(x) \
    ((sizeof(x) == sizeof(float)) ? fpclassify_float(x) : fpclassify_double(x))

#define isnan _isnan
#define isfinite _finite
#if !defined(COMPILER_MSVC) && _MSC_VER < 1700
inline bool signbit(double num) {
  return _copysign(1.0, num) < 0;
}
#endif
inline int isinf(double x) {
  const int float_point_class =_fpclass(x);
  if (float_point_class == _FPCLASS_PINF) return 1;
  if (float_point_class == _FPCLASS_NINF) return -1;
  return 0;
}

// #include "conflict-signal.h"
typedef void (*sig_t)(int);

// These actually belong in errno.h but there's a name confilict in errno
// on WinNT. They (and a ton more) are also found in Winsock2.h, but
// if'd out under NT. We need this subset at minimum.
#define EXFULL      ENOMEM  // not really that great a translation...
// The following are already defined in VS2010.
#if (_MSC_VER < 1600)
#define EWOULDBLOCK WSAEWOULDBLOCK
#ifndef PTHREADS_REDHAT_WIN32
#define ETIMEDOUT   WSAETIMEDOUT
#endif
#define ENOTSOCK    WSAENOTSOCK
#define EINPROGRESS WSAEINPROGRESS
#define ECONNRESET  WSAECONNRESET
#endif

//
// Really from <string.h>
//

inline void bzero(void *s, int n) {
  memset(s, 0, n);
}

// From glob.h
#define __ptr_t   void *

// Defined all over the place.
typedef int pid_t;

// From stat.h
typedef unsigned int mode_t;

// u_int16_t, int16_t don't exist in MSVC
typedef unsigned short u_int16_t;
typedef short int16_t;

// ----- END VC++ STUBS & FAKE DEFINITIONS ----------------------------------

#endif  // COMPILER_MSVC

#ifdef STL_MSVC  // not always the same as COMPILER_MSVC
#include "base/port_hash.h"
#else
struct PortableHashBase { };
#endif

// The SWIGged version of an abstract class must be concrete if any methods
// return objects of the abstract type.
//
// This location is deprecated, the new preferred location is in base/macros.h.
#ifndef SWIG
#define ABSTRACT = 0
#endif

#if defined(OS_WINDOWS) || defined(OS_MACOSX)
// gethostbyname() *is* thread-safe for Windows native threads. It is also
// safe on Mac OS X, where it uses thread-local storage, even though the
// manpages claim otherwise. For details, see
// http://lists.apple.com/archives/Darwin-dev/2006/May/msg00008.html
#else
// gethostbyname() is not thread-safe.  So disallow its use.  People
// should either use the HostLookup::Lookup*() methods, or gethostbyname_r()
#define gethostbyname gethostbyname_is_not_thread_safe_DO_NOT_USE
#endif

// create macros in which the programmer should enclose all specializations
// for hash_maps and hash_sets. This is necessary since these classes are not
// STL standardized. Depending on the STL implementation they are in different
// namespaces. Right now the right namespace is passed by the Makefile
// Examples: gcc3: -DHASH_NAMESPACE=__gnu_cxx
//           icc:  -DHASH_NAMESPACE=std
//           gcc2: empty

#ifndef HASH_NAMESPACE
#  define HASH_NAMESPACE_DECLARATION_START
#  define HASH_NAMESPACE_DECLARATION_END
#else
#  define HASH_NAMESPACE_DECLARATION_START  namespace HASH_NAMESPACE {
#  define HASH_NAMESPACE_DECLARATION_END    }
#endif

// Our STL-like classes use __STD.
#if defined(COMPILER_GCC3) || defined(COMPILER_ICC) || \
    defined(OS_MACOSX) || defined(COMPILER_MSVC)
#define __STD std
#endif

#if defined COMPILER_GCC3 || defined COMPILER_ICC
#define STREAM_SET(s, bit) (s).setstate(ios_base::bit)
#define STREAM_SETF(s, flag) (s).setf(ios_base::flag)
#else
#define STREAM_SET(s, bit) (s).set(ios::bit)
#define STREAM_SETF(s, flag) (s).setf(ios::flag)
#endif

// Portable handling of unaligned loads and stores

#if defined(ARCH_PIII) || defined(ARCH_ATHLON) || \
    defined(ARCH_K8) || defined(_ARCH_PPC)

// x86 and x86-64 can perform unaligned loads/stores directly;
// modern PowerPC hardware can also do unaligned integer loads and stores;
// but note: the FPU still sends unaligned loads and stores to a trap handler!

#define UNALIGNED_LOAD16(_p) (*reinterpret_cast<const uint16 *>(_p))
#define UNALIGNED_LOAD32(_p) (*reinterpret_cast<const uint32 *>(_p))
#define UNALIGNED_LOAD64(_p) (*reinterpret_cast<const uint64 *>(_p))

#define UNALIGNED_STORE16(_p, _val) (*reinterpret_cast<uint16 *>(_p) = (_val))
#define UNALIGNED_STORE32(_p, _val) (*reinterpret_cast<uint32 *>(_p) = (_val))
#define UNALIGNED_STORE64(_p, _val) (*reinterpret_cast<uint64 *>(_p) = (_val))

#else

#define NEED_ALIGNED_LOADS

// These functions are provided for architectures that don't support
// unaligned loads and stores.

inline uint16 UNALIGNED_LOAD16(const void *p) {
  uint16 t;
  memcpy(&t, p, sizeof t);
  return t;
}

inline uint32 UNALIGNED_LOAD32(const void *p) {
  uint32 t;
  memcpy(&t, p, sizeof t);
  return t;
}

inline uint64 UNALIGNED_LOAD64(const void *p) {
  uint64 t;
  memcpy(&t, p, sizeof t);
  return t;
}

inline void UNALIGNED_STORE16(void *p, uint16 v) {
  memcpy(p, &v, sizeof v);
}

inline void UNALIGNED_STORE32(void *p, uint32 v) {
  memcpy(p, &v, sizeof v);
}

inline void UNALIGNED_STORE64(void *p, uint64 v) {
  memcpy(p, &v, sizeof v);
}

#endif

#ifdef _LP64
#define UNALIGNED_LOADW(_p) UNALIGNED_LOAD64(_p)
#define UNALIGNED_STOREW(_p, _val) UNALIGNED_STORE64(_p, _val)
#else
#define UNALIGNED_LOADW(_p) UNALIGNED_LOAD32(_p)
#define UNALIGNED_STOREW(_p, _val) UNALIGNED_STORE32(_p, _val)
#endif

// printf macros for size_t, in the style of inttypes.h
#ifdef _LP64
#define __PRIS_PREFIX "z"
#else
#define __PRIS_PREFIX
#endif

// Use these macros after a % in a printf format string
// to get correct 32/64 bit behavior, like this:
// size_t size = records.size();
// printf("%"PRIuS"\n", size);

#define PRIdS __PRIS_PREFIX "d"
#define PRIxS __PRIS_PREFIX "x"
#define PRIuS __PRIS_PREFIX "u"
#define PRIXS __PRIS_PREFIX "X"
#define PRIoS __PRIS_PREFIX "o"

#define GPRIuPTHREAD "lu"
#define GPRIxPTHREAD "lx"
#ifdef OS_CYGWIN
#define PRINTABLE_PTHREAD(pthreadt) reinterpret_cast<uintptr_t>(pthreadt)
#else
#define PRINTABLE_PTHREAD(pthreadt) pthreadt
#endif

#define SIZEOF_MEMBER(t, f)   sizeof(((t*) 4096)->f)

#define OFFSETOF_MEMBER(t, f)         \
  (reinterpret_cast<char*>(           \
     &reinterpret_cast<t*>(16)->f) -  \
   reinterpret_cast<char*>(16))

#ifdef PTHREADS_REDHAT_WIN32
#include <iosfwd>
#include <pthread.h>
// pthread_t is not a simple integer or pointer on Win32
std::ostream& operator << (std::ostream& out, const pthread_t& thread_id);
#endif

// GXX_EXPERIMENTAL_CXX0X is defined by gcc and clang up to at least
// gcc-4.7 and clang-3.1 (2011-12-13).  __cplusplus was defined to 1
// in gcc before 4.7 (Crosstool 16) and clang before 3.1, but is
// defined according to the language version in effect thereafter.  I
// believe MSVC will also define __cplusplus according to the language
// version, but haven't checked that.
#if defined(__GXX_EXPERIMENTAL_CXX0X__) || __cplusplus >= 201103L
// Define this to 1 if the code is compiled in C++11 mode; leave it
// undefined otherwise.  Do NOT define it to 0 -- that causes
// '#ifdef LANG_CXX11' to behave differently from '#if LANG_CXX11'.
#define LANG_CXX11 1
// TODO(jyasskin): s/LANG_CXX0X/LANG_CXX11/g and remove it.
#define LANG_CXX0X 1
#endif

#if defined(COMPILER_MSVC)
// Cache line alignment
#define CACHELINE_SIZE 64
#endif

#if defined(__ANDROID__)

#include <errno.h>
#include <unistd.h>
namespace std {}  // Avoid error if we didn't see std.
using namespace std;  // Just like VC++, we need a using here.
namespace __gnu_cxx {}  // Avoid error if we didn't see __gnu_cxx.
using namespace __gnu_cxx;
// For weak functions
#undef ATTRIBUTE_WEAK
#define ATTRIBUTE_WEAK __attribute__ ((weak))
#undef HAVE_ATTRIBUTE_WEAK
#define HAVE_ATTRIBUTE_WEAK 1
//
// Log base 2
//
#include <math.h>  // for log2
template <typename T>
inline T log2(const T &v) {
  return log(v) / log(2.0);
}
inline float log(int v) {
  return log(static_cast<float>(v));
}

#define strtoq  strtoll
#define strtouq strtoull

#define FALSE false

// TODO(zkfan): Open these two macros in util/gtl/manual_constructor.h instead.
#define UTIL_GTL_ALIGN_ATTRIBUTE(X) __attribute__((aligned(X)))
#define UTIL_GTL_ALIGN_OF(T) __alignof__(T)

#endif

#if defined(OS_NACL)

#define strtoq  strtoll
#define strtouq strtoull
#define CACHELINE_SIZE 32

namespace std {}  // Avoid error if we didn't see std.
using namespace std;
#endif  // OS_NACL

// Private implementation detail: __has_extension is useful to implement
// static_assert, and defining it for all toolchains avoids an extra level of
// nesting of #if/#ifdef/#ifndef.
#ifndef __has_extension
#define __has_extension(x) 0  // MSVC 10's preprocessor can't handle 'false'.
#endif

#ifdef __cplusplus
// We support C++11's static_assert(expression, message) for all C++
// builds, though for some pre-C++11 toolchains we fall back to using
// GG_PRIVATE_STATIC_ASSERT, which has two limitations: (1) the
// expression argument will need to be parenthesized if it would
// otherwise contain commas outside of parentheses, and (2) the
// message is ignored (though the compiler error will likely mention
// "static_assert_failed" and point to the line with the failing assertion).

#if LANG_CXX11 || __has_extension(cxx_static_assert) || _MSC_VER >= 1600
// There's a native implementation of static_assert, no need to define our own.
// Except that Crosstool V15 blocks use of static_assert, and lacks a warning
// option to permit it, so we fall back to _Static_assert in that case.
// TODO(jdennett): Eliminate this when we no longer need to support compilation
// with Crosstool V15.
#if defined(__clang__)
#if !__has_warning("-Wc++98-compat-static-assert")
#define static_assert _Static_assert
#else
#endif
#endif
#elif __has_extension(c_static_assert)
// C11's _Static_assert is available, and makes a great static_assert.
#define static_assert _Static_assert
#else
// Fall back on our home-grown implementation, with its limitations.
#define static_assert GG_PRIVATE_STATIC_ASSERT
#endif

// CompileAssert is an implementation detail of COMPILE_ASSERT and
// GG_PRIVATE_STATIC_ASSERT.
template <bool>
struct CompileAssert {
};

// GG_PRIVATE_STATIC_ASSERT: A poor man's static_assert.  This doesn't handle
// condition expressions that contain unparenthesized top-level commas;
// write GG_PRIVATE_STATIC_ASSERT((expr), "comment") when needed.
#define GG_PRIVATE_CAT_IMMEDIATE(a, b) a ## b
#define GG_PRIVATE_CAT(a, b) GG_PRIVATE_CAT_IMMEDIATE(a, b)
#define GG_PRIVATE_STATIC_ASSERT(expr, ignored) \
  typedef CompileAssert<(static_cast<bool>(expr))> \
  GG_PRIVATE_CAT(static_assert_failed_at_line, __LINE__)[bool(expr) ? 1 : -1]

#endif  // __cplusplus

#endif  // BASE_PORT_H_

// Modified by: zyb@google.com (Yuanbo Zhang)
//
// These are weird things we need to do to get this compiling on
// random systems (and on SWIG).

#ifndef BASE_PORT_H_
#define BASE_PORT_H_

#include <limits.h>         // So we can set the bounds of our types
#include <string.h>         // for memcpy()
#include <stdlib.h>         // for free()

#if defined(OS_MACOSX)
#include <unistd.h>         // for getpagesize() on mac
#elif defined(OS_CYGWIN) || defined(OS_NACL)
#include <malloc.h>         // for memalign()
#endif

#include "base/integral_types.h"

// Must happens before inttypes.h inclusion */
#if defined(OS_MACOSX)
/* From MacOSX's inttypes.h:
 * "C++ implementations should define these macros only when
 *  __STDC_FORMAT_MACROS is defined before <inttypes.h> is included." */
#ifndef __STDC_FORMAT_MACROS
#define __STDC_FORMAT_MACROS
#endif  /* __STDC_FORMAT_MACROS */
#endif  /* OS_MACOSX */

/* Default for most OSes */
/* We use SIGPWR since that seems unlikely to be used for other reasons. */
#define GOOGLE_OBSCURE_SIGNAL  SIGPWR

#if defined OS_LINUX || defined OS_CYGWIN || defined __ANDROID__

// _BIG_ENDIAN
#include <endian.h>

// The uint mess:
// mysql.h sets _GNU_SOURCE which sets __USE_MISC in <features.h>
// sys/types.h typedefs uint if __USE_MISC
// mysql typedefs uint if HAVE_UINT not set
// The following typedef is carefully considered, and should not cause
//  any clashes
#if !defined(__USE_MISC)
#if !defined(HAVE_UINT)
#define HAVE_UINT 1
typedef unsigned int uint;
#endif
#if !defined(HAVE_USHORT)
#define HAVE_USHORT 1
typedef unsigned short ushort;
#endif
#if !defined(HAVE_ULONG)
#define HAVE_ULONG 1
typedef unsigned long ulong;
#endif
#endif

#if defined(__cplusplus)
#include <cstddef>              // For _GLIBCXX macros
#endif

#if !defined(HAVE_TLS) && defined(_GLIBCXX_HAVE_TLS) && defined(ARCH_K8)
#define HAVE_TLS 1
#endif

// using namespace std so we can compile google3 codes
namespace std {} // Avoid error if we didn't see std
using namespace std;

#elif defined OS_FREEBSD

// _BIG_ENDIAN
#include <machine/endian.h>

#elif defined OS_SOLARIS

// _BIG_ENDIAN
#include <sys/isa_defs.h>

// Solaris doesn't define sig_t (function taking an int, returning void)
typedef void (*sig_t)(int);

// Solaris only defines strtoll, not strtoq
#define strtoq  strtoll
#define strtouq strtoull

// It doesn't define the posix-standard(?) u_int_16
#include <sys/int_types.h>
typedef uint16_t u_int16_t;

#elif defined OS_MACOSX

#if !defined(HAVE_UINT)
#define HAVE_UINT 1
typedef unsigned int uint;
#endif
#if !defined(HAVE_USHORT)
#define HAVE_USHORT 1
typedef unsigned short ushort;
#endif
#if !defined(HAVE_ULONG)
#define HAVE_ULONG 1
typedef unsigned long ulong;
#endif

#endif  // OS_MACOSX

#if defined(OS_MACOSX) || defined(OS_NACL)
// BIG_ENDIAN
#include <machine/endian.h>
/* Let's try and follow the Linux convention */
#define __BYTE_ORDER  BYTE_ORDER
#define __LITTLE_ENDIAN LITTLE_ENDIAN
#define __BIG_ENDIAN BIG_ENDIAN
#endif  // OS_MACOSX || OS_NACL

// The following guarenty declaration of the byte swap functions, and
// define __BYTE_ORDER for MSVC
#ifdef COMPILER_MSVC
#include <stdlib.h>
#define __BYTE_ORDER __LITTLE_ENDIAN
#define bswap_16(x) _byteswap_ushort(x)
#define bswap_32(x) _byteswap_ulong(x)
#define bswap_64(x) _byteswap_uint64(x)

#elif defined(OS_MACOSX)
// Mac OS X / Darwin features
#include <libkern/OSByteOrder.h>
#define bswap_16(x) OSSwapInt16(x)
#define bswap_32(x) OSSwapInt32(x)
#define bswap_64(x) OSSwapInt64(x)

#elif defined(OS_NACL)
#include "i18n/input/engine/stubs/nacl/newlib_port/byteswap.h"
#define bswap_16(x) i18n_input::engine::stubs::byteswap_16(x)
#define bswap_32(x) i18n_input::engine::stubs::byteswap_32(x)
#define bswap_64(x) i18n_input::engine::stubs::byteswap_64(x)
#define __bswap_constant_16(x) bswap_16(x)
#define __bswap_constant_32(x) bswap_32(x)
#define __bswap_constant_64(x) bswap_64(x)

#else
#include <byteswap.h>  // IWYU pragma: export
#endif

// define the macros IS_LITTLE_ENDIAN or IS_BIG_ENDIAN
// using the above endian defintions from endian.h if
// endian.h was included
#ifdef __BYTE_ORDER
#if __BYTE_ORDER == __LITTLE_ENDIAN
#define IS_LITTLE_ENDIAN
#endif

#if __BYTE_ORDER == __BIG_ENDIAN
#define IS_BIG_ENDIAN
#endif

#else

#if defined(__LITTLE_ENDIAN__)
#define IS_LITTLE_ENDIAN
#elif defined(__BIG_ENDIAN__)
#define IS_BIG_ENDIAN
#endif

// there is also PDP endian ...

#endif  // __BYTE_ORDER

// Define the OS's path separator
#ifdef __cplusplus  // C won't merge duplicate const variables at link time
// Some headers provide a macro for this (GCC's system.h), remove it so that we
// can use our own.
#undef PATH_SEPARATOR
#if OS_WINDOWS
const char PATH_SEPARATOR = '\\';
#else
const char PATH_SEPARATOR = '/';
#endif
#endif

// Windows has O_BINARY as a flag to open() (like "b" for fopen).
// Linux doesn't need make this distinction.
#if defined OS_LINUX && !defined O_BINARY
#define O_BINARY 0
#endif

// va_copy portability definitions
#ifdef COMPILER_MSVC
// MSVC doesn't have va_copy yet.
// This is believed to work for 32-bit msvc.  This may not work at all for
// other platforms.
// If va_list uses the single-element-array trick, you will probably get
// a compiler error here.
//
#include <stdarg.h>
inline void va_copy(va_list& a, va_list& b) {
  a = b;
}

// Nor does it have uid_t
typedef int uid_t;

#endif

// Mac OS X / Darwin features

#if defined(OS_MACOSX)

#include <errno.h>

// For mmap, Linux defines both MAP_ANONYMOUS and MAP_ANON and says MAP_ANON is
// deprecated. In Darwin, MAP_ANON is all there is.
#if !defined MAP_ANONYMOUS
#define MAP_ANONYMOUS MAP_ANON
#endif

// Linux has this in <sys/cdefs.h>
#define __ptr_t void *

// Linux has this in <linux/errno.h>
#define EXFULL      ENOMEM  // not really that great a translation...

// Mach-O supports sections (albeit with small names), but doesn't have
// vars at the beginning and end.  Instead you should call the function
// getsectdata("__DATA", name, &size).
#define HAVE_ATTRIBUTE_SECTION 1

// Any function with ATTRIBUTE_SECTION must not be inlined, or it will
// be placed into whatever section its caller is placed into.
#define ATTRIBUTE_SECTION(name) \
  __attribute__ ((section ("__DATA, " #name))) __attribute__ ((noinline))

#define ENUM_DYLD_BOOL  // so that we don't pollute the global namespace
extern "C" {
  #include <mach-o/getsect.h>
  #include <mach-o/dyld.h>
}
class AssignAttributeStartEnd {
 public:
  AssignAttributeStartEnd(const char* name, char** pstart, char** pend) {
    // Find out what dynamic library name is defined in
    for (int i = _dyld_image_count() - 1; i >= 0; --i) {
      const mach_header* hdr = _dyld_get_image_header(i);
      uint32_t len;
      *pstart = getsectdatafromheader(hdr, "__DATA", name, &len);
      if (*pstart) {   // NULL if not defined in this dynamic library
        *pstart += _dyld_get_image_vmaddr_slide(i);   // correct for reloc
        *pend = *pstart + len;
        return;
      }
    }
    // If we get here, not defined in a dll at all.  See if defined statically.
    unsigned long len;    // don't ask me why this type isn't uint32_t too...
    *pstart = getsectdata("__DATA", name, &len);
    *pend = *pstart + len;
  }
};

// 1) DEFINE_ATTRIBUTE_SECTION_VARS: must be called once per unique
//    name.  You want to make sure this is executed before any
//    DECLARE_ATTRIBUTE_SECTION_VARS; the easiest way is to put them
//    in the same .cc file.  Put this call at the global level.
// 2) INIT_ATTRIBUTE_SECTION_VARS: you can scatter calls to this in
//    multiple places to help ensure execution before any
//    DECLARE_ATTRIBUTE_SECTION_VARS.  You must have at least one
//    DEFINE, but you can have many INITs.  Put each in its own scope.
// 3) DECLARE_ATTRIBUTE_SECTION_VARS: must be called before using
//    ATTRIBUTE_SECTION_START or ATTRIBUTE_SECTION_STOP on a name.
//    Put this call at the global level.
#define DECLARE_ATTRIBUTE_SECTION_VARS(name) \
  extern char* __start_##name; \
  extern char* __stop_##name;

#define INIT_ATTRIBUTE_SECTION_VARS(name)               \
  DECLARE_ATTRIBUTE_SECTION_VARS(name);                 \
  static const AssignAttributeStartEnd __assign_##name( \
    #name, &__start_##name, &__stop_##name)

#define DEFINE_ATTRIBUTE_SECTION_VARS(name)             \
  char* __start_##name, *__stop_##name;                 \
  INIT_ATTRIBUTE_SECTION_VARS(name)

// Darwin doesn't have strnlen. No comment.
inline size_t strnlen(const char *s, size_t maxlen) {
  const char* end = (const char *)memchr(s, '\0', maxlen);
  if (end)
    return end - s;
  return maxlen;
}

namespace std {}  // Avoid error if we didn't see std.
using namespace std;  // Just like VC++, we need a using here.

// Doesn't exist on OSX; used in google.cc for send() to mean "no flags".
#define MSG_NOSIGNAL 0

// No SIGPWR on MacOSX.  SIGINFO seems suitably obscure.
#undef GOOGLE_OBSCURE_SIGNAL
#define GOOGLE_OBSCURE_SIGNAL  SIGINFO

#elif defined(OS_CYGWIN)  // Cygwin-specific behavior.

#if defined(__CYGWIN32__)
#define __WORDSIZE 32
#else
// It's probably possible to support 64-bit, but the #defines will need checked.
#error "Cygwin is currently only 32-bit."
#endif

// No signalling on Windows.
#undef GOOGLE_OBSCURE_SIGNAL
#define GOOGLE_OBSCURE_SIGNAL 0

struct stack_t {
  void* ss_sp;
  int ss_flags;
  size_t ss_size;
};
inline int sigaltstack(stack_t* ss, stack_t* oss) { return 0; }

#define PTHREAD_STACK_MIN 0  // Not provided by cygwin

// Scans memory for a character.
// memrchr is used in a few places, but it's linux-specific.
inline void* memrchr(const void* bytes, int find_char, size_t len) {
  const unsigned char* cursor =
      reinterpret_cast<const unsigned char*>(bytes) + len - 1;
  unsigned char actual_char = find_char;
  for (; cursor >= bytes; --cursor) {
    if (*cursor == actual_char) {
      return const_cast<void*>(reinterpret_cast<const void*>(cursor));
    }
  }
  return NULL;
}

#endif

// Klocwork static analysis tool's C/C++ complier kwcc
#if defined(__KLOCWORK__)
#define STATIC_ANALYSIS
#endif // __KLOCWORK__

// GCC-specific features

#if (defined(COMPILER_GCC3) || defined(COMPILER_ICC) || \
     defined(OS_MACOSX) || defined(__ANDROID__)) && !defined(SWIG)

//
// Tell the compiler to do printf format string checking if the
// compiler supports it; see the 'format' attribute in
// <http://gcc.gnu.org/onlinedocs/gcc-4.3.0/gcc/Function-Attributes.html>.
//
// N.B.: As the GCC manual states, "[s]ince non-static C++ methods
// have an implicit 'this' argument, the arguments of such methods
// should be counted from two, not one."
//

#if defined(__clang__)
// Clang sucks anyway
#define PRINTF_ATTRIBUTE(string_index, first_to_check)
#define SCANF_ATTRIBUTE(string_index, first_to_check)
#else
#define PRINTF_ATTRIBUTE(string_index, first_to_check) \
    __attribute__((__format__ (__printf__, string_index, first_to_check)))
#define SCANF_ATTRIBUTE(string_index, first_to_check) \
    __attribute__((__format__ (__scanf__, string_index, first_to_check)))
#endif

//
// Prevent the compiler from padding a structure to natural alignment
//
#define PACKED __attribute__ ((packed))

// Cache line alignment
#if defined(__i386__) || defined(__x86_64__)
#define CACHELINE_SIZE 64
#define CACHELINE_ALIGNED __attribute__((aligned(CACHELINE_SIZE)))
#elif defined(__arm__)
// Cache line sizes for ARM: These values are not strictly correct since
// cache line sizes depend on implementations, not architectures.  There
// are even implementations with cache line sizes configurable at boot
// time.
#if defined(__ARM_ARCH_5T__)
#define CACHELINE_SIZE 32
#elif defined(__ARM_ARCH_7A__)
#define CACHELINE_SIZE 64
#endif
#define CACHELINE_ALIGNED
#else
#define CACHELINE_ALIGNED
#endif

//
// Prevent the compiler from complaining about or optimizing away variables
// that appear unused
// (careful, others e.g. third_party/libxml/xmlversion.h also define this)
#undef ATTRIBUTE_UNUSED
#define ATTRIBUTE_UNUSED __attribute__ ((unused))

//
// For functions we want to force inline or not inline.
// Introduced in gcc 3.1.
#define ATTRIBUTE_ALWAYS_INLINE  __attribute__ ((always_inline))
#define HAVE_ATTRIBUTE_ALWAYS_INLINE 1
#define ATTRIBUTE_NOINLINE __attribute__ ((noinline))
#define HAVE_ATTRIBUTE_NOINLINE 1

// For weak functions
#undef ATTRIBUTE_WEAK
#define ATTRIBUTE_WEAK __attribute__ ((weak))
#define HAVE_ATTRIBUTE_WEAK 1

// Tell the compiler to use "initial-exec" mode for a thread-local variable.
// See http://people.redhat.com/drepper/tls.pdf for the gory details.
#define ATTRIBUTE_INITIAL_EXEC __attribute__ ((tls_model ("initial-exec")))

//
// Tell the compiler that some function parameters should be non-null pointers.
// Note: As the GCC manual states, "[s]ince non-static C++ methods
// have an implicit 'this' argument, the arguments of such methods
// should be counted from two, not one."
//
#define ATTRIBUTE_NONNULL(arg_index) __attribute__((nonnull(arg_index)))

//
// Tell the compiler that a given function never returns
//
#define ATTRIBUTE_NORETURN __attribute__((noreturn))

#ifndef HAVE_ATTRIBUTE_SECTION  // may have been pre-set to 0, e.g. for Darwin
#define HAVE_ATTRIBUTE_SECTION 1
#endif

#if HAVE_ATTRIBUTE_SECTION  // define section support for the case of GCC

//
// Tell the compiler/linker to put a given function into a section and define
// "__start_ ## name" and "__stop_ ## name" symbols to bracket the section.
// Sections can not span more than none compilation unit.
// This functionality is supported by GNU linker.
// Any function with ATTRIBUTE_SECTION must not be inlined, or it will
// be placed into whatever section its caller is placed into.
//
#ifndef ATTRIBUTE_SECTION
#define ATTRIBUTE_SECTION(name) \
  __attribute__ ((section (#name))) __attribute__ ((noinline))
#endif

//
// Weak section declaration to be used as a global declaration
// for ATTRIBUTE_SECTION_START|STOP(name) to compile and link
// even without functions with ATTRIBUTE_SECTION(name).
// DEFINE_ATTRIBUTE_SECTION should be in the exactly one file; it's
// a no-op on ELF but not on Mach-O.
//
#ifndef DECLARE_ATTRIBUTE_SECTION_VARS
#define DECLARE_ATTRIBUTE_SECTION_VARS(name) \
  extern char __start_##name[] ATTRIBUTE_WEAK; \
  extern char __stop_##name[] ATTRIBUTE_WEAK
#endif
#ifndef DEFINE_ATTRIBUTE_SECTION_VARS
#define INIT_ATTRIBUTE_SECTION_VARS(name)
#define DEFINE_ATTRIBUTE_SECTION_VARS(name)
#endif

//
// Return void* pointers to start/end of a section of code with
// functions having ATTRIBUTE_SECTION(name).
// Returns 0 if no such functions exits.
// One must DECLARE_ATTRIBUTE_SECTION_VARS(name) for this to compile and link.
//
#define ATTRIBUTE_SECTION_START(name) (reinterpret_cast<void*>(__start_##name))
#define ATTRIBUTE_SECTION_STOP(name) (reinterpret_cast<void*>(__stop_##name))

#endif  // HAVE_ATTRIBUTE_SECTION

// Support for aligning the stack on 32-bit x86.  See http://b/issue?id=798841
//
// The legacy prod71 libc does not provide the stack alignment required for use
// of SSE intrinsics.  In order to properly use the intrinsics you need to use
// a trampoline function which aligns the stack prior to calling your code,
// or as of crosstool v10 with gcc 4.2.0 there is an attribute which asks
// gcc to do this for you.
//
// It has also been discovered that crosstool up to and including v10 does not
// provide proper alignment for pthread_once() functions in x86-64 code either.
// Unfortunately gcc does not provide force_align_arg_pointer as an option in
// x86-64 code, so this requires us to always have a trampoline.
//
// For an example of using this see util/hash/adler32*

#if defined(__i386__) && \
  (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 2))
#define ATTRIBUTE_STACK_ALIGN_FOR_OLD_LIBC \
  __attribute__((force_align_arg_pointer))
#define REQUIRE_STACK_ALIGN_TRAMPOLINE (0)
#elif defined(__i386__) || defined(__x86_64__)
#define REQUIRE_STACK_ALIGN_TRAMPOLINE (1)
#define ATTRIBUTE_STACK_ALIGN_FOR_OLD_LIBC
#else
#define REQUIRE_STACK_ALIGN_TRAMPOLINE (0)
#define ATTRIBUTE_STACK_ALIGN_FOR_OLD_LIBC
#endif

//
// Tell the compiler to warn about unused return values for functions declared
// with this macro.  The macro should be used on function declarations
// following the argument list:
//
//   Sprocket* AllocateSprocket() MUST_USE_RESULT;
//
#undef MUST_USE_RESULT
#if (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) \
  && !defined(COMPILER_ICC)
#define MUST_USE_RESULT __attribute__ ((warn_unused_result))
#else
#define MUST_USE_RESULT
#endif

#if (defined(COMPILER_ICC) || defined(COMPILER_GCC3) || defined(__llvm__))
// Defined behavior on some of the uarchs:
// PREFETCH_HINT_T0:
//   prefetch to all levels of the hierarchy (except on p4: prefetch to L2)
// PREFETCH_HINT_NTA:
//   p4: fetch to L2, but limit to 1 way (out of the 8 ways)
//   core: skip L2, go directly to L1
//   k8 rev E and later: skip L2, can go to either of the 2-ways in L1
enum PrefetchHint {
  PREFETCH_HINT_T0 = 3,  // More temporal locality
  PREFETCH_HINT_T1 = 2,
  PREFETCH_HINT_T2 = 1,  // Less temporal locality
  PREFETCH_HINT_NTA = 0  // No temporal locality
};
#else
// prefetch is a no-op for this target. Feel free to add more sections above.
#endif

extern inline void prefetch(const char *x, int hint) {
#if defined(COMPILER_ICC) || defined(__llvm__)
  // In the gcc version of prefetch(), hint is only a constant _after_ inlining
  // (assumed to have been successful).  icc views things differently, and
  // checks constant-ness _before_ inlining.  This leads to compilation errors
  // with the gcc version in icc.
  //
  // One way round this is to use a switch statement to explicitly match
  // prefetch hint enumerations, and invoke __builtin_prefetch for each valid
  // value.  icc's optimization removes the switch and unused case statements
  // after inlining, so that this boils down in the end to the same as for gcc;
  // that is, a single inlined prefetchX instruction.  Demonstrate by compiling
  // with icc options -xK -O2 and viewing assembly language output.
  //
  // Note that this version of prefetch() cannot verify constant-ness of hint.
  // If client code calls prefetch() with a variable value for hint, it will
  // receive the full expansion of the switch below, perhaps also not inlined.
  // This should however not be a problem in the general case of well behaved
  // caller code that uses the supplied prefetch hint enumerations.
  switch (hint) {
    case PREFETCH_HINT_T0:
      __builtin_prefetch(x, 0, PREFETCH_HINT_T0);
      break;
    case PREFETCH_HINT_T1:
      __builtin_prefetch(x, 0, PREFETCH_HINT_T1);
      break;
    case PREFETCH_HINT_T2:
      __builtin_prefetch(x, 0, PREFETCH_HINT_T2);
      break;
    case PREFETCH_HINT_NTA:
      __builtin_prefetch(x, 0, PREFETCH_HINT_NTA);
      break;
    default:
      __builtin_prefetch(x);
      break;
  }
#elif defined(COMPILER_GCC3)
 #if !defined(ARCH_PIII) || defined(__SSE__)
  if (__builtin_constant_p(hint)) {
    __builtin_prefetch(x, 0, hint);
  } else {
    // Defaults to PREFETCH_HINT_T0
    __builtin_prefetch(x);
  }
#else
  // We want a __builtin_prefetch, but we build with the default -march=i386
  // where __builtin_prefetch quietly turns into nothing.
  // Once we crank up to -march=pentium3 or higher the __SSE__
  // clause above will kick in with the builtin.
  // -- mec 2006-06-06
  if (hint == PREFETCH_HINT_NTA)
    __asm__ __volatile__("prefetchnta (%0)" : : "r"(x));
 #endif
#else
  // You get no effect.  Feel free to add more sections above.
#endif
}

#ifdef __cplusplus
// prefetch intrinsic (bring data to L1 without polluting L2 cache)
extern inline void prefetch(const char *x) {
  return prefetch(x, 0);
}
#endif  // ifdef __cplusplus

//
// GCC can be told that a certain branch is not likely to be taken (for
// instance, a CHECK failure), and use that information in static analysis.
// Giving it this information can help it optimize for the common case in
// the absence of better information (ie. -fprofile-arcs).
//
#if defined(COMPILER_GCC3)
#define PREDICT_FALSE(x) (__builtin_expect(x, 0))
#define PREDICT_TRUE(x) (__builtin_expect(!!(x), 1))
#else
#define PREDICT_FALSE(x) x
#define PREDICT_TRUE(x) x
#endif

#define FTELLO ftello
#define FSEEKO fseeko

#if !defined(__cplusplus) && !defined(OS_MACOSX) && !defined(OS_CYGWIN) && \
    !defined(__ANDROID__)
// stdlib.h only declares this in C++, not in C, so we declare it here.
// Also make sure to avoid declaring it on platforms which don't support it.
extern int posix_memalign(void **memptr, size_t alignment, size_t size);
#endif

inline void *aligned_malloc(size_t size, int minimum_alignment) {
#if defined(OS_MACOSX)
  // mac lacks memalign(), posix_memalign(), however, according to
  // http://stackoverflow.com/questions/196329/osx-lacks-memalign
  // mac allocs are already 16-byte aligned.
  if (minimum_alignment <= 16)
    return malloc(size);
  // next, try to return page-aligned memory. perhaps overkill
  if (minimum_alignment <= getpagesize())
    return valloc(size);
  // give up
  return NULL;
#elif defined(OS_CYGWIN) || defined(__ANDROID__) || defined(OS_NACL)
  return memalign(minimum_alignment, size);
#else  // !OS_MACOSX && !OS_CYGWIN
  void *ptr = NULL;
  if (posix_memalign(&ptr, minimum_alignment, size) != 0)
    return NULL;
  else
    return ptr;
#endif
}

inline void aligned_free(void *aligned_memory) {
  free(aligned_memory);
}

#else   // not GCC

#define PRINTF_ATTRIBUTE(string_index, first_to_check)
#define SCANF_ATTRIBUTE(string_index, first_to_check)
#define PACKED
#define CACHELINE_ALIGNED
#define ATTRIBUTE_UNUSED
#define ATTRIBUTE_ALWAYS_INLINE
#define ATTRIBUTE_NOINLINE
#define ATTRIBUTE_WEAK
#define HAVE_ATTRIBUTE_WEAK 0
#define ATTRIBUTE_INITIAL_EXEC
#define ATTRIBUTE_NONNULL(arg_index)
#define ATTRIBUTE_NORETURN
#define HAVE_ATTRIBUTE_SECTION 0
#define ATTRIBUTE_STACK_ALIGN_FOR_OLD_LIBC
#define REQUIRE_STACK_ALIGN_TRAMPOLINE (0)
#define MUST_USE_RESULT
extern inline void prefetch(const char *x) {}
#define PREDICT_FALSE(x) x
#define PREDICT_TRUE(x) x

// These should be redefined appropriately if better alternatives to
// ftell/fseek exist in the compiler
#define FTELLO ftell
#define FSEEKO fseek

#endif  // GCC

//
// Provides a char array with the exact same alignment as another type. The
// first parameter must be a complete type, the second parameter is how many
// of that type to provide space for.
//
//   ALIGNED_CHAR_ARRAY(struct stat, 16) storage_;
//
#if defined(__cplusplus)
#undef ALIGNED_CHAR_ARRAY
// Because MSVC and older GCCs require that the argument to their alignment
// construct to be a literal constant integer, we use a template instantiated
// at all the possible powers of two.
#ifndef SWIG
template<int alignment, int size> struct AlignType { };
template<int size> struct AlignType<0, size> { typedef char result[size]; };
#if defined(COMPILER_MSVC)
#define BASE_PORT_H_ALIGN_ATTRIBUTE(X) __declspec(align(X))
#define BASE_PORT_H_ALIGN_OF(T) __alignof(T)
#elif defined(COMPILER_GCC3) || defined(COMPILER_ICC)
#define BASE_PORT_H_ALIGN_ATTRIBUTE(X) __attribute__((aligned(X)))
#define BASE_PORT_H_ALIGN_OF(T) __alignof__(T)
#endif

#if defined(BASE_PORT_H_ALIGN_ATTRIBUTE)

#define BASE_PORT_H_ALIGNTYPE_TEMPLATE(X) \
  template<int size> struct AlignType<X, size> { \
    typedef BASE_PORT_H_ALIGN_ATTRIBUTE(X) char result[size]; \
  }

BASE_PORT_H_ALIGNTYPE_TEMPLATE(1);
BASE_PORT_H_ALIGNTYPE_TEMPLATE(2);
BASE_PORT_H_ALIGNTYPE_TEMPLATE(4);
BASE_PORT_H_ALIGNTYPE_TEMPLATE(8);
BASE_PORT_H_ALIGNTYPE_TEMPLATE(16);
BASE_PORT_H_ALIGNTYPE_TEMPLATE(32);
BASE_PORT_H_ALIGNTYPE_TEMPLATE(64);
BASE_PORT_H_ALIGNTYPE_TEMPLATE(128);
BASE_PORT_H_ALIGNTYPE_TEMPLATE(256);
BASE_PORT_H_ALIGNTYPE_TEMPLATE(512);
BASE_PORT_H_ALIGNTYPE_TEMPLATE(1024);
BASE_PORT_H_ALIGNTYPE_TEMPLATE(2048);
BASE_PORT_H_ALIGNTYPE_TEMPLATE(4096);
BASE_PORT_H_ALIGNTYPE_TEMPLATE(8192);
// Any larger and MSVC++ will complain.

#define ALIGNED_CHAR_ARRAY(T, Size) \
  typename AlignType<BASE_PORT_H_ALIGN_OF(T), sizeof(T) * Size>::result

#undef BASE_PORT_H_ALIGNTYPE_TEMPLATE
#undef BASE_PORT_H_ALIGN_ATTRIBUTE

#else  // defined(BASE_PORT_H_ALIGN_ATTRIBUTE)
#define ALIGNED_CHAR_ARRAY \
    you_must_define_ALIGNED_CHAR_ARRAY_for_your_compiler_in_base_port_h
#endif // defined(BASE_PORT_H_ALIGN_ATTRIBUTE)

#else  // !SWIG

// SWIG can't represent alignment and doesn't care about alignment on data
// members (it works fine without it).
template<typename Size>
struct AlignType { typedef char result[Size]; };
#define ALIGNED_CHAR_ARRAY(T, Size) AlignType<Size * sizeof(T)>::result

#endif // !SWIG
#else  // __cpluscplus
#define ALIGNED_CHAR_ARRAY ALIGNED_CHAR_ARRAY_is_not_available_without_Cplusplus
#endif // __cplusplus

#if !HAVE_ATTRIBUTE_SECTION  // provide dummy definitions

#define ATTRIBUTE_SECTION(name)
#define INIT_ATTRIBUTE_SECTION_VARS(name)
#define DEFINE_ATTRIBUTE_SECTION_VARS(name)
#define DECLARE_ATTRIBUTE_SECTION_VARS(name)
#define ATTRIBUTE_SECTION_START(name) (reinterpret_cast<void*>(0))
#define ATTRIBUTE_SECTION_STOP(name) (reinterpret_cast<void*>(0))

#endif  // !HAVE_ATTRIBUTE_SECTION

#ifdef COMPILER_MSVC     /* if Visual C++ */

// This compiler flag can be easily overlooked on MSVC.
// _CHAR_UNSIGNED gets set with the /J flag.
#ifndef _CHAR_UNSIGNED
#error chars must be unsigned!  Use the /J flag on the compiler command line.
#endif

// MSVC is a little hyper-active in its warnings
// Signed vs. unsigned comparison is ok.
#pragma warning(disable : 4018 )
// We know casting from a long to a char may lose data
#pragma warning(disable : 4244 )
// Don't need performance warnings about converting ints to bools
#pragma warning(disable : 4800 )
// Integral constant overflow is apparently ok too
// for example:
//  short k;  int n;
//  k = k + n;
#pragma warning(disable : 4307 )
// It's ok to use this* in constructor
// Example:
//  class C {
//   Container cont_;
//   C() : cont_(this) { ...
#pragma warning(disable : 4355 )
// Truncating from double to float is ok
#pragma warning(disable : 4305 )

#include <assert.h>
#include <windows.h>
#undef ERROR

#include <float.h>  // for nextafter functionality on windows
#define _USE_MATH_DEFINES
#include <math.h>  // for HUGE_VAL
#ifdef STL_MSVC
inline double log2(double n) {
  return log(n) / log(2.);
}
inline double log(int n) {
  return log(static_cast<double>(n));
}
inline bool isblank(char c) {
  return c == ' ' || c == '\t';
}
#endif  // STL_MSVC

#ifndef HUGE_VALF
#define HUGE_VALF (static_cast<float>(HUGE_VAL))
#endif

namespace std {}  // Avoid error if we didn't see std.
using namespace std;

// VC++ doesn't understand "uint"
#ifndef HAVE_UINT
#define HAVE_UINT 1
typedef unsigned int uint;
#endif  // HAVE_UINT

#ifndef HAVE_USHORT
#define HAVE_USHORT 1
typedef unsigned short ushort;
#endif  // HAVE_USHORT

#ifndef HAVE_ULONG
#define HAVE_ULONG 1
typedef unsigned long ulong;
#endif  // HAVE_ULONG

// VC++ doesn't understand "ssize_t"
// <windows.h> from above includes <BaseTsd.h> and <BaseTsd.h> defines SSIZE_T
#ifndef HAVE_SSIZET
#define HAVE_SSIZET 1
typedef SSIZE_T ssize_t;
#endif  // HAVE_SSIZET

#define strtof(a,b)   stof((a), reinterpret_cast<size_t*>(b))
#define strtoq   _strtoi64
#define strtouq  _strtoui64
#define strtoll  _strtoi64
#define strtoull _strtoui64
#define atoll    _atoi64

// You say tomato, I say atotom
#define PATH_MAX MAX_PATH

// You say tomato, I say _tomato
#if (_MSC_VER < 1600)
#define vsnprintf _vsnprintf
#endif  // _MSC_VER < 1600
#define snprintf _snprintf
#define strcasecmp _stricmp
#define strncasecmp _strnicmp

#define nextafter _nextafter

#define hypot _hypot
#define hypotf _hypotf

#define strdup _strdup
#define tempnam _tempnam
#define chdir  _chdir
#define putenv  _putenv

#undef gmtime_r
#define gmtime_r(x, y) gmtime_s((y), (x))

// You say tomato, I say toma
#define srandom(x) srand(x)

// You say juxtapose, I say transpose
#define bcopy(s, d, n) memcpy(d, s, n)

inline void *aligned_malloc(size_t size, int minimum_alignment) {
  return _aligned_malloc(size, minimum_alignment);
}

inline void aligned_free(void *aligned_memory) {
  _aligned_free(aligned_memory);
}

// ----- BEGIN VC++ STUBS & FAKE DEFINITIONS ---------------------------------

// See http://en.wikipedia.org/wiki/IEEE_754 for details of
// floating point format.

enum {
  FP_NAN,  //  is "Not a Number"
  FP_INFINITE,  //  is either plus or minus infinity.
  FP_ZERO,
  FP_SUBNORMAL,  // is too small to be represented in normalized format.
  FP_NORMAL  // if nothing of the above is correct that it must be a
  // normal floating-point number.
};

inline int fpclassify_double(double x) {
  const int float_point_class =_fpclass(x);
  int c99_class;
  switch  (float_point_class) {
  case _FPCLASS_SNAN:  // Signaling NaN
  case _FPCLASS_QNAN:  // Quiet NaN
    c99_class = FP_NAN;
    break;
  case _FPCLASS_NZ:  // Negative zero ( -0)
  case _FPCLASS_PZ:  // Positive 0 (+0)
    c99_class = FP_ZERO;
    break;
  case _FPCLASS_NINF:  // Negative infinity ( -INF)
  case _FPCLASS_PINF:  // Positive infinity (+INF)
    c99_class = FP_INFINITE;
    break;
  case _FPCLASS_ND:  // Negative denormalized
  case _FPCLASS_PD:  // Positive denormalized
    c99_class = FP_SUBNORMAL;
    break;
  case _FPCLASS_NN:  // Negative normalized non-zero
  case _FPCLASS_PN:  // Positive normalized non-zero
    c99_class = FP_NORMAL;
    break;
  default:
    c99_class = FP_NAN;  // Should never happen
    break;
  }
  return  c99_class;
}

// This function handle the special subnormal case for float; it will
// become a normal number while casting to double.
// bit_cast is avoided to simplify dependency and to create a code that is
// easy to deploy in C code
inline int fpclassify_float(float x) {
  uint32 bitwise_representation;
  memcpy(&bitwise_representation, &x, 4);
  if ((bitwise_representation & 0x7f800000) == 0 &&
      (bitwise_representation & 0x007fffff) != 0)
    return FP_SUBNORMAL;
  return fpclassify_double(x);
}
//
// This define takes care of the denormalized float; the casting to
// double make it a normal number
#define fpclassify(x) \
    ((sizeof(x) == sizeof(float)) ? fpclassify_float(x) : fpclassify_double(x))

#define isnan _isnan
#define isfinite _finite
inline bool signbit(double num) {
  return _copysign(1.0, num) < 0;
}

inline int isinf(double x) {
  const int float_point_class =_fpclass(x);
  if (float_point_class == _FPCLASS_PINF) return 1;
  if (float_point_class == _FPCLASS_NINF) return -1;
  return 0;
}

// #include "conflict-signal.h"
typedef void (*sig_t)(int);

// These actually belong in errno.h but there's a name confilict in errno
// on WinNT. They (and a ton more) are also found in Winsock2.h, but
// if'd out under NT. We need this subset at minimum.
#define EXFULL      ENOMEM  // not really that great a translation...
// The following are already defined in VS2010.
#if (_MSC_VER < 1600)
#define EWOULDBLOCK WSAEWOULDBLOCK
#ifndef PTHREADS_REDHAT_WIN32
#define ETIMEDOUT   WSAETIMEDOUT
#endif
#define ENOTSOCK    WSAENOTSOCK
#define EINPROGRESS WSAEINPROGRESS
#define ECONNRESET  WSAECONNRESET
#endif

//
// Really from <string.h>
//

inline void bzero(void *s, int n) {
  memset(s, 0, n);
}

// From glob.h
#define __ptr_t   void *

// Defined all over the place.
typedef int pid_t;

// From stat.h
typedef unsigned int mode_t;

// u_int16_t, int16_t don't exist in MSVC
typedef unsigned short u_int16_t;
typedef short int16_t;

// ----- END VC++ STUBS & FAKE DEFINITIONS ----------------------------------

#endif  // COMPILER_MSVC

#ifdef STL_MSVC  // not always the same as COMPILER_MSVC
#include "base/port_hash.h"
#else
struct PortableHashBase { };
#endif

// The SWIGged version of an abstract class must be concrete if any methods
// return objects of the abstract type.
//
// This location is deprecated, the new preferred location is in base/macros.h.
#ifndef SWIG
#define ABSTRACT = 0
#endif

#if defined(OS_WINDOWS) || defined(OS_MACOSX)
// gethostbyname() *is* thread-safe for Windows native threads. It is also
// safe on Mac OS X, where it uses thread-local storage, even though the
// manpages claim otherwise. For details, see
// http://lists.apple.com/archives/Darwin-dev/2006/May/msg00008.html
#else
// gethostbyname() is not thread-safe.  So disallow its use.  People
// should either use the HostLookup::Lookup*() methods, or gethostbyname_r()
#define gethostbyname gethostbyname_is_not_thread_safe_DO_NOT_USE
#endif

// create macros in which the programmer should enclose all specializations
// for hash_maps and hash_sets. This is necessary since these classes are not
// STL standardized. Depending on the STL implementation they are in different
// namespaces. Right now the right namespace is passed by the Makefile
// Examples: gcc3: -DHASH_NAMESPACE=__gnu_cxx
//           icc:  -DHASH_NAMESPACE=std
//           gcc2: empty

#ifndef HASH_NAMESPACE
#  define HASH_NAMESPACE_DECLARATION_START
#  define HASH_NAMESPACE_DECLARATION_END
#else
#  define HASH_NAMESPACE_DECLARATION_START  namespace HASH_NAMESPACE {
#  define HASH_NAMESPACE_DECLARATION_END    }
#endif

// Our STL-like classes use __STD.
#if defined(COMPILER_GCC3) || defined(COMPILER_ICC) || \
    defined(OS_MACOSX) || defined(COMPILER_MSVC)
#define __STD std
#endif

#if defined COMPILER_GCC3 || defined COMPILER_ICC
#define STREAM_SET(s, bit) (s).setstate(ios_base::bit)
#define STREAM_SETF(s, flag) (s).setf(ios_base::flag)
#else
#define STREAM_SET(s, bit) (s).set(ios::bit)
#define STREAM_SETF(s, flag) (s).setf(ios::flag)
#endif

// Portable handling of unaligned loads and stores

#if defined(ARCH_PIII) || defined(ARCH_ATHLON) || \
    defined(ARCH_K8) || defined(_ARCH_PPC)

// x86 and x86-64 can perform unaligned loads/stores directly;
// modern PowerPC hardware can also do unaligned integer loads and stores;
// but note: the FPU still sends unaligned loads and stores to a trap handler!

#define UNALIGNED_LOAD16(_p) (*reinterpret_cast<const uint16 *>(_p))
#define UNALIGNED_LOAD32(_p) (*reinterpret_cast<const uint32 *>(_p))
#define UNALIGNED_LOAD64(_p) (*reinterpret_cast<const uint64 *>(_p))

#define UNALIGNED_STORE16(_p, _val) (*reinterpret_cast<uint16 *>(_p) = (_val))
#define UNALIGNED_STORE32(_p, _val) (*reinterpret_cast<uint32 *>(_p) = (_val))
#define UNALIGNED_STORE64(_p, _val) (*reinterpret_cast<uint64 *>(_p) = (_val))

#else

#define NEED_ALIGNED_LOADS

// These functions are provided for architectures that don't support
// unaligned loads and stores.

inline uint16 UNALIGNED_LOAD16(const void *p) {
  uint16 t;
  memcpy(&t, p, sizeof t);
  return t;
}

inline uint32 UNALIGNED_LOAD32(const void *p) {
  uint32 t;
  memcpy(&t, p, sizeof t);
  return t;
}

inline uint64 UNALIGNED_LOAD64(const void *p) {
  uint64 t;
  memcpy(&t, p, sizeof t);
  return t;
}

inline void UNALIGNED_STORE16(void *p, uint16 v) {
  memcpy(p, &v, sizeof v);
}

inline void UNALIGNED_STORE32(void *p, uint32 v) {
  memcpy(p, &v, sizeof v);
}

inline void UNALIGNED_STORE64(void *p, uint64 v) {
  memcpy(p, &v, sizeof v);
}

#endif

#ifdef _LP64
#define UNALIGNED_LOADW(_p) UNALIGNED_LOAD64(_p)
#define UNALIGNED_STOREW(_p, _val) UNALIGNED_STORE64(_p, _val)
#else
#define UNALIGNED_LOADW(_p) UNALIGNED_LOAD32(_p)
#define UNALIGNED_STOREW(_p, _val) UNALIGNED_STORE32(_p, _val)
#endif

// printf macros for size_t, in the style of inttypes.h
#ifdef _LP64
#define __PRIS_PREFIX "z"
#else
#define __PRIS_PREFIX
#endif

// Use these macros after a % in a printf format string
// to get correct 32/64 bit behavior, like this:
// size_t size = records.size();
// printf("%"PRIuS"\n", size);

#define PRIdS __PRIS_PREFIX "d"
#define PRIxS __PRIS_PREFIX "x"
#define PRIuS __PRIS_PREFIX "u"
#define PRIXS __PRIS_PREFIX "X"
#define PRIoS __PRIS_PREFIX "o"

#define GPRIuPTHREAD "lu"
#define GPRIxPTHREAD "lx"
#ifdef OS_CYGWIN
#define PRINTABLE_PTHREAD(pthreadt) reinterpret_cast<uintptr_t>(pthreadt)
#else
#define PRINTABLE_PTHREAD(pthreadt) pthreadt
#endif

#define SIZEOF_MEMBER(t, f)   sizeof(((t*) 4096)->f)

#define OFFSETOF_MEMBER(t, f)         \
  (reinterpret_cast<char*>(           \
     &reinterpret_cast<t*>(16)->f) -  \
   reinterpret_cast<char*>(16))

#ifdef PTHREADS_REDHAT_WIN32
#include <iosfwd>
#include <pthread.h>
// pthread_t is not a simple integer or pointer on Win32
std::ostream& operator << (std::ostream& out, const pthread_t& thread_id);
#endif

// GXX_EXPERIMENTAL_CXX0X is defined by gcc and clang up to at least
// gcc-4.7 and clang-3.1 (2011-12-13).  __cplusplus was defined to 1
// in gcc before 4.7 (Crosstool 16) and clang before 3.1, but is
// defined according to the language version in effect thereafter.  I
// believe MSVC will also define __cplusplus according to the language
// version, but haven't checked that.
#if defined(__GXX_EXPERIMENTAL_CXX0X__) || __cplusplus >= 201103L
// Define this to 1 if the code is compiled in C++11 mode; leave it
// undefined otherwise.  Do NOT define it to 0 -- that causes
// '#ifdef LANG_CXX11' to behave differently from '#if LANG_CXX11'.
#define LANG_CXX11 1
// TODO(jyasskin): s/LANG_CXX0X/LANG_CXX11/g and remove it.
#define LANG_CXX0X 1
#endif

#if defined(COMPILER_MSVC)
// Cache line alignment
#define CACHELINE_SIZE 64
#endif

#if defined(__ANDROID__)

#include <errno.h>
#include <unistd.h>
namespace std {}  // Avoid error if we didn't see std.
using namespace std;  // Just like VC++, we need a using here.
namespace __gnu_cxx {}  // Avoid error if we didn't see __gnu_cxx.
using namespace __gnu_cxx;
// For weak functions
#undef ATTRIBUTE_WEAK
#define ATTRIBUTE_WEAK __attribute__ ((weak))
#undef HAVE_ATTRIBUTE_WEAK
#define HAVE_ATTRIBUTE_WEAK 1
//
// Log base 2
//
#include <math.h>  // for log2
template <typename T>
inline T log2(const T &v) {
  return log(v) / log(2.0);
}
inline float log(int v) {
  return log(static_cast<float>(v));
}

#define strtoq  strtoll
#define strtouq strtoull

#define FALSE false

// TODO(zkfan): Open these two macros in util/gtl/manual_constructor.h instead.
#define UTIL_GTL_ALIGN_ATTRIBUTE(X) __attribute__((aligned(X)))
#define UTIL_GTL_ALIGN_OF(T) __alignof__(T)

#endif

#if defined(OS_NACL)

#define strtoq  strtoll
#define strtouq strtoull
#define CACHELINE_SIZE 32

namespace std {}  // Avoid error if we didn't see std.
using namespace std;
#endif  // OS_NACL

// Private implementation detail: __has_extension is useful to implement
// static_assert, and defining it for all toolchains avoids an extra level of
// nesting of #if/#ifdef/#ifndef.
#ifndef __has_extension
#define __has_extension(x) 0  // MSVC 10's preprocessor can't handle 'false'.
#endif

#ifdef __cplusplus
// We support C++11's static_assert(expression, message) for all C++
// builds, though for some pre-C++11 toolchains we fall back to using
// GG_PRIVATE_STATIC_ASSERT, which has two limitations: (1) the
// expression argument will need to be parenthesized if it would
// otherwise contain commas outside of parentheses, and (2) the
// message is ignored (though the compiler error will likely mention
// "static_assert_failed" and point to the line with the failing assertion).

#if LANG_CXX11 || __has_extension(cxx_static_assert) || _MSC_VER >= 1600
// There's a native implementation of static_assert, no need to define our own.
// Except that Crosstool V15 blocks use of static_assert, and lacks a warning
// option to permit it, so we fall back to _Static_assert in that case.
// TODO(jdennett): Eliminate this when we no longer need to support compilation
// with Crosstool V15.
#if defined(__clang__)
#if !__has_warning("-Wc++98-compat-static-assert")
#define static_assert _Static_assert
#else
#endif
#endif
#elif __has_extension(c_static_assert)
// C11's _Static_assert is available, and makes a great static_assert.
#define static_assert _Static_assert
#else
// Fall back on our home-grown implementation, with its limitations.
#define static_assert GG_PRIVATE_STATIC_ASSERT
#endif

// CompileAssert is an implementation detail of COMPILE_ASSERT and
// GG_PRIVATE_STATIC_ASSERT.
template <bool>
struct CompileAssert {
};

// GG_PRIVATE_STATIC_ASSERT: A poor man's static_assert.  This doesn't handle
// condition expressions that contain unparenthesized top-level commas;
// write GG_PRIVATE_STATIC_ASSERT((expr), "comment") when needed.
#define GG_PRIVATE_CAT_IMMEDIATE(a, b) a ## b
#define GG_PRIVATE_CAT(a, b) GG_PRIVATE_CAT_IMMEDIATE(a, b)
#define GG_PRIVATE_STATIC_ASSERT(expr, ignored) \
  typedef CompileAssert<(static_cast<bool>(expr))> \
  GG_PRIVATE_CAT(static_assert_failed_at_line, __LINE__)[bool(expr) ? 1 : -1]

#endif  // __cplusplus

#endif  // BASE_PORT_H_


text:
require 'rails_helper'

RSpec.describe Group, type: :model do
  describe 'scopes' do
    before :each do
      @chapter1 = create :chapter
      @chapter2 = create :chapter

      @group1 = create :group, chapter: @chapter1
      @group2 = create :group, chapter: @chapter2
      @group3 = create :group, deleted_at: Time.zone.now, chapter: @chapter1
    end

    describe 'exclude_deleted' do
      it 'returns only non-deleted groups' do
        expect(Group.exclude_deleted.length).to eq 2
        expect(Group.exclude_deleted).to include @group1, @group2
      end

      it 'returns only groups belonging to a specific chapter' do
        expect(Group.by_chapter(@chapter1.id).length).to eq 2
        expect(Group.by_chapter(@chapter1.id)).to include @group1, @group3
      end
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
var models = require('../../models'),
    config = require('../../config.js'),
    _ = require('underscore')
, common = require('./common');

module.exports ={

    get: function(req, res){
        var host = req.get('host');
        var data = {
            next: req.query.next,
            title: "רישום",
            is_no_sheatufim : false,
            subject : {}
        };
        if(!_.find(config.hosts, function(hst){return hst == host; })){
            data.is_no_sheatufim = true;
            models.Subject.findOne().where('host_details.host_address', 'http://' + host).exec(function(err, subject){
                if(err || !subject) throw new Error('Subject with this host was not found');
                data.subject = subject;
                res.render('reset_password.ejs', data);
            });
        } else {
            res.render('reset_password.ejs', data);
        }
    },

    post: function(req, res){

       var user_id = req.query.id;
       var validation_code = req.query.code;
       var password= req.body.new_password;

       if(user_id){
           models.User.findById(user_id, function(err, user){
               if(!err && user){
                   if(user.validation_code ==  validation_code){
                       user.password = common.hash_password(password);
                       user.is_activated = true;
                       user.has_reset_password = true;
                       user.save(function(err, user){
                           if(!err){
                               req.body.password = password;
                               req.body.email = user.email;
                               req.authenticate('simple', function (err, is_authenticated) {
                                   if (is_authenticated) {
                                       var next = req.query.next || common.DEFAULT_LOGIN_REDIRECT;
                                       if(next.indexOf('?') > -1)
                                          next += '&is_new=reset';
                                       else
                                           next += '?is_new=reset';
                                       res.redirect(next);
                                   }
                                   else {
                                       res.render('500.ejs', {error:err});
                                   }
                               });
                           }else{
                               console.error('cant save',err);
                               res.render('500.ejs', {error:err});
                           }
                       })

                   }else{
                       console.error('bad link');
                       res.render('500.ejs', {error:'לינק שגוי או מיושן, שלח מייל מחדש'});
                   }
               }else{
                   console.error('no user',err);
                   res.render('500.ejs', {error:err});
               }
           })
       } else{
           console.error('bad link');
           res.render('500.ejs', {error:'לינק שגוי'});
       }
    }
}


text:
layout: page
title: Melendez Wild Productions Dinner
date: 2016-05-24
author: Maria Acevedo
tags: weekly links, java
status: published
summary: Etiam id quam vel quam sodales consequat ac.
banner: images/banner/wedding.jpg
booking:
  startDate: 05/07/2019
  endDate: 05/11/2019
  ctyhocn: BALCYHX
  groupCode: MWPD
published: true
---
Suspendisse vel dolor elit. Donec tempus eros sit amet velit suscipit, a aliquam libero auctor. Integer imperdiet turpis ut mauris consectetur sodales. Vestibulum bibendum quam non nulla vulputate, eu laoreet lorem ultricies. Aliquam viverra imperdiet tortor. Integer nec convallis ligula, eget consequat ligula. Etiam scelerisque at metus nec pretium. In ullamcorper sapien ligula, quis finibus mauris viverra ut.

* Etiam eu sapien et leo cursus accumsan et eu arcu
* Cras laoreet sem nec risus pulvinar, eget pulvinar sapien faucibus.

Etiam cursus mattis diam, tristique pretium diam fermentum sit amet. Mauris viverra, enim a elementum aliquam, tellus arcu feugiat nulla, at dictum lectus turpis nec sapien. Nam nec bibendum mi. Nunc ornare, tortor sit amet pulvinar sollicitudin, tellus nunc porta dui, quis dignissim nisl diam et justo. Aenean ac interdum justo, et auctor purus. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Quisque eleifend sollicitudin urna suscipit tincidunt. Cras pulvinar condimentum placerat. Suspendisse vitae pulvinar neque. Mauris eget varius nisi. Proin scelerisque lobortis elit, eu hendrerit nisi vestibulum vehicula. Mauris ac dui nec purus vestibulum imperdiet.
Fusce quis malesuada lacus, sit amet consequat leo. Fusce gravida rhoncus neque, at posuere dui dictum et. Maecenas imperdiet, ipsum vel sodales bibendum, lacus magna maximus neque, in cursus justo orci sed neque. Vestibulum accumsan varius varius. Vestibulum posuere varius molestie. Quisque faucibus nisl nunc, et sodales magna sagittis et. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.


text:
<title>
Meetings on Marx
</title>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<?php include "../../legacy-includes/Script.htmlf" ?>

<?php include "../../legacy-includes/TopLogo.htmlf" ?>

<?php include "../../legacy-includes/TopAd.htmlf" ?>

<?php include "../../legacy-includes/LeftButtons.htmlf" ?>

<?php include "../../legacy-includes/BodyInsert.htmlf" ?>

MEETINGS AROUND THE COUNTRY

The Revolutionary Ideas of Karl Marx

Time and again, Marxism has been declared dead, and capitalism the final form of human fulfillment. Yet every generation--the workers of the great U.S. union struggles of the 1930s, student radicals in the 1960s, the millions who struggled to overthrow apartheid in South Africa, or those who joined the Solidarity movement in Stalinist Poland--has rediscovered the "buried" ideas of Marxism as a way to understand the world around them.

The International Socialist Organization is sponsoring meetings around the country on "The Revolutionary Ideas of Karl Marx." Join us for a discussion of Marx's legacy and how these ideas can provide a guide to changing the world. Listed below is information on the Marx forums for a number of places:

EAST

Amherst, Mass. | April 26 | 7 pm

University of Massachusetts Campus Center. Call 413-351-2323 or e-mail contact@isonoho.org.

Baltimore | April 27 | 7 pm

First Unitarian Church, at the corner of Charles Street and West Hamilton (enter on West Hamilton and ring the buzzer). Call 410-488-6767 or e-mail baltimore_iso@yahoo.com.

Boston | May 3 | 7 pm

Call 617-648-0561 or e-mail isoboston@yahoo.com.

Burlington, Vt. | April 12 | 7 pm

University of Vermont campus, Lafayette Building, Room 403. Call 802-309-4824.

College Park, Md.--University of Maryland | April 25 | 7 pm

University of Maryland campus, Jimenez Hall, Room 2206. Call 202-609-8264 or e-mail iso_district@yahoo.com.

New York City--Brooklyn | April 21 | 1 pm

Brooklyn Library-Pacific Branch, 25 4th Ave. at Pacific Street (trains to Pacific Street or Atlantic Avenue). Call 646-452-8631 or e-mail nyciso@hotmail.com.

New York City--Brooklyn College | April 19 | 2 pm

Aviary Room, 4th Floor of Student Union (Q to Avenue H or 2, 5 to Flatbush/Norstrand). Call 646-452-8631 or e-mail nyciso@hotmail.com.

New York City--City College | April 19

City College of New York, Room 1/211, 138th and Convent Avenue. Call 646-452-8631 or e-mail nyciso@hotmail.com.

New York City--Hunter College | April 18 | 7 pm

Hunter College, Room TH105. Call 646-452-8631 or e-mail nyciso@yahoo.com.

New York City--Jackson Heights | April 21 | 6:30 pm

Community United Methodist Church, 81-10 35th Ave. (between 81st and 82nd Streets; 7 train to 82nd Street). Call 646-452-8631 or e-mail nyciso@hotmail.com.

New York City--Queens | April 18 | 2:15 pm

LaGuardia Community College, Room TBA. Call 646-452-8631 or e-mail nyciso@hotmail.com.

Philadelphia | April 19 | 7:30 pm

U Penn campus, David Rittenhouse Lab, Room A-6, 209 S. 33rd St. Call 917-763-6764 or e-mail isophilly@googlegroups.com.

Providence, R.I. | April 25 | 7 pm

Rhode Island College, Student Union. Call 401-525-1957 or e-mail iso_ri@yahoo.com.

Rochester, N.Y. | April 26

Call 585-436-3886 or e-mail rochiso@yahoo.com.

Washington, D.C. | April 26 | 7 p.m.

St. Stephens Church. Call 202-609-8264 or e-mail iso_district@yahoo.com.

MIDWEST

Champaign, Ill. | April 4 | 7 pm

University of Illinois, Greg Hall, Room 113. Call 217-649-8830 or e-mail iso.champaign@gmail.com.

Chicago--Northeastern Illinois University | April 11 | 7 pm

Northeastern Illinois University, Student Union Room 215. E-mail neiusocialists@yahoogroups.com.

Chicago--University of Illinois-Chicago | April 12 | 7 pm

UIC campus. Call 773-902-5282 or e-mail chicago_socialists@yahoo.com.

Cincinnati | May 10 | 7 pm

University of Cincinnati, Swift Hall, Room 500. Call 859-801-2870 or e-mail iso_nati@yahoo.com.

Madison, Wis. | May 2 | 7:30 pm

University of Wisconsin-Madison, Humanities Hall, Room 1131. Call 608-354-6690 or e-mail ewrigleyfield@gmail.com.

SOUTH

Austin, Texas | April 26 | 7 pm

University of Texas campus, Mezes Hall Room 1.120 (south of the UT Tower). Call 512-494-0667 or e-mail austinsocialist@hotmail.com.

Greensboro, N.C. | April 26 | 8 pm

University of North Carolina at Greensboro, Elliott University Center, Joyner Room. Call 336-312-2918 or e-mail iso_gso@yahoo.com.

WEST

Berkeley, Calif. | April 22 | 5 pm

Black Oak Books, 1491 Shattuck Ave. Call 415-272-5049 or e-mail iso_berkeley@yahoo.com.

Eugene, Ore. | May 11 | 7 pm

University of Oregon, McKenzie Hall, Room 240C. Call 541-206-1905 or visit iso.breadlandpeace.org.

Los Angeles | April 21 | 3 pm

Echo Park Film Center, 1200 N. Alvarado St. Call 213-309-2713.

Portland, Ore. | May 10 | 7:30 pm

Call 503-887-5457 or e-mail pdxiso@yahoo.com.

San Francisco | April 23 | 7:30 pm

Modern Times Bookstore, 888 Valencia. Call 415-336-5034 e-mail missioniso@yahoo.com.

San Diego | May 12 | 1 pm

Call 619-708-5282 or e-mail isosandiego@yahoo.com.

Seattle | May 9 | 7 pm

Seattle Central Community College, Room TBA (Broadway & Pine on Capitol Hill). Call 206-931-2922 or e-mail seattleiso@yahoo.com.

<?php include "../../legacy-includes/BottomNavLinks.htmlf" ?>

<?php include "../../legacy-includes/RightAdFolder.htmlf" ?>


text:
Each package in the generated build system divided by a number of stages which are performed in
order:

* clean
* update/unpack
* patch
* clean:config
* configure:config
* compile:config
* install:config

Those stages can be subdivided to "common" and "config-specific". Each package has at least the
following common stages: "clean", "update" (for SCM type sources) or "unpack" (for other sources)
and "patch".

If some build type is set (`build.type` is not `nil`) and there are some configs defined for the
package then "configure" and "compile" stages are added. Additionally, `install.type` is set from
`build.type` unless overridden which causes "install" stage to be added.

The "clean" stages return the package to the initial state by removing temporary build directories.
Common stage deletes `$pkg_work_dir` (\<project dir\>/build/\<package name\>) directory by default,
config-specific clean stages remove `$pkg_build_dir` (\<project dir\>/build/\<config\>). The
directories removed by "clean" stages can be changes by setting `build.clean` property.

The "update" stage updates the source repository by pulling or cloning if the target directory is
not exists. The "unpack" stage unpacks the distribution archive to the `$pkg_work_dir`.

The "patch" stages applies patches and copies supplementary files if defined or can be overridden
to perform custom steps to prepare the package for the build.

The "configure" stage runs `configure` for "gnu" build type or CMake for "cmake" build type passing
it the defined build options.

The "compile" runs runs steps necessary for compilation, for most build types this just means
"make" command.

The "install" stage runs `make install` or equivalent for the defined install type.

### Configs

There are 2 predefined package configs in Jagen: "host" and "target". The "host" packages are
installed to the `host` subdirectory of the project root and are generally meant as helpers for
building the "target" packages (such as code generators, debuggers and utilities). The "target"
packages are meant for the target system, so they are cross-compiled using the chosen target
toolchain and are installed to the `target` subdirectory of the project which can also serve as a
staging area.

To allow running "host" packages directly for the current project the `host/bin` is added to
`$PATH` and `host/lib` is added to `$LD_LIBRARY_PATH` when you source the generated `env.sh` script
in the project directory.

Additionally, if no package rules with explicitly set config found but there are definitions
without config an empty package with "host" config is automatically defined for each such rule.
This facilitates the use case when you just need to compile a set of packages for the local system
using the native toolchain.

If the package is built or installed (has non empty `build.type` or `install.type` it will also
always have a config. So, even if you have not written any rules with the config set the "host"
will be added anyway and you will need to spell the stage by full name such as
`package:compile:host` when specifying the targets to build.

### Logs

All output from the build command is saved in `log` subdirectory of the project in files named
after the target with `.log` appended, such as `log/zeromq:patch.log` for patch stage of a package
"zeromq" or `log/zeromq:install:host.log` for "install" stage of the package "zeromq" for the
"host" config.

When you see that some target failed inspect those log files to see the commands output to diagnose
the problem.

### Targets

Targets are specified as '\<name\>:\<stage\>:\<config\>'. Available package stages are filtered
with the given expression. Omitted component means 'all'.  For example:

- utils              - select all stages of the utils package
- utils:install      - select all utils install stages
- utils::host        - select all host utils stages
- utils:compile:host - select only host utils compile stage
- :build:host        - select host build stages of all packages

When a target is successfully built the stamp file is created in the build directory with the name:
`<name>:<stage>:<config>`. This file is used to determine if the target is up to date. Deleting it
will cause the corresponding target to be rebuilt unconditionally the next time the build system
runs.

## Build system internals

_TODO: this section is out of date._

The build system is generated from a set of rules represented by tables
(key-value pairs) which are found in `rules.lua` and `pkg/<name>.lua` files
across layer directories. Each rule defines some piece of information about a
package: build stages, type, location of source directory and so on. Rules with
the same name are considered as belonging to the same package but evaluated
independently at the point of reference. So, mentioning the package in the
"requires" list of a package which has config will produce different result from
standalone "package" declaration. Also order of rules matters, both in the rules
file and across layers. See the `package` function in `src/Package.lua` file for
complete information about evaluation logic.

Package dependencies and build commands are written to `build.ninja` file in
the `build` directory, additional package specific environment goes into
"include scripts" in the `include` directory. All code dealing with include
script generation is in `src/Script.lua` file which can be used as a reference.
Dependencies are resolved by touching specifically named files in the build
directory after the command succeeded, see the generated `build.ninja` for
details.

At the core of the build system is a `jagen-stage` script. Given a package
name, stage and config it finds and imports all necessary environment files,
runs the stage script and returns its result. Default build stage scripts and
utility functions are placed in a `src/pkg.sh` file which can be used as a
reference.  Every `pkg/<name>.lua` file can have `pkg/<name>.sh` backing file
in the same directory which is included by `jagen-stage` during the build and
can be used to override default stages or environment.

Layers, build type and directory locations are set in 'config.sh' which is
generated during project initialization. It is also included indirectly in
every build command.


text:
from __future__ import division
import string
import os
def istext(filename):
    if(os.path.isdir(filename)):
        return False
    s=open(filename).read(512)
    text_characters = "".join(map(chr, range(32, 127)) + list("\n\r\t\b"))
    _null_trans = string.maketrans("", "")
    if not s:
        # Empty files are considered text
        return True
    if "\0" in s:
        # Files with null bytes are likely binary
        return False
    # Get the non-text characters (maps a character to itself then
    # use the 'remove' option to get rid of the text characters.)
    t = s.translate(_null_trans, text_characters)
    # If more than 30% non-text characters, then
    # this is considered a binary file
    if len(t)/len(s) > 0.30:
        return False
    return True