text:
#ifndef Py_CONFIG_H
#define Py_CONFIG_H

/* pyconfig.h.  NOT Generated automatically by configure.

This is a manually maintained version used for the Watcom,
Borland and Microsoft Visual C++ compilers.  It is a
standard part of the Python distribution.

WINDOWS DEFINES:
The code specific to Windows should be wrapped around one of
the following #defines

MS_WIN64 - Code specific to the MS Win64 API
MS_WIN32 - Code specific to the MS Win32 (and Win64) API (obsolete, this covers all supported APIs)
MS_WINDOWS - Code specific to Windows, but all versions.
MS_WINCE - Code specific to Windows CE
Py_ENABLE_SHARED - Code if the Python core is built as a DLL.

Also note that neither "_M_IX86" or "_MSC_VER" should be used for
any purpose other than "Windows Intel x86 specific" and "Microsoft
compiler specific".  Therefore, these should be very rare.

NOTE: The following symbols are deprecated:
NT, USE_DL_EXPORT, USE_DL_IMPORT, DL_EXPORT, DL_IMPORT
MS_CORE_DLL.

WIN32 is still required for the locale module.

*/

#ifdef _WIN32_WCE
#define MS_WINCE
#endif

/* Deprecated USE_DL_EXPORT macro - please use Py_BUILD_CORE */
#ifdef USE_DL_EXPORT
#	define Py_BUILD_CORE
#endif /* USE_DL_EXPORT */

/* Visual Studio 2005 introduces deprecation warnings for
   "insecure" and POSIX functions. The insecure functions should
   be replaced by *_s versions (according to Microsoft); the
   POSIX functions by _* versions (which, according to Microsoft,
   would be ISO C conforming). Neither renaming is feasible, so
   we just silence the warnings. */

#ifndef _CRT_SECURE_NO_DEPRECATE
#define _CRT_SECURE_NO_DEPRECATE 1
#endif
#ifndef _CRT_NONSTDC_NO_DEPRECATE
#define _CRT_NONSTDC_NO_DEPRECATE 1
#endif

/* Windows CE does not have these */
#ifndef MS_WINCE
#define HAVE_IO_H
#define HAVE_SYS_UTIME_H
#define HAVE_TEMPNAM
#define HAVE_TMPFILE
#define HAVE_TMPNAM
#define HAVE_CLOCK
#define HAVE_STRERROR
#endif

#ifdef HAVE_IO_H
#include <io.h>
#endif

#define HAVE_HYPOT
#define HAVE_STRFTIME
#define DONT_HAVE_SIG_ALARM
#define DONT_HAVE_SIG_PAUSE
#define LONG_BIT	32
#define WORD_BIT 32
#define PREFIX ""
#define EXEC_PREFIX ""

#define MS_WIN32 /* only support win32 and greater. */
#define MS_WINDOWS
#ifndef PYTHONPATH
#	define PYTHONPATH ".\\DLLs;.\\lib;.\\lib\\plat-win;.\\lib\\lib-tk"
#endif
#define NT_THREADS
#define WITH_THREAD
#ifndef NETSCAPE_PI
#define USE_SOCKET
#endif

/* CE6 doesn't have strdup() but _strdup(). Assume the same for earlier versions. */
#if defined(MS_WINCE)
#  include <stdlib.h>
#  define strdup _strdup
#endif

#ifdef MS_WINCE
/* Windows CE does not support environment variables */
#define getenv(v) (NULL)
#define environ (NULL)
#endif

/* Compiler specific defines */

/* ------------------------------------------------------------------------*/
/* Microsoft C defines _MSC_VER */
#ifdef _MSC_VER

/* We want COMPILER to expand to a string containing _MSC_VER's *value*.
 * This is horridly tricky, because the stringization operator only works
 * on macro arguments, and doesn't evaluate macros passed *as* arguments.
 * Attempts simpler than the following appear doomed to produce "_MSC_VER"
 * literally in the string.
 */
#define _Py_PASTE_VERSION(SUFFIX) \
	("[MSC v." _Py_STRINGIZE(_MSC_VER) " " SUFFIX "]")
/* e.g., this produces, after compile-time string catenation,
 * 	("[MSC v.1200 32 bit (Intel)]")
 *
 * _Py_STRINGIZE(_MSC_VER) expands to
 * _Py_STRINGIZE1((_MSC_VER)) expands to
 * _Py_STRINGIZE2(_MSC_VER) but as this call is the result of token-pasting
 *      it's scanned again for macros and so further expands to (under MSVC 6)
 * _Py_STRINGIZE2(1200) which then expands to
 * "1200"
 */
#define _Py_STRINGIZE(X) _Py_STRINGIZE1((X))
#define _Py_STRINGIZE1(X) _Py_STRINGIZE2 ## X
#define _Py_STRINGIZE2(X) #X

/* MSVC defines _WINxx to differentiate the windows platform types

   Note that for compatibility reasons _WIN32 is defined on Win32
   *and* on Win64. For the same reasons, in Python, MS_WIN32 is
   defined on Win32 *and* Win64. Win32 only code must therefore be
   guarded as follows:
   	#if defined(MS_WIN32) && !defined(MS_WIN64)
   Some modules are disabled on Itanium processors, therefore we
   have MS_WINI64 set for those targets, otherwise MS_WINX64
*/
#ifdef _WIN64
#define MS_WIN64
#endif

/* set the COMPILER */
#ifdef MS_WIN64
#if defined(_M_IA64)
#define COMPILER _Py_PASTE_VERSION("64 bit (Itanium)")
#define MS_WINI64
#elif defined(_M_X64) || defined(_M_AMD64)
#ifdef __INTEL_COMPILER
#define COMPILER ("[ICC v." _Py_STRINGIZE(__INTEL_COMPILER) " 64 bit (amd64) with MSC v." _Py_STRINGIZE(_MSC_VER) " CRT]")
#else
#define COMPILER _Py_PASTE_VERSION("64 bit (AMD64)")
#endif /* __INTEL_COMPILER */
#define MS_WINX64
#else
#define COMPILER _Py_PASTE_VERSION("64 bit (Unknown)")
#endif
#endif /* MS_WIN64 */

/* set the version macros for the windows headers */
#ifdef MS_WINX64
/* 64 bit only runs on XP or greater */
#define Py_WINVER _WIN32_WINNT_WINXP
#define Py_NTDDI NTDDI_WINXP
#else
/* Python 2.6+ requires Windows 2000 or greater */
#ifdef _WIN32_WINNT_WIN2K
#define Py_WINVER _WIN32_WINNT_WIN2K
#else
#define Py_WINVER 0x0500
#endif
#define Py_NTDDI NTDDI_WIN2KSP4
#endif

/* We only set these values when building Python - we don't want to force
   these values on extensions, as that will affect the prototypes and
   structures exposed in the Windows headers. Even when building Python, we
   allow a single source file to override this - they may need access to
   structures etc so it can optionally use new Windows features if it
   determines at runtime they are available.
*/
#if defined(Py_BUILD_CORE) || defined(Py_BUILD_CORE_MODULE)
#ifndef NTDDI_VERSION
#define NTDDI_VERSION Py_NTDDI
#endif
#ifndef WINVER
#define WINVER Py_WINVER
#endif
#ifndef _WIN32_WINNT
#define _WIN32_WINNT Py_WINVER
#endif
#endif

/* _W64 is not defined for VC6 or eVC4 */
#ifndef _W64
#define _W64
#endif

/* Define like size_t, omitting the "unsigned" */
#ifdef MS_WIN64
typedef __int64 ssize_t;
#else
typedef _W64 int ssize_t;
#endif
#define HAVE_SSIZE_T 1

#if defined(MS_WIN32) && !defined(MS_WIN64)
#ifdef _M_IX86
#ifdef __INTEL_COMPILER
#define COMPILER ("[ICC v." _Py_STRINGIZE(__INTEL_COMPILER) " 32 bit (Intel) with MSC v." _Py_STRINGIZE(_MSC_VER) " CRT]")
#else
#define COMPILER _Py_PASTE_VERSION("32 bit (Intel)")
#endif /* __INTEL_COMPILER */
#else
#define COMPILER _Py_PASTE_VERSION("32 bit (Unknown)")
#endif
#endif /* MS_WIN32 && !MS_WIN64 */

// Maya doesn't like a couple of these, as we have our own
// typedef int pid_t;

#include <float.h>
#define Py_IS_NAN _isnan
#define Py_IS_INFINITY(X) (!_finite(X) && !_isnan(X))
#define Py_IS_FINITE(X) _finite(X)

#if _MSC_VER < 1800
#define copysign _copysign
#define hypot _hypot
#endif

#endif /* _MSC_VER */

/* define some ANSI types that are not defined in earlier Win headers */
#if defined(_MSC_VER) && _MSC_VER >= 1200
/* This file only exists in VC 6.0 or higher */
#include <basetsd.h>
#endif

/* ------------------------------------------------------------------------*/
/* The Borland compiler defines __BORLANDC__ */
/* XXX These defines are likely incomplete, but should be easy to fix. */
#ifdef __BORLANDC__
#define COMPILER "[Borland]"

#ifdef _WIN32
/* tested with BCC 5.5 (__BORLANDC__ >= 0x0550)
 */

// Maya doesn't like a couple of these, as we have our own
// typedef int pid_t;

/* BCC55 seems to understand __declspec(dllimport), it is used in its
   own header files (winnt.h, ...) - so we can do nothing and get the default*/

#undef HAVE_SYS_UTIME_H
#define HAVE_UTIME_H
#define HAVE_DIRENT_H

/* rename a few functions for the Borland compiler */
#include <io.h>
#define _chsize chsize
#define _setmode setmode

#else /* !_WIN32 */
#error "Only Win32 and later are supported"
#endif /* !_WIN32 */

#endif /* BORLANDC */

/* ------------------------------------------------------------------------*/
/* egcs/gnu-win32 defines __GNUC__ and _WIN32 */
#if defined(__GNUC__) && defined(_WIN32)
/* XXX These defines are likely incomplete, but should be easy to fix.
   They should be complete enough to build extension modules. */
/* Suggested by Rene Liebscher <R.Liebscher@gmx.de> to avoid a GCC 2.91.*
   bug that requires structure imports.  More recent versions of the
   compiler don't exhibit this bug.
*/
#if (__GNUC__==2) && (__GNUC_MINOR__<=91)
#warning "Please use an up-to-date version of gcc! (>2.91 recommended)"
#endif

#define COMPILER "[gcc]"
#define hypot _hypot
#define PY_LONG_LONG long long
#define PY_LLONG_MIN LLONG_MIN
#define PY_LLONG_MAX LLONG_MAX
#define PY_ULLONG_MAX ULLONG_MAX
#endif /* GNUC */

/* ------------------------------------------------------------------------*/
/* lcc-win32 defines __LCC__ */
#if defined(__LCC__)
/* XXX These defines are likely incomplete, but should be easy to fix.
   They should be complete enough to build extension modules. */

#define COMPILER "[lcc-win32]"
// Maya doesn't like a couple of these, as we have our own
// typedef int pid_t;

/* __declspec() is supported here too - do nothing to get the defaults */

#endif /* LCC */

/* ------------------------------------------------------------------------*/
/* End of compilers - finish up */

#ifndef NO_STDIO_H
#	include <stdio.h>
#endif

/* 64 bit ints are usually spelt __int64 unless compiler has overridden */
#define HAVE_LONG_LONG 1
#ifndef PY_LONG_LONG
#	define PY_LONG_LONG __int64
#	define PY_LLONG_MAX _I64_MAX
#	define PY_LLONG_MIN _I64_MIN
#	define PY_ULLONG_MAX _UI64_MAX
#endif

/* For Windows the Python core is in a DLL by default.  Test
Py_NO_ENABLE_SHARED to find out.  Also support MS_NO_COREDLL for b/w compat */
#if !defined(MS_NO_COREDLL) && !defined(Py_NO_ENABLE_SHARED)
#	define Py_ENABLE_SHARED 1 /* standard symbol for shared library */
#	define MS_COREDLL	/* deprecated old symbol */
#endif /* !MS_NO_COREDLL && ... */

/*  All windows compilers that use this header support __declspec */
#define HAVE_DECLSPEC_DLL

/* For an MSVC DLL, we can nominate the .lib files used by extensions */
#ifdef MS_COREDLL
#	ifndef Py_BUILD_CORE /* not building the core - must be an ext */
#		if defined(_MSC_VER)
			/* So MSVC users need not specify the .lib file in
			their Makefile (other compilers are generally
			taken care of by distutils.) */
#			ifdef _DEBUG
#				pragma comment(lib,"python27_d.lib")
#			else
#				pragma comment(lib,"python27.lib")
#			endif /* _DEBUG */
#		endif /* _MSC_VER */
#	endif /* Py_BUILD_CORE */
#endif /* MS_COREDLL */

#if defined(MS_WIN64)
/* maintain "win32" sys.platform for backward compatibility of Python code,
   the Win64 API should be close enough to the Win32 API to make this
   preferable */
#	define PLATFORM "win32"
#	define SIZEOF_VOID_P 8
#	define SIZEOF_TIME_T 8
#	define SIZEOF_OFF_T 4
#	define SIZEOF_FPOS_T 8
#	define SIZEOF_HKEY 8
#	define SIZEOF_SIZE_T 8
/* configure.ac defines HAVE_LARGEFILE_SUPPORT iff HAVE_LONG_LONG,
   sizeof(off_t) > sizeof(long), and sizeof(PY_LONG_LONG) >= sizeof(off_t).
   On Win64 the second condition is not true, but if fpos_t replaces off_t
   then this is true. The uses of HAVE_LARGEFILE_SUPPORT imply that Win64
   should define this. */
#	define HAVE_LARGEFILE_SUPPORT
#elif defined(MS_WIN32)
#	define PLATFORM "win32"
#	define HAVE_LARGEFILE_SUPPORT
#	define SIZEOF_VOID_P 4
#	define SIZEOF_OFF_T 4
#	define SIZEOF_FPOS_T 8
#	define SIZEOF_HKEY 4
#	define SIZEOF_SIZE_T 4
	/* MS VS2005 changes time_t to an 64-bit type on all platforms */
#	if defined(_MSC_VER) && _MSC_VER >= 1400
#	define SIZEOF_TIME_T 8
#	else
#	define SIZEOF_TIME_T 4
#	endif
#endif

#ifdef _DEBUG
#	define Py_DEBUG
#endif

#ifdef MS_WIN32

#define SIZEOF_SHORT 2
#define SIZEOF_INT 4
#define SIZEOF_LONG 4
#define SIZEOF_LONG_LONG 8
#define SIZEOF_DOUBLE 8
#define SIZEOF_FLOAT 4

/* VC 7.1 has them and VC 6.0 does not.  VC 6.0 has a version number of 1200.
   Microsoft eMbedded Visual C++ 4.0 has a version number of 1201 and doesn't
   define these.
   If some compiler does not provide them, modify the #if appropriately. */
#if defined(_MSC_VER)
#if _MSC_VER > 1300
#define HAVE_UINTPTR_T 1
#define HAVE_INTPTR_T 1
#else
/* VC6, VS 2002 and eVC4 don't support the C99 LL suffix for 64-bit integer literals */
#define Py_LL(x) x##I64
#endif  /* _MSC_VER > 1200  */
#endif  /* _MSC_VER */

#endif

/* define signed and unsigned exact-width 32-bit and 64-bit types, used in the
   implementation of Python long integers. */
#ifndef PY_UINT32_T
#if SIZEOF_INT == 4
#define HAVE_UINT32_T 1
#define PY_UINT32_T unsigned int
#elif SIZEOF_LONG == 4
#define HAVE_UINT32_T 1
#define PY_UINT32_T unsigned long
#endif
#endif

#ifndef PY_UINT64_T
#if SIZEOF_LONG_LONG == 8
#define HAVE_UINT64_T 1
#define PY_UINT64_T unsigned PY_LONG_LONG
#endif
#endif

#ifndef PY_INT32_T
#if SIZEOF_INT == 4
#define HAVE_INT32_T 1
#define PY_INT32_T int
#elif SIZEOF_LONG == 4
#define HAVE_INT32_T 1
#define PY_INT32_T long
#endif
#endif

#ifndef PY_INT64_T
#if SIZEOF_LONG_LONG == 8
#define HAVE_INT64_T 1
#define PY_INT64_T PY_LONG_LONG
#endif
#endif

/* Fairly standard from here! */

/* Define to 1 if you have the `copysign' function. */
#define HAVE_COPYSIGN 1

/* Define to 1 if you have the `round' function. */
#if _MSC_VER >= 1800
#define HAVE_ROUND 1
#endif

/* Define to 1 if you have the `isinf' macro. */
#define HAVE_DECL_ISINF 1

/* Define to 1 if you have the `isnan' function. */
#define HAVE_DECL_ISNAN 1

/* Define if on AIX 3.
   System headers sometimes define this.
   We just want to avoid a redefinition error message.  */
#ifndef _ALL_SOURCE
/* #undef _ALL_SOURCE */
#endif

/* Define to empty if the keyword does not work.  */
/* #define const  */

/* Define to 1 if you have the <conio.h> header file. */
#ifndef MS_WINCE
#define HAVE_CONIO_H 1
#endif

/* Define to 1 if you have the <direct.h> header file. */
#ifndef MS_WINCE
#define HAVE_DIRECT_H 1
#endif

/* Define if you have dirent.h.  */
/* #define DIRENT 1 */

/* Define to the type of elements in the array set by `getgroups'.
   Usually this is either `int' or `gid_t'.  */
/* #undef GETGROUPS_T */

/* Define to `int' if <sys/types.h> doesn't define.  */
/* #undef gid_t */

/* Define if your struct tm has tm_zone.  */
/* #undef HAVE_TM_ZONE */

/* Define if you don't have tm_zone but do have the external array
   tzname.  */
#define HAVE_TZNAME

/* Define to `int' if <sys/types.h> doesn't define.  */
/* #undef mode_t */

/* Define if you don't have dirent.h, but have ndir.h.  */
/* #undef NDIR */

/* Define to `long' if <sys/types.h> doesn't define.  */
/* #undef off_t */

/* Define to `int' if <sys/types.h> doesn't define.  */
/* #undef pid_t */

/* Define if the system does not provide POSIX.1 features except
   with this defined.  */
/* #undef _POSIX_1_SOURCE */

/* Define if you need to in order for stat and other things to work.  */
/* #undef _POSIX_SOURCE */

/* Define as the return type of signal handlers (int or void).  */
#define RETSIGTYPE void

/* Define to `unsigned' if <sys/types.h> doesn't define.  */
/* #undef size_t */

/* Define if you have the ANSI C header files.  */
#define STDC_HEADERS 1

/* Define if you don't have dirent.h, but have sys/dir.h.  */
/* #undef SYSDIR */

/* Define if you don't have dirent.h, but have sys/ndir.h.  */
/* #undef SYSNDIR */

/* Define if you can safely include both <sys/time.h> and <time.h>.  */
/* #undef TIME_WITH_SYS_TIME */

/* Define if your <sys/time.h> declares struct tm.  */
/* #define TM_IN_SYS_TIME 1 */

/* Define to `int' if <sys/types.h> doesn't define.  */
/* #undef uid_t */

/* Define if the closedir function returns void instead of int.  */
/* #undef VOID_CLOSEDIR */

/* Define if getpgrp() must be called as getpgrp(0)
   and (consequently) setpgrp() as setpgrp(0, 0). */
/* #undef GETPGRP_HAVE_ARGS */

/* Define this if your time.h defines altzone */
/* #define HAVE_ALTZONE */

/* Define if you have the putenv function.  */
#ifndef MS_WINCE
#define HAVE_PUTENV
#endif

/* Define if your compiler supports function prototypes */
#define HAVE_PROTOTYPES

/* Define if  you can safely include both <sys/select.h> and <sys/time.h>
   (which you can't on SCO ODT 3.0). */
/* #undef SYS_SELECT_WITH_SYS_TIME */

/* Define if you want documentation strings in extension modules */
#define WITH_DOC_STRINGS 1

/* Define if you want to compile in rudimentary thread support */
/* #undef WITH_THREAD */

/* Define if you want to use the GNU readline library */
/* #define WITH_READLINE 1 */

/* Define if you want to have a Unicode type. */
#define Py_USING_UNICODE

/* Define as the size of the unicode type. */
/* This is enough for unicodeobject.h to do the "right thing" on Windows. */
#define Py_UNICODE_SIZE 2

/* Use Python's own small-block memory-allocator. */
#define WITH_PYMALLOC 1

/* Define if you have clock.  */
/* #define HAVE_CLOCK */

/* Define when any dynamic module loading is enabled */
#define HAVE_DYNAMIC_LOADING

/* Define if you have ftime.  */
#ifndef MS_WINCE
#define HAVE_FTIME
#endif

/* Define if you have getpeername.  */
#define HAVE_GETPEERNAME

/* Define if you have getpgrp.  */
/* #undef HAVE_GETPGRP */

/* Define if you have getpid.  */
#ifndef MS_WINCE
#define HAVE_GETPID
#endif

/* Define if you have gettimeofday.  */
/* #undef HAVE_GETTIMEOFDAY */

/* Define if you have getwd.  */
/* #undef HAVE_GETWD */

/* Define if you have lstat.  */
/* #undef HAVE_LSTAT */

/* Define if you have the mktime function.  */
#define HAVE_MKTIME

/* Define if you have nice.  */
/* #undef HAVE_NICE */

/* Define if you have readlink.  */
/* #undef HAVE_READLINK */

/* Define if you have select.  */
/* #undef HAVE_SELECT */

/* Define if you have setpgid.  */
/* #undef HAVE_SETPGID */

/* Define if you have setpgrp.  */
/* #undef HAVE_SETPGRP */

/* Define if you have setsid.  */
/* #undef HAVE_SETSID */

/* Define if you have setvbuf.  */
#define HAVE_SETVBUF

/* Define if you have siginterrupt.  */
/* #undef HAVE_SIGINTERRUPT */

/* Define if you have symlink.  */
/* #undef HAVE_SYMLINK */

/* Define if you have tcgetpgrp.  */
/* #undef HAVE_TCGETPGRP */

/* Define if you have tcsetpgrp.  */
/* #undef HAVE_TCSETPGRP */

/* Define if you have times.  */
/* #undef HAVE_TIMES */

/* Define if you have uname.  */
/* #undef HAVE_UNAME */

/* Define if you have waitpid.  */
/* #undef HAVE_WAITPID */

/* Define to 1 if you have the `wcscoll' function. */
#ifndef MS_WINCE
#define HAVE_WCSCOLL 1
#endif

/* Define if the zlib library has inflateCopy */
#define HAVE_ZLIB_COPY 1

/* Define if you have the <dlfcn.h> header file.  */
/* #undef HAVE_DLFCN_H */

/* Define to 1 if you have the <errno.h> header file. */
#ifndef MS_WINCE
#define HAVE_ERRNO_H 1
#endif

/* Define if you have the <fcntl.h> header file.  */
#ifndef MS_WINCE
#define HAVE_FCNTL_H 1
#endif

/* Define to 1 if you have the <process.h> header file. */
#ifndef MS_WINCE
#define HAVE_PROCESS_H 1
#endif

/* Define to 1 if you have the <signal.h> header file. */
#ifndef MS_WINCE
#define HAVE_SIGNAL_H 1
#endif

/* Define if you have the <stdarg.h> prototypes.  */
#define HAVE_STDARG_PROTOTYPES

/* Define if you have the <stddef.h> header file.  */
#define HAVE_STDDEF_H 1

/* Define if you have the <sys/audioio.h> header file.  */
/* #undef HAVE_SYS_AUDIOIO_H */

/* Define if you have the <sys/param.h> header file.  */
/* #define HAVE_SYS_PARAM_H 1 */

/* Define if you have the <sys/select.h> header file.  */
/* #define HAVE_SYS_SELECT_H 1 */

/* Define to 1 if you have the <sys/stat.h> header file.  */
#ifndef MS_WINCE
#define HAVE_SYS_STAT_H 1
#endif

/* Define if you have the <sys/time.h> header file.  */
/* #define HAVE_SYS_TIME_H 1 */

/* Define if you have the <sys/times.h> header file.  */
/* #define HAVE_SYS_TIMES_H 1 */

/* Define to 1 if you have the <sys/types.h> header file.  */
#ifndef MS_WINCE
#define HAVE_SYS_TYPES_H 1
#endif

/* Define if you have the <sys/un.h> header file.  */
/* #define HAVE_SYS_UN_H 1 */

/* Define if you have the <sys/utime.h> header file.  */
/* #define HAVE_SYS_UTIME_H 1 */

/* Define if you have the <sys/utsname.h> header file.  */
/* #define HAVE_SYS_UTSNAME_H 1 */

/* Define if you have the <thread.h> header file.  */
/* #undef HAVE_THREAD_H */

/* Define if you have the <unistd.h> header file.  */
/* #define HAVE_UNISTD_H 1 */

/* Define if you have the <utime.h> header file.  */
/* #define HAVE_UTIME_H 1 */

/* Define if the compiler provides a wchar.h header file. */
#define HAVE_WCHAR_H 1

/* Define if you have the dl library (-ldl).  */
/* #undef HAVE_LIBDL */

/* Define if you have the mpc library (-lmpc).  */
/* #undef HAVE_LIBMPC */

/* Define if you have the nsl library (-lnsl).  */
#define HAVE_LIBNSL 1

/* Define if you have the seq library (-lseq).  */
/* #undef HAVE_LIBSEQ */

/* Define if you have the socket library (-lsocket).  */
#define HAVE_LIBSOCKET 1

/* Define if you have the sun library (-lsun).  */
/* #undef HAVE_LIBSUN */

/* Define if you have the termcap library (-ltermcap).  */
/* #undef HAVE_LIBTERMCAP */

/* Define if you have the termlib library (-ltermlib).  */
/* #undef HAVE_LIBTERMLIB */

/* Define if you have the thread library (-lthread).  */
/* #undef HAVE_LIBTHREAD */

/* WinSock does not use a bitmask in select, and uses
   socket handles greater than FD_SETSIZE */
#define Py_SOCKET_FD_CAN_BE_GE_FD_SETSIZE

/* Define if C doubles are 64-bit IEEE 754 binary format, stored with the
   least significant byte first */
#define DOUBLE_IS_LITTLE_ENDIAN_IEEE754 1

#endif /* !Py_CONFIG_H */


text:
package DBDemo;
use Moose;
use namespace::autoclean;

use Catalyst::Runtime 5.80;

# Set flags and add plugins for the application.
#
# Note that ORDERING IS IMPORTANT here as plugins are initialized in order,
# therefore you almost certainly want to keep ConfigLoader at the head of the
# list if you're using it.
#
#         -Debug: activates the debug mode for very useful log messages
#   ConfigLoader: will load the configuration from a Config::General file in the
#                 application's home directory
# Static::Simple: will serve static files from the application's root
#                 directory

use Catalyst qw/
    -Debug
    ConfigLoader
    Authentication
    Session
    Session::Store::FastMmap
    Session::State::Cookie
    Static::Simple
    +CatalystX::SimpleLogin
    Authorization::Roles
    StackTrace
/;

extends 'Catalyst';

our $VERSION = '0.01';

# Configure the application.
#
# Note that settings in dbdemo.conf (or other external
# configuration file that you set up manually) take precedence
# over this when using ConfigLoader. Thus configuration
# details given here can function as a default configuration,
# with an external configuration file acting as an override for
# local deployment.

__PACKAGE__->config(
    name => 'DBDemo',
    # Disable deprecated behavior needed by old applications
    disable_component_resolution_regex_fallback => 1,
    enable_catalyst_header => 1, # Send X-Catalyst header
);

# Start the application
__PACKAGE__->setup();

=encoding utf8

=head1 NAME

DBDemo - Catalyst based application

=head1 SYNOPSIS

    script/dbdemo_server.pl

=head1 DESCRIPTION

[enter your description here]

=head1 SEE ALSO

L<DBDemo::Controller::Root>, L<Catalyst>

=head1 AUTHOR

Ynon Perek

=head1 LICENSE

This library is free software. You can redistribute it and/or modify
it under the same terms as Perl itself.

=cut

1;

redpajama_set_name: RedPajamaGithub


text:
package com.licryle.veliby.UI;

import android.view.View;

public interface OnSwipeListener {
  public void onSwipeRight(View mOrigin);
  public void onSwipeLeft(View mOrigin);
  public void onSwipeUp(View mOrigin);
  public void onSwipeDown(View mOrigin);
}


text:
class CJTokenValueType : public CJObjType {
 public:
  static CJObjTypeP instance(CJavaScript *js);

  CJTokenValueType(CJavaScript *js);

  CJValueP exec(CJavaScript *js, const std::string &name, const Values &values) override;

 private:
  static CJObjTypeP type_;
};

//------

// TokenValue Value
class CJTokenValue : public CJValue {
 public:
  typedef std::vector<CJTokenP> Tokens;

 public:
  CJTokenValue(CJavaScript *js, const Tokens &tokens=Tokens(), const CJValueP &value=CJValueP());

  CJTokenValue(const CJTokenValue &value);

  CJValue *dup(CJavaScript *) const override { return new CJTokenValue(*this); }

  const Tokens &tokens() const { return tokens_; }
  void setTokens(const Tokens &tokens) { tokens_ = tokens; }

  CJValueP value() const { return value_; }
  void setValue(CJValueP value);

  //---

  COptReal toReal() const override;

  COptLong toInteger() const override;

  bool toBoolean() const override;

  //---

  void addToken(CJTokenP token);

  std::string toString() const override;

  void print(std::ostream &os) const override;

 private:
  Tokens   tokens_;
  CJValueP value_;
};

#endif


text:
import moment from 'moment';
import logger from '../utils/logger';
import * as events from '../services/events';
import { STATUS_UP } from '../services/status';
import * as notifier from '../services/notifier';
import { synchronize } from '../services/persistence';

/**
 * Start listening for monitor events.
 */
export function listen() {
  events.addListener(events.EVENT_STATUS_CHANGED, handleStatusChange);
  events.addListener(events.EVENT_MONITORING_STARTED, handleMonitoringStarted);
}

/**
 * Handle status change event.
 *
 * @param {any} params
 */
async function handleStatusChange(params) {
  const { serviceName, status, time, lastStatusChanged, id, service } = params;
  const notification = {
    id,
    status,
    service,
    name: serviceName,
    time: time.clone(),
    lastStatusChanged: lastStatusChanged ? moment(lastStatusChanged).clone() : null
  };

  if (status === STATUS_UP && lastStatusChanged) {
    const downtime = time.diff(lastStatusChanged);

    notification.downtime = moment.duration(downtime, 'milliseconds').humanize();

    logger().info(`${serviceName} is up after ${notification.downtime} of downtime.`);
  } else {
    logger().info(`${serviceName} is ${status}`);
  }

  // Send notifications
  notifier.notify(notification);

  // Persist to database
  await synchronize();
}

/**
 * Handle service monitoring started event.
 *
 * @param {Object} params
 */
function handleMonitoringStarted(params) {
  logger().info(`Started monitoring ${params.serviceName}`);
}


text:
log-browse
==========

A lightweight, CGI-based tool for viewing log files via the Web, written in Haskell.


text:
package it.unibz.inf.ontop.reformulation.tests;

import com.google.common.collect.Lists;
import it.unibz.inf.ontop.ontology.Assertion;
import it.unibz.inf.ontop.ontology.OntologyVocabulary;
import it.unibz.inf.ontop.ontology.impl.OntologyFactoryImpl;
import it.unibz.inf.ontop.owlapi.OWLAPIABoxIterator;
import junit.framework.TestCase;
import org.semanticweb.owlapi.apibinding.OWLManager;
import org.semanticweb.owlapi.model.OWLOntology;
import org.semanticweb.owlapi.model.OWLOntologyManager;

import java.io.File;
import java.util.HashSet;
import java.util.Iterator;

public class OWLAPIABoxIteratorTest extends TestCase {

	private OntologyVocabulary voc;

	protected void setUp() throws Exception {
		voc = OntologyFactoryImpl.getInstance().createVocabulary();
		voc.createObjectProperty("http://it.unibz.inf/obda/ontologies/test/translation/onto2.owl#P");
		voc.createObjectProperty("http://it.unibz.inf/obda/ontologies/test/translation/onto2.owl#R");
	    voc.createDataProperty("http://it.unibz.inf/obda/ontologies/test/translation/onto2.owl#age");
	    voc.createClass("http://it.unibz.inf/obda/ontologies/test/translation/onto2.owl#Man");
	    voc.createClass("http://it.unibz.inf/obda/ontologies/test/translation/onto2.owl#Person");
	    voc.createClass("http://it.unibz.inf/obda/ontologies/test/translation/onto2.owl#Woman");
		super.setUp();
	}

	public void testAssertionIterator() throws Exception {
		String owlfile = "src/test/resources/test/ontologies/translation/onto2.owl";

		// Loading the OWL file
		OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
		OWLOntology ontology = manager.loadOntologyFromOntologyDocument(new File(owlfile));

		//Iterator<OWLAxiom> owliterator = ontology.getAxioms().iterator();
		Iterator<Assertion> aboxit = new OWLAPIABoxIterator(Lists.newArrayList(ontology), voc);
		int count = 0;
		while (aboxit.hasNext()) {
			count += 1;
			aboxit.next();
		}
		assertTrue("Count: " + count, count == 9);
	}

	public void testAssertionIterable() throws Exception {
		String owlfile = "src/test/resources/test/ontologies/translation/onto2.owl";

		// Loading the OWL file
		OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
		OWLOntology ontology = manager.loadOntologyFromOntologyDocument(new File(owlfile));

		Iterator<Assertion> aboxit = new OWLAPIABoxIterator(Lists.newArrayList(ontology), voc);
		int count = 0;
		while (aboxit.hasNext()) {
			count += 1;
			aboxit.next();
		}
		assertTrue("Count: " + count, count == 9);
	}

	public void testAssertionEmptyIterable() throws Exception {

		Iterator<Assertion> aboxit = new OWLAPIABoxIterator(Lists.<OWLOntology>newArrayList(), voc);
		int count = 0;
		while (aboxit.hasNext()) {
			count += 1;
			aboxit.next();
		}
		assertTrue("Count: " + count, count == 0);
	}

	public void testAssertionOntology() throws Exception {
		String owlfile = "src/test/resources/test/ontologies/translation/onto2.owl";

		// Loading the OWL file
		OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
		OWLOntology ontology = manager.loadOntologyFromOntologyDocument(new File(owlfile));

		Iterator<Assertion> aboxit = new OWLAPIABoxIterator(Lists.newArrayList(ontology), voc);
		int count = 0;
		while (aboxit.hasNext()) {
			count += 1;
			aboxit.next();
		}
		assertTrue("Count: " + count, count == 9);
	}

	public void testAssertionEmptyOntology() throws Exception {

		OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
		OWLOntology ontology = manager.createOntology();

		Iterator<Assertion> aboxit = new OWLAPIABoxIterator(Lists.newArrayList(ontology), voc);
		int count = 0;
		while (aboxit.hasNext()) {
			count += 1;
			aboxit.next();
		}
		assertTrue("Count: " + count, count == 0);
	}

	public void testAssertionOntologies() throws Exception {
		String owlfile1 = "src/test/resources/test/ontologies/translation/onto1.owl";
		String owlfile2 = "src/test/resources/test/ontologies/translation/onto2.owl";
		String owlfile3 = "src/test/resources/test/ontologies/translation/onto3.owl";

		// Loading the OWL file
		OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
		manager.loadOntologyFromOntologyDocument((new File(owlfile1)));
		manager.loadOntologyFromOntologyDocument((new File(owlfile2)));
		manager.loadOntologyFromOntologyDocument((new File(owlfile3)));

		Iterator<Assertion> aboxit = new OWLAPIABoxIterator(manager.getOntologies(), voc);
		int count = 0;
		while (aboxit.hasNext()) {
			count += 1;
			aboxit.next();
		}
		assertTrue("Count: " + count, count == 9);
	}

	public void testAssertionEmptyOntologySet() throws Exception {

		Iterator<Assertion> aboxit = new OWLAPIABoxIterator(new HashSet<OWLOntology>(), voc);
		int count = 0;
		while (aboxit.hasNext()) {
			count += 1;
			aboxit.next();
		}
		assertTrue("Count: " + count, count == 0);
	}

}


text:
require 'capybara/dsl'
include Capybara::DSL

# We will use the selenium driver
Capybara.current_driver = :selenium

# We will not run our own server; we will connect to a remote server
Capybara.run_server = false

# Set the base URL for all our tests
Capybara.app_host = 'http://wp.wrdsb.test'

RSpec.configure do |config|
  config.treat_symbols_as_metadata_keys_with_true_values = true
end

# Download test data: https://wpcom-themes.svn.automattic.com/demo/theme-unit-test-data.xml (updated 09/02/2014 18:49 UTC)
# Import test data into your WordPress install.
# Do this by going to Tools -> Import, using the "Download and import file attachements" option.
# Note you may have to repeat the Import step until you see "All Done" to obtain the full list of Posts and Media.

# WordPress Settings
# Adjust WordPress settings as follows:

# Settings -> General: set the Site Title to something fairly long, and set the Tagline to something even longer.
# These settings will facilitate testing how the Theme handles these values.

# Settings -> Reading: set "Blog pages show at most" to 5.
# This setting will ensure that index/archive pagination is triggered.

# Settings -> Discussion: enable Threaded Comments, at least 3 levels deep.
# This setting will facilitate testing of Theme comment list styling.

# Settings -> Discussion: enable Break comments into pages, and set 5 comments per page.
# This setting will facilitate testing of Theme paginating link markup/styling.

# Settings -> Media: ensure that no values are set for max width or height of Embedded media.
# This setting will facilitate testing of the Theme $content_width setting/implementation.

# Settings -> Permalinks: ensure that a non-default permalink setting is selected, e.g. "Month and name".
# This setting will facilitate stepping through the Theme Unit Tests.

# Create at least two Custom Menus:
# Long Menu: all included Pages
# Short Menu: a menu of 2-3 Pages

def login_as_admin
  visit('/')
  if !page.has_content?('Howdy, admin')
    visit('/wp-login.php')
    fill_in('user_login', :with => 'admin')
    fill_in('user_pass', :with => 'password')
    click_on('Log In')
  end
end

def logout
  visit('/wp-login.php?action=logout')
  click_on('log out')
end


text:
'use strict';

module.exports = {
    // Plugin - ava - https://github.com/avajs/eslint-plugin-ava
    parserOptions: {
        ecmaVersion: 8,
        sourceType: 'module',
        ecmaFeatures: {
            arrowFunctions: true,
            experimentalObjectRestSpread: false
        }
    },
    plugins: ['ava'],
    rules: {
        /********************
         * Stylistic Issues
         *******************/
        // http://eslint.org/docs/rules/id-length
        // enforce minimum and maximum identifier lengths
        'id-length': ['warn', { exceptions: ['t'] }],

        /********************
         * eslint-plugin-ava
         *******************/
        // https://github.com/avajs/eslint-plugin-ava/blob/master/docs/rules/assertion-arguments.md
        // Enforce passing correct arguments to assertions.
        'ava/assertion-arguments': 'error',

        // https://github.com/avajs/eslint-plugin-ava/blob/master/docs/rules/max-asserts.md
        // Limit the number of assertions in a test.
        'ava/max-asserts': ['off', 5],

        // https://github.com/avajs/eslint-plugin-ava/blob/master/docs/rules/no-async-fn-without-await.md
        // Ensure that async tests use `await`.
        'ava/no-async-fn-without-await': 'error',

        // https://github.com/avajs/eslint-plugin-ava/blob/master/docs/rules/no-cb-test.md
        //  Ensure no `test.cb()` is used.
        'ava/no-cb-test': 'warn',

        // https://github.com/avajs/eslint-plugin-ava/blob/master/docs/rules/no-duplicate-modifiers.md
        // Ensure tests do not have duplicate modifiers.
        'ava/no-duplicate-modifiers': 'error',

        // https://github.com/avajs/eslint-plugin-ava/blob/master/docs/rules/no-identical-title.md
        // Ensure no tests have the same title.
        'ava/no-identical-title': 'error',

        // https://github.com/avajs/eslint-plugin-ava/blob/master/docs/rules/no-ignored-test-files.md
        // Ensure no tests are written in ignored files.
        'ava/no-ignored-test-files': 'error',

        // https://github.com/avajs/eslint-plugin-ava/blob/master/docs/rules/no-invalid-end.md
        // Ensure `t.end()` is only called inside `test.cb()`.
        'ava/no-invalid-end': 'error',

        // https://github.com/avajs/eslint-plugin-ava/blob/master/docs/rules/no-nested-tests.md
        // Ensure no tests are nested.
        'ava/no-nested-tests': 'error',

        // https://github.com/avajs/eslint-plugin-ava/blob/master/docs/rules/no-only-test.md
        // Ensure no `test.only()` are present.
        'ava/no-only-test': 'error',

        // https://github.com/avajs/eslint-plugin-ava/blob/master/docs/rules/no-skip-assert.md
        // Ensure no assertions are skipped.
        'ava/no-skip-assert': 'error',

        // https://github.com/avajs/eslint-plugin-ava/blob/master/docs/rules/no-skip-test.md
        // Ensure no tests are skipped.
        'ava/no-skip-test': 'error',

        // https://github.com/avajs/eslint-plugin-ava/blob/master/docs/rules/no-statement-after-end.md
        // Ensure `t.end()` is the last statement executed.
        'ava/no-statement-after-end': 'error',

        // https://github.com/avajs/eslint-plugin-ava/blob/master/docs/rules/no-todo-implementation.md
        // Ensure `test.todo()` is not given an implementation function.
        'ava/no-todo-implementation': 'error',

        // https://github.com/avajs/eslint-plugin-ava/blob/master/docs/rules/no-todo-test.md
        // Ensure no `test.todo()` is used.
        'ava/no-todo-test': 'warn',

        // https://github.com/avajs/eslint-plugin-ava/blob/master/docs/rules/no-unknown-modifiers.md
        // Prevent the use of unknown test modifiers.
        'ava/no-unknown-modifiers': 'error',

        // https://github.com/avajs/eslint-plugin-ava/blob/master/docs/rules/prefer-async-await.md
        // Prefer using async/await instead of returning a Promise.
        'ava/prefer-async-await': 'error',

        // Allow only use of the asserts that have no power-assert alternative.
        // https://github.com/power-assert-js/power-assert
        // https://github.com/avajs/eslint-plugin-ava/blob/master/docs/rules/prefer-power-assert.md
        'ava/prefer-power-assert': 'off',

        // https://github.com/avajs/eslint-plugin-ava/blob/master/docs/rules/test-ended.md
        // Ensure callback tests are explicitly ended.
        'ava/test-ended': 'error',

        // https://github.com/avajs/eslint-plugin-ava/blob/master/docs/rules/test-title.md
        // Ensure tests have a title.
        'ava/test-title': ['error', 'if-multiple'],

        // https://github.com/avajs/eslint-plugin-ava/blob/master/docs/rules/use-t-well.md
        // Prevent the incorrect use of `t`.
        'ava/use-t-well': 'error',

        // https://github.com/avajs/eslint-plugin-ava/blob/master/docs/rules/use-t.md
        // Ensure test functions use `t` as their parameter.
        'ava/use-t': 'error',

        // https://github.com/avajs/eslint-plugin-ava/blob/master/docs/rules/use-test.md
        // Ensure that AVA is imported with `test` as the variable name.
        'ava/use-test': 'error',

        // https://github.com/avajs/eslint-plugin-ava/blob/master/docs/rules/use-true-false.md
        // Ensure that `t.true()`/`t.false()` are used instead of `t.truthy()`/`t.falsy()`.
        'ava/use-true-false': 'error'
    }
};


text:
package com.github.ambry.clustermap;

import com.codahale.metrics.Counter;
import com.codahale.metrics.MetricRegistry;
import com.github.ambry.clustermap.HelixClusterManager.HelixClusterChangeHandler;
import com.github.ambry.clustermap.HelixClusterManager.HelixClusterManagerQueryHelper;
import com.github.ambry.config.ClusterMapConfig;
import com.github.ambry.config.VerifiableProperties;
import com.github.ambry.utils.Utils;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Random;
import java.util.Set;
import java.util.stream.Collectors;
import org.apache.helix.model.InstanceConfig;
import org.apache.helix.zookeeper.datamodel.ZNRecord;
import org.json.JSONObject;
import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

import static com.github.ambry.clustermap.ClusterMapUtils.*;
import static com.github.ambry.clustermap.HelixClusterManagerTest.*;
import static com.github.ambry.clustermap.TestUtils.*;
import static org.junit.Assert.*;
import static org.junit.Assume.*;

/**
 * Test {@link HelixClusterChangeHandler} to verify its behavior is expected when handling cluster changes.
 */
@RunWith(Parameterized.class)
public class ClusterChangeHandlerTest {
  private static final String DEFAULT_PARTITION_CLASS = "defaultPartitionClass";
  private final HashMap<String, com.github.ambry.utils.TestUtils.ZkInfo> dcsToZkInfo = new HashMap<>();
  private final String[] dcs = new String[]{"DC0", "DC1"};
  private final String clusterNameStatic = "ClusterChangeHandlerTest";
  private final MockHelixCluster helixCluster;
  private final String selfInstanceName;
  private final DataNode currentNode;
  private final String localDc;
  private final String remoteDc;
  private final boolean overrideEnabled;
  private final String hardwareLayoutPath;
  private final String partitionLayoutPath;
  private final TestHardwareLayout testHardwareLayout;
  private final TestPartitionLayout testPartitionLayout;
  private final Map<String, Map<String, String>> partitionOverrideMap = new HashMap<>();
  private final Map<String, ZNRecord> znRecordMap = new HashMap<>();
  private final HelixClusterManagerTest.MockHelixManagerFactory helixManagerFactory;
  private final Properties props = new Properties();

  @Parameterized.Parameters
  public static List<Object[]> data() {
    return Arrays.asList(new Object[][]{{false}, {true}});
  }

  // set up a mock helix cluster, create separate HelixClusterManager with both Simple and Dynamic cluster change handler
  public ClusterChangeHandlerTest(boolean overrideEnabled) throws Exception {
    this.overrideEnabled = overrideEnabled;
    File tempDir = Files.createTempDirectory("ClusterChangeHandlerTest-").toFile();
    String tempDirPath = tempDir.getAbsolutePath();
    tempDir.deleteOnExit();
    hardwareLayoutPath = tempDirPath + File.separator + "hardwareLayoutTest.json";
    partitionLayoutPath = tempDirPath + File.separator + "partitionLayoutTest.json";
    String zkLayoutPath = tempDirPath + File.separator + "zkLayoutPath.json";
    localDc = dcs[0];
    remoteDc = dcs[1];
    int basePort = 2300;
    byte dcId = (byte) 0;
    for (String dc : dcs) {
      dcsToZkInfo.put(dc, new com.github.ambry.utils.TestUtils.ZkInfo(tempDirPath, dc, dcId++, basePort++, true));
    }
    JSONObject zkJson = constructZkLayoutJSON(dcsToZkInfo.values());
    // initial partition count = 3, all three partitions are Read_Write
    // cluster default setup:  6 nodes per data center. Each partition has 6 replicas (3 in local dc, 3 in remote dc)
    testHardwareLayout = constructInitialHardwareLayoutJSON(clusterNameStatic);
    testPartitionLayout = constructInitialPartitionLayoutJSON(testHardwareLayout, 3, localDc);
    Utils.writeJsonObjectToFile(zkJson, zkLayoutPath);
    Utils.writeJsonObjectToFile(testHardwareLayout.getHardwareLayout().toJSONObject(), hardwareLayoutPath);
    Utils.writeJsonObjectToFile(testPartitionLayout.getPartitionLayout().toJSONObject(), partitionLayoutPath);
    // pick one partition to override its SEAL state (mark it Read_Only)
    Random random = new Random();
    int partitionIndexToOverride = random.nextInt(testPartitionLayout.getPartitionCount());
    partitionOverrideMap.computeIfAbsent(String.valueOf(partitionIndexToOverride), k -> new HashMap<>())
        .put(ClusterMapUtils.PARTITION_STATE, ClusterMapUtils.READ_ONLY_STR);
    ZNRecord znRecord = new ZNRecord(PARTITION_OVERRIDE_STR);
    znRecord.setMapFields(partitionOverrideMap);
    znRecordMap.put(PARTITION_OVERRIDE_ZNODE_PATH, znRecord);

    currentNode = testHardwareLayout.getRandomDataNodeFromDc(localDc);
    String hostname = currentNode.getHostname();
    int portNum = currentNode.getPort();
    selfInstanceName = getInstanceName(hostname, portNum);
    props.setProperty("clustermap.host.name", hostname);
    props.setProperty("clustermap.cluster.name", clusterNamePrefixInHelix + clusterNameStatic);
    props.setProperty("clustermap.datacenter.name", localDc);
    props.setProperty("clustermap.port", Integer.toString(portNum));
    props.setProperty("clustermap.dcs.zk.connect.strings", zkJson.toString(2));
    props.setProperty("clustermap.current.xid", Long.toString(CURRENT_XID));
    props.setProperty("clustermap.enable.partition.override", Boolean.toString(overrideEnabled));
    props.setProperty("clustermap.listen.cross.colo", Boolean.toString(true));
    helixCluster =
        new MockHelixCluster(clusterNamePrefixInHelix, hardwareLayoutPath, partitionLayoutPath, zkLayoutPath);
    helixManagerFactory = new HelixClusterManagerTest.MockHelixManagerFactory(helixCluster, znRecordMap, null);
  }

  /**
   * Close the zk servers.
   */
  @After
  public void after() {
    for (com.github.ambry.utils.TestUtils.ZkInfo zkInfo : dcsToZkInfo.values()) {
      zkInfo.shutdown();
    }
  }

  /**
   * 1. test static initialization success case
   * 2. verify live instance change is able to make node HardwareState.AVAILABLE
   * 3. verify partition override behaves correctly (if enabled)
   * @throws Exception
   */
  @Test
  public void initializationSuccessTest() throws Exception {
    // After Helix bootstrap tool adds instances to cluster, MockHelixAdmin makes them up by default. Let's test a more
    // realistic case where all instances are added but no node has participated yet. For dynamic cluster change handler,
    // all instances in this case should be initialized to UNAVAILABLE. Until they have participated into cluster, the
    // subsequent live instance changes will make them up.
    helixCluster.bringAllInstancesDown();
    Properties properties = new Properties();
    properties.putAll(props);
    ClusterMapConfig clusterMapConfig2 = new ClusterMapConfig(new VerifiableProperties(properties));
    HelixClusterManager managerWithDynamicHandler =
        new HelixClusterManager(clusterMapConfig2, selfInstanceName, helixManagerFactory, new MetricRegistry());
    Set<String> partitionsInStaticMap = new HashSet<>(testPartitionLayout.getPartitionLayout().getAllPartitionNames());
    Set<String> partitionsInDynamicHandler = managerWithDynamicHandler.getAllPartitionIds(null)
        .stream()
        .map(PartitionId::toPathString)
        .collect(Collectors.toSet());
    assertEquals("Partitions from dynamic change handler don't match those in static layout", partitionsInStaticMap,
        partitionsInDynamicHandler);
    HelixClusterManagerQueryHelper dynamicHandlerCallback = managerWithDynamicHandler.getManagerQueryHelper();
    // verify that all nodes (except for current node) are down in HelixClusterManager with dynamic cluster change handler
    assertEquals("All nodes (except for self node) should be down", helixCluster.getDownInstances().size() - 1,
        dynamicHandlerCallback.getDownDatanodesCount());
    // then we bring all instances up and trigger live instance change again
    helixCluster.bringAllInstancesUp();
    // verify all nodes are up now up
    assertEquals("All nodes should be up now", 0, dynamicHandlerCallback.getDownDatanodesCount());
    // verify partition override, for now we have 3 partitions and one of them is overridden to Read_Only (if enabled)
    int partitionCnt = testPartitionLayout.getPartitionCount();
    assertEquals("Number of writable partitions is not correct", overrideEnabled ? partitionCnt - 1 : partitionCnt,
        dynamicHandlerCallback.getPartitionReadWriteCount());
    // close helix cluster managers
    managerWithDynamicHandler.close();
  }

  /**
   * Test failure case when initializing {@link HelixClusterManager} with dynamic cluster change handler
   */
  @Test
  public void initializationFailureTest() {
    // save current local dc for restore purpose
    int savedport = dcsToZkInfo.get(localDc).getPort();
    // mock local dc connectivity issue
    dcsToZkInfo.get(localDc).setPort(0);
    JSONObject invalidZkJson = constructZkLayoutJSON(dcsToZkInfo.values());
    Properties properties = new Properties();
    properties.putAll(props);
    properties.setProperty("clustermap.dcs.zk.connect.strings", invalidZkJson.toString(2));
    ClusterMapConfig invalidClusterMapConfig = new ClusterMapConfig(new VerifiableProperties(properties));
    MetricRegistry metricRegistry = new MetricRegistry();
    try {
      new HelixClusterManager(invalidClusterMapConfig, selfInstanceName, helixManagerFactory, metricRegistry);
      fail("Instantiation with dynamic cluster change handler should fail due to connection issue to zk");
    } catch (IOException e) {
      assertEquals(1L,
          metricRegistry.getGauges().get(HelixClusterManager.class.getName() + ".instantiationFailed").getValue());
      assertEquals(1L, metricRegistry.getGauges()
          .get(HelixClusterManager.class.getName() + ".instantiationExceptionCount")
          .getValue());
    }
    // restore original setup
    dcsToZkInfo.get(localDc).setPort(savedport);
  }

  /**
   * Test that {@link HelixClusterChangeHandler} is able to handle invalid info entry in the InstanceConfig at runtime
   * or during initialization.
   */
  @Test
  public void instanceConfigInvalidInfoEntryTest() throws IOException {
    Properties properties = new Properties();
    properties.putAll(props);
    ClusterMapConfig clusterMapConfig = new ClusterMapConfig(new VerifiableProperties(properties));
    HelixClusterManager helixClusterManager =
        new HelixClusterManager(clusterMapConfig, selfInstanceName, helixManagerFactory, new MetricRegistry());

    Counter initFailureCount = new Counter();
    HelixClusterChangeHandler helixClusterChangeHandler =
        helixClusterManager.new HelixClusterChangeHandler(localDc, e -> initFailureCount.inc(), false);
    // create an InstanceConfig with invalid entry that mocks error info added by Helix controller
    PartitionId selectedPartition = testPartitionLayout.getPartitionLayout().getPartitions(null).get(0);
    Replica testReplica = (Replica) selectedPartition.getReplicaIds().get(0);
    DataNode testNode = (DataNode) testReplica.getDataNodeId();
    InstanceConfig instanceConfig = new InstanceConfig(getInstanceName(testNode.getHostname(), testNode.getPort()));
    instanceConfig.setHostName(testNode.getHostname());
    instanceConfig.setPort(Integer.toString(testNode.getPort()));
    instanceConfig.getRecord().setSimpleField(ClusterMapUtils.DATACENTER_STR, testNode.getDatacenterName());
    instanceConfig.getRecord().setSimpleField(ClusterMapUtils.RACKID_STR, testNode.getRackId());
    instanceConfig.getRecord()
        .setSimpleField(ClusterMapUtils.SCHEMA_VERSION_STR, Integer.toString(ClusterMapUtils.CURRENT_SCHEMA_VERSION));
    instanceConfig.getRecord().setListField(ClusterMapUtils.SEALED_STR, Collections.emptyList());
    instanceConfig.getRecord().setListField(ClusterMapUtils.STOPPED_REPLICAS_STR, Collections.emptyList());

    Map<String, Map<String, String>> diskInfos = new HashMap<>();
    assertNotNull("testReplica should not be null", testReplica);
    Map<String, String> diskInfo = new HashMap<>();
    diskInfo.put(ClusterMapUtils.DISK_CAPACITY_STR, Long.toString(testReplica.getDiskId().getRawCapacityInBytes()));
    diskInfo.put(ClusterMapUtils.DISK_STATE, ClusterMapUtils.AVAILABLE_STR);
    String replicasStrBuilder =
        testReplica.getPartition().getId() + ClusterMapUtils.REPLICAS_STR_SEPARATOR + testReplica.getCapacityInBytes()
            + ClusterMapUtils.REPLICAS_STR_SEPARATOR + testReplica.getPartition().getPartitionClass()
            + ClusterMapUtils.REPLICAS_DELIM_STR;
    diskInfo.put(ClusterMapUtils.REPLICAS_STR, replicasStrBuilder);
    diskInfos.put(testReplica.getDiskId().getMountPath(), diskInfo);
    // add an invalid entry at the end of diskInfos
    Map<String, String> invalidEntry = new HashMap<>();
    invalidEntry.put("INVALID_KEY", "INVALID_VALUE");
    diskInfos.put("INVALID_MOUNT_PATH", invalidEntry);
    instanceConfig.getRecord().setMapFields(diskInfos);
    // we call onInstanceConfigChange() twice
    InstanceConfigToDataNodeConfigAdapter.Converter converter =
        new InstanceConfigToDataNodeConfigAdapter.Converter(clusterMapConfig);
    // 1st call, to verify initialization code path
    helixClusterChangeHandler.onDataNodeConfigChange(Collections.singleton(converter.convert(instanceConfig)));
    // 2nd call, to verify dynamic update code path
    helixClusterChangeHandler.onDataNodeConfigChange(Collections.singletonList(converter.convert(instanceConfig)));
    assertEquals("There shouldn't be initialization errors", 0, initFailureCount.getCount());
  }

  /**
   * Test new instances/partitions are added to cluster dynamically. {@link HelixClusterManager} with
   * {@link HelixClusterChangeHandler} should absorb the change and update in-mem cluster map.
   * 1. add new instance
   * 2. add new partition onto new instance
   * 3. add new partition onto existing instance
   */
  @Test
  public void addNewInstancesAndPartitionsTest() throws Exception {
    // create a HelixClusterManager with DynamicClusterChangeHandler
    Properties properties = new Properties();
    properties.putAll(props);
    ClusterMapConfig clusterMapConfig = new ClusterMapConfig(new VerifiableProperties(properties));
    HelixClusterManager helixClusterManager =
        new HelixClusterManager(clusterMapConfig, selfInstanceName, helixManagerFactory, new MetricRegistry());
    // before adding new instances, let's first ensure current number of nodes is correct.
    List<DataNode> dataNodesInLayout = new ArrayList<>();
    testHardwareLayout.getHardwareLayout().getDatacenters().forEach(dc -> dataNodesInLayout.addAll(dc.getDataNodes()));
    assertEquals("Number of data nodes is not expected", dataNodesInLayout.size(),
        helixClusterManager.getDataNodeIds().size());

    // pick 2 existing nodes from each dc (also the nodes from local dc should be different from currentNode)
    List<DataNode> nodesToHostNewPartition = new ArrayList<>();
    List<DataNode> localDcNodes = testHardwareLayout.getAllDataNodesFromDc(localDc);
    localDcNodes.remove(currentNode);
    DataNode localDcNode1 = localDcNodes.get(0);
    DataNode localDcNode2 = localDcNodes.get(localDcNodes.size() - 1);
    List<DataNode> remoteDcNodes = testHardwareLayout.getAllDataNodesFromDc(remoteDc);
    DataNode remoteDcNode1 = remoteDcNodes.get(0);
    DataNode remoteDcNode2 = remoteDcNodes.get(remoteDcNodes.size() - 1);

    // add a new node into static layout
    testHardwareLayout.addNewDataNodes(1);
    // add a new partition to static layout and put its replicas to both existing nodes and new node
    List<DataNode> newAddedNodes = new ArrayList<>();
    testHardwareLayout.getHardwareLayout().getDatacenters().forEach(dc -> newAddedNodes.addAll(dc.getDataNodes()));
    newAddedNodes.removeAll(dataNodesInLayout);
    // pick 2 existing nodes and 1 new node from each dc to add a replica from new partition
    nodesToHostNewPartition.addAll(Arrays.asList(localDcNode1, localDcNode2));
    nodesToHostNewPartition.addAll(Arrays.asList(remoteDcNode1, remoteDcNode2));
    nodesToHostNewPartition.addAll(newAddedNodes);
    testPartitionLayout.addNewPartition(testHardwareLayout, nodesToHostNewPartition, DEFAULT_PARTITION_CLASS);
    // write new HardwareLayout and PartitionLayout into files
    Utils.writeJsonObjectToFile(testHardwareLayout.getHardwareLayout().toJSONObject(), hardwareLayoutPath);
    Utils.writeJsonObjectToFile(testPartitionLayout.getPartitionLayout().toJSONObject(), partitionLayoutPath);
    // this triggers a InstanceConfig change notification.
    // In each dc, 2 existing instance configs are updated and 1 new instance is added as well as 1 new partition
    helixCluster.upgradeWithNewHardwareLayout(hardwareLayoutPath);

    // verify after InstanceConfig change, HelixClusterManager contains the one more node per dc.
    assertEquals("Number of data nodes after instance addition is not correct",
        testHardwareLayout.getAllExistingDataNodes().size(), helixClusterManager.getDataNodeIds().size());
    // verify number of partitions in cluster manager has increased by 1
    assertEquals("Number of partitions after partition addition is not correct",
        testPartitionLayout.getPartitionCount(), helixClusterManager.getAllPartitionIds(null).size());
    // verify writable partitions in HelixClusterManager with partition override enabled/disabled (to call getWritablePartitionIds,
    // we need to bring new added instances up because that method checks if all local replicas are up)
    for (DataNode newNode : newAddedNodes) {
      helixCluster.bringInstanceUp(getInstanceName(newNode.getHostname(), newNode.getPort()));
    }
    assertEquals("Number of writable partitions after partition addition is not correct",
        overrideEnabled ? testPartitionLayout.getPartitionCount() - 1 : testPartitionLayout.getPartitionCount(),
        helixClusterManager.getWritablePartitionIds(null).size());

    // verify capacity stats are updated
    HelixClusterManagerQueryHelper clusterManagerCallback = helixClusterManager.getManagerQueryHelper();
    // note that we add one node to each dc, so the raw capacity = (# of nodes) * (# of disks) * (disk capacity)
    long rawCapacityInStaticLayout =
        testHardwareLayout.getAllExistingDataNodes().size() * testHardwareLayout.getDiskCount()
            * testHardwareLayout.getDiskCapacityInBytes();
    assertEquals("Raw capacity of entire cluster is not expected", rawCapacityInStaticLayout,
        clusterManagerCallback.getRawCapacity());
    // we have added one more partition, so now the allocated raw capacity in cluster is 4 (partition count) * 6 * ReplicaCapacity
    assertEquals("Allocated raw capacity of entire cluster is not correct",
        testPartitionLayout.getAllocatedRawCapacityInBytes(), clusterManagerCallback.getAllocatedRawCapacity());
    // verify usable capacity
    assertEquals("Allocated usable capacity of entire cluster is not correct",
        testPartitionLayout.getAllocatedUsableCapacityInBytes(), clusterManagerCallback.getAllocatedUsableCapacity());

    // additional tests to verify getting replicas, disks and resources etc returns correct results.
    for (DataNode newNode : newAddedNodes) {
      AmbryDataNode ambryNode = helixClusterManager.getDataNodeId(newNode.getHostname(), newNode.getPort());
      assertNotNull("New added node should exist in HelixClusterManager", ambryNode);
      List<AmbryReplica> ambryReplicas = helixClusterManager.getReplicaIds(ambryNode);
      assertEquals("There should be one replica on the new node", 1, ambryReplicas.size());
      Set<AmbryDisk> ambryDisks = new HashSet<>(clusterManagerCallback.getDisks(ambryNode));
      assertEquals("Disk count on the new node is not correct", localDcNode1.getDisks().size(), ambryDisks.size());
      // verify that get a non-existent partition on new node should return null
      assertNull("Should return null when getting a non-existent replica on new node",
          helixClusterManager.getReplicaForPartitionOnNode(ambryNode, "0"));
    }
    // trigger IdealState change and refresh partition-to-resource mapping (bring in the new partition in resource map)
    helixCluster.refreshIdealState();
    Map<String, String> partitionNameToResource = helixClusterManager.getPartitionToResourceMap().get(localDc);
    List<PartitionId> partitionIds = testPartitionLayout.getPartitionLayout().getPartitions(null);
    // verify all partitions (including the new added one) are present in partition-to-resource map
    Set<String> partitionNames = partitionIds.stream().map(PartitionId::toPathString).collect(Collectors.toSet());
    assertEquals("Some partitions are not present in partition-to-resource map", partitionNames,
        partitionNameToResource.keySet());
    // verify all partitions are able to get their resource name
    helixClusterManager.getAllPartitionIds(DEFAULT_PARTITION_CLASS)
        .forEach(partitionId -> assertEquals("Resource name is not expected",
            partitionNameToResource.get(partitionId.toPathString()), partitionId.getResourceName()));
    helixClusterManager.close();
  }

  /**
   * Test the case where replica is added or removed and {@link PartitionSelectionHelper} is able to incorporate cluster
   * map changes.
   * Test setup: (1) remove one replica of Partition1 from local dc;
   *             (2) add another replica of Partition2 to local dc;
   *             (3) add one replica of Partition1 to remote dc;
   * @throws Exception
   */
  @Test
  public void partitionSelectionOnReplicaAddedOrRemovedTest() throws Exception {
    assumeTrue(!overrideEnabled);
    // create a HelixClusterManager with DynamicClusterChangeHandler
    Properties properties = new Properties();
    properties.putAll(props);
    ClusterMapConfig clusterMapConfig = new ClusterMapConfig(new VerifiableProperties(properties));
    HelixClusterManager helixClusterManager =
        new HelixClusterManager(clusterMapConfig, selfInstanceName, helixManagerFactory, new MetricRegistry());

    List<PartitionId> partitions = testPartitionLayout.getPartitionLayout().getPartitions(null);
    // partition1 has a replica to remove in local dc; partition2 has a replica to add in local dc
    // also add an extra replica from partition1 in remote dc
    PartitionId partition1 = partitions.get(0);
    PartitionId partition2 = partitions.get(partitions.size() - 1);
    int replicaCountForPart1 = partition1.getReplicaIds().size();
    int replicaCountForPart2 = partition2.getReplicaIds().size();
    List<DataNodeId> remoteNodesForPartition1 = getPartitionDataNodesFromDc(partition1, remoteDc);
    List<DataNodeId> localNodesForPartition2 = getPartitionDataNodesFromDc(partition2, localDc);
    // remove one replica from partition1 in local dc
    Replica replicaToRemove = (Replica) partition1.getReplicaIds()
        .stream()
        .filter(r -> r.getDataNodeId().getDatacenterName().equals(localDc))
        .findFirst()
        .get();
    testPartitionLayout.removeReplicaFromPartition(replicaToRemove);
    // add one replica of partition1 to remote dc
    Datacenter localDataCenter = null, remoteDataCenter = null;
    for (Datacenter datacenter : testHardwareLayout.getHardwareLayout().getDatacenters()) {
      if (datacenter.getName().equals(localDc)) {
        localDataCenter = datacenter;
      } else {
        remoteDataCenter = datacenter;
      }
    }
    assertNotNull("Remote data center is null", remoteDataCenter);
    assertNotNull("Local data center is null", localDataCenter);
    DataNode nodeToAddPartition1 =
        remoteDataCenter.getDataNodes().stream().filter(n -> !remoteNodesForPartition1.contains(n)).findFirst().get();
    testPartitionLayout.addReplicaToPartition(nodeToAddPartition1, (Partition) partition1);
    // add one replica of partition2 to node in local dc (the node should be different to currentNode as we didn't
    // populate bootstrap replica map for this test)
    DataNode nodeToAddPartition2 = localDataCenter.getDataNodes()
        .stream()
        .filter(n -> !localNodesForPartition2.contains(n) && n != currentNode)
        .findFirst()
        .get();
    testPartitionLayout.addReplicaToPartition(nodeToAddPartition2, (Partition) partition2);
    Utils.writeJsonObjectToFile(testPartitionLayout.getPartitionLayout().toJSONObject(), partitionLayoutPath);

    helixCluster.upgradeWithNewPartitionLayout(partitionLayoutPath,
        HelixBootstrapUpgradeUtil.HelixAdminOperation.BootstrapCluster);

    List<PartitionId> partitionsInManager = helixClusterManager.getAllPartitionIds(null);
    PartitionId ambryPartition1 =
        partitionsInManager.stream().filter(p -> p.toPathString().equals(partition1.toPathString())).findFirst().get();
    PartitionId ambryPartition2 =
        partitionsInManager.stream().filter(p -> p.toPathString().equals(partition2.toPathString())).findFirst().get();
    assertEquals("Replica count of partition1 is not expected", replicaCountForPart1,
        ambryPartition1.getReplicaIds().size());
    assertEquals("Replica count of partition2 is not expected", replicaCountForPart2 + 1,
        ambryPartition2.getReplicaIds().size());
    // Note that there are 3 partitions in total in cluster, partition[0] has 2 replicas, partition[1] has 3 replicas
    // and partition[2] has 4 replicas in local dc. Also the minimumLocalReplicaCount = 3, so this is to test if partition
    // selection helper is able to pick right partitions with local replica count >= 3.
    List<PartitionId> writablePartitions = helixClusterManager.getWritablePartitionIds(DEFAULT_PARTITION_CLASS);
    assertEquals("Number of writable partition is not expected", 2, writablePartitions.size());
    helixClusterManager.close();
  }

  /**
   * Test the case where a current replica is moved between existing nodes.
   */
  @Test
  public void moveReplicaTest() throws Exception {
    // create a HelixClusterManager with DynamicClusterChangeHandler
    Properties properties = new Properties();
    properties.putAll(props);
    ClusterMapConfig clusterMapConfig = new ClusterMapConfig(new VerifiableProperties(properties));
    HelixClusterManager helixClusterManager =
        new HelixClusterManager(clusterMapConfig, selfInstanceName, helixManagerFactory, new MetricRegistry());
    // pick a partition and move one of its replicas
    Partition testPartition =
        (Partition) testPartitionLayout.getPartitionLayout().getRandomWritablePartition(null, null);
    int previousReplicaCnt = testPartition.getReplicaIds().size();
    // 1. find out nodes in local dc that host this partition
    List<DataNodeId> localDcNodes = getPartitionDataNodesFromDc(testPartition, localDc);
    // 2. then find a node in local dc that doesn't host this partition (this is the node we will add replica to)
    Datacenter localDatacenter = testHardwareLayout.getHardwareLayout()
        .getDatacenters()
        .stream()
        .filter(dc -> dc.getName().equals(localDc))
        .findFirst()
        .get();
    // since we didn't populate bootstrap replica map, we have to avoid adding replica to currentNode
    DataNode nodeToAddReplica = localDatacenter.getDataNodes()
        .stream()
        .filter(node -> !localDcNodes.contains(node) && node != currentNode)
        .findFirst()
        .get();
    testPartitionLayout.addReplicaToPartition(nodeToAddReplica, testPartition);
    Utils.writeJsonObjectToFile(testPartitionLayout.getPartitionLayout().toJSONObject(), partitionLayoutPath);
    // 3. We upgrade helix by adding new replica to the chosen node in local dc. This is to mock "replica addition" on
    //    chosen node and chosen node updates its instanceConfig in Helix. There should be 7 (= 6+1) replicas in the
    //    intermediate state.
    helixCluster.upgradeWithNewPartitionLayout(partitionLayoutPath,
        HelixBootstrapUpgradeUtil.HelixAdminOperation.BootstrapCluster);
    PartitionId partitionInManager = helixClusterManager.getAllPartitionIds(null)
        .stream()
        .filter(p -> p.toPathString().equals(testPartition.toPathString()))
        .findFirst()
        .get();
    assertEquals("Replica count of testing partition is not correct", previousReplicaCnt + 1,
        partitionInManager.getReplicaIds().size());
    // 4. find a replica (from same partition) in local dc that is not just added one
    Replica oldReplica = (Replica) testPartition.getReplicaIds()
        .stream()
        .filter(r -> r.getDataNodeId().getDatacenterName().equals(localDc) && r.getDataNodeId() != nodeToAddReplica)
        .findFirst()
        .get();
    testPartitionLayout.removeReplicaFromPartition(oldReplica);
    Utils.writeJsonObjectToFile(testPartitionLayout.getPartitionLayout().toJSONObject(), partitionLayoutPath);
    // 5. disable the replica in Helix to mock replica decommission which will remove it from InstanceConfig but keep it
    //    in IdealState temporarily.
    helixCluster.upgradeWithNewPartitionLayout(partitionLayoutPath,
        HelixBootstrapUpgradeUtil.HelixAdminOperation.DisablePartition);
    Set<ReplicaId> replicasInDifferentStates = new HashSet<>();
    for (ReplicaState state : EnumSet.of(ReplicaState.STANDBY, ReplicaState.LEADER, ReplicaState.OFFLINE,
        ReplicaState.INACTIVE, ReplicaState.BOOTSTRAP)) {
      replicasInDifferentStates.addAll(partitionInManager.getReplicaIdsByState(state, null));
    }
    // verify there is no null replica
    replicasInDifferentStates.forEach(r -> assertNotNull("found null replica", r));
    // 6. updates the IdealState in Helix. The number of replicas should become 6 again.
    helixCluster.upgradeWithNewPartitionLayout(partitionLayoutPath,
        HelixBootstrapUpgradeUtil.HelixAdminOperation.UpdateIdealState);
    assertEquals("Replica count of testing partition is not correct", previousReplicaCnt,
        partitionInManager.getReplicaIds().size());

    helixClusterManager.close();
  }

  /**
   * Test the case where current node receives InstanceConfig change triggered by itself due to replica addition. We need
   * to verify {@link HelixClusterChangeHandler} will check if new replica from InstanceConfig exists in bootstrap
   * replica map. The intention here is to avoid creating a second instance of replica on current node.
   */
  @Test
  public void replicaAdditionOnCurrentNodeTest() throws Exception {
    // create a HelixClusterManager with DynamicClusterChangeHandler
    Properties properties = new Properties();
    properties.putAll(props);
    ClusterMapConfig clusterMapConfig = new ClusterMapConfig(new VerifiableProperties(properties));
    HelixClusterManager helixClusterManager =
        new HelixClusterManager(clusterMapConfig, selfInstanceName, helixManagerFactory, new MetricRegistry());
    // test setup: create 2 new partitions and place their replicas onto nodes that exclude currentNode. This is to avoid
    // edge case where currentNode already has all partitions in cluster
    Set<PartitionId> initialPartitionSet = new HashSet<>(testPartitionLayout.getPartitionLayout().getPartitions(null));
    List<DataNode> nodesToHostNewPartition = new ArrayList<>();
    List<DataNode> localDcNodes = testHardwareLayout.getAllDataNodesFromDc(localDc)
        .stream()
        .filter(node -> node != currentNode)
        .collect(Collectors.toList());
    List<DataNode> remoteDcNodes = testHardwareLayout.getAllDataNodesFromDc(remoteDc);
    nodesToHostNewPartition.addAll(localDcNodes.subList(0, 3));
    nodesToHostNewPartition.addAll(remoteDcNodes.subList(0, 3));
    testPartitionLayout.addNewPartition(testHardwareLayout, nodesToHostNewPartition, DEFAULT_PARTITION_CLASS);
    // add one more new partition
    testPartitionLayout.addNewPartition(testHardwareLayout, nodesToHostNewPartition, DEFAULT_PARTITION_CLASS);
    // write new HardwareLayout and PartitionLayout into files
    Utils.writeJsonObjectToFile(testHardwareLayout.getHardwareLayout().toJSONObject(), hardwareLayoutPath);
    Utils.writeJsonObjectToFile(testPartitionLayout.getPartitionLayout().toJSONObject(), partitionLayoutPath);
    // this triggers a InstanceConfig change notification.
    helixCluster.upgradeWithNewHardwareLayout(hardwareLayoutPath);
    Set<PartitionId> updatedPartitionSet = new HashSet<>(testPartitionLayout.getPartitionLayout().getPartitions(null));
    updatedPartitionSet.removeAll(initialPartitionSet);
    List<PartitionId> addedPartitions = new ArrayList<>(updatedPartitionSet);
    assertEquals("There should be 2 added partitions", 2, addedPartitions.size());
    Partition addedPartition1 = (Partition) addedPartitions.get(0);
    Partition addedPartition2 = (Partition) addedPartitions.get(1);
    // add one replica of this newly added partition1 to currentNode
    testPartitionLayout.addReplicaToPartition(currentNode, addedPartition1);
    // before upgrading Helix, let's save the replica count of test partition to a variable
    PartitionId partitionInManager = helixClusterManager.getAllPartitionIds(null)
        .stream()
        .filter(p -> p.toPathString().equals(addedPartition1.toPathString()))
        .findFirst()
        .get();
    int previousReplicaCnt = partitionInManager.getReplicaIds().size();
    // test case 1: without populating bootstrap replica, new replica in InstanceConfig will trigger exception on current
    // node (this shouldn't happen in practice but we still mock this situation to perform exhaustive testing)
    Utils.writeJsonObjectToFile(testPartitionLayout.getPartitionLayout().toJSONObject(), partitionLayoutPath);
    helixCluster.upgradeWithNewPartitionLayout(partitionLayoutPath,
        HelixBootstrapUpgradeUtil.HelixAdminOperation.BootstrapCluster);
    assertEquals("Replica count of testing partition shouldn't change", previousReplicaCnt,
        partitionInManager.getReplicaIds().size());
    // verify there is an exception when handling instance config change due to replica not found in bootstrap replica map
    assertEquals("Instance config change error count should be 1", 1,
        helixClusterManager.helixClusterManagerMetrics.instanceConfigChangeErrorCount.getCount());
    helixClusterManager.close();
    // test case 2: call getBootstrapReplica in HelixClusterManager to populate bootstrap replica map and then upgrade
    // Helix again.
    Map<String, Map<String, String>> partitionToReplicaInfosMap = new HashMap<>();
    Map<String, String> newReplicaInfos = new HashMap<>();
    newReplicaInfos.put(PARTITION_CLASS_STR, DEFAULT_PARTITION_CLASS);
    newReplicaInfos.put(REPLICAS_CAPACITY_STR, String.valueOf(TestPartitionLayout.defaultReplicaCapacityInBytes));
    newReplicaInfos.put(currentNode.getHostname() + "_" + currentNode.getPort(),
        currentNode.getDisks().get(0).getMountPath());
    partitionToReplicaInfosMap.put(addedPartition2.toPathString(), newReplicaInfos);
    // set ZNRecord
    ZNRecord replicaInfosZNRecord = new ZNRecord(REPLICA_ADDITION_STR);
    replicaInfosZNRecord.setMapFields(partitionToReplicaInfosMap);
    znRecordMap.put(REPLICA_ADDITION_ZNODE_PATH, replicaInfosZNRecord);
    // create a new HelixClusterManager with replica addition info in Helix
    helixClusterManager = new HelixClusterManager(clusterMapConfig, selfInstanceName,
        new HelixClusterManagerTest.MockHelixManagerFactory(helixCluster, znRecordMap, null), new MetricRegistry());
    ReplicaId bootstrapReplica = helixClusterManager.getBootstrapReplica(addedPartition2.toPathString(), currentNode);
    assertNotNull("Getting bootstrap replica should succeed", bootstrapReplica);
    // add replica of new partition2 to currentNode
    testPartitionLayout.addReplicaToPartition(currentNode, addedPartition2);
    Utils.writeJsonObjectToFile(testPartitionLayout.getPartitionLayout().toJSONObject(), partitionLayoutPath);
    helixCluster.upgradeWithNewPartitionLayout(partitionLayoutPath,
        HelixBootstrapUpgradeUtil.HelixAdminOperation.BootstrapCluster);

    partitionInManager = helixClusterManager.getAllPartitionIds(null)
        .stream()
        .filter(p -> p.toPathString().equals(addedPartition2.toPathString()))
        .findFirst()
        .get();
    // this time the new replica should be present in bootstrap replica map and therefore replica count should increase
    assertEquals("Replica count of testing partition shouldn't change", previousReplicaCnt + 1,
        partitionInManager.getReplicaIds().size());
    // verify that the replica instance in HelixClusterManager is same with bootstrap replica instance
    ReplicaId replicaInManager = helixClusterManager.getReplicaIds(
        helixClusterManager.getDataNodeId(currentNode.getHostname(), currentNode.getPort()))
        .stream()
        .filter(r -> r.getPartitionId().toPathString().equals(addedPartition2.toPathString()))
        .findFirst()
        .get();
    assertSame("There should be exactly one instance for added replica", replicaInManager, bootstrapReplica);
    helixClusterManager.close();
  }

  /**
   * Test the case where the disk capacity is updated dynamically.
   * @throws Exception
   */
  @Test
  public void diskCapacityUpdateTest() throws Exception {
    // create a HelixClusterManager with DynamicClusterChangeHandler
    Properties properties = new Properties();
    properties.putAll(props);
    ClusterMapConfig clusterMapConfig = new ClusterMapConfig(new VerifiableProperties(properties));
    HelixClusterManager helixClusterManager =
        new HelixClusterManager(clusterMapConfig, selfInstanceName, helixManagerFactory, new MetricRegistry());
    // disk capacity after initialization should equal to original value (100L * 1024 * 1024 * 1024)
    PartitionId partitionId = helixClusterManager.getAllPartitionIds(null).get(0);
    assertEquals("Mismatch in disk capacity", 100L * 1024 * 1024 * 1024,
        partitionId.getReplicaIds().get(0).getDiskId().getRawCapacityInBytes());
    // update disk capacity
    testHardwareLayout.updateDiskCapacity(500L * 1024 * 1024 * 1024);
    Utils.writeJsonObjectToFile(testHardwareLayout.getHardwareLayout().toJSONObject(), hardwareLayoutPath);
    helixCluster.upgradeWithNewHardwareLayout(hardwareLayoutPath);
    partitionId = helixClusterManager.getAllPartitionIds(null).get(0);
    assertEquals("Mismatch in disk capacity", 500L * 1024 * 1024 * 1024,
        partitionId.getReplicaIds().get(0).getDiskId().getRawCapacityInBytes());
    helixClusterManager.close();
  }

  /**
   * Get data nodes that hold given partition in certain datacenter
   * @param partitionId the partition which the nodes should hold.
   * @param dcName the data center in which these nodes are.
   * @return a list of nodes that hold given partition.
   */
  private List<DataNodeId> getPartitionDataNodesFromDc(PartitionId partitionId, String dcName) {
    return partitionId.getReplicaIds()
        .stream()
        .filter(r -> r.getDataNodeId().getDatacenterName().equals(dcName))
        .map(ReplicaId::getDataNodeId)
        .collect(Collectors.toList());
  }
}


text:
namespace kythe {

std::string getMacroUnexpandedString(clang::SourceRange Range,
                                     clang::Preprocessor &PP,
                                     llvm::StringRef MacroName,
                                     const clang::MacroInfo *MI) {
  clang::SourceLocation BeginLoc(Range.getBegin());
  const char *BeginPtr = PP.getSourceManager().getCharacterData(BeginLoc);
  size_t Length;
  std::string Unexpanded;
  if (MI->isFunctionLike()) {
    clang::SourceLocation EndLoc(Range.getEnd());
    const char *EndPtr = PP.getSourceManager().getCharacterData(EndLoc) + 1;
    Length = (EndPtr - BeginPtr) + 1; // +1 is ')' width.
  } else
    Length = MacroName.size();
  return llvm::StringRef(BeginPtr, Length).trim().str();
}

// Changed vs. modularize: added Visited set.
std::string getMacroExpandedStringInternal(
    clang::Preprocessor &PP, llvm::StringRef MacroName,
    const clang::MacroInfo *MI, const clang::MacroArgs *Args,
    std::set<const clang::MacroInfo *> &Visited) {
  if (!Visited.insert(MI).second) {
    return MacroName.str();
  }
  std::string Expanded;
  // Walk over the macro Tokens.
  typedef clang::MacroInfo::tokens_iterator Iter;
  for (Iter I = MI->tokens_begin(), E = MI->tokens_end(); I != E; ++I) {
    clang::IdentifierInfo *II = I->getIdentifierInfo();
    int ArgNo = (II && Args ? MI->getArgumentNum(II) : -1);
    if (ArgNo == -1) {
      // This isn't an argument, just add it.
      if (II == nullptr)
        Expanded += PP.getSpelling((*I)); // Not an identifier.
      else {
        // Token is for an identifier.
        std::string Name = II->getName().str();
        // Check for nexted macro references.
        clang::MacroInfo *MacroInfo = PP.getMacroInfo(II);
        if (MacroInfo)
          Expanded += getMacroExpandedStringInternal(PP, Name, MacroInfo,
                                                     nullptr, Visited);
        else
          Expanded += Name;
      }
      continue;
    }
    // We get here if it's a function-style macro with arguments.
    const clang::Token *ResultArgToks;
    const clang::Token *ArgTok = Args->getUnexpArgument(ArgNo);
    if (Args->ArgNeedsPreexpansion(ArgTok, PP))
      ResultArgToks = &(const_cast<clang::MacroArgs *>(Args))
                           ->getPreExpArgument(ArgNo, MI, PP)[0];
    else
      ResultArgToks = ArgTok; // Use non-preexpanded Tokens.
    // If the arg token didn't expand into anything, ignore it.
    if (ResultArgToks->is(clang::tok::eof))
      continue;
    unsigned NumToks = clang::MacroArgs::getArgLength(ResultArgToks);
    // Append the resulting argument expansions.
    for (unsigned ArgumentIndex = 0; ArgumentIndex < NumToks; ++ArgumentIndex) {
      const clang::Token &AT = ResultArgToks[ArgumentIndex];
      clang::IdentifierInfo *II = AT.getIdentifierInfo();
      if (II == nullptr)
        Expanded += PP.getSpelling(AT); // Not an identifier.
      else {
        // It's an identifier.  Check for further expansion.
        std::string Name = II->getName().str();
        clang::MacroInfo *MacroInfo = PP.getMacroInfo(II);
        if (MacroInfo)
          Expanded += getMacroExpandedStringInternal(PP, Name, MacroInfo,
                                                     nullptr, Visited);
        else
          Expanded += Name;
      }
    }
  }
  return Expanded;
}

std::string getMacroExpandedString(clang::Preprocessor &PP,
                                   llvm::StringRef MacroName,
                                   const clang::MacroInfo *MI,
                                   const clang::MacroArgs *Args) {
  std::set<const clang::MacroInfo *> Visited;
  return getMacroExpandedStringInternal(PP, MacroName, MI, Args, Visited);
}

std::string getSourceString(clang::Preprocessor &PP, clang::SourceRange Range) {
  clang::SourceLocation BeginLoc = Range.getBegin();
  clang::SourceLocation EndLoc = Range.getEnd();
  if (!BeginLoc.isValid() || !EndLoc.isValid() ||
      BeginLoc.isFileID() != EndLoc.isFileID()) {
    return llvm::StringRef();
  }
  const char *BeginPtr = PP.getSourceManager().getCharacterData(BeginLoc);
  const char *EndPtr = PP.getSourceManager().getCharacterData(EndLoc);
  if (BeginPtr > EndPtr) {
    return llvm::StringRef();
  }
  size_t Length = EndPtr - BeginPtr;
  return llvm::StringRef(BeginPtr, Length).trim().str();
}
}


text:
package eu.hyvar.dataValues.resource.hydatavalue.util;

import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.util.BasicInternalEList;
import org.eclipse.emf.ecore.util.InternalEList;

public class HydatavalueCopiedEObjectInternalEList extends eu.hyvar.dataValues.resource.hydatavalue.util.HydatavalueCopiedEList<EObject> implements InternalEList<EObject> {

	private InternalEList<EObject> original;
	private InternalEList<EObject> copy;

	public HydatavalueCopiedEObjectInternalEList(InternalEList<EObject> original) {
		super(original);
		this.original = original;
		this.copy = new BasicInternalEList<EObject>(EObject.class);
		this.copy.addAll(this.original);
	}

	public boolean basicContains(Object object) {
		return copy.basicContains(object);
	}

	public boolean basicContainsAll(Collection<?> collection) {
		return copy.basicContainsAll(collection);
	}

	public EObject basicGet(int index) {
		return copy.basicGet(index);
	}

	public int basicIndexOf(Object object) {
		return copy.basicIndexOf(object);
	}

	public Iterator<EObject> basicIterator() {
		return copy.basicIterator();
	}

	public int basicLastIndexOf(Object object) {
		return copy.basicLastIndexOf(object);
	}

	public List<EObject> basicList() {
		return copy.basicList();
	}

	public ListIterator<EObject> basicListIterator() {
		return copy.basicListIterator();
	}

	public ListIterator<EObject> basicListIterator(int index) {
		return copy.basicListIterator(index);
	}

	public Object[] basicToArray() {
		return copy.basicToArray();
	}

	public <T> T[] basicToArray(T[] array) {
		return copy.basicToArray(array);
	}

	public boolean equals(Object o) {
		return copy.equals(o);
	}

	public int hashCode() {
		return copy.hashCode();
	}

	public boolean addAllUnique(Collection<? extends EObject> collection) {
		copy.addAllUnique(collection);
		return original.addAllUnique(collection);
	}

	public boolean addAllUnique(int index, Collection<? extends EObject> collection) {
		copy.addAllUnique(index, collection);
		return original.addAllUnique(index, collection);
	}

	public void addUnique(EObject object) {
		copy.addUnique(object);
		original.addUnique(object);
	}

	public void addUnique(int index, EObject object) {
		copy.addUnique(index, object);
		original.addUnique(index, object);
	}

	public NotificationChain basicAdd(EObject object, NotificationChain notifications) {
		copy.basicAdd(object, notifications);
		return original.basicAdd(object, notifications);
	}

	public NotificationChain basicRemove(Object object,
	NotificationChain notifications) {
		copy.basicRemove(object, notifications);
		return original.basicRemove(object, notifications);
	}

	public EObject setUnique(int index, EObject object) {
		copy.setUnique(index, object);
		return original.setUnique(index, object);
	}
}


text:
package edu.inlab.service.wage;

import edu.inlab.models.Task;
import edu.inlab.models.UserTask;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * Created by inlab-dell on 2016/6/7.
 * 直接根据Task中wage的数值发钱
 */

public class TaskOneShotWageAssigner implements WageAssigner {
    public Double assignWage(Task task, UserTask userTask) {
        return assignWage(task);
    }

    public Double assignWage(Task task) {
        Double retVal = null;
        try{
            retVal = Double.valueOf(task.getWage());
        } catch (NullPointerException e){
            e.printStackTrace();
        } catch (NumberFormatException e){
            e.printStackTrace();
        }
        return retVal;
    }
}


text:
'use strict';

const imports = [
  {import: 'sinon', message: 'Importing sinon is forbidden'},
  {
    import: 'preact',
    message:
      "Please import preact from 'src/preact'. This gives us type safety.",
  },
  {
    import: 'preact/hooks',
    message:
      "Please import preact/hooks from 'src/preact'. This gives us type safety.",
  },
];

module.exports = function(context) {
  return {
    ImportDeclaration(node) {
      const comments = context.getCommentsBefore(node.source);
      const ok = comments.some(comment => comment.value === 'OK');
      if (ok) {
        return;
      }

      const name = node.source.value;

      for (const forbidden of imports) {
        if (name !== forbidden.import) {
          continue;
        }

        context.report({
          node,
          message: forbidden.message,
        });
      }
    },
  };
};


text:
package org.kie.workbench.common.dmn.api.definition.model;

import org.kie.workbench.common.dmn.api.property.dmn.Description;
import org.kie.workbench.common.dmn.api.property.dmn.Id;

public abstract class Artifact extends DMNElement {

    public Artifact() {
    }

    public Artifact(final Id id,
                    final Description description) {
        super(id,
              description);
    }
}


text:
package org.swingeasy;

import java.text.Format;
import java.util.Locale;

import javax.swing.JFormattedTextField;
import javax.swing.ToolTipManager;
import javax.swing.text.DefaultFormatterFactory;

import org.swingeasy.MethodInvoker.InvocationException;
import org.swingeasy.formatters.EFormatBuilder;
import org.swingeasy.system.SystemSettings;

/**
 * @author Jurgen
 */
public class EFormattedTextField<T> extends JFormattedTextField implements EComponentI {
    private static final long serialVersionUID = 3962285208926281649L;

    protected EFormatBuilder factory;

    protected final EFormattedTextFieldConfig cfg;

    // public EFormattedTextField(DefaultFormatter factory) {
    // this(new DefaultFormatterFactory(factory, factory, factory, factory));
    // }
    //
    // public EFormattedTextField(DefaultFormatter factory, T currentValue) {
    // this(new DefaultFormatterFactory(factory, factory, factory, factory));
    // this.setValue(currentValue);
    // }

    public EFormattedTextField(EFormattedTextFieldConfig cfg) {
        this.init(this.cfg = cfg.lock());
    }

    public EFormattedTextField(EFormattedTextFieldConfig cfg, T currentValue) {
        this.init(this.cfg = cfg.lock());
        this.setValue(currentValue);
    }

    public void addDocumentKeyListener(DocumentKeyListener listener) {
        this.getDocument().addDocumentListener(listener);
        this.addKeyListener(listener);
    }

    /**
     *
     * @see javax.swing.JComponent#getToolTipText()
     */
    @Override
    public String getToolTipText() {
        String toolTipText = super.getToolTipText();
        if (toolTipText == null) {
            String text = this.getText();
            if (text.trim().length() == 0) {
                text = null;
            }
            return text;
        }
        return toolTipText;
    }

    protected void init(EFormattedTextFieldConfig config) {
        if (config.isTooltips()) {
            ToolTipManager.sharedInstance().registerComponent(this);
        }

        if (config.isDefaultPopupMenu()) {
            this.installPopupMenuAction(EComponentPopupMenu.installTextComponentPopupMenu(this));
        }

        if (config.isLocalized()) {
            UIUtils.registerLocaleChangeListener((EComponentI) this);
        }

        this.setFocusLostBehavior(JFormattedTextField.COMMIT_OR_REVERT);

        if (config.getFactory() != null) {
            this.factory = config.getFactory();
            this.setFormat(this.factory.build(SystemSettings.getCurrentLocale()));
        } else {
            this.setFormatter(config.other);
        }
    }

    protected void installPopupMenuAction( EComponentPopupMenu menu) {
        //
    }

    public void removeDocumentKeyListener(DocumentKeyListener listener) {
        this.getDocument().removeDocumentListener(listener);
        this.removeKeyListener(listener);
    }

    protected void setFormat(Format format) {
        AbstractFormatterFactory ff;
        try {
            // thank you for making this private
            ff = MethodInvoker.invoke(this, "getDefaultFormatterFactory", Object.class, format, AbstractFormatterFactory.class);

            if (ff instanceof DefaultFormatterFactory) {
                DefaultFormatterFactory defaultFormatterFactory = DefaultFormatterFactory.class.cast(ff);
                defaultFormatterFactory.setDisplayFormatter(defaultFormatterFactory.getDefaultFormatter());
                defaultFormatterFactory.setEditFormatter(defaultFormatterFactory.getDefaultFormatter());
                defaultFormatterFactory.setNullFormatter(defaultFormatterFactory.getDefaultFormatter());
            }
        } catch (InvocationException ex) {
            throw new RuntimeException(ex);
        }
        this.setFormatterFactory(ff);
    }

    /**
     *
     * @see java.awt.Component#setLocale(java.util.Locale)
     */
    @Override
    public void setLocale(Locale l) {
        super.setLocale(l);
        if (this.factory != null) {
            this.setFormat(this.factory.build(l));
        }
    }
}


text:
Mendeley Stats
==============

A command line tool to extract information about papers in a Mendeley folder.

## Installation

### OS X and Linux:

```
pip install numpy
pip install mendeleystats
```

Also, you need to set API keys to a configuration file. First, enter http://dev.mendeley.com/ and register an app.
to access the values of Consumer Key and Consumer Secret. With this information in hands, create a
file .mendeleystatsconfig in your home directory. The content of this file must follow the format:

```
{
    "api_key" : "the value of the consumer key",
    "api_secret" : "the value of the consumer secret"
}
```

### Windows

I do not know. I accept help to write this :)

## How to use

It is super simple to use:

```
mendeleystats [-h] --info {year,type,authors,keywords,publishedin}
                --output {chart,csv} --folder FOLDER
```

For example:

```
mendeleystats --info year --output chart --folder datamining
```

It displays a chart with information about papers per year from the "datamining" folder.
You can get other types of information, you only need to change the value of the argument --info,
the options are: year, type, authors, keywords, and publishedin.

Besides, you can choose to save a .csv file with the information instead get a chart.
For this, you need to use the value csv in the argument --output.

## Credits

I'm using two modules from https://github.com/Mendeley/mendeley-oapi-example


text:
<!--
Please link the GitHub issue this pull request resolves in the format of `#1234`. If you discussed this change
with a maintainer, please mention her/him using the `@` syntax (e.g. `@aeneasr`).

If this change neither resolves an existing issue nor has sign-off from one of the maintainers, there is a
chance substantial changes will be requested or that the changes will be rejected.

You can discuss changes with maintainers either in the [ORY Community Forums](https://community.ory.sh/) or
join the [ORY Chat](https://www.ory.sh/chat).
-->

## Proposed changes

<!--
Describe the big picture of your changes here to communicate to the maintainers why we should accept this pull request.
-->

## Checklist

<!--
Put an `x` in the boxes that apply. You can also fill these out after creating the PR. If you're unsure about any of
them, don't hesitate to ask. We're here to help! This is simply a reminder of what we are going to look for before merging your code.
-->

- [ ] I have read the [contributing guidelines](../blob/master/CONTRIBUTING.md)
- [ ] I have read the [security policy](../security/policy)
- [ ] I confirm that this pull request does not address a security vulnerability. If this pull request addresses a security
vulnerability, I confirm that I got green light (please contact [security@ory.sh](mailto:security@ory.sh)) from the maintainers to push the changes.
- [ ] I have added tests that prove my fix is effective or that my feature works
- [ ] I have added necessary documentation within the code base (if appropriate)

## Further comments

<!--
If this is a relatively large or complex change, kick off the discussion by explaining why you chose the solution
you did and what alternatives you considered, etc...
-->


text:
////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2010-2017. Lapinin "lastrix" Sergey.                          /
//                                                                             /
// Permission is hereby granted, free of charge, to any person                 /
// obtaining a copy of this software and associated documentation              /
// files (the "Software"), to deal in the Software without                     /
// restriction, including without limitation the rights to use,                /
// copy, modify, merge, publish, distribute, sublicense, and/or                /
// sell copies of the Software, and to permit persons to whom the              /
// Software is furnished to do so, subject to the following                    /
// conditions:                                                                 /
//                                                                             /
// The above copyright notice and this permission notice shall be              /
// included in all copies or substantial portions of the Software.             /
//                                                                             /
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,             /
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES             /
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND                    /
// NON INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT                /
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,                /
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING                /
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE                  /
// OR OTHER DEALINGS IN THE SOFTWARE.                                          /
////////////////////////////////////////////////////////////////////////////////

package org.asn1s.api.value;

import org.asn1s.api.*;
import org.asn1s.api.type.Type;
import org.asn1s.api.value.x680.*;
import org.asn1s.api.value.x681.ObjectValue;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

public interface DefinedValue extends Value, Validation, Disposable, Scoped
{
	@NotNull
	Scope createScope();

	String getName();

	Type getType();

	Value getValue();

	Ref<Value> toRef();

	@Nullable
	Template getTemplate();

	/**
	 * Copy this value, allowing to use instantiation for parameterized values.
	 *
	 * @return copy of value
	 */
	@NotNull
	DefinedValue copy();

	/**
	 * Returns true if this value is abstract and can not be instantiated directly
	 *
	 * @return boolean
	 */
	default boolean isAbstract()
	{
		return false;
	}

	@Override
	default BooleanValue toBooleanValue()
	{
		return getValue().toBooleanValue();
	}

	@Override
	default IntegerValue toIntegerValue()
	{
		return getValue().toIntegerValue();
	}

	@Override
	default RealValue toRealValue()
	{
		return getValue().toRealValue();
	}

	@Override
	default NullValue toNullValue()
	{
		return getValue().toNullValue();
	}

	@Override
	default NamedValue toNamedValue()
	{
		return getValue().toNamedValue();
	}

	@Override
	default ValueCollection toValueCollection()
	{
		return getValue().toValueCollection();
	}

	@Override
	default StringValue toStringValue()
	{
		return getValue().toStringValue();
	}

	@Override
	default ByteArrayValue toByteArrayValue()
	{
		return getValue().toByteArrayValue();
	}

	@Override
	default DateValue toDateValue()
	{
		return getValue().toDateValue();
	}

	@Override
	default ObjectValue toObjectValue()
	{
		return getValue().toObjectValue();
	}

	@Override
	default ObjectIdentifierValue toObjectIdentifierValue()
	{
		return getValue().toObjectIdentifierValue();
	}

	@Override
	default OpenTypeValue toOpenTypeValue()
	{
		return getValue().toOpenTypeValue();
	}

}